@deveco/deveco-cli-common 1.3.11 → 1.3.12
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/THIRD-PARTY-LICENSES
CHANGED
|
@@ -3,8 +3,8 @@ https://www.npmjs.com/package/generate-license-file
|
|
|
3
3
|
|
|
4
4
|
The following npm packages may be included in this product:
|
|
5
5
|
|
|
6
|
-
- @deveco/deveco-cli-knowledgebase@1.3.
|
|
7
|
-
- @deveco/deveco-cli@1.3.
|
|
6
|
+
- @deveco/deveco-cli-knowledgebase@1.3.12
|
|
7
|
+
- @deveco/deveco-cli@1.3.12
|
|
8
8
|
|
|
9
9
|
These packages each contain the following license:
|
|
10
10
|
|
|
@@ -44,7 +44,7 @@ SOFTWARE.
|
|
|
44
44
|
|
|
45
45
|
The following npm package may be included in this product:
|
|
46
46
|
|
|
47
|
-
- @deveco/deveco-cli-common@1.3.
|
|
47
|
+
- @deveco/deveco-cli-common@1.3.12
|
|
48
48
|
|
|
49
49
|
This package contains the following license:
|
|
50
50
|
|
package/dist/cli.js
CHANGED
|
@@ -41,7 +41,7 @@ zYl5snR6SmrDfVmtsyz8aMqifx4gsVV2M5/owv8H3bUdOd5RbkKhzOS2Pmep0bbw
|
|
|
41
41
|
WRFUrWuQ+5ci2LLkZyIt9ffNR8W9gbmZOZZTrwSFRIT1Q433NOzCQNDjKwnekGAx
|
|
42
42
|
8o746tqqZxGCXgy2MaIIqvajhNw9Dr3NBQ8ziWyqaQBk2RrCWh6Q++Sd0b5L3RwH
|
|
43
43
|
rQ==
|
|
44
|
-
-----END CERTIFICATE-----`,O0=new sh.X509Certificate(N0),jP=[{cert:O0}];function M0(r){let e=[],t=r.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let n of t)try{e.push({cert:new sh.X509Certificate(n)})}catch{}return e}var HP=new Set,Jd;function _0(){let r=process.env.NODE_EXTRA_CA_CERTS;if(Jd&&Jd.envValue===r)return Jd.anchors;let e=r?L0(r):[],t=e.length?[...jP,...e]:jP;return Jd={envValue:r,anchors:t},t}function L0(r){try{let e=M0(x0.readFileSync(r,"utf8"));return e.length===0&&UP(r,"no parseable certificate found"),e}catch(e){return UP(r,e instanceof Error?e.message:String(e)),[]}}function UP(r,e){HP.has(r)||(HP.add(r),console.warn(T0(`[devecocli] GRS TLS: failed to load NODE_EXTRA_CA_CERTS (${I0.basename(r)}): ${e} \u2014 falling back to the built-in CA only.`)))}function $0(r){let e=[],t=new Set,n=r;for(;n&&n.raw;){let i=n.fingerprint256||n.fingerprint||"";if(!i||t.has(i))break;t.add(i);try{e.push(new sh.X509Certificate(n.raw))}catch{break}let o=n.issuerCertificate??null;if(o===r)break;n=o}return e}function F0(r,e,t){if(r.length===0)return new Error("[GRS TLS] Server did not provide a certificate");if(!j0(r,t))return f(()=>"[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=H0(r[0],e);if(n)return n;f(()=>"[GRS TLS] Verification passed: certificate chain anchored on a trusted CA")}function j0(r,e){for(let n of e){let i=r.findIndex(o=>o.fingerprint256===n.cert.fingerprint256);if(i>=0&&BP(r,i))return!0}let t=r[r.length-1];for(let n of e)if(n.cert.subject===t.issuer)try{if(t.verify(n.cert.publicKey)&&BP(r,r.length-1))return!0}catch{}return!1}function BP(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 H0(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(!B0(r,e))return new Error(`[GRS TLS] Server certificate does not match host ${e}`)}function U0(r,e){let t=r.getPeerCertificate(!0);if(!t||!t.raw)return new Error("[GRS TLS] Server did not provide a certificate");let n=$0(t);return n.length===0?new Error("[GRS TLS] Server certificate could not be parsed"):F0(n,e,_0())}function B0(r,e){let t=r.subjectAltName??"",n=e.toLowerCase();for(let i of t.split(",")){let o=i.trim();if(!o.startsWith("DNS:"))continue;let s=o.slice(4).toLowerCase();if(s===n)return!0;if(s.startsWith("*.")){let a=s.slice(1),c=n.slice(0,-a.length);if(n.endsWith(a)&&c.length>0&&!c.includes("."))return!0}}return!1}var W0=8e3,ih=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)}}},oh=class extends A0.Agent{connectTimeoutMs;constructor(e){super(e),this.connectTimeoutMs=e?.connectTimeoutMs??W0}createConnection(e,t){let n=e.host||e.servername||"",i=e.port||443,o=`https://${n}:${i}`,s=zd(o),a=new ih(t,this.connectTimeoutMs);if(a.start(),s){this.createConnectionViaProxy(e,s,n,i,a);return}return this.createDirectConnection(e,a,n)}createDirectConnection(e,t,n){let i=FP.connect({...e,rejectUnauthorized:!1});return t.onDestroy(()=>i.destroy()),this.attachTlsVerification(i,t,n),i}createConnectionViaProxy(e,t,n,i,o){let s;try{s=new D0(t)}catch{o.settle(new Error(`[GRS] Invalid proxy URL: ${t}`));return}let a=Number(s.port)||(s.protocol==="https:"?443:80),c=this.buildProxyHeaders(s,n,i);f(()=>`[GRS] Connecting via proxy ${s.hostname}:${a} to ${n}:${i}`);let l=R0.request({host:s.hostname,port:a,method:"CONNECT",path:`${n}:${i}`,headers:c});o.onDestroy(()=>l.destroy()),l.on("connect",(d,m)=>{if(d.statusCode!==200){m.destroy(),o.settle(new Error(`[GRS] Proxy CONNECT failed: ${d.statusCode} ${d.statusMessage||""}`));return}o.onDestroy(()=>m.destroy()),this.startTlsOverTunnel(e,m,o,n)}),l.on("error",d=>{o.settle(new Error(`[GRS] Proxy connection failed: ${d.message}`))}),l.end()}startTlsOverTunnel(e,t,n,i){f(()=>"[GRS] Proxy tunnel established, starting TLS handshake");let o=FP.connect({...e,socket:t,rejectUnauthorized:!1});n.onDestroy(()=>o.destroy()),this.attachTlsVerification(o,n,i)}buildProxyHeaders(e,t,n){let i={Host:`${t}:${n}`};if(e.username||e.password){let o=`${decodeURIComponent(e.username)}:${decodeURIComponent(e.password)}`;i["Proxy-Authorization"]=`Basic ${Buffer.from(o).toString("base64")}`}return i}attachTlsVerification(e,t,n){e.once("secureConnect",()=>{let i=U0(e,n);i?(e.destroy(i),t.settle(i)):t.settle(null,e)}),e.once("error",i=>{t.settle(i)})}},ah=new oh({keepAlive:!0});var ch=[{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"}],On=class extends Error{kind;constructor(e,t){super(t),this.name="GrsError",this.kind=e}};var V0=["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"],G0="com.huawei.deveco.common-grs/0.1 (Windows;Linux;Mac) Deveco-grs/-1",z0="devecostudio",q0=8e3;async function Kd(r){let e=[],t="";for(let o of V0){let s=await J0(o,r);if(s.outcome==="ok")return s.services;e.push(s.outcome),s.detail&&(t=s.detail)}if(e.some(o=>o==="incomplete"))throw new On("no-config",`GRS returned no valid configuration for country code ${r} (this region may not be supported)`);let n=process.env.HTTPS_PROXY||process.env.HTTP_PROXY,i=n?`Current proxy: ${n}. Verify the proxy is running and allows CONNECT to grs.dbankcloud.com:443. If the proxy inspects TLS, set NODE_EXTRA_CA_CERTS to a PEM file with your corporate CA \u2014 untrusted GRS certificates are rejected.`:"No proxy configured (HTTP_PROXY/HTTPS_PROXY). If you are behind a corporate firewall, set HTTPS_PROXY=http://your-proxy:port.";throw new On("network",`GRS endpoints unreachable (grs.dbankcloud.com is globally reachable). ${i}${t?` Last endpoint error: ${t}`:""}`)}async function J0(r,e){let t=`${r}?issue_country=${encodeURIComponent(e)}&app_name=${z0}`;f(()=>`[GRS] POST ${t}`);try{let n=await W.post(t,{headers:{"User-Agent":G0},httpsAgent:ah,timeout:q0}),i=W.parseJson(n);return i.resultCode!==0?(f(()=>`[GRS] ${r} resultCode=${i.resultCode}, skipping`),{outcome:"incomplete",detail:`resultCode=${i.resultCode}`}):K0(i.services)?(f(()=>`[GRS] hit ${r}, received ${Object.keys(i.services).length} service groups`),{outcome:"ok",services:i.services}):(f(()=>`[GRS] ${r} returned incomplete config (missing required service keys), skipping`),{outcome:"incomplete",detail:"missing required service keys"})}catch(n){let i=n instanceof Error?n.message:String(n);return f(()=>`[GRS] ${r} request failed: ${i}`),{outcome:"network",detail:i}}}function K0(r){return ch.every(({group:e,key:t})=>typeof r[e]?.[t]=="string")}import ph from"fs";import Q0 from"path";import*as uc from"fs";import*as VP from"path";import{homedir as Y0}from"os";function lh(r){let e=r.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function Yd(r){let e=lh(r);if(!e)throw new Error("Path must not be empty.");return nn(e)}var X0="deveco-cli",WP,dh=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function Z0(){let r=process.env.DEVECO_CLI_DATA_DIR,t=(r===void 0||r===""?"":lh(r))||VP.join(Y0(),".local","share",X0);try{return Yd(t)}catch(n){throw new dh(n instanceof Error?n.message:String(n))}}function F(){if(WP!==void 0)return WP;let r=Z0();try{if(uc.existsSync(r))return uc.realpathSync(r)}catch{}return r}var e$="com.huawei.devecostudio.region",GP={[e$]:{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"}},t$=1440*60*1e3,zP=new Set(["CN","HK","MO"]),uh=class{countryCode="";services={};resolved=!1;isCN(){return this.countryCode==="CN"}isOnlineAllowed(){return zP.has(this.countryCode)}getService(e,t){let n=this.services[e]?.[t];if(!n)throw new Error(`GRS service ${e}.${t} not available`);return n}setCountryCode(e){this.countryCode=e}async resolve(){if(!this.countryCode)throw new Error("Country code not set, cannot resolve GRS");if(this.countryCode==="CN"){this.services=GP,this.resolved=!0,f(()=>"[GRS] CN uses hardcoded services, skipping GRS request");return}let e=await qP(this.countryCode);if(e){this.services=e.services,this.resolved=!0,f(()=>`[GRS] cache hit country=${this.countryCode}, skipping request`);return}f(()=>`[GRS] cache miss or expired, requesting GRS country=${this.countryCode}`);let t=await Kd(this.countryCode);this.services=t,this.resolved=!0,await JP(this.countryCode,t)}},B=new uh;function mh(r){return Q0.join(F(),`grs_${r}.json`)}async function qP(r){try{let e=await ph.promises.readFile(mh(r),"utf8"),t=JSON.parse(e);return t.countryCode!==r||Date.now()-t.fetchedAt>t$?null:t}catch{return null}}async function JP(r,e){let t={services:e,fetchedAt:Date.now(),countryCode:r};try{await ph.promises.writeFile(mh(r),JSON.stringify(t),"utf8")}catch{}}async function fh(r){try{await ph.promises.unlink(mh(r))}catch{}}async function KP(r){if(r==="CN")return GP;let e=await qP(r);if(e)return e.services;let t=await Kd(r);return await JP(r,t),t}var mo="com.huawei.devecostudio.region",r$="/api/ups/user-permission-service/v1/user-team-list",n$="/agreementservice/user";function cr(){if(!B.isOnlineAllowed())throw new Error(`CLI online services are not available in your region (detected: ${B.countryCode||"unknown"}).`)}async function on(){B.resolved||await B.resolve()}function Mn(){return B.getService(mo,"spaceintroduce")}async function gh(r){let t=(await KP(r))[mo]?.spaceintroduce;if(!t)throw new Error(`GRS service ${mo}.spaceintroduce not available`);return t}function hh(){return`${B.getService(mo,"agcups")}${r$}`}function Jt(){return B.getService(mo,"agcsign")}function yh(){return`${B.getService(mo,"agreementservice")}${n$}`}var YP={CN:"https://legal.cloud.huawei.com",HK:"https://legal.cloud.huawei.com",MO:"https://legal.cloud.huawei.com"};function wh(r,e){return`${YP[r]??YP.CN}/terms/scope/huawei/deveco-cli/privacy-statement.htm?code=${r}&language=${e}&branchid=0&contenttag=default`}function Xd(){return B.getService(mo,"agcdeveloper")}var pc=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 Md;storageDir="";failedDir="";installId="";get disabled(){return gt()||!B.isCN()}traceFileKey=Buffer.alloc(0);sessionId=XP.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){h.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=Kt.join(e,"failed"),this.cliVersion="1.3.11",this.nodeVersion=process.version,this.installId=TP(e).replace(/-/g,""),this.traceFileKey=oP(e),xe.mkdirSync(e,{recursive:!0}),xe.mkdirSync(this.failedDir,{recursive:!0}),h.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,h.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,h.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,h.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)return h.debug("[telemetry] track skipped: telemetry not initialized"),typeof t=="function"?t():void 0;if(!t){await this.record(e,0,!0,null);return}if(typeof t!="function"){let o=t;await this.record(e,o.duration_ms,o.success,o.error_code);return}let n=t,i=Date.now();try{let o=await n(),s=Date.now()-i;return await this.record(e,s,!0,null),o}catch(o){let s=Date.now()-i,a=this.toErrorCode(o);throw await this.record(e,s,!1,a),o}}async record(e,t,n,i){let o=this.buildTraceEvent(e,t,n,i);try{let s=sP(JSON.stringify(o),this.traceFileKey);await xe.promises.appendFile(this.currentFile(),s+`
|
|
44
|
+
-----END CERTIFICATE-----`,O0=new sh.X509Certificate(N0),jP=[{cert:O0}];function M0(r){let e=[],t=r.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let n of t)try{e.push({cert:new sh.X509Certificate(n)})}catch{}return e}var HP=new Set,Jd;function _0(){let r=process.env.NODE_EXTRA_CA_CERTS;if(Jd&&Jd.envValue===r)return Jd.anchors;let e=r?L0(r):[],t=e.length?[...jP,...e]:jP;return Jd={envValue:r,anchors:t},t}function L0(r){try{let e=M0(x0.readFileSync(r,"utf8"));return e.length===0&&UP(r,"no parseable certificate found"),e}catch(e){return UP(r,e instanceof Error?e.message:String(e)),[]}}function UP(r,e){HP.has(r)||(HP.add(r),console.warn(T0(`[devecocli] GRS TLS: failed to load NODE_EXTRA_CA_CERTS (${I0.basename(r)}): ${e} \u2014 falling back to the built-in CA only.`)))}function $0(r){let e=[],t=new Set,n=r;for(;n&&n.raw;){let i=n.fingerprint256||n.fingerprint||"";if(!i||t.has(i))break;t.add(i);try{e.push(new sh.X509Certificate(n.raw))}catch{break}let o=n.issuerCertificate??null;if(o===r)break;n=o}return e}function F0(r,e,t){if(r.length===0)return new Error("[GRS TLS] Server did not provide a certificate");if(!j0(r,t))return f(()=>"[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=H0(r[0],e);if(n)return n;f(()=>"[GRS TLS] Verification passed: certificate chain anchored on a trusted CA")}function j0(r,e){for(let n of e){let i=r.findIndex(o=>o.fingerprint256===n.cert.fingerprint256);if(i>=0&&BP(r,i))return!0}let t=r[r.length-1];for(let n of e)if(n.cert.subject===t.issuer)try{if(t.verify(n.cert.publicKey)&&BP(r,r.length-1))return!0}catch{}return!1}function BP(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 H0(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(!B0(r,e))return new Error(`[GRS TLS] Server certificate does not match host ${e}`)}function U0(r,e){let t=r.getPeerCertificate(!0);if(!t||!t.raw)return new Error("[GRS TLS] Server did not provide a certificate");let n=$0(t);return n.length===0?new Error("[GRS TLS] Server certificate could not be parsed"):F0(n,e,_0())}function B0(r,e){let t=r.subjectAltName??"",n=e.toLowerCase();for(let i of t.split(",")){let o=i.trim();if(!o.startsWith("DNS:"))continue;let s=o.slice(4).toLowerCase();if(s===n)return!0;if(s.startsWith("*.")){let a=s.slice(1),c=n.slice(0,-a.length);if(n.endsWith(a)&&c.length>0&&!c.includes("."))return!0}}return!1}var W0=8e3,ih=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)}}},oh=class extends A0.Agent{connectTimeoutMs;constructor(e){super(e),this.connectTimeoutMs=e?.connectTimeoutMs??W0}createConnection(e,t){let n=e.host||e.servername||"",i=e.port||443,o=`https://${n}:${i}`,s=zd(o),a=new ih(t,this.connectTimeoutMs);if(a.start(),s){this.createConnectionViaProxy(e,s,n,i,a);return}return this.createDirectConnection(e,a,n)}createDirectConnection(e,t,n){let i=FP.connect({...e,rejectUnauthorized:!1});return t.onDestroy(()=>i.destroy()),this.attachTlsVerification(i,t,n),i}createConnectionViaProxy(e,t,n,i,o){let s;try{s=new D0(t)}catch{o.settle(new Error(`[GRS] Invalid proxy URL: ${t}`));return}let a=Number(s.port)||(s.protocol==="https:"?443:80),c=this.buildProxyHeaders(s,n,i);f(()=>`[GRS] Connecting via proxy ${s.hostname}:${a} to ${n}:${i}`);let l=R0.request({host:s.hostname,port:a,method:"CONNECT",path:`${n}:${i}`,headers:c});o.onDestroy(()=>l.destroy()),l.on("connect",(d,m)=>{if(d.statusCode!==200){m.destroy(),o.settle(new Error(`[GRS] Proxy CONNECT failed: ${d.statusCode} ${d.statusMessage||""}`));return}o.onDestroy(()=>m.destroy()),this.startTlsOverTunnel(e,m,o,n)}),l.on("error",d=>{o.settle(new Error(`[GRS] Proxy connection failed: ${d.message}`))}),l.end()}startTlsOverTunnel(e,t,n,i){f(()=>"[GRS] Proxy tunnel established, starting TLS handshake");let o=FP.connect({...e,socket:t,rejectUnauthorized:!1});n.onDestroy(()=>o.destroy()),this.attachTlsVerification(o,n,i)}buildProxyHeaders(e,t,n){let i={Host:`${t}:${n}`};if(e.username||e.password){let o=`${decodeURIComponent(e.username)}:${decodeURIComponent(e.password)}`;i["Proxy-Authorization"]=`Basic ${Buffer.from(o).toString("base64")}`}return i}attachTlsVerification(e,t,n){e.once("secureConnect",()=>{let i=U0(e,n);i?(e.destroy(i),t.settle(i)):t.settle(null,e)}),e.once("error",i=>{t.settle(i)})}},ah=new oh({keepAlive:!0});var ch=[{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"}],On=class extends Error{kind;constructor(e,t){super(t),this.name="GrsError",this.kind=e}};var V0=["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"],G0="com.huawei.deveco.common-grs/0.1 (Windows;Linux;Mac) Deveco-grs/-1",z0="devecostudio",q0=8e3;async function Kd(r){let e=[],t="";for(let o of V0){let s=await J0(o,r);if(s.outcome==="ok")return s.services;e.push(s.outcome),s.detail&&(t=s.detail)}if(e.some(o=>o==="incomplete"))throw new On("no-config",`GRS returned no valid configuration for country code ${r} (this region may not be supported)`);let n=process.env.HTTPS_PROXY||process.env.HTTP_PROXY,i=n?`Current proxy: ${n}. Verify the proxy is running and allows CONNECT to grs.dbankcloud.com:443. If the proxy inspects TLS, set NODE_EXTRA_CA_CERTS to a PEM file with your corporate CA \u2014 untrusted GRS certificates are rejected.`:"No proxy configured (HTTP_PROXY/HTTPS_PROXY). If you are behind a corporate firewall, set HTTPS_PROXY=http://your-proxy:port.";throw new On("network",`GRS endpoints unreachable (grs.dbankcloud.com is globally reachable). ${i}${t?` Last endpoint error: ${t}`:""}`)}async function J0(r,e){let t=`${r}?issue_country=${encodeURIComponent(e)}&app_name=${z0}`;f(()=>`[GRS] POST ${t}`);try{let n=await W.post(t,{headers:{"User-Agent":G0},httpsAgent:ah,timeout:q0}),i=W.parseJson(n);return i.resultCode!==0?(f(()=>`[GRS] ${r} resultCode=${i.resultCode}, skipping`),{outcome:"incomplete",detail:`resultCode=${i.resultCode}`}):K0(i.services)?(f(()=>`[GRS] hit ${r}, received ${Object.keys(i.services).length} service groups`),{outcome:"ok",services:i.services}):(f(()=>`[GRS] ${r} returned incomplete config (missing required service keys), skipping`),{outcome:"incomplete",detail:"missing required service keys"})}catch(n){let i=n instanceof Error?n.message:String(n);return f(()=>`[GRS] ${r} request failed: ${i}`),{outcome:"network",detail:i}}}function K0(r){return ch.every(({group:e,key:t})=>typeof r[e]?.[t]=="string")}import ph from"fs";import Q0 from"path";import*as uc from"fs";import*as VP from"path";import{homedir as Y0}from"os";function lh(r){let e=r.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function Yd(r){let e=lh(r);if(!e)throw new Error("Path must not be empty.");return nn(e)}var X0="deveco-cli",WP,dh=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function Z0(){let r=process.env.DEVECO_CLI_DATA_DIR,t=(r===void 0||r===""?"":lh(r))||VP.join(Y0(),".local","share",X0);try{return Yd(t)}catch(n){throw new dh(n instanceof Error?n.message:String(n))}}function F(){if(WP!==void 0)return WP;let r=Z0();try{if(uc.existsSync(r))return uc.realpathSync(r)}catch{}return r}var e$="com.huawei.devecostudio.region",GP={[e$]:{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"}},t$=1440*60*1e3,zP=new Set(["CN","HK","MO"]),uh=class{countryCode="";services={};resolved=!1;isCN(){return this.countryCode==="CN"}isOnlineAllowed(){return zP.has(this.countryCode)}getService(e,t){let n=this.services[e]?.[t];if(!n)throw new Error(`GRS service ${e}.${t} not available`);return n}setCountryCode(e){this.countryCode=e}async resolve(){if(!this.countryCode)throw new Error("Country code not set, cannot resolve GRS");if(this.countryCode==="CN"){this.services=GP,this.resolved=!0,f(()=>"[GRS] CN uses hardcoded services, skipping GRS request");return}let e=await qP(this.countryCode);if(e){this.services=e.services,this.resolved=!0,f(()=>`[GRS] cache hit country=${this.countryCode}, skipping request`);return}f(()=>`[GRS] cache miss or expired, requesting GRS country=${this.countryCode}`);let t=await Kd(this.countryCode);this.services=t,this.resolved=!0,await JP(this.countryCode,t)}},B=new uh;function mh(r){return Q0.join(F(),`grs_${r}.json`)}async function qP(r){try{let e=await ph.promises.readFile(mh(r),"utf8"),t=JSON.parse(e);return t.countryCode!==r||Date.now()-t.fetchedAt>t$?null:t}catch{return null}}async function JP(r,e){let t={services:e,fetchedAt:Date.now(),countryCode:r};try{await ph.promises.writeFile(mh(r),JSON.stringify(t),"utf8")}catch{}}async function fh(r){try{await ph.promises.unlink(mh(r))}catch{}}async function KP(r){if(r==="CN")return GP;let e=await qP(r);if(e)return e.services;let t=await Kd(r);return await JP(r,t),t}var mo="com.huawei.devecostudio.region",r$="/api/ups/user-permission-service/v1/user-team-list",n$="/agreementservice/user";function cr(){if(!B.isOnlineAllowed())throw new Error(`CLI online services are not available in your region (detected: ${B.countryCode||"unknown"}).`)}async function on(){B.resolved||await B.resolve()}function Mn(){return B.getService(mo,"spaceintroduce")}async function gh(r){let t=(await KP(r))[mo]?.spaceintroduce;if(!t)throw new Error(`GRS service ${mo}.spaceintroduce not available`);return t}function hh(){return`${B.getService(mo,"agcups")}${r$}`}function Jt(){return B.getService(mo,"agcsign")}function yh(){return`${B.getService(mo,"agreementservice")}${n$}`}var YP={CN:"https://legal.cloud.huawei.com",HK:"https://legal.cloud.huawei.com",MO:"https://legal.cloud.huawei.com"};function wh(r,e){return`${YP[r]??YP.CN}/terms/scope/huawei/deveco-cli/privacy-statement.htm?code=${r}&language=${e}&branchid=0&contenttag=default`}function Xd(){return B.getService(mo,"agcdeveloper")}var pc=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 Md;storageDir="";failedDir="";installId="";get disabled(){return gt()||!B.isCN()}traceFileKey=Buffer.alloc(0);sessionId=XP.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){h.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=Kt.join(e,"failed"),this.cliVersion="1.3.12",this.nodeVersion=process.version,this.installId=TP(e).replace(/-/g,""),this.traceFileKey=oP(e),xe.mkdirSync(e,{recursive:!0}),xe.mkdirSync(this.failedDir,{recursive:!0}),h.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,h.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,h.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,h.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)return h.debug("[telemetry] track skipped: telemetry not initialized"),typeof t=="function"?t():void 0;if(!t){await this.record(e,0,!0,null);return}if(typeof t!="function"){let o=t;await this.record(e,o.duration_ms,o.success,o.error_code);return}let n=t,i=Date.now();try{let o=await n(),s=Date.now()-i;return await this.record(e,s,!0,null),o}catch(o){let s=Date.now()-i,a=this.toErrorCode(o);throw await this.record(e,s,!1,a),o}}async record(e,t,n,i){let o=this.buildTraceEvent(e,t,n,i);try{let s=sP(JSON.stringify(o),this.traceFileKey);await xe.promises.appendFile(this.currentFile(),s+`
|
|
45
45
|
`,"utf8"),xP(this.storageDir)}catch{}}buildTraceEvent(e,t,n,i){let o=`${r.EVENT_PREFIX}${e.event}`,s=rP.toObject(e);return s&&typeof s=="object"&&delete s.event,{countryCode:r.COUNTRY_CODE,event:o,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:XP.randomUUID(),trace_os_version:r.TRACE_OS_VERSION,os_arch:this.resolveOsArch(),action:o,trace_os_name:this.resolveOsName(),version:`${this.cliVersion}_${this.resolveOsSuffix()}`,deveco_studio_version:this.formatVersion(this.devecoStudioVersion),command_line_version:this.formatVersion(this.cltVersion),source_type:this.sourceType,session_id:this.sessionId,node_version:this.nodeVersion,ram:this.resolveTotalRam(),duration_ms:t,success:n,error_code:i,event_detail:s}}}toErrorCode(e){return e instanceof Error?e.code??e.name:"UnknownError"}resolveOsArch(){let e=Zd.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=Zd.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 Zd.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(Zd.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 Kt.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){h.debug("[telemetry] scheduler not started (telemetry disabled)");return}h.debug(`[telemetry] scheduler started (flush every ${cc/1e3}s, retry failed every ${lc/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},cc)},cc),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},lc)},lc)}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),h.debug("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)return h.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 RP(this.storageDir),t}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)return h.debug("[telemetry] retryFailed skipped: telemetry not initialized"),!0;await this.reclaimStalePending();let e=Date.now(),t;try{t=await xe.promises.readdir(this.failedDir)}catch{return!0}let n=t.filter(o=>o.startsWith("telemetry-")&&o.endsWith(".txt")).map(o=>Kt.join(this.failedDir,o)),i=!0;for(let o of n){let s=Kt.basename(o),a=Qg(s);if(a!==null){if(e-a>Yg){try{await xe.promises.unlink(o)}catch{}continue}await this.flushFile(o)||(i=!1)}}return i||h.warn("[telemetry] retry failed"),AP(this.storageDir),i}async reclaimStalePending(){let e=Date.now();for(let t of[this.storageDir,this.failedDir]){let n;try{n=await xe.promises.readdir(t)}catch{continue}for(let i of n)th(i)&&await this.reclaimOrphan(Kt.join(t,i),e)}}async reclaimOrphan(e,t){let n;try{let l=await xe.promises.stat(e);if(t-l.mtimeMs<Xg)return;n=l.size}catch{return}let i=Kt.dirname(e),o=eh(Kt.basename(e));if(o===null)return;let s=await this.claimOrphan(e,i,o);if(s===null)return;let a=Kt.join(i,o),c=hs-await this.fileSize(a);if(n>c){try{await xe.promises.unlink(s)}catch{}h.warn(`[telemetry] dropped stale orphan pending: ${s} (${n} bytes > budget ${c})`);return}if(await this.mergeOrphanInto(s,a)){h.warn(`[telemetry] reclaimed orphan pending: ${s} (${n} bytes)`);return}h.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${n} bytes)`)}async claimOrphan(e,t,n){let i=Kt.join(t,`${n}.pending.reclaim-${process.pid}-${Date.now()}`);try{await xe.promises.rename(e,i)}catch{return null}return await this.touch(i),i}async mergeOrphanInto(e,t){try{await xe.promises.appendFile(t,await xe.promises.readFile(e))}catch(n){return h.warn(`[telemetry] merge orphan pending failed: ${e} -> ${t}: ${n instanceof Error?n.message:String(n)}`),!1}try{await xe.promises.unlink(e)}catch(n){h.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 xe.promises.stat(e)).size}catch{return 0}}async touch(e){let t=new Date;try{await xe.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 xe.promises.readdir(this.storageDir)}catch{return[]}return e.filter(t=>t.startsWith("telemetry-")&&t.endsWith(".txt")).map(t=>Kt.join(this.storageDir,t)).sort()}async flushFile(e){let t=await this.fileSize(e);if(t>hs){h.warn(`[telemetry] ${Kt.basename(e)} is ${t} bytes (> ${hs}), dropped without uploading`);try{await xe.promises.unlink(e)}catch{}return!0}let n=e+".pending";try{await xe.promises.rename(e,n)}catch{return!1}await this.touch(n);let i;try{i=await xe.promises.readFile(n,"utf8")}catch{return!1}let o=i.split(`
|
|
46
46
|
`).map(s=>s.trim()).filter(Boolean);if(o.length===0){try{await xe.promises.unlink(n)}catch{}return!0}return this.uploadInBatches(n,o)}collectDecryptBatch(e,t){let n=[],i=16,o=t;for(;o<e.length&&n.length<r.MAX_BATCH;){let s=aP(e[o],this.traceFileKey);if(s===null){o++;continue}let a=Buffer.byteLength(s,"utf8")+1;if(n.length>0&&i+a>r.MAX_PAYLOAD_BYTES)break;n.push(s),i+=a,o++}return{batch:n,next:o}}async uploadInBatches(e,t){let n=0;for(;n<t.length;){let i=n,{batch:o,next:s}=this.collectDecryptBatch(t,n);n=s;let a=this.buildPayloadItems(o);if(a.length===0)continue;let c=JSON.stringify(a),l=!1;try{l=await this.uploader.upload(c,this.installId)}catch{}if(!l){h.warn("[telemetry] upload failed");let d=t.slice(i).join(`
|
|
47
47
|
`)+`
|
|
@@ -54,7 +54,7 @@ rQ==
|
|
|
54
54
|
`,"utf8")}function SC(r){let e=["serve","mcp","--auto-init"];return r!==void 0&&r!==""&&e.push("--path",r),e}function bC(r,e){return r||(e==="workspaceFolder"?"${workspaceFolder}":".")}async function EC(){await hC("npm",["install","-g",yC],{stdio:"inherit"})}async function PC(){return A$()?(await hC("npm",["install","-g",`${yC}@latest`],{stdio:"inherit"}),"upgraded"):"skipped"}var Dh="deveco-mcp",CC="homegraph",lu={"trae-cn":".trae-cn",opencode:".config/opencode",pi:".pi/agent",deveco:".config/deveco",cursor:".cursor",codebuddy:".codebuddy",qoder:".qoder","claude-code":".claude",codex:".codex",atomcode:".atomcode",dsh:".dsh"};var $n={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:Lt.join(cn(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},pi:{name:"pi",displayName:"Pi Coding Agent",supportsGlobal:!0,globalConfigPath:Lt.join(cn(),".pi","agent","mcp.json"),projectConfigPath:".pi/mcp.json",mcpServersKey:"mcpServers",format:"standard"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:Lt.join(process.platform==="win32"?Lt.join(process.env.APPDATA??Lt.join(cn(),"AppData","Roaming"),"Trae CN","User"):Lt.join(cn(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:Lt.join(cn(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:Lt.join(cn(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"codebuddy"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:Lt.join(process.platform==="win32"?Lt.join(process.env.APPDATA??Lt.join(cn(),"AppData","Roaming"),"Qoder","SharedClientCache"):Lt.join(cn(),"Library","Application Support","Qoder","SharedClientCache"),"mcp.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"standard"},"claude-code":{name:"claude-code",displayName:"Claude Code",supportsGlobal:!0,globalConfigPath:Lt.join(cn(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:Lt.join(cn(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function kC(r){switch(r){case"opencode":case"claude-code":case"codex":case"codebuddy":return"cwdDot";default:return"workspaceFolder"}}function xC(r,e){if(r==="opencode"){let n={type:"local",command:[e.command,...e.args],enabled:!0};return e.env&&(n.environment=e.env),n}let t={type:"stdio",command:e.command,args:e.args};return e.env&&(t.env=e.env),(r==="claude-code"||r==="codex")&&(t.enabled=!0),t}function Th(r,e){let t=kC(r.format);return xC(r.format,{command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:e??(t==="cwdDot"?".":"${workspaceFolder}")}})}function RC(r,e){let t=kC(r.format);return xC(r.format,{command:"homegraph",args:SC(bC(e,t))})}var hc="https://developer.huawei.com/consumer/cn/download/";import*as AC from"fs";import*as IC from"path";var DC=["DevEco"];async function du(){let r=await W.get(lr.TAGS_API_URL),t=mu(r,"Tags API").data.skill.filter(n=>n.name==="HMOS");if(t.length===0)throw new Error("No HMOS tag found.");return t.map(n=>n.id)}async function I$(r){let e=[],t=lr.DEFAULT_PAGE_SIZE,n=lr.DEFAULT_MAX_PAGES,i=1;for(;i<=n;){let o=await W.post(lr.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:i,pageSize:t,tagIds:[r]}}),s=mu(o,"Skills API");if(e.push(...s.data.list),s.data.list.length<t)break;i++}return e}async function uu(r){let e=new Map,t=r.map(i=>I$(i)),n=await Promise.all(t);for(let i of n)for(let o of i)e.has(o.id)||e.set(o.id,o);return Array.from(e.values()).filter(i=>i.tags?.every(o=>!DC.includes(o.name)))}async function D$(r,e){let t=await W.post(lr.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:lr.DEFAULT_PAGE_SIZE,keyword:r,tagIds:[e]}});return mu(t,"Skills API").data.list}async function pu(r,e){let t=new Map,n=e.map(o=>D$(r,o)),i=await Promise.all(n);for(let o of i)for(let s of o)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(o=>o.tags?.every(s=>!DC.includes(s.name)))}function Nh(r){Mt(r);let e=[];for(let t of Le()){let n=ur(t);if(!fo(t))continue;let i=IC.join(n,r);AC.existsSync(i)&&e.push(dr(t).displayName)}return e.sort()}function mu(r,e){if(r.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${r.statusCode}`);let t=W.parseJson(r);if(t.code!==lr.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function TC(r){Mt(r);let e=`${lr.SKILL_API_BASE}/${r}/checksum`,t=await W.get(e);return mu(t,"Checksum API").data}var NC=M$.promises;function OC(r,e){let t=bi.resolve(e),n=bi.resolve(r),i=bi.relative(n,t);if(i.startsWith("..")||bi.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function Oh(r){return bi.isAbsolute(r)?r:bi.resolve(process.cwd(),r)}function _$(r){return N$.createHash("sha256").update(r).digest("hex")}async function L$(r,e){if(r.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let n=_$(r),i=e.sha256.toLowerCase(),o=Buffer.from(n,"hex"),s=Buffer.from(i,"hex");if(o.length!==s.length||!O$(o,s))throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function Mh(r){Mt(r);let e=`${lr.SKILL_API_BASE}/${r}/install?format=zip`,t=await W.getBinary(e),n=await TC(r);return await L$(t,n),t}async function MC(r,e,t){Mt(t);let n=new T$(r),i=n.getEntries();try{await NC.stat(e)}catch{await NC.mkdir(e,{recursive:!0})}let o=bi.join(e,t);OC(e,o);for(let s of i){let a=bi.join(o,s.entryName);OC(o,a)}n.extractAllTo(o,!0)}function _h(r){return r?pr.join(r,".deveco-cli","skills"):pr.join(F(),"skills")}function j$(r,e){return Mt(r),pr.join(_h(e),"store",r)}async function Lh(r,e){let t=e??F(),n=await Ss.realpath(t).catch(s=>{if(s.code==="ENOENT")return be(t);throw s}),i=pr.join(n,pr.relative(t,r)),o=await be(i);if(!ee(i,o))throw new Error(`Skill storage parent redirects outside its managed location: ${i}`);return o}async function fu(r,e){return Lh(j$(r,e),e)}async function gu(r,e){return Mt(r),Lh(pr.join(_h(e),"consumers",`${r}.json`),e)}async function yc(r,e,t){Mt(r);let n=e.customPath??_h(e.project),i=e.customPath?await be(pr.join(n,`.${r}.lock`)):await Lh(pr.join(n,"locks",`${r}.lock`),e.project);await Ss.mkdir(pr.dirname(i),{recursive:!0});let o=await F$(n,{realpath:!1,lockfilePath:i,stale:3e4,update:1e4,retries:{retries:100,minTimeout:50,maxTimeout:200}});try{return await t()}finally{await o()}}async function _C(r){let e=await Ss.lstat(r);if(!e.isDirectory()||e.isSymbolicLink()||!(await Ss.stat(pr.join(r,"SKILL.md"))).isFile())throw new Error(`Invalid Skill store: ${r}`)}async function LC(r,e,t,n,i){let o=await fu(r,t),s=await Ne(o);if(!i&&!s&&(await Promise.all(n.map(c=>Ne(c.path)))).every(Boolean))return{results:n.map(c=>Mr(c.path,"already-exists"))};for(let a of n)for(let c of[a.path,...a.legacy])if(ws(o,c))throw new Error(`Skill store and destination overlap: ${o}, ${c}`);if(!i&&s){try{await _C(o)}catch(a){throw new Error(`Cannot reuse Skill store ${o}; use --force to replace: ${a.message}`,{cause:a})}return{source:o,results:[]}}return{source:o,results:[await FC(r,e,o)]}}async function $C(r,e,t,n){let i=await be(t);return await aC(i,n)??FC(r,e,i)}async function FC(r,e,t){await Ss.mkdir(pr.dirname(t),{recursive:!0});let n=`${t}.extract-${$$()}`;try{await MC(e,n,r);let i=pr.join(n,r);return await _C(i),await Ph(i,t),{success:!0,path:t,reason:"shared-entity-updated"}}finally{await Ss.rm(n,{recursive:!0,force:!0})}}import{randomUUID as H$}from"crypto";import bs from"fs/promises";import U$ from"path";async function hu(r){let e=await Ne(r);if(!e)return!1;if(!e.isFile()||e.isSymbolicLink()||e.nlink!==1)throw new Error(`Invalid Skill consumer record: ${r}`);return!0}function B$(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid Skill consumer record structure.");let e=r,t=e.agents;if(e.schemaVersion!==1||Object.keys(e).some(i=>i!=="schemaVersion"&&i!=="agents")||!t||typeof t!="object"||Array.isArray(t))throw new Error("Invalid Skill consumer record structure.");let n=Le();for(let[i,o]of Object.entries(t))if(!n.includes(i)||typeof o!="boolean")throw new Error(`Invalid Skill consumer: ${i}`);return t}async function $h(r,e){let t=await gu(r,e);return await hu(t)?B$(JSON.parse(await bs.readFile(t,"utf8"))):{}}async function jC(r,e,t){let n=await gu(r,e);await hu(n),await bs.mkdir(U$.dirname(n),{recursive:!0});let i=`${n}.write-${H$()}`;try{await bs.writeFile(i,JSON.stringify({schemaVersion:1,agents:t},null,2)+`
|
|
55
55
|
`,{flag:"wx",mode:384}),await hu(n),await bs.rename(i,n)}finally{await bs.rm(i,{force:!0})}}async function HC(r,e){let t=await gu(r,e);await hu(t)&&await bs.unlink(t)}function Fh(r){return r?`the bundled skill (deveco-cli ${r})`:"this skill's source"}var UC={"same-source":()=>({status:"destination is the skill source itself",action:"nothing to do"}),"correct-link":({detail:r,sourceVersion:e})=>({status:`already linked to ${e?`the bundled skill (deveco-cli ${e})`:"this skill"}${r?` \u2192 ${r}`:""}`,action:"nothing to do"}),"already-exists":({detail:r,sourceVersion:e})=>({status:`already exists as a ${r??"directory or file"} with unknown version, not a link to ${Fh(e)}`,action:"use --force to replace it"}),"broken-link":({detail:r,sourceVersion:e})=>({status:`existing link is broken${r?` \u2014 its target ${r} no longer exists`:""}`,action:`use --force to replace it with ${Fh(e)}`}),"linked-elsewhere":({detail:r,localVersion:e,sourceVersion:t})=>({status:e&&e===t?`links to ${r} (another deveco-cli ${e} installation), not this installation's bundled skill`:`links to ${r??"another location"}${e?` (deveco-cli ${e})`:""}, not ${Fh(t)}`,action:"use --force to replace it"}),"agent-project-root-missing":()=>({status:"agent has no project directory in this project"}),"not-installed":()=>({status:"not installed",action:"nothing to remove"})};function BC(r){let e=UC[r.reason??""];if(!e)return r.reason;let{status:t,action:n}=e(r);return n?`${t}; ${n}`:t}function WC(r){return UC[r.reason??""]?.(r).status??r.reason}function wc(r,e){return{success:!1,path:r,error:e instanceof Error?e.message:String(e)}}async function jh(r,e,t){let n=[];for(let i of pC(e))try{n.push(...await yc(r,i,()=>t(i)))}catch(o){n.push(wc(mr.join(Yt(i.project),r),o))}return n}async function GC(r){return Hh.realpath(r).catch(e=>{if(e.code==="ENOENT"||e.code==="ELOOP")return r;throw e})}async function W$(r,e){let t=await Hh.realpath(e);for(let n of r.legacy){let i=await Ne(n);if(i&&!i.isSymbolicLink()&&ws(t,n))throw new Error(`Skill source and legacy destination overlap: ${e}, ${n}`);await ru(n)}}async function V$(r,e,t,n,i={}){let o=[],s=await be(mr.join(Yt(e.project),r));for(let a of Le()){let c=ur(a,e.project);if(e.agents.includes(a))continue;let l=await be(mr.join(c,r)),d=ee(l,s),m=d?i[a]:void 0;if(m===!1)continue;let y=m===!0,b=fo(a,e.project);if(d&&!y&&!b)continue;let A=await Ne(l);A&&(ee(l,t)&&(y||b)||n&&(y||ee(l,n)||A.isSymbolicLink()&&ee(await GC(l),n)))&&o.push(dr(a).displayName)}return[...new Set(o)]}function G$(r,e,t=console.log){let n=`still used by ${e.join(", ")}`;return t(`Skill ${mr.basename(r)} in ${mr.dirname(r)} is kept: ${n}.`),Mr(r,n)}function z$(r,e,t=console.log){return t(`Skill ${r} not found for the selected agents.`),Mr(e,"not-installed")}async function VC(r,e,t,n,i={},o={}){try{if(!await Ne(r))return;let s=await V$(e,t,r,n,o);return s.length?G$(r,s,i.log):await ru(r)}catch(s){return wc(r,s)}}var Xt=class{async installBundledSkill(e,t,n,i=!1){return Mt(e),await Hh.access(mr.join(t,"SKILL.md")),n.customPath?this.installCustom(e,t,n.customPath,i):jh(e,n,o=>this.installScope(e,t,o,n.explicitAgents,i))}async installArchiveSkill(e,t,n,i=!1,o={}){return Mt(e),n.customPath?this.installCustom(e,t,n.customPath,i,o):jh(e,n,s=>this.installScope(e,t,s,n.explicitAgents,i,o))}async installCustom(e,t,n,i,o={}){let s=mr.join(n,e);try{return await yc(e,{customPath:n},async()=>(await this.validateEntries([s],o),[typeof t=="string"?await tu(t,s,i):await $C(e,t,s,i)]))}catch(a){return[wc(s,a)]}}async installScope(e,t,n,i=!0,o=!1,s={}){let a=await mC(n,e,i),c=a.filter(d=>!d.skipped),l=a.filter(d=>d.skipped).map(d=>Mr(d.path,"agent-project-root-missing"));if(!c.length)return l;try{let d=await $h(e,n.project);await this.validateScopeEntries(e,n,c,s);let m=[...l,...await this.installActive(e,t,n,c,o)];return await this.recordSharedConsumers(e,n,m,d,!0),m}catch(d){return[...l,...c.map(m=>wc(m.path,d))]}}async installActive(e,t,n,i,o){let s=typeof t=="string"?{source:t,results:[]}:await LC(e,t,n.project,i,o);return[...s.results,...s.source?await this.installSkillEntries(s.source,i,o):[]]}async recordSharedConsumers(e,t,n,i,o){let s=await be(mr.join(Yt(t.project),e)),a=!1;for(let c of t.agents){let l=await be(mr.join(ur(c,t.project),e));!n.some(m=>m.path&&ee(m.path,l)&&m.success)||i[c]===o||!ee(l,s)&&!Object.hasOwn(i,c)||(i[c]=o,a=!0)}a&&await jC(e,t.project,i)}async validateEntries(e,t,n){if(!t.validateExisting)return;let i=await Promise.all(e.map(be));for(let o of new Set(i))await Ne(o)&&await t.validateExisting(o,n)}async validateScopeEntries(e,t,n,i){if(!i.validateExisting)return;let o=await fu(e,t.project),s=await be(mr.join(Yt(t.project),e)),a=n.filter(c=>!c.skipped).flatMap(c=>[c.path,...c.legacy]);await this.validateEntries([...a,s,o],i,o)}async installSkillEntries(e,t,n){let i=[];for(let o of t)try{i.push(await tu(e,o.path,n)),n&&await W$(o,e)}catch(s){i.push(wc(o.path,s))}return i}async migrateBundledSkill(e,t,n){await yc(e,n,()=>this.migrateBundledScope(e,t,n))}async migrateBundledScope(e,t,n){let i,o=[],s=[];for(let a of n.agents)try{for(let c of await fc({...n,agents:[a]},e))await this.migrateBundledDestination(t,c,o,s)}catch(c){i=c,console.error(`Skill migration failed for ${a}: ${c.message}`)}if(s.length>0&&console.warn(`Skill migration skipped: ${e} has ${s.length} existing ${s.length===1?"entry":"entries"} (run devecocli init --force to replace):
|
|
56
56
|
${s.map(a=>`${a.path} (${WC(a)})`).join(`
|
|
57
|
-
`)}`),i)throw i}async migrateBundledDestination(e,t,n,i){let o=await Ne(t.path);if(!((!o||!o.isDirectory()&&!o.isSymbolicLink())&&!t.legacy.length)&&!n.some(s=>ee(s,t.path))){let s=await tu(e,t.path);s.skipped&&s.reason!=="correct-link"&&s.reason!=="same-source"&&i.push(s),n.push(t.path)}}async removeSkill(e,t,n={}){if(Mt(e),t.customPath){let i=mr.join(t.customPath,e);return yc(e,t,async()=>(await this.validateEntries([i],n),[await ru(i)]))}return jh(e,t,async i=>{let o=await $h(e,i.project);if(n.validateExisting){let s=await fc(i,e,t.explicitAgents);await this.validateScopeEntries(e,i,s,n)}return this.removeScope(e,i,t.explicitAgents,n,o)})}async removeScope(e,t,n=!0,i={},o={}){let s=await be(mr.join(Yt(t.project),e)),a=await fu(e,t.project),c=await this.removeAgentEntries(e,t,s,a,n,i,o);for(let l of[s,a]){if(!c.every(m=>m.success))break;let d=await VC(l,e,t,await GC(l),i,o);d&&c.push(d)}return c.length||c.push(z$(e,s,i.log)),await this.completeConsumerRemoval(e,t,s,a,c,o),c}async completeConsumerRemoval(e,t,n,i,o,s){if(!await Ne(n)&&!await Ne(i)){await HC(e,t.project);return}await this.recordSharedConsumers(e,t,o,s,!1)}async removeAgentEntries(e,t,n,i,o,s,a){let c=new Set;for(let d of await fc(t,e,o))if(!d.skipped)for(let m of[d.path,...d.legacy])!ee(m,n)&&!ee(m,i)&&c.add(m);let l=[];for(let d of c){let m=await VC(d,e,t,void 0,s,a);m&&l.push(m)}return l}};import Z$ from"p-limit";import yu from"fs";import ho from"path";import{fileURLToPath as q$}from"url";function Uh(){let r=ho.dirname(q$(import.meta.url));for(;;){if(yu.existsSync(ho.join(r,"skills","deveco-cli","SKILL.md")))return ho.join(r,"skills");let e=ho.dirname(r);if(e===r)break;r=e}throw new Error("skills/deveco-cli directory not found in deveco-cli package. Reinstall deveco-cli.")}function Es(){Uh()}function J$(r){return r.sort((e,t)=>e==="deveco-cli"?-1:t==="deveco-cli"?1:e.localeCompare(t))}function K$(r){let e=yu.readdirSync(r,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).map(t=>t.name).filter(t=>yu.existsSync(ho.join(r,t,"SKILL.md")));return J$(e).map(t=>({name:t,dir:ho.join(r,t)}))}function fr(){return K$(Uh())}function Ps(r){try{return fr().some(e=>e.name===r)}catch{return!1}}function Y$(r){try{let e=JSON.parse(r);return Array.isArray(e.skills)?e.skills.filter(t=>typeof t=="object"&&t!==null).filter(t=>typeof t.name=="string").map(t=>({name:t.name,...typeof t.description=="string"?{description:t.description}:{}})):[]}catch{return[]}}function Bh(){try{let r=ho.join(Uh(),"index.json");return Y$(yu.readFileSync(r,"utf8"))}catch{return[]}}function Wh(){let r=new Map(Bh().map(e=>[e.name,e]));return fr().map(({name:e})=>({name:e,description:r.get(e)?.description}))}function X$(r,e){let t=new Set(e);return r.filter(n=>!t.has(n.name)).map(n=>n.name)}function zC(r){return`Warning: bundled skill "${r}" is listed in the package index but missing from disk. The package may be corrupted \u2014 reinstall deveco-cli.`}function qC(){try{let r=Bh();if(r.length===0)return[];let e=fr().map(t=>t.name);return X$(r,e)}catch{return[]}}function yo(r=qC()){for(let e of r)console.warn(zC(e))}async function JC(r,e){try{let t=await du();return await r(t)}catch(t){return e?.(t instanceof Error?t.message:"network error"),[]}}function KC(r){return r.map(e=>({...e,bundled:Ps(e.enName)}))}function YC(r,e){let t=new Set(r.map(n=>n.enName));return[...r,...e.filter(n=>!t.has(n.enName))]}var wo=class{constructor(e=[]){this.providers=e}catalog(){return this.mergeCatalog(this.providers.map(e=>e.catalog()))}search(e){return this.mergeCatalog(this.providers.flatMap(t=>t.search(e)))}async listCatalog(e){let t=KC(this.catalog()),n=await JC(uu,e);return YC(t,n)}async findCatalog(e,t){let n=KC(this.search(e)),i=await JC(o=>pu(e,o),t);return YC(n,i)}mergeCatalog(e){let t=new Map;for(let n of e)t.has(n.name)||t.set(n.name,{enName:n.name,description:n.description??""});return[...t.values()]}async resolveNames(e){if(e.skill&&this.provider(e.skill))return[e.skill];let t=await du();if(e.all)return(await uu(t)).map(o=>o.enName);let i=(await pu(e.skill,t)).find(o=>o.enName===e.skill);if(!i)throw Object.assign(new Error(`Skill "${e.skill}" not found`),{name:"ValidationError",code:"errorCode"});return[i.enName]}async installSkills(e,t,n,i){let o=Z$(5),s=e.map(l=>o(()=>this.prepareArchive(l))),a=[],c=0;for(let[l,d]of e.entries()){let m={name:d,index:l,total:e.length};i({...m,phase:"installing"});let y=await s[l];if(!y.success){i({...m,phase:"download-failed",error:y.error}),a.push({success:!1});continue}c+=y.buffer?.length??0,i({...m,phase:"ready"});let b=this.provider(d);a.push(...b?await b.installForTargets(d,t,n):await new Xt().installArchiveSkill(d,y.buffer,t,n))}return{results:a,diskBytes:c}}removeSkill(e,t,n=!1){let i=this.provider(e);return i?i.uninstallForTargets(e,t,n):new Xt().removeSkill(e,t)}provider(e){return this.providers.find(t=>t.handles(e))}async prepareArchive(e){try{return{success:!0,buffer:this.provider(e)?void 0:await Mh(e)}}catch(t){return{success:!1,error:t instanceof Error?t.message:"unknown error"}}}};var wu=class{constructor(e){this.skill=e}handles(e){return e===this.skill.name}catalog(){return{name:this.skill.name,aliases:[],description:this.skill.description}}search(e){let t=e.trim().toLowerCase(),n=`${this.skill.name} ${this.skill.description??""}`.toLowerCase();return!t||n.includes(t)?[this.catalog()]:[]}installForTargets(){return Promise.reject(new Error(`Skill "${this.skill.name}" is bundled with deveco-cli. Bundled skills are installed by devecocli init and update with the CLI package.`))}uninstallForTargets(){return Promise.reject(new Error(`Skill "${this.skill.name}" is bundled with deveco-cli and cannot be removed. Bundled skills are managed by the CLI package and update with npm update.`))}};function Vh(){try{return Wh().map(r=>new wu(r))}catch{return[]}}import Gh from"fs/promises";import Q$ from"path";function eF(r){return`'${process.platform==="win32"?r.replace(/'/g,"''"):r.replace(/'/g,"'\\''")}'`}async function tF(r,e){try{if(!(await Ne(r))?.isSymbolicLink())return;let n=await Gh.realpath(r);return ee(n,e)?void 0:{path:r,reason:`points to ${n}`,repair:!0}}catch(t){let n=t.code,i=n==="ENOENT"||n==="ELOOP"||n==="ENOTDIR";return{path:r,reason:i?"broken link":`cannot check: ${t.message}`,repair:i}}}var zh=class{checked=new Set;async warnInvalidBundledLinks(e){try{let t=await Gh.realpath(e),n=process.platform==="win32"?t.toLowerCase():t;if(this.checked.has(n))return;this.checked.add(n);let i=await this.checkKnownEntries(t,fr());this.reportIssues(t,i)}catch(t){console.warn(`Cannot check project Skill links for ${e}: ${t.message}`)}}async checkKnownEntries(e,t){let n=new Set([Yt(e),...Le().map(o=>kh(e,o))]),i=[];for(let o of t){let s=await Gh.realpath(o.dir),a=[];for(let c of n){let l=await this.checkDirectoryEntry(Q$.join(c,o.name),s,a);l&&i.push(l)}}return i}async checkDirectoryEntry(e,t,n){try{let i=await be(e);return n.some(o=>ee(o,i))?void 0:(n.push(i),await tF(i,t))}catch(i){return{path:e,reason:`cannot check: ${i.message}`,repair:!1}}}reportIssues(e,t){for(let n of t)console.warn(`Project Skill link: ${n.path} (${n.reason}).`);t.some(n=>n.repair)&&(console.warn(`Run: devecocli init --project ${eF(e)} -f`),console.warn("Existing copies and local edits in the selected installation scope will be replaced."))}},$t=new zh;import Xh from"fs";import rk from"path";import{cyan as hF}from"colorette";import{spawn as uF}from"child_process";import*as tk from"fs";import*as Su from"path";import{yellow as pF,cyan as mF}from"colorette";import fF from"proper-lockfile";import{compare as rF}from"semver";function gr(r,e){return rF(r,e)}function Cs(r,e){let t=Math.max(r.split(".").length,e.split(".").length);for(let n=0;n<t;n++){let i=Number(r.split(".")[n]??0)-Number(e.split(".")[n]??0);if(i)return i}return 0}var XC={name:"@deveco/deveco-cli-common",version:"1.3.11",description:"HarmonyOS application development command line tool",supportedDocsApi:1,license:"MIT",type:"module",files:["dist","templates","src/resources","THIRD-PARTY-LICENSES","skills"],scripts:{prebuild:"node ../../scripts/sync-cli-docs.mjs",build:"npm run build -w design2arkts-engine && tsup",dev:"tsx watch src/cli.ts",start:"tsx src/cli.ts","prebundle:skills":"node ../../scripts/sync-cli-docs.mjs","bundle:skills":"tsx scripts/bundle-skills.ts","precheck:skills":"node ../../scripts/sync-cli-docs.mjs","check:skills":"tsx scripts/bundle-skills.ts --check",test:"vitest run",lint:'eslint "src/**/*.ts"',"lint:fix":"eslint src --fix",format:"prettier --write src",prepack:"node ../../scripts/sync-cli-docs.mjs",prepublishOnly:"npm run lint && npm run build && npm run check:skills"},engines:{node:">=22"},os:["darwin","linux","win32"],cpu:["x64","arm64"],keywords:["harmonyos","deveco","cli"],dependencies:{"@modelcontextprotocol/sdk":"^1.29.0","@xmldom/xmldom":"^0.8.15","adm-zip":"0.6.1",axios:"1.20.0",colorette:"^2.0.20",commander:"^13.1.0",execa:"^9.6.1","fs-extra":"^11.3.4","global-agent":"^4.1.3",json5:"^2.2.3",mp4box:"^2.4.1","node-forge":"^1.4.0",ora:"^9.4.0","p-limit":"^5.0.0","proper-lockfile":"^4.1.2",semver:"^7.8.5","smol-toml":"^1.6.1","socket.io-client":"^4.7.5","ui-verification-mcp":"0.0.20",xpath:"^0.0.35",zod:"^4.4.3","@deveco/deveco-cli-knowledgebase":"1.3.11"},devDependencies:{"@types/adm-zip":"^0.5.8","@types/fs-extra":"^11.0.4","@types/global-agent":"^3.0.0","@types/node-forge":"^1.3.14","@types/proper-lockfile":"^4.1.4","@types/semver":"^7.7.1","design2arkts-engine":"0.1.0"}};function vc(){return process.env.DEVECO_CLI_WRAPPER_NAME?process.env.DEVECO_CLI_WRAPPER_NAME:"@deveco/deveco-cli-common"}function hr(){return process.env.DEVECO_CLI_WRAPPER_VERSION?process.env.DEVECO_CLI_WRAPPER_VERSION:"1.3.11"}function Ei(){return"latest"}function qh(){return"@deveco/deveco-cli-common"}function yr(){return Number.isFinite(1),1}var _r=(()=>{let r=Object.keys(XC.dependencies).find(e=>e.endsWith("/deveco-cli-knowledgebase"));if(!r)throw new Error("CLI package.json must declare a deveco-cli-knowledgebase dependency.");return r})();function ks(){let r=process.env.DEVECO_CLI_DISABLE_UPDATE;return r==="check"||r==="all"?r:"off"}import*as Sc from"fs";import*as bc from"path";var iF={lastCheckedTimestamp:null,latestVersion:null,blockedVersions:[],checkError:null,latestDocsVersion:null,latestDocsApiVersion:null,latestCompatibleDocsVersion:null,checkedAgainstDocsApi:null},Jh=new Map,Pi=class r{static CHECK_WINDOW_HOUR=21;static ONE_DAY_MS=1440*60*1e3;cacheFilePath;lockFilePath;constructor(e){this.cacheFilePath=bc.join(e,"cache.json"),this.lockFilePath=bc.join(e,"check.lock")}async writeSuccess(e,t=[],n,i,o){let s=this.read();await this.write({lastCheckedTimestamp:Date.now(),latestVersion:e,blockedVersions:t,checkError:null,checkedAgainstVersion:n,checkedAgainstTag:i,latestDocsVersion:o?o.latestDocsVersion:s.latestDocsVersion??null,latestDocsApiVersion:o?o.latestDocsApiVersion:s.latestDocsApiVersion??null,latestCompatibleDocsVersion:o?o.latestCompatibleDocsVersion:s.latestCompatibleDocsVersion??null,checkedAgainstDocsApi:o?o.checkedAgainstDocsApi:s.checkedAgainstDocsApi??null})}async writeError(e){let t=this.read();await this.write({...t,lastCheckedTimestamp:Date.now(),checkError:e})}getLatestVersion(){return this.read().latestVersion}getBlockedVersions(){return[...this.read().blockedVersions]}getCheckedAgainstVersion(){return this.read().checkedAgainstVersion}getCheckedAgainstTag(){return this.read().checkedAgainstTag}getLatestDocsVersion(){return this.read().latestDocsVersion??null}getLatestDocsApiVersion(){return this.read().latestDocsApiVersion??null}getLatestCompatibleDocsVersion(){return this.read().latestCompatibleDocsVersion??null}getCheckedAgainstDocsApi(){return this.read().checkedAgainstDocsApi??null}isCheckNeeded(){let{lastCheckedTimestamp:e}=this.read();if(!e||e>Date.now())return!0;let t=new Date().setHours(r.CHECK_WINDOW_HOUR,0,0,0),n=t>Date.now()?t-r.ONE_DAY_MS:t;return e<n}getLockPath(){return this.lockFilePath}read(){let e=Jh.get(this.cacheFilePath);if(e)return e;try{let t=Sc.readFileSync(this.cacheFilePath,"utf-8"),n=JSON.parse(t);return Jh.set(this.cacheFilePath,n),n}catch{return{...iF}}}async write(e){f(()=>`Writing update cache: lastChecked=${e.lastCheckedTimestamp}, latest=${e.latestVersion}, blocked=[${e.blockedVersions.join(",")}], error=${e.checkError}`),await Sc.promises.mkdir(bc.dirname(this.cacheFilePath),{recursive:!0}),await Sc.promises.writeFile(this.cacheFilePath,JSON.stringify(e,null,2),"utf-8"),Jh.set(this.cacheFilePath,e)}};import{createRequire as oF}from"module";import{dirname as sF,join as xs}from"path";import{pathToFileURL as aF}from"url";import{readFile as ZC,access as Kh}from"fs/promises";import*as QC from"semver";var cF=oF(import.meta.url);async function lF(){try{let r=cF.resolve(`${_r}/package.json`),e=JSON.parse(await ZC(r,"utf8"));return{version:e.version,apiVersion:e.apiVersion??0,dir:sF(r)}}catch{return null}}async function ek(){let r=F(),e=xs(r,"doc-data","current.json"),t;try{t=JSON.parse(await ZC(e,"utf8"))}catch{return null}let n=xs(r,"doc-data",t.version);try{return await Kh(xs(n,"dist","engine","index.js")),await Kh(xs(n,"docs.zip")),await Kh(xs(n,"index.zip")),{version:t.version,apiVersion:t.apiVersion,dir:n}}catch{return null}}async function dF(){return[await ek(),await lF()].filter(e=>e!==null).sort((e,t)=>QC.rcompare(e.version,t.version))}async function Rs(){let r=yr(),e=await ek();return e&&e.apiVersion<=r?e.version:null}async function vu(){let r=yr(),e=await dF(),t=!1;for(let n of e){if(n.apiVersion>r){f(`docs: skip candidate v${n.version} (apiVersion ${n.apiVersion} > ${r})`);continue}t=!0;try{let i=xs(n.dir,"dist","engine","index.js");return await import(aF(i).href)}catch(i){f(`docs: candidate v${n.version} load failed: ${i instanceof Error?i.message:String(i)}`)}}throw e.length>0&&!t?new Error("Documentation package version is incompatible, please upgrade CLI"):new Error("No available documentation package, please run `devecocli docs update` or reinstall CLI")}var Ec=class{constructor(e){this.actionCommand=e}cache=new Pi(Su.join(F(),"update"));async checkAndNotify(){if(!this.shouldSkip())try{let e=hr(),t=Ei(),n=this.cache.getCheckedAgainstVersion(),i=this.cache.getCheckedAgainstTag(),o=i!=null&&i!==t,s=n!=null&&n!==e,a=[],c=o?null:this.cache.getLatestVersion();c&&gr(c,e)>0&&a.push(pF(`New cli version ${c} available, run \`devecocli update\` to update`));let l=await this.buildDocsMessage();if(l.message&&a.push(l.message),a.length>0){console.log();for(let d of a)console.log(d)}(o||s||l.stale||this.cache.isCheckNeeded())&&await this.spawnBackgroundCheck()}catch(e){f(`Update check failed: ${e instanceof Error?e.message:String(e)}`)}}async buildDocsMessage(){let e=yr(),t=this.cache.getCheckedAgainstDocsApi();if(t!=null&&t!==e)return{message:null,stale:!0};let n=this.cache.getLatestCompatibleDocsVersion();if(!n)return{message:null,stale:!1};let i=await Rs();return i&&gr(n,i)<=0?{message:null,stale:!1}:{message:mF(`New docs version ${n} available, run \`devecocli docs update\` to upgrade`),stale:!1}}shouldSkip(){let e=this.actionCommand;for(;e;){if(e.name()==="update")return!0;e=e.parent}return!1}async spawnBackgroundCheck(){if(!process.argv[1]?.endsWith(".ts"))try{await gF(this.cache.getLockPath(),()=>{let e=[process.argv[1],"update","_check"];f(`Executing: ${process.execPath} ${e.join(" ")}`),uF(process.execPath,e,{detached:!0,windowsHide:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1"}}).unref()})}catch{f("Update check lock held by another process, skipping")}}};async function gF(r,e){await tk.promises.mkdir(Su.dirname(r),{recursive:!0});let t=await fF.lock(r,{stale:6e4,retries:0,realpath:!1});try{await e()}finally{await t()}}var Yh=Xh.promises;async function bu(r){let e=su(r);for(let t of e)dr(t);return e}async function Eu(r){return Le().filter(e=>fo(e,r))}async function yF(){let r=new Xt,e=[];for(let{name:t,dir:n}of fr())try{await r.migrateBundledSkill(t,n,{agents:Le()})}catch(i){e.push({name:t,error:i})}if(e.length>0){let t=e.map(({name:n,error:i})=>`${n}: ${i instanceof Error?i.message:String(i)}`).join("; ");throw new Error(`Bundled skill migration failed \u2014 ${t}`)}}async function nk(){try{let r=rk.join(F(),"skills","migration-version"),e=await Yh.readFile(r,"utf8").catch(n=>{if(n.code==="ENOENT")return"";throw n}),t=hr();if(e.trim()===t)return;await yF(),await Yh.mkdir(rk.dirname(r),{recursive:!0}),await Yh.writeFile(r,t,"utf8")}catch(r){console.warn(`Bundled skill migration failed (will retry on the next command): ${r instanceof Error?r.message:String(r)}`)}}function As(r){let e=r.filter(i=>i.success&&!i.skipped).length,t=r.filter(i=>i.skipped).length,n=r.filter(i=>!i.success).length;console.log(),console.log(hF("Finished:"));for(let i of r){if(!i.path)continue;let o=BC(i),s=i.fallbackReason?" (link failed: "+i.fallbackReason+")":o??i.error?" ("+(o??i.error)+")":"",a=i.success?i.skipped?"skipped":i.mode??(i.reason==="shared-entity-updated"?"updated":"removed"):"failed";console.log(" "+a+": "+i.path+s)}console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`),n>0&&(process.exitCode=1)}function Lr(r,e,t){if(!Xh.existsSync(r)){if(t)return;throw new Error(`${e} "${r}" not found`)}if(!Xh.statSync(r).isDirectory())throw new Error(`"${r}" is not a directory`)}function Is(r,e,t){if(r&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:r?Oh(r):void 0,resolvedProject:e?Oh(e):void 0}}async function Pu(r,e,t="No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location."){let n=r.agent?await bu(r.agent):await Eu(e);if(!n.length)throw new Error(t);return n.map(i=>({agent:i,directory:ur(i,e),explicit:!!r.agent}))}async function Ds(r,e,t){if(e)return{agents:[],projectAgents:[],customPath:e};let n=await Pu(r,t),i=n.some(o=>o.explicit);return t?{agents:[],explicitAgents:i,projectAgents:n.map(({agent:o})=>({project:t,agent:o}))}:{agents:n.map(({agent:o})=>o),projectAgents:[],explicitAgents:i}}import wF from"fs";import Cu from"path";import{cyan as vF}from"colorette";import*as ku from"smol-toml";var Ts=wF.promises;async function SF(r){try{let e=await Ts.readFile(r,"utf8");return e.trim()===""?{}:JSON.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read configuration file ${r}: ${e.message}`,{cause:e})}}async function bF(r){try{let e=await Ts.readFile(r,"utf8");return e.trim()===""?{}:ku.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read TOML config file ${r}: ${e.message}`,{cause:e})}}async function EF(r,e){let t=Cu.dirname(r);await Ts.mkdir(t,{recursive:!0});let n=JSON.stringify(e,null,2);await Ts.writeFile(r,n,"utf8")}async function PF(r,e){let t=Cu.dirname(r);await Ts.mkdir(t,{recursive:!0});let n=ku.stringify(e);await Ts.writeFile(r,n,"utf8")}function CF(r,e,t){let n=r[e];return!n||typeof n!="object"?!1:t in n}function kF(r,e,t,n,i){(!r[e]||typeof r[e]!="object")&&(r[e]={});let o=r[e];return t in o&&!i?!1:(o[t]=n,!0)}async function xF(r,e){return r.format==="codex"?bF(e):SF(e)}async function RF(r,e,t){return r.format==="codex"?PF(e,t):EF(e,t)}function ik(r={}){return{force:r.force??!1,withHomegraph:r.withHomegraph??!1}}function AF(r,e,t,n,i){let o=[],s=[],a=!1,c=(l,d)=>{if(CF(r,e.mcpServersKey,l)&&!n){s.push(l);return}kF(r,e.mcpServersKey,l,d,n),o.push(l),a=!0};return c(Dh,Th(e,t)),i&&c(CC,RC(e,t)),{changed:a,configured:o,skipped:s}}async function ok(r,e,t,n,i,o){try{let s=await xF(e,t),{changed:a,configured:c,skipped:l}=AF(s,e,n,o.force,o.withHomegraph);return a?(await RF(e,t,s),console.log(`MCP server(s) ${c.join(", ")} configured in ${t}.`),{success:!0,configPath:t,agentName:r,installType:i}):(console.log(`MCP already configured in ${t} (${l.join(", ")}).`),{success:!0,skipped:!0,configPath:t,agentName:r,installType:i})}catch(s){return{success:!1,error:`Failed to configure MCP for ${e.displayName}: ${s.message}`}}}async function Zh(r,e={}){let t=ik(e),n=$n[r];return n?n.supportsGlobal?ok(r,n,n.globalConfigPath,void 0,"global",t):{success:!1,error:`${n.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`}:{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys($n).join(", ")}`}}async function xu(r,e,t={}){let n=ik(t),i=$n[r];if(!i)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys($n).join(", ")}`};let o=Cu.isAbsolute(i.projectConfigPath)?i.projectConfigPath:Cu.join(e,i.projectConfigPath);return ok(r,i,o,e,"project",n)}function Qh(r){let e=r.filter(i=>i.success&&!i.skipped).length,t=r.filter(i=>i.skipped).length,n=r.filter(i=>!i.success).length;console.log(),console.log(vF("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`);for(let i of r)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);n>0&&(process.exitCode=1)}import IF from"fs";import DF from"path";import{homedir as TF}from"os";async function ey(r,e){let t=[],n=r.agent?su(r.agent):Object.keys(lu);for(let i of n){if(!Object.prototype.hasOwnProperty.call(lu,i))throw new Error(`Invalid MCP agent: ${i}`);(r.agent||IF.existsSync(DF.join(TF(),lu[i])))&&t.push(i)}if(!t.length)throw new Error("No agents supporting MCP configuration found; use --skill");return e?{agents:[],projectAgents:t.map(i=>({project:e,agent:i}))}:{agents:t,projectAgents:[]}}import{spawnSync as fk}from"child_process";import yt from"fs";import*as Ft from"os";import*as O from"path";import Fn from"fs";import*as vo from"os";import*as jn from"path";import{execa as MF}from"execa";import{execFileSync as NF}from"child_process";import sk from"fs";import*as ak from"os";import*as ty from"path";function Ru(r,e){let t=ty.join(r,"Contents","Info.plist");if(!sk.existsSync(t)){f(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[n,i]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let o=NF(n,i,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(o&&!o.includes("Does Not Exist"))return o}catch{}}function OF(r){let e=Ru(r,"CFBundleShortVersionString");if(!e)return Ru(r,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),n=[Ru(r,"CFBundleVersion"),Ru(r,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let i of n){let o=i?.split(".").at(-1)?.replace(new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`),"");if(o&&/^\d+$/.test(o))return`${e}.${o}`}return e}function Ci(r){if(ak.platform()==="darwin")return OF(r);let e=ty.join(r,"product-info.json");try{let t=JSON.parse(sk.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}var _F="DevEco Studio",LF=jn.join("C:","Program Files","Huawei","DevEco Studio"),$F=["Contents","Resources","product-info.json"],FF="name";function jF(r){return r.filter(e=>{try{return Fn.statSync(e).isDirectory()}catch{return!1}})}function HF(r){let e=jn.join(r,...$F);if(Fn.existsSync(e))try{let n=JSON.parse(Fn.readFileSync(e,"utf8"))[FF];return typeof n=="string"&&n.trim()?n.trim():void 0}catch{return}}function UF(r){return HF(r)===_F}function BF(){let r=[];for(let e of[jn.join(vo.homedir(),"Applications"),"/Applications"])try{r.push(...Fn.readdirSync(e).filter(t=>t.endsWith(".app")).map(t=>jn.join(e,t)).filter(UF))}catch{}return r}function lk(r){return{HKLM:"2147483650",HKEY_LOCAL_MACHINE:"2147483650",HKCU:"2147483649",HKEY_CURRENT_USER:"2147483649",HKCR:"2147483648",HKEY_CLASSES_ROOT:"2147483648",HKU:"2147483651",HKEY_USERS:"2147483651"}[r]||"2147483650"}function dk(r){let e=r.indexOf("\\");return e>0?{hive:r.slice(0,e),subPath:r.slice(e+1)}:{hive:r,subPath:""}}function WF(r){let e="";for(let t of r){let n=t.charCodeAt(0);if(!(n===13||n===10)){if(n===92){e+="\\\\";continue}if(n===34){e+='\\"';continue}e+=t}}return e}function VF(r){let e="";for(let t of r){let n=t.charCodeAt(0);if(n>=32&&n<=126){e+=t;continue}e+=`\\u${n.toString(16).padStart(4,"0")}`}return e}function Au(r){return VF(WF(r))}var uk=['var fso = new ActiveXObject("Scripting.FileSystemObject");','var locator = new ActiveXObject("WbemScripting.SWbemLocator");','var svc = locator.ConnectServer(".", "root\\\\default");','var reg = svc.Get("StdRegProv");'],ry="@OUT@";function GF(r){let{hive:e,subPath:t}=dk(r);return["try {",...uk,'var inP = reg.Methods_("EnumKey").InParameters.SpawnInstance_();',`inP.hDefKey = ${lk(e)};`,`inP.sSubKeyName = "${Au(t)}";`,'var out = reg.ExecMethod_("EnumKey", inP);',"if (out.ReturnValue != 0 || out.sNames == null) { WScript.Quit(1); }","var names = new VBArray(out.sNames).toArray();",`var f = fso.CreateTextFile("${ry}", true, true);`,"for (var i = 0; i < names.length; i++) { f.WriteLine(names[i]); }","f.Close();","} catch (e) { WScript.Quit(1); }"].join(`\r
|
|
57
|
+
`)}`),i)throw i}async migrateBundledDestination(e,t,n,i){let o=await Ne(t.path);if(!((!o||!o.isDirectory()&&!o.isSymbolicLink())&&!t.legacy.length)&&!n.some(s=>ee(s,t.path))){let s=await tu(e,t.path);s.skipped&&s.reason!=="correct-link"&&s.reason!=="same-source"&&i.push(s),n.push(t.path)}}async removeSkill(e,t,n={}){if(Mt(e),t.customPath){let i=mr.join(t.customPath,e);return yc(e,t,async()=>(await this.validateEntries([i],n),[await ru(i)]))}return jh(e,t,async i=>{let o=await $h(e,i.project);if(n.validateExisting){let s=await fc(i,e,t.explicitAgents);await this.validateScopeEntries(e,i,s,n)}return this.removeScope(e,i,t.explicitAgents,n,o)})}async removeScope(e,t,n=!0,i={},o={}){let s=await be(mr.join(Yt(t.project),e)),a=await fu(e,t.project),c=await this.removeAgentEntries(e,t,s,a,n,i,o);for(let l of[s,a]){if(!c.every(m=>m.success))break;let d=await VC(l,e,t,await GC(l),i,o);d&&c.push(d)}return c.length||c.push(z$(e,s,i.log)),await this.completeConsumerRemoval(e,t,s,a,c,o),c}async completeConsumerRemoval(e,t,n,i,o,s){if(!await Ne(n)&&!await Ne(i)){await HC(e,t.project);return}await this.recordSharedConsumers(e,t,o,s,!1)}async removeAgentEntries(e,t,n,i,o,s,a){let c=new Set;for(let d of await fc(t,e,o))if(!d.skipped)for(let m of[d.path,...d.legacy])!ee(m,n)&&!ee(m,i)&&c.add(m);let l=[];for(let d of c){let m=await VC(d,e,t,void 0,s,a);m&&l.push(m)}return l}};import Z$ from"p-limit";import yu from"fs";import ho from"path";import{fileURLToPath as q$}from"url";function Uh(){let r=ho.dirname(q$(import.meta.url));for(;;){if(yu.existsSync(ho.join(r,"skills","deveco-cli","SKILL.md")))return ho.join(r,"skills");let e=ho.dirname(r);if(e===r)break;r=e}throw new Error("skills/deveco-cli directory not found in deveco-cli package. Reinstall deveco-cli.")}function Es(){Uh()}function J$(r){return r.sort((e,t)=>e==="deveco-cli"?-1:t==="deveco-cli"?1:e.localeCompare(t))}function K$(r){let e=yu.readdirSync(r,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).map(t=>t.name).filter(t=>yu.existsSync(ho.join(r,t,"SKILL.md")));return J$(e).map(t=>({name:t,dir:ho.join(r,t)}))}function fr(){return K$(Uh())}function Ps(r){try{return fr().some(e=>e.name===r)}catch{return!1}}function Y$(r){try{let e=JSON.parse(r);return Array.isArray(e.skills)?e.skills.filter(t=>typeof t=="object"&&t!==null).filter(t=>typeof t.name=="string").map(t=>({name:t.name,...typeof t.description=="string"?{description:t.description}:{}})):[]}catch{return[]}}function Bh(){try{let r=ho.join(Uh(),"index.json");return Y$(yu.readFileSync(r,"utf8"))}catch{return[]}}function Wh(){let r=new Map(Bh().map(e=>[e.name,e]));return fr().map(({name:e})=>({name:e,description:r.get(e)?.description}))}function X$(r,e){let t=new Set(e);return r.filter(n=>!t.has(n.name)).map(n=>n.name)}function zC(r){return`Warning: bundled skill "${r}" is listed in the package index but missing from disk. The package may be corrupted \u2014 reinstall deveco-cli.`}function qC(){try{let r=Bh();if(r.length===0)return[];let e=fr().map(t=>t.name);return X$(r,e)}catch{return[]}}function yo(r=qC()){for(let e of r)console.warn(zC(e))}async function JC(r,e){try{let t=await du();return await r(t)}catch(t){return e?.(t instanceof Error?t.message:"network error"),[]}}function KC(r){return r.map(e=>({...e,bundled:Ps(e.enName)}))}function YC(r,e){let t=new Set(r.map(n=>n.enName));return[...r,...e.filter(n=>!t.has(n.enName))]}var wo=class{constructor(e=[]){this.providers=e}catalog(){return this.mergeCatalog(this.providers.map(e=>e.catalog()))}search(e){return this.mergeCatalog(this.providers.flatMap(t=>t.search(e)))}async listCatalog(e){let t=KC(this.catalog()),n=await JC(uu,e);return YC(t,n)}async findCatalog(e,t){let n=KC(this.search(e)),i=await JC(o=>pu(e,o),t);return YC(n,i)}mergeCatalog(e){let t=new Map;for(let n of e)t.has(n.name)||t.set(n.name,{enName:n.name,description:n.description??""});return[...t.values()]}async resolveNames(e){if(e.skill&&this.provider(e.skill))return[e.skill];let t=await du();if(e.all)return(await uu(t)).map(o=>o.enName);let i=(await pu(e.skill,t)).find(o=>o.enName===e.skill);if(!i)throw Object.assign(new Error(`Skill "${e.skill}" not found`),{name:"ValidationError",code:"errorCode"});return[i.enName]}async installSkills(e,t,n,i){let o=Z$(5),s=e.map(l=>o(()=>this.prepareArchive(l))),a=[],c=0;for(let[l,d]of e.entries()){let m={name:d,index:l,total:e.length};i({...m,phase:"installing"});let y=await s[l];if(!y.success){i({...m,phase:"download-failed",error:y.error}),a.push({success:!1});continue}c+=y.buffer?.length??0,i({...m,phase:"ready"});let b=this.provider(d);a.push(...b?await b.installForTargets(d,t,n):await new Xt().installArchiveSkill(d,y.buffer,t,n))}return{results:a,diskBytes:c}}removeSkill(e,t,n=!1){let i=this.provider(e);return i?i.uninstallForTargets(e,t,n):new Xt().removeSkill(e,t)}provider(e){return this.providers.find(t=>t.handles(e))}async prepareArchive(e){try{return{success:!0,buffer:this.provider(e)?void 0:await Mh(e)}}catch(t){return{success:!1,error:t instanceof Error?t.message:"unknown error"}}}};var wu=class{constructor(e){this.skill=e}handles(e){return e===this.skill.name}catalog(){return{name:this.skill.name,aliases:[],description:this.skill.description}}search(e){let t=e.trim().toLowerCase(),n=`${this.skill.name} ${this.skill.description??""}`.toLowerCase();return!t||n.includes(t)?[this.catalog()]:[]}installForTargets(){return Promise.reject(new Error(`Skill "${this.skill.name}" is bundled with deveco-cli. Bundled skills are installed by devecocli init and update with the CLI package.`))}uninstallForTargets(){return Promise.reject(new Error(`Skill "${this.skill.name}" is bundled with deveco-cli and cannot be removed. Bundled skills are managed by the CLI package and update with npm update.`))}};function Vh(){try{return Wh().map(r=>new wu(r))}catch{return[]}}import Gh from"fs/promises";import Q$ from"path";function eF(r){return`'${process.platform==="win32"?r.replace(/'/g,"''"):r.replace(/'/g,"'\\''")}'`}async function tF(r,e){try{if(!(await Ne(r))?.isSymbolicLink())return;let n=await Gh.realpath(r);return ee(n,e)?void 0:{path:r,reason:`points to ${n}`,repair:!0}}catch(t){let n=t.code,i=n==="ENOENT"||n==="ELOOP"||n==="ENOTDIR";return{path:r,reason:i?"broken link":`cannot check: ${t.message}`,repair:i}}}var zh=class{checked=new Set;async warnInvalidBundledLinks(e){try{let t=await Gh.realpath(e),n=process.platform==="win32"?t.toLowerCase():t;if(this.checked.has(n))return;this.checked.add(n);let i=await this.checkKnownEntries(t,fr());this.reportIssues(t,i)}catch(t){console.warn(`Cannot check project Skill links for ${e}: ${t.message}`)}}async checkKnownEntries(e,t){let n=new Set([Yt(e),...Le().map(o=>kh(e,o))]),i=[];for(let o of t){let s=await Gh.realpath(o.dir),a=[];for(let c of n){let l=await this.checkDirectoryEntry(Q$.join(c,o.name),s,a);l&&i.push(l)}}return i}async checkDirectoryEntry(e,t,n){try{let i=await be(e);return n.some(o=>ee(o,i))?void 0:(n.push(i),await tF(i,t))}catch(i){return{path:e,reason:`cannot check: ${i.message}`,repair:!1}}}reportIssues(e,t){for(let n of t)console.warn(`Project Skill link: ${n.path} (${n.reason}).`);t.some(n=>n.repair)&&(console.warn(`Run: devecocli init --project ${eF(e)} -f`),console.warn("Existing copies and local edits in the selected installation scope will be replaced."))}},$t=new zh;import Xh from"fs";import rk from"path";import{cyan as hF}from"colorette";import{spawn as uF}from"child_process";import*as tk from"fs";import*as Su from"path";import{yellow as pF,cyan as mF}from"colorette";import fF from"proper-lockfile";import{compare as rF}from"semver";function gr(r,e){return rF(r,e)}function Cs(r,e){let t=Math.max(r.split(".").length,e.split(".").length);for(let n=0;n<t;n++){let i=Number(r.split(".")[n]??0)-Number(e.split(".")[n]??0);if(i)return i}return 0}var XC={name:"@deveco/deveco-cli-common",version:"1.3.12",description:"HarmonyOS application development command line tool",supportedDocsApi:1,license:"MIT",type:"module",files:["dist","templates","src/resources","THIRD-PARTY-LICENSES","skills"],scripts:{prebuild:"node ../../scripts/sync-cli-docs.mjs",build:"npm run build -w design2arkts-engine && tsup",dev:"tsx watch src/cli.ts",start:"tsx src/cli.ts","prebundle:skills":"node ../../scripts/sync-cli-docs.mjs","bundle:skills":"tsx scripts/bundle-skills.ts","precheck:skills":"node ../../scripts/sync-cli-docs.mjs","check:skills":"tsx scripts/bundle-skills.ts --check",test:"vitest run",lint:'eslint "src/**/*.ts"',"lint:fix":"eslint src --fix",format:"prettier --write src",prepack:"node ../../scripts/sync-cli-docs.mjs",prepublishOnly:"npm run lint && npm run build && npm run check:skills"},engines:{node:">=22"},os:["darwin","linux","win32"],cpu:["x64","arm64"],keywords:["harmonyos","deveco","cli"],dependencies:{"@modelcontextprotocol/sdk":"^1.29.0","@xmldom/xmldom":"^0.8.15","adm-zip":"0.6.1",axios:"1.20.0",colorette:"^2.0.20",commander:"^13.1.0",execa:"^9.6.1","fs-extra":"^11.3.4","global-agent":"^4.1.3",json5:"^2.2.3",mp4box:"^2.4.1","node-forge":"^1.4.0",ora:"^9.4.0","p-limit":"^5.0.0","proper-lockfile":"^4.1.2",semver:"^7.8.5","smol-toml":"^1.6.1","socket.io-client":"^4.7.5","ui-verification-mcp":"0.0.20",xpath:"^0.0.35",zod:"^4.4.3","@deveco/deveco-cli-knowledgebase":"1.3.12"},devDependencies:{"@types/adm-zip":"^0.5.8","@types/fs-extra":"^11.0.4","@types/global-agent":"^3.0.0","@types/node-forge":"^1.3.14","@types/proper-lockfile":"^4.1.4","@types/semver":"^7.7.1","design2arkts-engine":"0.1.0"}};function vc(){return process.env.DEVECO_CLI_WRAPPER_NAME?process.env.DEVECO_CLI_WRAPPER_NAME:"@deveco/deveco-cli-common"}function hr(){return process.env.DEVECO_CLI_WRAPPER_VERSION?process.env.DEVECO_CLI_WRAPPER_VERSION:"1.3.12"}function Ei(){return"latest"}function qh(){return"@deveco/deveco-cli-common"}function yr(){return Number.isFinite(1),1}var _r=(()=>{let r=Object.keys(XC.dependencies).find(e=>e.endsWith("/deveco-cli-knowledgebase"));if(!r)throw new Error("CLI package.json must declare a deveco-cli-knowledgebase dependency.");return r})();function ks(){let r=process.env.DEVECO_CLI_DISABLE_UPDATE;return r==="check"||r==="all"?r:"off"}import*as Sc from"fs";import*as bc from"path";var iF={lastCheckedTimestamp:null,latestVersion:null,blockedVersions:[],checkError:null,latestDocsVersion:null,latestDocsApiVersion:null,latestCompatibleDocsVersion:null,checkedAgainstDocsApi:null},Jh=new Map,Pi=class r{static CHECK_WINDOW_HOUR=21;static ONE_DAY_MS=1440*60*1e3;cacheFilePath;lockFilePath;constructor(e){this.cacheFilePath=bc.join(e,"cache.json"),this.lockFilePath=bc.join(e,"check.lock")}async writeSuccess(e,t=[],n,i,o){let s=this.read();await this.write({lastCheckedTimestamp:Date.now(),latestVersion:e,blockedVersions:t,checkError:null,checkedAgainstVersion:n,checkedAgainstTag:i,latestDocsVersion:o?o.latestDocsVersion:s.latestDocsVersion??null,latestDocsApiVersion:o?o.latestDocsApiVersion:s.latestDocsApiVersion??null,latestCompatibleDocsVersion:o?o.latestCompatibleDocsVersion:s.latestCompatibleDocsVersion??null,checkedAgainstDocsApi:o?o.checkedAgainstDocsApi:s.checkedAgainstDocsApi??null})}async writeError(e){let t=this.read();await this.write({...t,lastCheckedTimestamp:Date.now(),checkError:e})}getLatestVersion(){return this.read().latestVersion}getBlockedVersions(){return[...this.read().blockedVersions]}getCheckedAgainstVersion(){return this.read().checkedAgainstVersion}getCheckedAgainstTag(){return this.read().checkedAgainstTag}getLatestDocsVersion(){return this.read().latestDocsVersion??null}getLatestDocsApiVersion(){return this.read().latestDocsApiVersion??null}getLatestCompatibleDocsVersion(){return this.read().latestCompatibleDocsVersion??null}getCheckedAgainstDocsApi(){return this.read().checkedAgainstDocsApi??null}isCheckNeeded(){let{lastCheckedTimestamp:e}=this.read();if(!e||e>Date.now())return!0;let t=new Date().setHours(r.CHECK_WINDOW_HOUR,0,0,0),n=t>Date.now()?t-r.ONE_DAY_MS:t;return e<n}getLockPath(){return this.lockFilePath}read(){let e=Jh.get(this.cacheFilePath);if(e)return e;try{let t=Sc.readFileSync(this.cacheFilePath,"utf-8"),n=JSON.parse(t);return Jh.set(this.cacheFilePath,n),n}catch{return{...iF}}}async write(e){f(()=>`Writing update cache: lastChecked=${e.lastCheckedTimestamp}, latest=${e.latestVersion}, blocked=[${e.blockedVersions.join(",")}], error=${e.checkError}`),await Sc.promises.mkdir(bc.dirname(this.cacheFilePath),{recursive:!0}),await Sc.promises.writeFile(this.cacheFilePath,JSON.stringify(e,null,2),"utf-8"),Jh.set(this.cacheFilePath,e)}};import{createRequire as oF}from"module";import{dirname as sF,join as xs}from"path";import{pathToFileURL as aF}from"url";import{readFile as ZC,access as Kh}from"fs/promises";import*as QC from"semver";var cF=oF(import.meta.url);async function lF(){try{let r=cF.resolve(`${_r}/package.json`),e=JSON.parse(await ZC(r,"utf8"));return{version:e.version,apiVersion:e.apiVersion??0,dir:sF(r)}}catch{return null}}async function ek(){let r=F(),e=xs(r,"doc-data","current.json"),t;try{t=JSON.parse(await ZC(e,"utf8"))}catch{return null}let n=xs(r,"doc-data",t.version);try{return await Kh(xs(n,"dist","engine","index.js")),await Kh(xs(n,"docs.zip")),await Kh(xs(n,"index.zip")),{version:t.version,apiVersion:t.apiVersion,dir:n}}catch{return null}}async function dF(){return[await ek(),await lF()].filter(e=>e!==null).sort((e,t)=>QC.rcompare(e.version,t.version))}async function Rs(){let r=yr(),e=await ek();return e&&e.apiVersion<=r?e.version:null}async function vu(){let r=yr(),e=await dF(),t=!1;for(let n of e){if(n.apiVersion>r){f(`docs: skip candidate v${n.version} (apiVersion ${n.apiVersion} > ${r})`);continue}t=!0;try{let i=xs(n.dir,"dist","engine","index.js");return await import(aF(i).href)}catch(i){f(`docs: candidate v${n.version} load failed: ${i instanceof Error?i.message:String(i)}`)}}throw e.length>0&&!t?new Error("Documentation package version is incompatible, please upgrade CLI"):new Error("No available documentation package, please run `devecocli docs update` or reinstall CLI")}var Ec=class{constructor(e){this.actionCommand=e}cache=new Pi(Su.join(F(),"update"));async checkAndNotify(){if(!this.shouldSkip())try{let e=hr(),t=Ei(),n=this.cache.getCheckedAgainstVersion(),i=this.cache.getCheckedAgainstTag(),o=i!=null&&i!==t,s=n!=null&&n!==e,a=[],c=o?null:this.cache.getLatestVersion();c&&gr(c,e)>0&&a.push(pF(`New cli version ${c} available, run \`devecocli update\` to update`));let l=await this.buildDocsMessage();if(l.message&&a.push(l.message),a.length>0){console.log();for(let d of a)console.log(d)}(o||s||l.stale||this.cache.isCheckNeeded())&&await this.spawnBackgroundCheck()}catch(e){f(`Update check failed: ${e instanceof Error?e.message:String(e)}`)}}async buildDocsMessage(){let e=yr(),t=this.cache.getCheckedAgainstDocsApi();if(t!=null&&t!==e)return{message:null,stale:!0};let n=this.cache.getLatestCompatibleDocsVersion();if(!n)return{message:null,stale:!1};let i=await Rs();return i&&gr(n,i)<=0?{message:null,stale:!1}:{message:mF(`New docs version ${n} available, run \`devecocli docs update\` to upgrade`),stale:!1}}shouldSkip(){let e=this.actionCommand;for(;e;){if(e.name()==="update")return!0;e=e.parent}return!1}async spawnBackgroundCheck(){if(!process.argv[1]?.endsWith(".ts"))try{await gF(this.cache.getLockPath(),()=>{let e=[process.argv[1],"update","_check"];f(`Executing: ${process.execPath} ${e.join(" ")}`),uF(process.execPath,e,{detached:!0,windowsHide:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1"}}).unref()})}catch{f("Update check lock held by another process, skipping")}}};async function gF(r,e){await tk.promises.mkdir(Su.dirname(r),{recursive:!0});let t=await fF.lock(r,{stale:6e4,retries:0,realpath:!1});try{await e()}finally{await t()}}var Yh=Xh.promises;async function bu(r){let e=su(r);for(let t of e)dr(t);return e}async function Eu(r){return Le().filter(e=>fo(e,r))}async function yF(){let r=new Xt,e=[];for(let{name:t,dir:n}of fr())try{await r.migrateBundledSkill(t,n,{agents:Le()})}catch(i){e.push({name:t,error:i})}if(e.length>0){let t=e.map(({name:n,error:i})=>`${n}: ${i instanceof Error?i.message:String(i)}`).join("; ");throw new Error(`Bundled skill migration failed \u2014 ${t}`)}}async function nk(){try{let r=rk.join(F(),"skills","migration-version"),e=await Yh.readFile(r,"utf8").catch(n=>{if(n.code==="ENOENT")return"";throw n}),t=hr();if(e.trim()===t)return;await yF(),await Yh.mkdir(rk.dirname(r),{recursive:!0}),await Yh.writeFile(r,t,"utf8")}catch(r){console.warn(`Bundled skill migration failed (will retry on the next command): ${r instanceof Error?r.message:String(r)}`)}}function As(r){let e=r.filter(i=>i.success&&!i.skipped).length,t=r.filter(i=>i.skipped).length,n=r.filter(i=>!i.success).length;console.log(),console.log(hF("Finished:"));for(let i of r){if(!i.path)continue;let o=BC(i),s=i.fallbackReason?" (link failed: "+i.fallbackReason+")":o??i.error?" ("+(o??i.error)+")":"",a=i.success?i.skipped?"skipped":i.mode??(i.reason==="shared-entity-updated"?"updated":"removed"):"failed";console.log(" "+a+": "+i.path+s)}console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`),n>0&&(process.exitCode=1)}function Lr(r,e,t){if(!Xh.existsSync(r)){if(t)return;throw new Error(`${e} "${r}" not found`)}if(!Xh.statSync(r).isDirectory())throw new Error(`"${r}" is not a directory`)}function Is(r,e,t){if(r&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:r?Oh(r):void 0,resolvedProject:e?Oh(e):void 0}}async function Pu(r,e,t="No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location."){let n=r.agent?await bu(r.agent):await Eu(e);if(!n.length)throw new Error(t);return n.map(i=>({agent:i,directory:ur(i,e),explicit:!!r.agent}))}async function Ds(r,e,t){if(e)return{agents:[],projectAgents:[],customPath:e};let n=await Pu(r,t),i=n.some(o=>o.explicit);return t?{agents:[],explicitAgents:i,projectAgents:n.map(({agent:o})=>({project:t,agent:o}))}:{agents:n.map(({agent:o})=>o),projectAgents:[],explicitAgents:i}}import wF from"fs";import Cu from"path";import{cyan as vF}from"colorette";import*as ku from"smol-toml";var Ts=wF.promises;async function SF(r){try{let e=await Ts.readFile(r,"utf8");return e.trim()===""?{}:JSON.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read configuration file ${r}: ${e.message}`,{cause:e})}}async function bF(r){try{let e=await Ts.readFile(r,"utf8");return e.trim()===""?{}:ku.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read TOML config file ${r}: ${e.message}`,{cause:e})}}async function EF(r,e){let t=Cu.dirname(r);await Ts.mkdir(t,{recursive:!0});let n=JSON.stringify(e,null,2);await Ts.writeFile(r,n,"utf8")}async function PF(r,e){let t=Cu.dirname(r);await Ts.mkdir(t,{recursive:!0});let n=ku.stringify(e);await Ts.writeFile(r,n,"utf8")}function CF(r,e,t){let n=r[e];return!n||typeof n!="object"?!1:t in n}function kF(r,e,t,n,i){(!r[e]||typeof r[e]!="object")&&(r[e]={});let o=r[e];return t in o&&!i?!1:(o[t]=n,!0)}async function xF(r,e){return r.format==="codex"?bF(e):SF(e)}async function RF(r,e,t){return r.format==="codex"?PF(e,t):EF(e,t)}function ik(r={}){return{force:r.force??!1,withHomegraph:r.withHomegraph??!1}}function AF(r,e,t,n,i){let o=[],s=[],a=!1,c=(l,d)=>{if(CF(r,e.mcpServersKey,l)&&!n){s.push(l);return}kF(r,e.mcpServersKey,l,d,n),o.push(l),a=!0};return c(Dh,Th(e,t)),i&&c(CC,RC(e,t)),{changed:a,configured:o,skipped:s}}async function ok(r,e,t,n,i,o){try{let s=await xF(e,t),{changed:a,configured:c,skipped:l}=AF(s,e,n,o.force,o.withHomegraph);return a?(await RF(e,t,s),console.log(`MCP server(s) ${c.join(", ")} configured in ${t}.`),{success:!0,configPath:t,agentName:r,installType:i}):(console.log(`MCP already configured in ${t} (${l.join(", ")}).`),{success:!0,skipped:!0,configPath:t,agentName:r,installType:i})}catch(s){return{success:!1,error:`Failed to configure MCP for ${e.displayName}: ${s.message}`}}}async function Zh(r,e={}){let t=ik(e),n=$n[r];return n?n.supportsGlobal?ok(r,n,n.globalConfigPath,void 0,"global",t):{success:!1,error:`${n.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`}:{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys($n).join(", ")}`}}async function xu(r,e,t={}){let n=ik(t),i=$n[r];if(!i)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys($n).join(", ")}`};let o=Cu.isAbsolute(i.projectConfigPath)?i.projectConfigPath:Cu.join(e,i.projectConfigPath);return ok(r,i,o,e,"project",n)}function Qh(r){let e=r.filter(i=>i.success&&!i.skipped).length,t=r.filter(i=>i.skipped).length,n=r.filter(i=>!i.success).length;console.log(),console.log(vF("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`);for(let i of r)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);n>0&&(process.exitCode=1)}import IF from"fs";import DF from"path";import{homedir as TF}from"os";async function ey(r,e){let t=[],n=r.agent?su(r.agent):Object.keys(lu);for(let i of n){if(!Object.prototype.hasOwnProperty.call(lu,i))throw new Error(`Invalid MCP agent: ${i}`);(r.agent||IF.existsSync(DF.join(TF(),lu[i])))&&t.push(i)}if(!t.length)throw new Error("No agents supporting MCP configuration found; use --skill");return e?{agents:[],projectAgents:t.map(i=>({project:e,agent:i}))}:{agents:t,projectAgents:[]}}import{spawnSync as fk}from"child_process";import yt from"fs";import*as Ft from"os";import*as O from"path";import Fn from"fs";import*as vo from"os";import*as jn from"path";import{execa as MF}from"execa";import{execFileSync as NF}from"child_process";import sk from"fs";import*as ak from"os";import*as ty from"path";function Ru(r,e){let t=ty.join(r,"Contents","Info.plist");if(!sk.existsSync(t)){f(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[n,i]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let o=NF(n,i,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(o&&!o.includes("Does Not Exist"))return o}catch{}}function OF(r){let e=Ru(r,"CFBundleShortVersionString");if(!e)return Ru(r,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),n=[Ru(r,"CFBundleVersion"),Ru(r,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let i of n){let o=i?.split(".").at(-1)?.replace(new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`),"");if(o&&/^\d+$/.test(o))return`${e}.${o}`}return e}function Ci(r){if(ak.platform()==="darwin")return OF(r);let e=ty.join(r,"product-info.json");try{let t=JSON.parse(sk.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}var _F="DevEco Studio",LF=jn.join("C:","Program Files","Huawei","DevEco Studio"),$F=["Contents","Resources","product-info.json"],FF="name";function jF(r){return r.filter(e=>{try{return Fn.statSync(e).isDirectory()}catch{return!1}})}function HF(r){let e=jn.join(r,...$F);if(Fn.existsSync(e))try{let n=JSON.parse(Fn.readFileSync(e,"utf8"))[FF];return typeof n=="string"&&n.trim()?n.trim():void 0}catch{return}}function UF(r){return HF(r)===_F}function BF(){let r=[];for(let e of[jn.join(vo.homedir(),"Applications"),"/Applications"])try{r.push(...Fn.readdirSync(e).filter(t=>t.endsWith(".app")).map(t=>jn.join(e,t)).filter(UF))}catch{}return r}function lk(r){return{HKLM:"2147483650",HKEY_LOCAL_MACHINE:"2147483650",HKCU:"2147483649",HKEY_CURRENT_USER:"2147483649",HKCR:"2147483648",HKEY_CLASSES_ROOT:"2147483648",HKU:"2147483651",HKEY_USERS:"2147483651"}[r]||"2147483650"}function dk(r){let e=r.indexOf("\\");return e>0?{hive:r.slice(0,e),subPath:r.slice(e+1)}:{hive:r,subPath:""}}function WF(r){let e="";for(let t of r){let n=t.charCodeAt(0);if(!(n===13||n===10)){if(n===92){e+="\\\\";continue}if(n===34){e+='\\"';continue}e+=t}}return e}function VF(r){let e="";for(let t of r){let n=t.charCodeAt(0);if(n>=32&&n<=126){e+=t;continue}e+=`\\u${n.toString(16).padStart(4,"0")}`}return e}function Au(r){return VF(WF(r))}var uk=['var fso = new ActiveXObject("Scripting.FileSystemObject");','var locator = new ActiveXObject("WbemScripting.SWbemLocator");','var svc = locator.ConnectServer(".", "root\\\\default");','var reg = svc.Get("StdRegProv");'],ry="@OUT@";function GF(r){let{hive:e,subPath:t}=dk(r);return["try {",...uk,'var inP = reg.Methods_("EnumKey").InParameters.SpawnInstance_();',`inP.hDefKey = ${lk(e)};`,`inP.sSubKeyName = "${Au(t)}";`,'var out = reg.ExecMethod_("EnumKey", inP);',"if (out.ReturnValue != 0 || out.sNames == null) { WScript.Quit(1); }","var names = new VBArray(out.sNames).toArray();",`var f = fso.CreateTextFile("${ry}", true, true);`,"for (var i = 0; i < names.length; i++) { f.WriteLine(names[i]); }","f.Close();","} catch (e) { WScript.Quit(1); }"].join(`\r
|
|
58
58
|
`)}function zF(r,e){let{hive:t,subPath:n}=dk(r),i=lk(t),o=`"${Au(n)}"`,s=`"${Au(e)}"`;return["var f = null;","try {",...uk,`f = fso.CreateTextFile("${ry}", true, true);`,'var inP = reg.Methods_("GetStringValue").InParameters.SpawnInstance_();',`inP.hDefKey = ${i};`,`inP.sSubKeyName = ${o};`,`inP.sValueName = ${s};`,'var out = reg.ExecMethod_("GetStringValue", inP);',"if (out.ReturnValue == 0 && out.sValue != null) { f.WriteLine(out.sValue); f.Close(); WScript.Quit(0); }","} catch (e) {}","try {",'var inP2 = reg.Methods_("GetExpandedStringValue").InParameters.SpawnInstance_();',`inP2.hDefKey = ${i};`,`inP2.sSubKeyName = ${o};`,`inP2.sValueName = ${s};`,'var out2 = reg.ExecMethod_("GetExpandedStringValue", inP2);',"if (out2.ReturnValue == 0 && out2.sValue != null) { f.WriteLine(out2.sValue); f.Close(); WScript.Quit(0); }","} catch (e) {}","if (f != null) { f.Close(); }","WScript.Quit(1);"].join(`\r
|
|
59
59
|
`)}var qF=0,JF="deveco-cli-reg-";async function pk(r){let e=`${JF}${process.pid}-${++qF}`,t=jn.join(vo.tmpdir(),`${e}.js`),n=jn.join(vo.tmpdir(),`${e}.out`);try{Fn.writeFileSync(t,r.replace(new RegExp(ry,"g"),Au(n)),"ascii"),f(`Executing: cscript //E:JScript //Nologo ${jn.basename(t)}`);let{exitCode:i}=await MF("cscript",["//E:JScript","//Nologo",t],{windowsHide:!0,reject:!1});return i!==0||!Fn.existsSync(n)?{stdout:"",exitCode:1}:{stdout:Fn.readFileSync(n,"utf16le").replace(/^\uFEFF/,""),exitCode:0}}catch{return{stdout:"",exitCode:1}}finally{try{Fn.rmSync(t,{force:!0}),Fn.rmSync(n,{force:!0})}catch{}}}async function KF(r){let{stdout:e,exitCode:t}=await pk(GF(r));return t!==0?[]:e.split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0)}function YF(r){return r.replace(/%([^%]+)%/g,(e,t)=>{let n=process.env[t];return n!==void 0?n:e})}async function ny(r,e){let{stdout:t,exitCode:n}=await pk(zF(r,e));if(n!==0)return;let i=t.trim();if(i)return YF(i)}async function ck(r,e,t){let n=(await KF(r)).filter(e),i=[];for(let o of n){let s=await ny(`${r}\\${o}`,t);s&&i.push(s)}return i}async function XF(){let r=[LF];for(let e of["HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall","HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"])try{r.push(...await ck(e,t=>t.normalize("NFKC").trim().toLowerCase().startsWith("deveco studio"),"InstallLocation"))}catch{}for(let e of["HKLM\\SOFTWARE\\Huawei\\DevEco Studio","HKLM\\SOFTWARE\\WOW6432Node\\Huawei\\DevEco Studio"])try{r.push(...await ck(e,()=>!0,""))}catch{}return r}async function mk(){let r=vo.platform();if(r==="linux")throw new Error("DevEco Studio is not available on Linux. Set DEVECO_CLI_CLT_PATH to a Command Line Tools installation.");let e=r==="darwin"?BF():await XF(),t=jF(e).flatMap(n=>{let i=Ci(n);return i?(f(`[ToolProvider] ${n} => version ${i}`),[{root:n,version:i}]):(f(`[ToolProvider] Skipping ${n}: could not read version`),[])});if(!t.length)throw new Error("DevEco Studio installation not found in default locations. Set DEVECO_CLI_STUDIO_PATH to a DevEco Studio installation, or set DEVECO_CLI_CLT_PATH to a Command Line Tools installation.");return t.reduce((n,i)=>Cs(i.version,n.version)>0?i:n)}var ZF=/^#\s*Version:\s*(\S+)/,QF="26.0.0.810",ej="26.0.1";function tj(r){try{let e=JSON.parse(yt.readFileSync(r,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch(e){f(`[ToolProvider] Failed to parse API level from ${r}: ${e instanceof Error?e.message:String(e)}`);return}}function rj(r){let e=O.join(r,"default","openharmony");return[O.join(r,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>O.join(e,t,"oh-uni-package.json"))]}var k=class r{constructor(e,t,n,i,o,s,a,c,l,d,m){this._sourceType=e;this._toolchainRoot=t;this._devecoStudioPath=n;this._nodePath=i;this._ohpmJsPath=o;this._hvigorJsPath=s;this._javaPath=a;this._sdkPath=c;this._hdcPath=l;this._emulatorPath=d;this._appanalyzerPath=m}static installSourcePromise;get sourceType(){return this._sourceType}get toolchainRoot(){return this._toolchainRoot}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return this._nodePath}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get codelinterPath(){return r.resolveCodelinterPath(this._toolchainRoot,this._sourceType)}get arktsLangServerPath(){let e=r.buildToolPaths(this._toolchainRoot,this._sourceType).arktsLangServerCandidates;for(let t of e)if(yt.existsSync(t.marker))return t.root;return null}get clangdPath(){let e=r.buildToolPaths(this._toolchainRoot,this._sourceType).clangdPath;return yt.existsSync(e)?e:null}get javaPath(){return this._javaPath??""}get sdkPath(){return this._sdkPath}get hdcPath(){return this._hdcPath}get emulatorPath(){return this._emulatorPath}get appanalyzerPath(){return this._appanalyzerPath}get emulatorLauncherPath(){return this.emulatorPath}assertJava(){if(this._sourceType==="clt"&&(this._javaPath=r.resolveCltJava(!0)),!this._javaPath)throw new Error("Java runtime is required to run hvigor. Set JAVA_HOME or add Java to PATH.")}assertStudio(){if(this._sourceType==="clt")throw new Error("This operation requires DevEco Studio. Set DEVECO_CLI_STUDIO_PATH to a DevEco Studio installation.")}assertLsp(){this.assertStudio()}static compareVersion(e,t){return Cs(e,t)}static async checkVersion(){let e=await r.resolveInstallSource();(e.sourceType==="clt"?r.fromCLT(e.toolchainRoot):r.fromIDE(e.toolchainRoot,e.sourceType)).assertVersion()}static async new(){let e=await r.resolveInstallSource();return e.sourceType==="clt"?r.fromCLT(e.toolchainRoot):r.fromIDE(e.toolchainRoot,e.sourceType)}static fromCLT(e){let t=r.buildToolPaths(e,"clt");return r.assertBuiltPathsInsideRoot(e,t,!1),new r("clt",e,void 0,t.nodePath,t.ohpmJsPath,t.hvigorJsPath,r.resolveCltJava(!1),t.sdkPath,t.hdcPath,t.emulatorPath,t.appanalyzerPath)}static fromIDE(e,t="studio"){let n=r.buildToolPaths(e,"studio");return r.assertBuiltPathsInsideRoot(e,n,!0),new r(t,e,e,n.nodePath,n.ohpmJsPath,n.hvigorJsPath,n.javaPath,n.sdkPath,n.hdcPath,n.emulatorPath,n.appanalyzerPath)}assertVersion(){if(this._sourceType==="clt"){this.assertCltVersion();return}this.assertIdeVersion()}readVersion(){return this._sourceType==="clt"?r.readCltVersion(this._toolchainRoot):Ci(this._toolchainRoot)}assertCltVersion(e="26.0.0"){if(this._sourceType!=="clt")throw new Error("This operation requires Command Line Tools.");r.assertMinimumVersion(r.readCltVersion(this._toolchainRoot),"Command Line Tools","version.txt",e,this._toolchainRoot)}assertIdeVersion(e="6.0.0"){this.assertStudio(),r.assertMinimumVersion(Ci(this._toolchainRoot),"DevEco Studio","product-info.json / Info.plist",e,this._toolchainRoot)}require(e){if(this._sourceType==="clt"){this.requireClt(e.clt);return}this.requireIde(e.studio)}requireClt(e){if(e===!1)throw new Error("This operation is not supported in Command Line Tools mode.");typeof e=="string"&&this.assertCltVersion(e)}requireIde(e){if(e===!1)throw new Error("This operation is not supported in DevEco Studio mode.");typeof e=="string"&&this.assertIdeVersion(e)}static assertMinimumVersion(e,t,n,i,o){if(!e)throw new w(`Failed to determine ${t} version from ${n} at ${o}`,`Failed to determine ${t} version from ${n}`);if(!/^\d+(?:\.\d+){1,3}$/.test(e))throw new w(`Invalid ${t} version "${e}" from ${n} at ${o}`,`Invalid ${t} version "${e}" from ${n}`);if(Cs(e,i)<0)throw new Error(`The detected ${t} version is ${e}, which is below the minimum required version ${i}. Upgrade before using deveco-cli:
|
|
60
60
|
${hc}`)}static resolveCodelinterPath(e,t){let n=r.buildToolPaths(e,t).codelinterCandidates,i=n.find(r.isFile);if(!i){let a=t==="studio"?"Code Linter not found in DevEco Studio.":"Code Linter not found in DevEco Command Line Tools.";throw new w(`${a}
|
|
@@ -1437,7 +1437,7 @@ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let n=this
|
|
|
1437
1437
|
`):"No valid C/C++ files"}],isError:!0};for(let c of i){await F8(L8);try{let l=await this.checkFile(c);n.push($8(c,l))}catch(l){t.push(`${c} => wait for diagnostics failed: ${l.message}`)}}let o=t.length>0,s=[];t.length>0&&s.push(t.join(`
|
|
1438
1438
|
`)),n.length>0&&s.push(n.join(`
|
|
1439
1439
|
`));let a=s.join(`
|
|
1440
|
-
`).trim();return!o&&n.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:o}}async checkFile(e){let t=Or(e),n=await Zi.promises.readFile(e,"utf8"),i=Hd(e),o=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:n,languageId:i,version:n.length}}});try{return await o}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let n=os.resolve(this.manager.projectRoot),i=[];for(let o of e){let s=os.resolve(os.isAbsolute(o)?o:os.join(n,o));if(!Zi.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!Zi.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!lo(s)){t.push(`Not a supported C/C++ file: ${o}`);continue}try{i.push(Zi.realpathSync(s))}catch{i.push(s)}}return i}};function $8(r,e){if(Array.isArray(e))return e.length===0?`${r} => no diagnostics`:`${r} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${r} diagnostic failed, error_message: ${t}`}return`${r} => diagnostic failed, result: ${JSON.stringify(e)}`}function F8(r){return new Promise(e=>setTimeout(e,r))}import*as Ka from"fs";import*as jf from"path";var Ja=class r{manager;static FEATURE_METHOD_MAP={hover:S.HOVER,definition:S.DEFINITION,declaration:S.DECLARATION,references:S.REFERENCES,implementation:S.IMPLEMENTATION};constructor(e){this.manager=e}async handleLspFeature(e,t){if(!this.manager.ready)return za();let n=this.resolveSingleFile(t.file);if(!n)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${t.file}`}],isError:!0};let i=r.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`[ClangdLspTool] handleLspFeature: ${e} file=${n} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(n,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){return Ff(e,o)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(S.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return h.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return za();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};h.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let n=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(S.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:n==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(n,null,2)}`}]}}catch(n){return Ff("documentSymbol",n)}}async handleCallHierarchy(e){if(!this.manager.ready)return za();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};h.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let n=await this.withOpenFile(t,o=>this.fetchCallHierarchyResult(o,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(n,null,2)}`}]}}catch(n){return Ff("callHierarchy",n)}}async fetchCallHierarchyResult(e,t){let n=await this.manager.sendFeatureRequest(S.PREPARE_CALL_HIERARCHY,{textDocument:{uri:e},position:{line:t.line,character:t.character}}),i=this.normalizeCallHierarchyItems(n);if(i.length===0)return{items:[],calls:[]};let o=await this.collectIncomingCalls(i);return{items:i,calls:o}}normalizeCallHierarchyItems(e){return Array.isArray(e)?e:e?[e]:[]}async collectIncomingCalls(e){let t=[];for(let n of e)t.push(...await this.fetchIncomingCalls(n));return t}async fetchIncomingCalls(e){let t=await this.manager.sendFeatureRequest(S.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let n=Or(e),i=await Ka.promises.readFile(e,"utf8"),o=Hd(e);h.info(`[ClangdLspTool] withOpenFile didOpen uri=${n} langId=${o} len=${i.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:n,text:i,languageId:o,version:i.length}}});try{return await t(n)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:n}}})}}resolveSingleFile(e){let t=jf.isAbsolute(e)?e:jf.join(this.manager.projectRoot,e);return!Ka.existsSync(t)||!Ka.statSync(t).isFile()||!lo(t)?null:t}};import j8 from"fs";import*as GN from"path";function H8(r){try{return j8.statSync(GN.join(r,"AppScope","app.json5")).mtimeMs}catch{return-1}}function U8(r){try{return L.discover(r).rootDir}catch{return null}}var Hf=class{rootFor="";root=null;appJson5MtimeMs=-2;value;resolve(e){this.rootFor!==e&&(this.rootFor=e,this.root=U8(e),this.appJson5MtimeMs=-2);let t=this.root;if(t===null)return;let n=H8(t);return n!==this.appJson5MtimeMs&&(this.appJson5MtimeMs=n,this.value=L.tryResolveBundleName(t)),this.value}};import{spawn as B8}from"child_process";import*as Bf from"fs";import*as zN from"path";var W8=30*1e3,V8=30*1e3,Uf=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new Ji;diagnosticWaiters=new Map;lastStartErrorMessage=null;onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get clangdPid(){return this.clangdProcess?.pid??null}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}async start(e){let t=!1;try{g.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),g.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),g.info(`[ClangdLspProxy] compileCommandsDir: ${this.config.compileCommandsDir}`),this.ensureLogDir(),this.clangdProcess=this.spawnClangd();let n={serverPath:"",logPath:this.config.logPath,indexingDataLocation:this.config.logPath,cwd:this.config.workspaceRoot};this.client=new qi(n),this.client.on("message",o=>this.handleRawMessage(o)),this.client.on("error",o=>this.handleError(o)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let i=this.buildInitializeParams();await this.sendLspRequest(S.INITIALIZE,i,Ht),g.info("[ClangdLspProxy] initialize response received"),this.sendNotification(S.INITIALIZED,{}),t=!0}catch(n){this.lastStartErrorMessage=n instanceof Error?n.message:String(n),g.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(S.HOVER,e)}async definition(e){return this.sendLspRequest(S.DEFINITION,e)}async declaration(e){return this.sendLspRequest(S.DECLARATION,e)}async references(e){return this.sendLspRequest(S.REFERENCES,e)}async implementation(e){return this.sendLspRequest(S.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(S.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(S.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(S.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(S.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(S.DID_OPEN,e)}sendDidChange(e){this.sendNotification(S.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(S.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){g.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){g.warn(`[ClangdLspProxy] overwrite existing diagnostic waiter for ${t}`);let n=this.diagnosticWaiters.get(t);clearTimeout(n.timer),this.diagnosticWaiters.delete(t)}return new Promise((n,i)=>{let o=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&i(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},V8);this.diagnosticWaiters.set(t,{resolve:n,reject:i,timer:o})})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){this.requestCallbacks.rejectAll(new Error("ClangdLspProxy disposing"));for(let[,e]of this.diagnosticWaiters)clearTimeout(e.timer),e.reject(new Error("ClangdLspProxy disposing"));if(this.diagnosticWaiters.clear(),this.client&&this.clangdProcess)try{await this.sendLspRequest(S.SHUTDOWN,null,3e3).catch(e=>{g.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(S.EXIT,null),await this.client.waitForExitOrTimeout(300)}catch(e){g.warn(`[ClangdLspProxy] dispose error: ${e}`)}if(this.clangdProcess){try{this.clangdProcess.exitCode===null&&this.clangdProcess.signalCode===null&&this.clangdProcess.kill()}catch{}this.clangdProcess=null}this.client=null}spawnClangd(){let e=[`--compile-commands-dir=${Oe(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];g.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=B8(this.config.clangdPath,e,{cwd:this.config.workspaceRoot,stdio:["pipe","pipe","pipe"],windowsHide:!0});if(!t.stdin||!t.stdout||!t.stderr)throw new Error("Failed to spawn clangd: stdio not available");return t}buildInitializeParams(){let e=Fs(this.config.workspaceRoot),t=$r(e),n=zN.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.11"},rootPath:e,rootUri:t,workspaceFolders:[{uri:t,name:n}],capabilities:this.buildClientCapabilities(),initializationOptions:null}}buildClientCapabilities(){return{textDocument:{synchronization:{didOpen:!0,didChange:!0,didClose:!0,willSave:!1,save:!1},publishDiagnostics:{relatedInformation:!0,versionSupport:!1,tagSupport:{valueSet:[1,2]}},hover:{contentFormat:["markdown","plaintext"]},completion:{contextSupport:!1,completionItemKind:{valueSet:[]}},signatureHelp:{signatureInformation:{documentationFormat:["markdown","plaintext"]}},references:{},declaration:{linkSupport:!0},definition:{linkSupport:!0},implementation:{linkSupport:!0},documentSymbol:{hierarchicalDocumentSymbolSupport:!0,symbolKind:{valueSet:[]}},callHierarchy:{dynamicRegistration:!1}},workspace:{symbol:{symbolKind:{valueSet:[]}},configuration:!1,didChangeWatchedFiles:{dynamicRegistration:!1}}}}sendLspRequest(e,t,n=W8){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,n);return this.client.sendRequest(e,t,i),o}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(n){let i=n instanceof Error?n.message:String(n);g.error(`[ClangdLspProxy] JSON parse error: ${i}, raw: ${e.slice(0,200)}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotification(t):g.warn(`[ClangdLspProxy] unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t==null||typeof t!="string"&&typeof t!="number")return;let n=t;if(e.error!==void 0&&e.error!==null){let i=e.error;g.warn(`[ClangdLspProxy] LSP error id=${n}: code=${i.code??-1} message=${i.message??"unknown"}`),this.requestCallbacks.rejectPending(n,new Error(`LSP error ${i.code??-1}: ${i.message??"unknown"}`))}else this.requestCallbacks.resolvePending(n,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case S.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case S.PROGRESS:this.onMessage({jsonrpc:G,method:S.PROGRESS,params:e.params});break;case S.WINDOW_SHOW_MESSAGE:g.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case S.WINDOW_LOG_MESSAGE:g.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:G,method:t,params:e.params})}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=this.normalizeClangdUri(e.uri),n=this.diagnosticWaiters.get(t);if(!n&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;n=this.diagnosticWaiters.get(s),n&&this.diagnosticWaiters.delete(s)}else n&&this.diagnosticWaiters.delete(t);if(!n)return;clearTimeout(n.timer);let i=Array.isArray(e.diagnostics)?e.diagnostics:[],o=i.length;g.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${o}`),n.resolve(i)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:G,method:S.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{Bf.existsSync(this.config.logPath)||Bf.mkdirSync(this.config.logPath,{recursive:!0})}catch{}}normalizeClangdUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let n=decodeURIComponent(t.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(n)&&(n=n.slice(1)),$r(n)}}catch{}return e}};import*as Wf from"path";import*as ob from"fs";var Ql=class r{config;proxy=null;isInitialized=!1;onMessage=()=>{};disposeOnce=null;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;resolvedRoot="";constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get ready(){return this.isInitialized&&this.proxy!==null}get clangdPid(){return this.proxy?.clangdPid??null}get projectRoot(){return this.resolvedRoot}async start(){if(!this.isInitialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doStart();try{await this.initPromise}catch(e){throw this.initPromise=null,e}}}sendNotification(e){if(!this.proxy){g.warn("[ClangdLspManager] sendNotification before LSP ready, dropped");return}this.dispatchNotification(e)}async sendFeatureRequest(e,t){if(!this.proxy)throw new Error("[ClangdLspManager] LSP not ready");return this.proxy.sendFeatureRequest(e,t)}registerDiagnosticCallback(e){return this.proxy?this.proxy.registerDiagnosticCallback(e):Promise.reject(new Error("[ClangdLspManager] LSP not ready"))}static async handleSyncCppProject(e,t,n,i,o){if(g.info("[ClangdLspManager] Received cpp/syncProject"),!e||!t)return g.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};if(ki(e).length===0)return g.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let a=o?.skipCompileNative===!0,c=await Ou(e,a?(async()=>(g.info("[ClangdLspManager] compileNative skipped (C++ project up-to-date)"),{status:"success"})):(async()=>{let l=Date.now(),d=await r.executeCompileNative(e,t,n,i),m=Date.now()-l;return d.status!=="success"?d:{...d,cppSyncDurationMs:m}}));return c.acquired?c.result:(g.info("[ClangdLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}static async executeCompileNative(e,t,n,i){try{return await Tk(e,t,n,i),g.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(o){let s=o instanceof Error?o.message:String(o);return g.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}doStart(){return new Promise((e,t)=>{this.initResolve=e,this.initReject=t,this.armInitTimer(Ht);try{this.startProxy()}catch(n){this.failInit(n instanceof Error?n:new Error(String(n)))}})}startProxy(){let e=Nn(this.config.workspaceRoot);this.resolvedRoot=e?it(e):it(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();$u(t);let n=this.config.clangdPath;if(!n){let s="clangd not found (install DevEco Studio / CLT)";g.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let i=this.config.compileCommandsDir??Wf.dirname(co(this.resolvedRoot));try{ob.mkdirSync(i,{recursive:!0})}catch(s){g.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}g.info(`[ClangdLspManager] clangdPath: ${n}`),g.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),g.info(`[ClangdLspManager] compileCommandsDir: ${i}`);let o=new Uf({clangdPath:n,workspaceRoot:this.resolvedRoot,compileCommandsDir:i,logPath:t});o.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=o,o.start(s=>this.handleProxyInitialized(s)).catch(s=>{let a=s instanceof Error?s:new Error(String(s));this.handleProxyInitialized(!1,a.message)})}handleProxyInitialized=(e,t)=>{if(this.clearInitTimer(),e){this.isInitialized=!0,g.info("[ClangdLspManager] clangd initialized");let n=this.initResolve;this.clearInitHandlers(),n?.()}else{let n=t??this.proxy?.consumeStartErrorMessage()??"unknown error";g.error(`[ClangdLspManager] clangd initialization failed: ${n}`),this.isInitialized=!1,this.proxy=null;let i=this.initReject;this.clearInitHandlers(),i?.(new Error(`C++ LSP initialize failed: ${n}`))}};handleLspMessage(e){this.onMessage(e)}dispatchNotification(e){if(!this.proxy)return;let t=e,n=t.method;if(!n){g.warn("[ClangdLspManager] dispatchNotification: missing method");return}let i=t.params;switch(n){case S.DID_OPEN:this.proxy.sendDidOpen(i);break;case S.DID_CHANGE:this.proxy.sendDidChange(i);break;case S.DID_CLOSE:this.proxy.sendDidClose(i);break;default:this.proxy.sendNotification(n,i)}}armInitTimer(e){this.clearInitTimer(),this.initDeadlineTimer=setTimeout(()=>{this.failInit(new Error("C++ LSP initialize timeout"))},e)}clearInitTimer(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null)}clearInitHandlers(){this.clearInitTimer(),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async performDispose(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("ClangdLspManager disposing")),this.proxy){try{await this.proxy.dispose()}catch(t){g.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){let e=`${Date.now()}${process.hrtime.bigint()%1000000n}`;return zg(t=>{let n=Wf.join(t,"CppCheck","lsp-log",e);return ob.mkdirSync(n,{recursive:!0}),it(n)})??"auto"}};function qN(r){let e=_u(r);return g.info(`[SyncGuard] ${e.reason}`),e}var KN=(s=>(s[s.IDLE_CPP=0]="IDLE_CPP",s[s.DISCOVERING_CPP=1]="DISCOVERING_CPP",s[s.SYNCING_CPP=2]="SYNCING_CPP",s[s.INITIALIZING_CPP=3]="INITIALIZING_CPP",s[s.READY_CPP=4]="READY_CPP",s[s.ERROR_CPP=5]="ERROR_CPP",s))(KN||{}),In=3,sb=600*1e3,ab=100,Vf=["ohpm","hvigor","dep-parse","lsp-init"],JN={ohpm:"ohpm install",hvigor:"hvigor sync","dep-parse":"dependency parse","lsp-init":"LSP init"},ed=15;function q8(r){let{subAction:e,mcpMemory:t,lspMemory:n}=r,i={event:v.McpToolCall,subAction:e,mcpMemory:t,lspMemory:n,...r.bundleName!==void 0?{bundleName:r.bundleName}:{}};return e==="init_cpp"?{...i,cppSyncDurationMs:r.cppSyncDurationMs??0}:{...i,ohpmDurationMs:r.ohpmDurationMs??0,syncDurationMs:r.syncDurationMs??0}}var Gf=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";sdkPath="";arktsLangServerPath=null;nodePath="";ohpmJsPath="";hvigorJsPath="";clangdPath=null;initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;arktsInitProgress=null;arktsPipelineStartedAt=0;standardProtocolAvailable=!1;socketAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;cppEnabled;cppCustomCompileCommandsDir=null;cppCustomDirResolvedFor="";bundleNameResolver=new Hf;constructor(e={}){this.config=e,uo(e.debug??!1);let t,n=e.projectPath?.trim()??"";this.originalProjectPath=n,n==="."?(t=process.cwd(),h.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):n===""?(t="",h.info("Constructor: configuredPath is empty, startPath remains empty")):(t=n,h.info(`Constructor: using configured path as startPath: '${t}'`));let i=Nn(t);h.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0,this.sdkPath=this.config.sdkPath??"",this.arktsLangServerPath=this.config.arktsLangServerPath??null,this.nodePath=this.config.nodePath??"",this.ohpmJsPath=this.config.ohpmJsPath??"",this.hvigorJsPath=this.config.hvigorJsPath??"",this.clangdPath=this.config.clangdPath??null,this.cppEnabled=this.config.cppEnabled??!0,h.info(`Constructor: sdkPath='${this.sdkPath}', arktsLangServerPath='${this.arktsLangServerPath??"(null)"}', cppEnabled=${this.cppEnabled}, cppCompileCommandsPath='${this.config.cppCompileCommandsPath??"(none)"}'`),this.server=new G8({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=eb(e.telemetry,()=>this.arktsCheckTool?.aceServerPid??null,()=>this.config.projectPath??"",()=>this.sdkPath??"",()=>this.resolveProjectBundleName()),this.standardProtocolAvailable=this.detectStandardProtocolAvailable()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools(),this.socketAvailable||this.registerRestartTool()}registerRestartTool(){this.toolRouter.add({name:"restart",description:"Restart the MCP server in-place: re-sync the project and re-initialize the LSP, without dropping the client connection. Use to recover from a stuck/ERROR state after fixing the root cause, instead of exiting and reopening the agent. Use target to restart one side only (arkts/cpp) or both (all, default). Only callable when the project state is ready/idle/error; during discovery/sync/init (large-project init can take minutes) it returns an error\u2014wait for ready and retry tools instead. Caution: if initialization fails again after a restart, the cause is likely a persistent project/SDK configuration issue\u2014do not call restart repeatedly; ask the user to fix the project first.",inputSchema:rt.object({target:rt.enum(["arkts","cpp","all"]).default("all").describe('Which backend to restart: "arkts" (ArkTS ace-server), "cpp" (C++ clangd), or "all" (both, default).')})},async e=>this.handleRestartCall(e))}registerCheckTool(){this.toolRouter.add({name:"check",description:"Perform static syntax analysis on HarmonyOS project source files and return structured diagnostics. Supported languages: ArkTS and C/C++.",inputSchema:rt.object({files:rt.array(rt.string()).min(1).describe("List of source file paths to check, relative to the project root (absolute paths within the project are also accepted). Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}registerLspFeatureTools(){if(!this.standardProtocolAvailable){h.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=rt.object({file:rt.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets (ArkTS) and C/C++ extensions."),line:rt.number().describe("Line number (0-based)"),character:rt.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:n,feature:i}of this.getPositionFeatures())this.toolRouter.add({name:t,description:n,inputSchema:e},async o=>this.handleLspFeatureCall(i,o));this.registerSymbolTools(),this.registerCallHierarchyTool()}getPositionFeatures(){return[{name:"hover",description:"Get hover information (type info, documentation) at a specific position in an ArkTS (.ets) or C/C++ file.",feature:"hover"},{name:"definition",description:"Find where the symbol at the given position is defined. Returns file path, line, and character.",feature:"definition"},{name:"declaration",description:"Find the declaration of the symbol at the given position. In ArkTS, this may differ from definition.",feature:"declaration"},{name:"references",description:"Find all references to the symbol at the given position across the HarmonyOS project.",feature:"references"},{name:"implementation",description:"Find implementations of the symbol at the given position (e.g., interface implementations).",feature:"implementation"}]}registerSymbolTools(){this.toolRouter.add({name:"workspaceSymbol",description:"Search for symbols by name across the entire HarmonyOS project.",inputSchema:rt.object({query:rt.string().describe("Symbol name (or partial) to search for")})},async e=>this.handleWorkspaceSymbolCall(e)),this.toolRouter.add({name:"documentSymbol",description:"Get the symbol tree (functions, classes, variables with ranges) of an ArkTS (.ets) or C/C++ file. Useful for file overview, structured code breakdown, and large file slicing.",inputSchema:rt.object({file:rt.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets and C/C++ extensions.")})},async e=>this.handleDocumentSymbolCall(e))}registerCallHierarchyTool(){this.toolRouter.add({name:"callHierarchy",description:'Query call hierarchy for a function at the given position. Use direction "incoming" to find callers, "outgoing" to find callees. ArkTS supports both directions; C/C++ (clangd) supports incoming only.',inputSchema:rt.object({file:rt.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets and C/C++ extensions."),line:rt.number().describe("Line number (0-based)"),character:rt.number().describe("Character offset in the line (0-based)"),direction:rt.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.arktsLangServerPath;if(!e)return h.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=jd(e);return h.info(`ArktsCheck protocol: ${t?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${t})`),t}catch(e){return h.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}async detectSocketAvailable(){try{let e=this.arktsLangServerPath;if(!e){this.socketAvailable=!1;return}this.socketAvailable=await gP(e,bo(this.nodePath)),h.info(`Socket transport: ${this.socketAvailable?"enabled":"disabled (stdio mode)"} (--list-protocols probe)`)}catch{this.socketAvailable=!1}}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(d=>typeof d=="string"):[];if(t.length===0)return h.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>ab)return h.warn(`check tool called with ${t.length} files (max: ${ab})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${ab}.`}],isError:!0};let{etsFiles:n,cppFiles:i,unsupported:o}=J8(t);o.length>0&&h.warn(`Unsupported file types in check request: ${o.join(", ")}`);let s=o.map(d=>`Unsupported file type: ${d} (only .ets and C/C++ source/header files are supported)`),a=[];n.length>0&&this.mergeCheckResult(await this.callArktsCheck(n),s,a),i.length>0&&this.mergeCheckResult(await this.callCppCheck(i),s,a);let c=s.length>0;return{content:[{type:"text",text:[a.join(`
|
|
1440
|
+
`).trim();return!o&&n.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:o}}async checkFile(e){let t=Or(e),n=await Zi.promises.readFile(e,"utf8"),i=Hd(e),o=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:n,languageId:i,version:n.length}}});try{return await o}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let n=os.resolve(this.manager.projectRoot),i=[];for(let o of e){let s=os.resolve(os.isAbsolute(o)?o:os.join(n,o));if(!Zi.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!Zi.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!lo(s)){t.push(`Not a supported C/C++ file: ${o}`);continue}try{i.push(Zi.realpathSync(s))}catch{i.push(s)}}return i}};function $8(r,e){if(Array.isArray(e))return e.length===0?`${r} => no diagnostics`:`${r} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${r} diagnostic failed, error_message: ${t}`}return`${r} => diagnostic failed, result: ${JSON.stringify(e)}`}function F8(r){return new Promise(e=>setTimeout(e,r))}import*as Ka from"fs";import*as jf from"path";var Ja=class r{manager;static FEATURE_METHOD_MAP={hover:S.HOVER,definition:S.DEFINITION,declaration:S.DECLARATION,references:S.REFERENCES,implementation:S.IMPLEMENTATION};constructor(e){this.manager=e}async handleLspFeature(e,t){if(!this.manager.ready)return za();let n=this.resolveSingleFile(t.file);if(!n)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${t.file}`}],isError:!0};let i=r.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`[ClangdLspTool] handleLspFeature: ${e} file=${n} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(n,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){return Ff(e,o)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(S.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return h.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return za();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};h.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let n=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(S.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:n==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(n,null,2)}`}]}}catch(n){return Ff("documentSymbol",n)}}async handleCallHierarchy(e){if(!this.manager.ready)return za();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};h.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let n=await this.withOpenFile(t,o=>this.fetchCallHierarchyResult(o,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(n,null,2)}`}]}}catch(n){return Ff("callHierarchy",n)}}async fetchCallHierarchyResult(e,t){let n=await this.manager.sendFeatureRequest(S.PREPARE_CALL_HIERARCHY,{textDocument:{uri:e},position:{line:t.line,character:t.character}}),i=this.normalizeCallHierarchyItems(n);if(i.length===0)return{items:[],calls:[]};let o=await this.collectIncomingCalls(i);return{items:i,calls:o}}normalizeCallHierarchyItems(e){return Array.isArray(e)?e:e?[e]:[]}async collectIncomingCalls(e){let t=[];for(let n of e)t.push(...await this.fetchIncomingCalls(n));return t}async fetchIncomingCalls(e){let t=await this.manager.sendFeatureRequest(S.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let n=Or(e),i=await Ka.promises.readFile(e,"utf8"),o=Hd(e);h.info(`[ClangdLspTool] withOpenFile didOpen uri=${n} langId=${o} len=${i.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:n,text:i,languageId:o,version:i.length}}});try{return await t(n)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:n}}})}}resolveSingleFile(e){let t=jf.isAbsolute(e)?e:jf.join(this.manager.projectRoot,e);return!Ka.existsSync(t)||!Ka.statSync(t).isFile()||!lo(t)?null:t}};import j8 from"fs";import*as GN from"path";function H8(r){try{return j8.statSync(GN.join(r,"AppScope","app.json5")).mtimeMs}catch{return-1}}function U8(r){try{return L.discover(r).rootDir}catch{return null}}var Hf=class{rootFor="";root=null;appJson5MtimeMs=-2;value;resolve(e){this.rootFor!==e&&(this.rootFor=e,this.root=U8(e),this.appJson5MtimeMs=-2);let t=this.root;if(t===null)return;let n=H8(t);return n!==this.appJson5MtimeMs&&(this.appJson5MtimeMs=n,this.value=L.tryResolveBundleName(t)),this.value}};import{spawn as B8}from"child_process";import*as Bf from"fs";import*as zN from"path";var W8=30*1e3,V8=30*1e3,Uf=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new Ji;diagnosticWaiters=new Map;lastStartErrorMessage=null;onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get clangdPid(){return this.clangdProcess?.pid??null}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}async start(e){let t=!1;try{g.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),g.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),g.info(`[ClangdLspProxy] compileCommandsDir: ${this.config.compileCommandsDir}`),this.ensureLogDir(),this.clangdProcess=this.spawnClangd();let n={serverPath:"",logPath:this.config.logPath,indexingDataLocation:this.config.logPath,cwd:this.config.workspaceRoot};this.client=new qi(n),this.client.on("message",o=>this.handleRawMessage(o)),this.client.on("error",o=>this.handleError(o)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let i=this.buildInitializeParams();await this.sendLspRequest(S.INITIALIZE,i,Ht),g.info("[ClangdLspProxy] initialize response received"),this.sendNotification(S.INITIALIZED,{}),t=!0}catch(n){this.lastStartErrorMessage=n instanceof Error?n.message:String(n),g.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(S.HOVER,e)}async definition(e){return this.sendLspRequest(S.DEFINITION,e)}async declaration(e){return this.sendLspRequest(S.DECLARATION,e)}async references(e){return this.sendLspRequest(S.REFERENCES,e)}async implementation(e){return this.sendLspRequest(S.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(S.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(S.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(S.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(S.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(S.DID_OPEN,e)}sendDidChange(e){this.sendNotification(S.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(S.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){g.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){g.warn(`[ClangdLspProxy] overwrite existing diagnostic waiter for ${t}`);let n=this.diagnosticWaiters.get(t);clearTimeout(n.timer),this.diagnosticWaiters.delete(t)}return new Promise((n,i)=>{let o=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&i(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},V8);this.diagnosticWaiters.set(t,{resolve:n,reject:i,timer:o})})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){this.requestCallbacks.rejectAll(new Error("ClangdLspProxy disposing"));for(let[,e]of this.diagnosticWaiters)clearTimeout(e.timer),e.reject(new Error("ClangdLspProxy disposing"));if(this.diagnosticWaiters.clear(),this.client&&this.clangdProcess)try{await this.sendLspRequest(S.SHUTDOWN,null,3e3).catch(e=>{g.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(S.EXIT,null),await this.client.waitForExitOrTimeout(300)}catch(e){g.warn(`[ClangdLspProxy] dispose error: ${e}`)}if(this.clangdProcess){try{this.clangdProcess.exitCode===null&&this.clangdProcess.signalCode===null&&this.clangdProcess.kill()}catch{}this.clangdProcess=null}this.client=null}spawnClangd(){let e=[`--compile-commands-dir=${Oe(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];g.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=B8(this.config.clangdPath,e,{cwd:this.config.workspaceRoot,stdio:["pipe","pipe","pipe"],windowsHide:!0});if(!t.stdin||!t.stdout||!t.stderr)throw new Error("Failed to spawn clangd: stdio not available");return t}buildInitializeParams(){let e=Fs(this.config.workspaceRoot),t=$r(e),n=zN.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.12"},rootPath:e,rootUri:t,workspaceFolders:[{uri:t,name:n}],capabilities:this.buildClientCapabilities(),initializationOptions:null}}buildClientCapabilities(){return{textDocument:{synchronization:{didOpen:!0,didChange:!0,didClose:!0,willSave:!1,save:!1},publishDiagnostics:{relatedInformation:!0,versionSupport:!1,tagSupport:{valueSet:[1,2]}},hover:{contentFormat:["markdown","plaintext"]},completion:{contextSupport:!1,completionItemKind:{valueSet:[]}},signatureHelp:{signatureInformation:{documentationFormat:["markdown","plaintext"]}},references:{},declaration:{linkSupport:!0},definition:{linkSupport:!0},implementation:{linkSupport:!0},documentSymbol:{hierarchicalDocumentSymbolSupport:!0,symbolKind:{valueSet:[]}},callHierarchy:{dynamicRegistration:!1}},workspace:{symbol:{symbolKind:{valueSet:[]}},configuration:!1,didChangeWatchedFiles:{dynamicRegistration:!1}}}}sendLspRequest(e,t,n=W8){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,n);return this.client.sendRequest(e,t,i),o}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(n){let i=n instanceof Error?n.message:String(n);g.error(`[ClangdLspProxy] JSON parse error: ${i}, raw: ${e.slice(0,200)}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotification(t):g.warn(`[ClangdLspProxy] unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t==null||typeof t!="string"&&typeof t!="number")return;let n=t;if(e.error!==void 0&&e.error!==null){let i=e.error;g.warn(`[ClangdLspProxy] LSP error id=${n}: code=${i.code??-1} message=${i.message??"unknown"}`),this.requestCallbacks.rejectPending(n,new Error(`LSP error ${i.code??-1}: ${i.message??"unknown"}`))}else this.requestCallbacks.resolvePending(n,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case S.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case S.PROGRESS:this.onMessage({jsonrpc:G,method:S.PROGRESS,params:e.params});break;case S.WINDOW_SHOW_MESSAGE:g.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case S.WINDOW_LOG_MESSAGE:g.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:G,method:t,params:e.params})}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=this.normalizeClangdUri(e.uri),n=this.diagnosticWaiters.get(t);if(!n&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;n=this.diagnosticWaiters.get(s),n&&this.diagnosticWaiters.delete(s)}else n&&this.diagnosticWaiters.delete(t);if(!n)return;clearTimeout(n.timer);let i=Array.isArray(e.diagnostics)?e.diagnostics:[],o=i.length;g.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${o}`),n.resolve(i)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:G,method:S.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{Bf.existsSync(this.config.logPath)||Bf.mkdirSync(this.config.logPath,{recursive:!0})}catch{}}normalizeClangdUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let n=decodeURIComponent(t.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(n)&&(n=n.slice(1)),$r(n)}}catch{}return e}};import*as Wf from"path";import*as ob from"fs";var Ql=class r{config;proxy=null;isInitialized=!1;onMessage=()=>{};disposeOnce=null;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;resolvedRoot="";constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get ready(){return this.isInitialized&&this.proxy!==null}get clangdPid(){return this.proxy?.clangdPid??null}get projectRoot(){return this.resolvedRoot}async start(){if(!this.isInitialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doStart();try{await this.initPromise}catch(e){throw this.initPromise=null,e}}}sendNotification(e){if(!this.proxy){g.warn("[ClangdLspManager] sendNotification before LSP ready, dropped");return}this.dispatchNotification(e)}async sendFeatureRequest(e,t){if(!this.proxy)throw new Error("[ClangdLspManager] LSP not ready");return this.proxy.sendFeatureRequest(e,t)}registerDiagnosticCallback(e){return this.proxy?this.proxy.registerDiagnosticCallback(e):Promise.reject(new Error("[ClangdLspManager] LSP not ready"))}static async handleSyncCppProject(e,t,n,i,o){if(g.info("[ClangdLspManager] Received cpp/syncProject"),!e||!t)return g.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};if(ki(e).length===0)return g.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let a=o?.skipCompileNative===!0,c=await Ou(e,a?(async()=>(g.info("[ClangdLspManager] compileNative skipped (C++ project up-to-date)"),{status:"success"})):(async()=>{let l=Date.now(),d=await r.executeCompileNative(e,t,n,i),m=Date.now()-l;return d.status!=="success"?d:{...d,cppSyncDurationMs:m}}));return c.acquired?c.result:(g.info("[ClangdLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}static async executeCompileNative(e,t,n,i){try{return await Tk(e,t,n,i),g.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(o){let s=o instanceof Error?o.message:String(o);return g.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}doStart(){return new Promise((e,t)=>{this.initResolve=e,this.initReject=t,this.armInitTimer(Ht);try{this.startProxy()}catch(n){this.failInit(n instanceof Error?n:new Error(String(n)))}})}startProxy(){let e=Nn(this.config.workspaceRoot);this.resolvedRoot=e?it(e):it(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();$u(t);let n=this.config.clangdPath;if(!n){let s="clangd not found (install DevEco Studio / CLT)";g.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let i=this.config.compileCommandsDir??Wf.dirname(co(this.resolvedRoot));try{ob.mkdirSync(i,{recursive:!0})}catch(s){g.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}g.info(`[ClangdLspManager] clangdPath: ${n}`),g.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),g.info(`[ClangdLspManager] compileCommandsDir: ${i}`);let o=new Uf({clangdPath:n,workspaceRoot:this.resolvedRoot,compileCommandsDir:i,logPath:t});o.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=o,o.start(s=>this.handleProxyInitialized(s)).catch(s=>{let a=s instanceof Error?s:new Error(String(s));this.handleProxyInitialized(!1,a.message)})}handleProxyInitialized=(e,t)=>{if(this.clearInitTimer(),e){this.isInitialized=!0,g.info("[ClangdLspManager] clangd initialized");let n=this.initResolve;this.clearInitHandlers(),n?.()}else{let n=t??this.proxy?.consumeStartErrorMessage()??"unknown error";g.error(`[ClangdLspManager] clangd initialization failed: ${n}`),this.isInitialized=!1,this.proxy=null;let i=this.initReject;this.clearInitHandlers(),i?.(new Error(`C++ LSP initialize failed: ${n}`))}};handleLspMessage(e){this.onMessage(e)}dispatchNotification(e){if(!this.proxy)return;let t=e,n=t.method;if(!n){g.warn("[ClangdLspManager] dispatchNotification: missing method");return}let i=t.params;switch(n){case S.DID_OPEN:this.proxy.sendDidOpen(i);break;case S.DID_CHANGE:this.proxy.sendDidChange(i);break;case S.DID_CLOSE:this.proxy.sendDidClose(i);break;default:this.proxy.sendNotification(n,i)}}armInitTimer(e){this.clearInitTimer(),this.initDeadlineTimer=setTimeout(()=>{this.failInit(new Error("C++ LSP initialize timeout"))},e)}clearInitTimer(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null)}clearInitHandlers(){this.clearInitTimer(),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async performDispose(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("ClangdLspManager disposing")),this.proxy){try{await this.proxy.dispose()}catch(t){g.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){let e=`${Date.now()}${process.hrtime.bigint()%1000000n}`;return zg(t=>{let n=Wf.join(t,"CppCheck","lsp-log",e);return ob.mkdirSync(n,{recursive:!0}),it(n)})??"auto"}};function qN(r){let e=_u(r);return g.info(`[SyncGuard] ${e.reason}`),e}var KN=(s=>(s[s.IDLE_CPP=0]="IDLE_CPP",s[s.DISCOVERING_CPP=1]="DISCOVERING_CPP",s[s.SYNCING_CPP=2]="SYNCING_CPP",s[s.INITIALIZING_CPP=3]="INITIALIZING_CPP",s[s.READY_CPP=4]="READY_CPP",s[s.ERROR_CPP=5]="ERROR_CPP",s))(KN||{}),In=3,sb=600*1e3,ab=100,Vf=["ohpm","hvigor","dep-parse","lsp-init"],JN={ohpm:"ohpm install",hvigor:"hvigor sync","dep-parse":"dependency parse","lsp-init":"LSP init"},ed=15;function q8(r){let{subAction:e,mcpMemory:t,lspMemory:n}=r,i={event:v.McpToolCall,subAction:e,mcpMemory:t,lspMemory:n,...r.bundleName!==void 0?{bundleName:r.bundleName}:{}};return e==="init_cpp"?{...i,cppSyncDurationMs:r.cppSyncDurationMs??0}:{...i,ohpmDurationMs:r.ohpmDurationMs??0,syncDurationMs:r.syncDurationMs??0}}var Gf=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";sdkPath="";arktsLangServerPath=null;nodePath="";ohpmJsPath="";hvigorJsPath="";clangdPath=null;initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;arktsInitProgress=null;arktsPipelineStartedAt=0;standardProtocolAvailable=!1;socketAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;cppEnabled;cppCustomCompileCommandsDir=null;cppCustomDirResolvedFor="";bundleNameResolver=new Hf;constructor(e={}){this.config=e,uo(e.debug??!1);let t,n=e.projectPath?.trim()??"";this.originalProjectPath=n,n==="."?(t=process.cwd(),h.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):n===""?(t="",h.info("Constructor: configuredPath is empty, startPath remains empty")):(t=n,h.info(`Constructor: using configured path as startPath: '${t}'`));let i=Nn(t);h.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0,this.sdkPath=this.config.sdkPath??"",this.arktsLangServerPath=this.config.arktsLangServerPath??null,this.nodePath=this.config.nodePath??"",this.ohpmJsPath=this.config.ohpmJsPath??"",this.hvigorJsPath=this.config.hvigorJsPath??"",this.clangdPath=this.config.clangdPath??null,this.cppEnabled=this.config.cppEnabled??!0,h.info(`Constructor: sdkPath='${this.sdkPath}', arktsLangServerPath='${this.arktsLangServerPath??"(null)"}', cppEnabled=${this.cppEnabled}, cppCompileCommandsPath='${this.config.cppCompileCommandsPath??"(none)"}'`),this.server=new G8({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=eb(e.telemetry,()=>this.arktsCheckTool?.aceServerPid??null,()=>this.config.projectPath??"",()=>this.sdkPath??"",()=>this.resolveProjectBundleName()),this.standardProtocolAvailable=this.detectStandardProtocolAvailable()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools(),this.socketAvailable||this.registerRestartTool()}registerRestartTool(){this.toolRouter.add({name:"restart",description:"Restart the MCP server in-place: re-sync the project and re-initialize the LSP, without dropping the client connection. Use to recover from a stuck/ERROR state after fixing the root cause, instead of exiting and reopening the agent. Use target to restart one side only (arkts/cpp) or both (all, default). Only callable when the project state is ready/idle/error; during discovery/sync/init (large-project init can take minutes) it returns an error\u2014wait for ready and retry tools instead. Caution: if initialization fails again after a restart, the cause is likely a persistent project/SDK configuration issue\u2014do not call restart repeatedly; ask the user to fix the project first.",inputSchema:rt.object({target:rt.enum(["arkts","cpp","all"]).default("all").describe('Which backend to restart: "arkts" (ArkTS ace-server), "cpp" (C++ clangd), or "all" (both, default).')})},async e=>this.handleRestartCall(e))}registerCheckTool(){this.toolRouter.add({name:"check",description:"Perform static syntax analysis on HarmonyOS project source files and return structured diagnostics. Supported languages: ArkTS and C/C++.",inputSchema:rt.object({files:rt.array(rt.string()).min(1).describe("List of source file paths to check, relative to the project root (absolute paths within the project are also accepted). Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}registerLspFeatureTools(){if(!this.standardProtocolAvailable){h.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=rt.object({file:rt.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets (ArkTS) and C/C++ extensions."),line:rt.number().describe("Line number (0-based)"),character:rt.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:n,feature:i}of this.getPositionFeatures())this.toolRouter.add({name:t,description:n,inputSchema:e},async o=>this.handleLspFeatureCall(i,o));this.registerSymbolTools(),this.registerCallHierarchyTool()}getPositionFeatures(){return[{name:"hover",description:"Get hover information (type info, documentation) at a specific position in an ArkTS (.ets) or C/C++ file.",feature:"hover"},{name:"definition",description:"Find where the symbol at the given position is defined. Returns file path, line, and character.",feature:"definition"},{name:"declaration",description:"Find the declaration of the symbol at the given position. In ArkTS, this may differ from definition.",feature:"declaration"},{name:"references",description:"Find all references to the symbol at the given position across the HarmonyOS project.",feature:"references"},{name:"implementation",description:"Find implementations of the symbol at the given position (e.g., interface implementations).",feature:"implementation"}]}registerSymbolTools(){this.toolRouter.add({name:"workspaceSymbol",description:"Search for symbols by name across the entire HarmonyOS project.",inputSchema:rt.object({query:rt.string().describe("Symbol name (or partial) to search for")})},async e=>this.handleWorkspaceSymbolCall(e)),this.toolRouter.add({name:"documentSymbol",description:"Get the symbol tree (functions, classes, variables with ranges) of an ArkTS (.ets) or C/C++ file. Useful for file overview, structured code breakdown, and large file slicing.",inputSchema:rt.object({file:rt.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets and C/C++ extensions.")})},async e=>this.handleDocumentSymbolCall(e))}registerCallHierarchyTool(){this.toolRouter.add({name:"callHierarchy",description:'Query call hierarchy for a function at the given position. Use direction "incoming" to find callers, "outgoing" to find callees. ArkTS supports both directions; C/C++ (clangd) supports incoming only.',inputSchema:rt.object({file:rt.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets and C/C++ extensions."),line:rt.number().describe("Line number (0-based)"),character:rt.number().describe("Character offset in the line (0-based)"),direction:rt.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.arktsLangServerPath;if(!e)return h.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=jd(e);return h.info(`ArktsCheck protocol: ${t?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${t})`),t}catch(e){return h.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}async detectSocketAvailable(){try{let e=this.arktsLangServerPath;if(!e){this.socketAvailable=!1;return}this.socketAvailable=await gP(e,bo(this.nodePath)),h.info(`Socket transport: ${this.socketAvailable?"enabled":"disabled (stdio mode)"} (--list-protocols probe)`)}catch{this.socketAvailable=!1}}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(d=>typeof d=="string"):[];if(t.length===0)return h.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>ab)return h.warn(`check tool called with ${t.length} files (max: ${ab})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${ab}.`}],isError:!0};let{etsFiles:n,cppFiles:i,unsupported:o}=J8(t);o.length>0&&h.warn(`Unsupported file types in check request: ${o.join(", ")}`);let s=o.map(d=>`Unsupported file type: ${d} (only .ets and C/C++ source/header files are supported)`),a=[];n.length>0&&this.mergeCheckResult(await this.callArktsCheck(n),s,a),i.length>0&&this.mergeCheckResult(await this.callCppCheck(i),s,a);let c=s.length>0;return{content:[{type:"text",text:[a.join(`
|
|
1441
1441
|
`),s.join(`
|
|
1442
1442
|
`)].filter(d=>d.trim().length>0).join(`
|
|
1443
1443
|
`).trim()||"No diagnostics collected"}],isError:c}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:return h.warn(`ArkTS check rejected: project is DISCOVERING, files: ${e.join(", ")}`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 2:return h.warn(`ArkTS check rejected: project is SYNCING, files: ${e.join(", ")}`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 3:return h.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e});default:return h.error(`ArkTS check: unknown project state ${this.projectState}, files: ${e.join(", ")}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],isError:!0}}}async handleLspFeatureCall(e,t){let n=t.file,i=t.line,o=t.character;return typeof n!="string"||typeof i!="number"||typeof o!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:this.routeLspRequest(n,e,async()=>{if(n.endsWith(".ets"))return this.arktsCheckTool.handleLspFeature(e,{file:n,line:i,character:o});let s=e;return this.cppLspTool.handleLspFeature(s,{file:n,line:i,character:o})})}async handleWorkspaceSymbolCall(e){let t=e.query;return typeof t!="string"||t.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameter: query (non-empty string required)."}],isError:!0}:this.routeWorkspaceSymbolRequest(t)}async routeWorkspaceSymbolRequest(e){let t=this.projectState===4&&this.arktsCheckTool!==null,n=this.cppProjectState===4&&!this.cppHasNoCppCode&&this.cppLspTool!==null;if(!t&&!n){let a=this.describeArktsState(),c=this.describeCppState();return h.info(`workspaceSymbol rejected: ArkTS ${a}; C++ ${c}`),{content:[{type:"text",text:`workspaceSymbol: ArkTS ${a}; C++ ${c}`}],isError:!0}}let i=[],o=new Set;if(t)try{this.mergeSymbolItems(await this.arktsCheckTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){h.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(n)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){h.warn(`workspaceSymbol C++ query failed: ${a.message}`)}return{content:[{type:"text",text:i.length===0?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(i,null,2)}`}]}}symbolDedupKey(e){let t=e,n=t?.location?.uri??"",i=t?.location?.range?.start?.line??0,o=t?.location?.range?.start?.character??0;return`${n}:${i}:${o}`}mergeSymbolItems(e,t,n){if(e)for(let i of e){let o=this.symbolDedupKey(i);t.has(o)||(t.add(o),n.push(i))}}describeArktsState(){switch(this.projectState){case 0:return"idle";case 1:return"discovering";case 2:return`syncing (retry ${ed}s)`;case 3:return`initializing (retry ${ed}s)`;case 5:return`error (${this.initRetryCount}/${In})`;case 4:return"ready";default:return"unknown"}}describeCppState(){switch(this.cppProjectState){case 0:return"idle";case 1:return"discovering";case 2:return"syncing (retry 25s)";case 3:return"initializing (retry 10s)";case 5:return`error (${this.cppInitRetryCount}/${In})`;case 4:return this.cppHasNoCppCode?"ready (no C++ code)":"ready";default:return"unknown"}}async handleDocumentSymbolCall(e){let t=e.file;return typeof t!="string"?{content:[{type:"text",text:"Missing or invalid parameter: file (string required)."}],isError:!0}:this.routeLspRequest(t,"documentSymbol",async()=>t.endsWith(".ets")?this.arktsCheckTool.handleDocumentSymbol(t):this.cppLspTool.handleDocumentSymbol(t))}async handleCallHierarchyCall(e){let t=e.file,n=e.line,i=e.character,o=e.direction;return typeof t!="string"||typeof n!="number"||typeof i!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:o!=="incoming"&&o!=="outgoing"?{content:[{type:"text",text:'Parameter direction must be "incoming" or "outgoing".'}],isError:!0}:this.routeLspRequest(t,`callHierarchy(${o})`,async()=>t.endsWith(".ets")?this.arktsCheckTool.handleCallHierarchy({file:t,line:n,character:i,direction:o}):this.cppLspTool.handleCallHierarchy({file:t,line:n,character:i,direction:o}))}async routeArktsRequest(e,t){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:return h.warn(`ArkTS ${e} rejected: project is DISCOVERING`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 2:return h.warn(`ArkTS ${e} rejected: project is SYNCING`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 3:return h.warn(`ArkTS ${e} rejected: LSP is initializing`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 5:return this.handleErrorCheck();case 4:return t();default:return h.warn(`ArkTS ${e} rejected: unknown project state ${this.projectState}`),{content:[{type:"text",text:"Unknown project state, please retry"}],isError:!0}}}async handleIdleCheck(){if(this.ensureProjectReady(),this.config.projectPath){let e,t;return this.syncSkippedDueToLock?(e=`Another build process is running, sync deferred (waiting ${this.syncSkipStartedAt>0?Math.round((Date.now()-this.syncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,t="lock contention",this.syncSkippedDueToLock=!1):this.configChangedTriggeredResync?(e=this.arktsInitProgress?this.buildInitRetryMessage():`Config file changed, resyncing project.${this.buildRetrySuffix()}`,t="config changed",this.configChangedTriggeredResync=!1):(e=this.arktsInitProgress?this.buildInitRetryMessage():`ArkTS project detected, syncing.${this.buildRetrySuffix()}`,t="initial"),h.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(h.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:`Initializing.${this.buildRetrySuffix()}`}],isError:!0}):(h.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=In?(h.error(`Init retry limit reached (${this.initRetryCount}/${In}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${In}). Ask the user to investigate and confirm \`ohpm install\` + \`hvigor\` sync succeed manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],isError:!0}):(h.info(`Error check: auto-retrying (${this.initRetryCount}/${In})`),this.arktsInitProgress=null,this.ensureProjectReady(),{content:[{type:"text",text:`Project initialization failed, auto-retrying.${this.buildRetrySuffix()}`}],isError:!0})}buildRetrySuffix(){return` Retry in ${ed}s. Expected total: 30s\u201310min (depends on project size).`}buildInitRetryMessage(){let e=this.arktsInitProgress;if(!e)return`ArkTS init in progress.${this.buildRetrySuffix()}`;let t=Vf.indexOf(e.phase)+1,n=Math.round((Date.now()-e.startedAt)/1e3),i=this.arktsPipelineStartedAt?Math.round((Date.now()-this.arktsPipelineStartedAt)/1e3):n,o=e.percent!==null?` (${e.percent}%)`:"";return[`ArkTS init [${t}/4] ${JN[e.phase]}: ${e.detail}${o} [${n}s, total ${i}s]`,this.buildPipelineLine(e.phase),`Retry in ${ed}s. Expected total: 30s\u201310min (depends on project size).`].join(`
|
|
@@ -1534,4 +1534,4 @@ ${t.slice(-n)}`),console.log(t)}function Jee(r){let e=Ig.join(ms,r.id,"screensho
|
|
|
1534
1534
|
`);function lre(r){return[`\u9519\u8BEF: \u5F53\u524D DevEco Testing \u7248\u672C\u4E0D\u652F\u6301 testing ${r}`,"\u5EFA\u8BAE: \u8BF7\u6267\u884C devecocli testing update \u5347\u7EA7 DevEco Testing \u540E\u91CD\u8BD5"].join(`
|
|
1535
1535
|
`)}function YE(r){console.error(sre(r)),process.exitCode=1}async function dre(r,e){let t=await KE();if(!t.allowed)return YE(t.message),!1;let n=await new kd().isAvailable();if(n.kind==="not-installed")return YE(cre),!1;let i=$E(n.capabilities,r);if(i.kind==="unsupported")return YE(lre(i.command)),!1;let o=UE(r);o!==void 0&&console.error(hL(`[devecocli] \u6D4B\u8BD5\u65E5\u5FD7: ${o}`));let s=new xd(n.installation.cliPath,{logFile:o,onOutput:a=>e.push(a)});return process.exitCode=await s.run(r),o!==void 0&&ore(o)&&console.error(hL(`[devecocli] \u6D4B\u8BD5\u65E5\u5FD7\u5DF2\u4FDD\u5B58: ${o}`)),(process.exitCode??0)===0}async function ure(r){let e=GE(r),t=new Id,n=new Dd,i=Date.now(),o=!r.includes("--help")&&!r.includes("-h"),s=!1;try{s=await dre(r,t)}finally{o&&await n.report({invocation:e,output:t.text(),success:s,elapsedMs:Date.now()-i})}}var pre=new ire("testing").description("Run DevEco Testing CLI commands; every argument after `testing` is passed through as-is. Requires DevEco Testing to be installed.").helpOption(!1).allowUnknownOption(!0).allowExcessArguments(!0).action(async()=>{await ure(BE(process.argv))}),yL=pre;function wL(r){if(bN(r))return!0;let e=r.opts();if(r.name()==="log")return e.format==="json"||e.format==="hilog";if(r.name()!=="status"||e.format!=="json")return!1;let t=r.parent;for(;t!==null;){if(t.name()==="screenrecord")return!0;t=t.parent}return!1}nc(()=>{let r=vw();if(r)B.setCountryCode(r);else{let e=yw();e&&(B.setCountryCode(e.code),Ys(e.code))}});nc(()=>{Rt()&&(B.setCountryCode("CN"),Ys("CN"))});if(!gt()&&B.isCN())try{x.init(Lg.join(F(),"TraceLogData",B.countryCode)),x.startScheduler()}catch(r){h.error(`[telemetry] init failed: ${r instanceof Error?r.message:String(r)}`)}de.name("devecocli").description(`HarmonyOS application development command line tool${B.countryCode?`
|
|
1536
1536
|
|
|
1537
|
-
Privacy: ${wh(B.countryCode,ZE(B.countryCode))}`:""}`).version("1.3.
|
|
1537
|
+
Privacy: ${wh(B.countryCode,ZE(B.countryCode))}`:""}`).version("1.3.12");var vL=de.options.find(r=>r.long==="--version");vL&&(vL.flags="-V, -v, --version");de.addCommand(Bk);de.addCommand(CR);de.addCommand(TR);de.addCommand(MA);de.addCommand(sI);de.addCommand(RI);de.addCommand(TI(new wo([new zi,...Vh()])));de.addCommand(JI);de.addCommand(nN);de.addCommand(gN);de.addCommand(wN);de.addCommand(QN);de.addCommand(oO);de.addCommand(jO);de.addCommand(PM);de.addCommand(d_);de.addCommand(u_);de.addCommand(L_);de.addCommand(yL);ZS(de,process.argv,async()=>{if(!gt())try{let r=await k.new();x.setSourceType(r.sourceType);let e=r.readVersion();e&&(r.sourceType==="clt"?x.setCltVersion(e):x.setStudioVersion(e))}catch(r){h.error(`[telemetry] toolchain info failed: ${r instanceof Error?r.message:String(r)}`)}});for(let r=2;r<process.argv.length;r++){let e=process.argv[r];if(e==="-v"){process.argv[r]="-V";break}if(!e.startsWith("-"))break}var _g=process.argv.slice(2),[fre]=_g.filter(r=>!r.startsWith("-"));fre!==Rd&&_g.length>=2&&_g[_g.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);function gre(r){let e=r;for(;e.parent&&e.parent!==de;)e=e.parent;return e}var hre=new Set(["update","auth","serve","testing","design2arkts","plugin"]);de.hook("preAction",async(r,e)=>{await nk().catch(()=>{});let t=gre(e),n=ks();if(t.name()==="update"||t.name()==="docs"&&e.name()==="update")return;let i=new Pi(Lg.join(F(),"update")),o=hr();if(n==="off"&&i.getBlockedVersions().includes(o))throw new Error(`devecocli ${o} has been disabled, run \`devecocli update\` to upgrade`);process.env.DEVECO_CLI_SKIP_VERSION_CHECK||hre.has(t.name())||await k.checkVersion()});de.hook("postAction",async(r,e)=>{if(process.exitCode||ks()!=="off"||wL(e))return;await new Ec(e).checkAndNotify()});var yre=kE(process.argv),SL=yre??WE(process.argv);ZS(de,SL,()=>de.parseAsync(SL).finally(()=>{x.stopScheduler();try{Eh(Lg.join(F(),"TraceLogData",B.countryCode))}catch(r){h.error(`[telemetry] background upload spawn check failed: ${r instanceof Error?r.message:String(r)}`)}}).catch(r=>{let e=r instanceof Error?r.message:String(r??"Unknown error");console.error(mre(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&r instanceof Error&&r.stack&&console.error(r.stack),process.exit(1)}));
|
|
@@ -36,7 +36,7 @@ zYl5snR6SmrDfVmtsyz8aMqifx4gsVV2M5/owv8H3bUdOd5RbkKhzOS2Pmep0bbw
|
|
|
36
36
|
WRFUrWuQ+5ci2LLkZyIt9ffNR8W9gbmZOZZTrwSFRIT1Q433NOzCQNDjKwnekGAx
|
|
37
37
|
8o746tqqZxGCXgy2MaIIqvajhNw9Dr3NBQ8ziWyqaQBk2RrCWh6Q++Sd0b5L3RwH
|
|
38
38
|
rQ==
|
|
39
|
-
-----END CERTIFICATE-----`,er=new se.X509Certificate(Qt),Xe=[{cert:er}];function tr(r){let e=[],t=r.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let n of t)try{e.push({cert:new se.X509Certificate(n)})}catch{}return e}var Ye=new Set,j;function rr(){let r=process.env.NODE_EXTRA_CA_CERTS;if(j&&j.envValue===r)return j.anchors;let e=r?nr(r):[],t=e.length?[...Xe,...e]:Xe;return j={envValue:r,anchors:t},t}function nr(r){try{let e=tr(Kt.readFileSync(r,"utf8"));return e.length===0&&Je(r,"no parseable certificate found"),e}catch(e){return Je(r,e instanceof Error?e.message:String(e)),[]}}function Je(r,e){Ye.has(r)||(Ye.add(r),console.warn(Zt(`[devecocli] GRS TLS: failed to load NODE_EXTRA_CA_CERTS (${Yt.basename(r)}): ${e} \u2014 falling back to the built-in CA only.`)))}function ir(r){let e=[],t=new Set,n=r;for(;n&&n.raw;){let i=n.fingerprint256||n.fingerprint||"";if(!i||t.has(i))break;t.add(i);try{e.push(new se.X509Certificate(n.raw))}catch{break}let o=n.issuerCertificate??null;if(o===r)break;n=o}return e}function or(r,e,t){if(r.length===0)return new Error("[GRS TLS] Server did not provide a certificate");if(!sr(r,t))return p(()=>"[GRS TLS] No trusted anchor (built-in intermediate CA or NODE_EXTRA_CA_CERTS) matched the presented chain"),new Error("[GRS TLS] Server certificate chain is not trusted by the built-in CA or NODE_EXTRA_CA_CERTS");let n=ar(r[0],e);if(n)return n;p(()=>"[GRS TLS] Verification passed: certificate chain anchored on a trusted CA")}function sr(r,e){for(let n of e){let i=r.findIndex(o=>o.fingerprint256===n.cert.fingerprint256);if(i>=0&&Ze(r,i))return!0}let t=r[r.length-1];for(let n of e)if(n.cert.subject===t.issuer)try{if(t.verify(n.cert.publicKey)&&Ze(r,r.length-1))return!0}catch{}return!1}function Ze(r,e){try{for(let t=e;t>0;t--)if(!r[t-1].verify(r[t].publicKey))return!1;return!0}catch{return!1}}function ar(r,e){let t=Date.now();if(new Date(r.validFrom).getTime()>t||new Date(r.validTo).getTime()<t)return new Error("[GRS TLS] Server certificate is expired or not yet valid");if(!ur(r,e))return new Error(`[GRS TLS] Server certificate does not match host ${e}`)}function cr(r,e){let t=r.getPeerCertificate(!0);if(!t||!t.raw)return new Error("[GRS TLS] Server did not provide a certificate");let n=ir(t);return n.length===0?new Error("[GRS TLS] Server certificate could not be parsed"):or(n,e,rr())}function ur(r,e){let t=r.subjectAltName??"",n=e.toLowerCase();for(let i of t.split(",")){let o=i.trim();if(!o.startsWith("DNS:"))continue;let s=o.slice(4).toLowerCase();if(s===n)return!0;if(s.startsWith("*.")){let a=s.slice(1),l=n.slice(0,-a.length);if(n.endsWith(a)&&l.length>0&&!l.includes("."))return!0}}return!1}var lr=8e3,ie=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)}}},oe=class extends Xt.Agent{connectTimeoutMs;constructor(e){super(e),this.connectTimeoutMs=e?.connectTimeoutMs??lr}createConnection(e,t){let n=e.host||e.servername||"",i=e.port||443,o=`https://${n}:${i}`,s=G(o),a=new ie(t,this.connectTimeoutMs);if(a.start(),s){this.createConnectionViaProxy(e,s,n,i,a);return}return this.createDirectConnection(e,a,n)}createDirectConnection(e,t,n){let i=We.connect({...e,rejectUnauthorized:!1});return t.onDestroy(()=>i.destroy()),this.attachTlsVerification(i,t,n),i}createConnectionViaProxy(e,t,n,i,o){let s;try{s=new Jt(t)}catch{o.settle(new Error(`[GRS] Invalid proxy URL: ${t}`));return}let a=Number(s.port)||(s.protocol==="https:"?443:80),l=this.buildProxyHeaders(s,n,i);p(()=>`[GRS] Connecting via proxy ${s.hostname}:${a} to ${n}:${i}`);let g=Wt.request({host:s.hostname,port:a,method:"CONNECT",path:`${n}:${i}`,headers:l});o.onDestroy(()=>g.destroy()),g.on("connect",(h,S)=>{if(h.statusCode!==200){S.destroy(),o.settle(new Error(`[GRS] Proxy CONNECT failed: ${h.statusCode} ${h.statusMessage||""}`));return}o.onDestroy(()=>S.destroy()),this.startTlsOverTunnel(e,S,o,n)}),g.on("error",h=>{o.settle(new Error(`[GRS] Proxy connection failed: ${h.message}`))}),g.end()}startTlsOverTunnel(e,t,n,i){p(()=>"[GRS] Proxy tunnel established, starting TLS handshake");let o=We.connect({...e,socket:t,rejectUnauthorized:!1});n.onDestroy(()=>o.destroy()),this.attachTlsVerification(o,n,i)}buildProxyHeaders(e,t,n){let i={Host:`${t}:${n}`};if(e.username||e.password){let o=`${decodeURIComponent(e.username)}:${decodeURIComponent(e.password)}`;i["Proxy-Authorization"]=`Basic ${Buffer.from(o).toString("base64")}`}return i}attachTlsVerification(e,t,n){e.once("secureConnect",()=>{let i=cr(e,n);i?(e.destroy(i),t.settle(i)):t.settle(null,e)}),e.once("error",i=>{t.settle(i)})}},ae=new oe({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"}],w=class extends Error{kind;constructor(e,t){super(t),this.name="GrsError",this.kind=e}};var pr=["https://grs.dbankcloud.com/grs/2.0/router","https://grs.dbankcloud.cn/grs/2.0/router","https://grs.dbankcloud.asia/grs/2.0/router","https://grs.platform.dbankcloud.ru/grs/2.0/router"],dr="com.huawei.deveco.common-grs/0.1 (Windows;Linux;Mac) Deveco-grs/-1",fr="devecostudio",mr=8e3;async function ue(r){let e=[],t="";for(let o of pr){let s=await gr(o,r);if(s.outcome==="ok")return s.services;e.push(s.outcome),s.detail&&(t=s.detail)}if(e.some(o=>o==="incomplete"))throw new w("no-config",`GRS returned no valid configuration for country code ${r} (this region may not be supported)`);let n=process.env.HTTPS_PROXY||process.env.HTTP_PROXY,i=n?`Current proxy: ${n}. Verify the proxy is running and allows CONNECT to grs.dbankcloud.com:443. If the proxy inspects TLS, set NODE_EXTRA_CA_CERTS to a PEM file with your corporate CA \u2014 untrusted GRS certificates are rejected.`:"No proxy configured (HTTP_PROXY/HTTPS_PROXY). If you are behind a corporate firewall, set HTTPS_PROXY=http://your-proxy:port.";throw new w("network",`GRS endpoints unreachable (grs.dbankcloud.com is globally reachable). ${i}${t?` Last endpoint error: ${t}`:""}`)}async function gr(r,e){let t=`${r}?issue_country=${encodeURIComponent(e)}&app_name=${fr}`;p(()=>`[GRS] POST ${t}`);try{let n=await ne.post(t,{headers:{"User-Agent":dr},httpsAgent:ae,timeout:mr}),i=ne.parseJson(n);return i.resultCode!==0?(p(()=>`[GRS] ${r} resultCode=${i.resultCode}, skipping`),{outcome:"incomplete",detail:`resultCode=${i.resultCode}`}):hr(i.services)?(p(()=>`[GRS] hit ${r}, received ${Object.keys(i.services).length} service groups`),{outcome:"ok",services:i.services}):(p(()=>`[GRS] ${r} returned incomplete config (missing required service keys), skipping`),{outcome:"incomplete",detail:"missing required service keys"})}catch(n){let i=n instanceof Error?n.message:String(n);return p(()=>`[GRS] ${r} request failed: ${i}`),{outcome:"network",detail:i}}}function hr(r){return ce.every(({group:e,key:t})=>typeof r[e]?.[t]=="string")}import Qe from"fs";import yr from"path";var vr="com.huawei.devecostudio.region",Er={[vr]:{spaceintroduce:"https://cn.devecostudio.huawei.com",userinfo:"https://gopenuser-drcn.platform.dbankcloud.cn",agcsign:"https://connect-api.cloud.huawei.com",agcups:"https://connect-api.cloud.huawei.com",agreementservice:"https://terms-drcn.platform.dbankcloud.cn",agcdeveloper:"https://developer.huawei.com"}},Sr=1440*60*1e3,et=new Set(["CN","HK","MO"]),le=class{countryCode="";services={};resolved=!1;isCN(){return this.countryCode==="CN"}isOnlineAllowed(){return et.has(this.countryCode)}getService(e,t){let n=this.services[e]?.[t];if(!n)throw new Error(`GRS service ${e}.${t} not available`);return n}setCountryCode(e){this.countryCode=e}async resolve(){if(!this.countryCode)throw new Error("Country code not set, cannot resolve GRS");if(this.countryCode==="CN"){this.services=Er,this.resolved=!0,p(()=>"[GRS] CN uses hardcoded services, skipping GRS request");return}let e=await br(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 ue(this.countryCode);this.services=t,this.resolved=!0,await Tr(this.countryCode,t)}},E=new le;function tt(r){return yr.join(C(),`grs_${r}.json`)}async function br(r){try{let e=await Qe.promises.readFile(tt(r),"utf8"),t=JSON.parse(e);return t.countryCode!==r||Date.now()-t.fetchedAt>Sr?null:t}catch{return null}}async function Tr(r,e){let t={services:e,fetchedAt:Date.now(),countryCode:r};try{await Qe.promises.writeFile(tt(r),JSON.stringify(t),"utf8")}catch{}}var _=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 N;storageDir="";failedDir="";installId="";get disabled(){return $()||!E.isCN()}traceFileKey=Buffer.alloc(0);sessionId=rt.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){f.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=y.join(e,"failed"),this.cliVersion="1.3.11",this.nodeVersion=process.version,this.installId=Ue(e).replace(/-/g,""),this.traceFileKey=Ae(e),m.mkdirSync(e,{recursive:!0}),m.mkdirSync(this.failedDir,{recursive:!0}),f.debug(`[telemetry] init: dir=${e}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(e){this.devecoStudioVersion=e,f.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,f.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,f.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)return f.debug("[telemetry] track skipped: telemetry not initialized"),typeof t=="function"?t():void 0;if(!t){await this.record(e,0,!0,null);return}if(typeof t!="function"){let o=t;await this.record(e,o.duration_ms,o.success,o.error_code);return}let n=t,i=Date.now();try{let o=await n(),s=Date.now()-i;return await this.record(e,s,!0,null),o}catch(o){let s=Date.now()-i,a=this.toErrorCode(o);throw await this.record(e,s,!1,a),o}}async record(e,t,n,i){let o=this.buildTraceEvent(e,t,n,i);try{let s=we(JSON.stringify(o),this.traceFileKey);await m.promises.appendFile(this.currentFile(),s+`
|
|
39
|
+
-----END CERTIFICATE-----`,er=new se.X509Certificate(Qt),Xe=[{cert:er}];function tr(r){let e=[],t=r.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let n of t)try{e.push({cert:new se.X509Certificate(n)})}catch{}return e}var Ye=new Set,j;function rr(){let r=process.env.NODE_EXTRA_CA_CERTS;if(j&&j.envValue===r)return j.anchors;let e=r?nr(r):[],t=e.length?[...Xe,...e]:Xe;return j={envValue:r,anchors:t},t}function nr(r){try{let e=tr(Kt.readFileSync(r,"utf8"));return e.length===0&&Je(r,"no parseable certificate found"),e}catch(e){return Je(r,e instanceof Error?e.message:String(e)),[]}}function Je(r,e){Ye.has(r)||(Ye.add(r),console.warn(Zt(`[devecocli] GRS TLS: failed to load NODE_EXTRA_CA_CERTS (${Yt.basename(r)}): ${e} \u2014 falling back to the built-in CA only.`)))}function ir(r){let e=[],t=new Set,n=r;for(;n&&n.raw;){let i=n.fingerprint256||n.fingerprint||"";if(!i||t.has(i))break;t.add(i);try{e.push(new se.X509Certificate(n.raw))}catch{break}let o=n.issuerCertificate??null;if(o===r)break;n=o}return e}function or(r,e,t){if(r.length===0)return new Error("[GRS TLS] Server did not provide a certificate");if(!sr(r,t))return p(()=>"[GRS TLS] No trusted anchor (built-in intermediate CA or NODE_EXTRA_CA_CERTS) matched the presented chain"),new Error("[GRS TLS] Server certificate chain is not trusted by the built-in CA or NODE_EXTRA_CA_CERTS");let n=ar(r[0],e);if(n)return n;p(()=>"[GRS TLS] Verification passed: certificate chain anchored on a trusted CA")}function sr(r,e){for(let n of e){let i=r.findIndex(o=>o.fingerprint256===n.cert.fingerprint256);if(i>=0&&Ze(r,i))return!0}let t=r[r.length-1];for(let n of e)if(n.cert.subject===t.issuer)try{if(t.verify(n.cert.publicKey)&&Ze(r,r.length-1))return!0}catch{}return!1}function Ze(r,e){try{for(let t=e;t>0;t--)if(!r[t-1].verify(r[t].publicKey))return!1;return!0}catch{return!1}}function ar(r,e){let t=Date.now();if(new Date(r.validFrom).getTime()>t||new Date(r.validTo).getTime()<t)return new Error("[GRS TLS] Server certificate is expired or not yet valid");if(!ur(r,e))return new Error(`[GRS TLS] Server certificate does not match host ${e}`)}function cr(r,e){let t=r.getPeerCertificate(!0);if(!t||!t.raw)return new Error("[GRS TLS] Server did not provide a certificate");let n=ir(t);return n.length===0?new Error("[GRS TLS] Server certificate could not be parsed"):or(n,e,rr())}function ur(r,e){let t=r.subjectAltName??"",n=e.toLowerCase();for(let i of t.split(",")){let o=i.trim();if(!o.startsWith("DNS:"))continue;let s=o.slice(4).toLowerCase();if(s===n)return!0;if(s.startsWith("*.")){let a=s.slice(1),l=n.slice(0,-a.length);if(n.endsWith(a)&&l.length>0&&!l.includes("."))return!0}}return!1}var lr=8e3,ie=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)}}},oe=class extends Xt.Agent{connectTimeoutMs;constructor(e){super(e),this.connectTimeoutMs=e?.connectTimeoutMs??lr}createConnection(e,t){let n=e.host||e.servername||"",i=e.port||443,o=`https://${n}:${i}`,s=G(o),a=new ie(t,this.connectTimeoutMs);if(a.start(),s){this.createConnectionViaProxy(e,s,n,i,a);return}return this.createDirectConnection(e,a,n)}createDirectConnection(e,t,n){let i=We.connect({...e,rejectUnauthorized:!1});return t.onDestroy(()=>i.destroy()),this.attachTlsVerification(i,t,n),i}createConnectionViaProxy(e,t,n,i,o){let s;try{s=new Jt(t)}catch{o.settle(new Error(`[GRS] Invalid proxy URL: ${t}`));return}let a=Number(s.port)||(s.protocol==="https:"?443:80),l=this.buildProxyHeaders(s,n,i);p(()=>`[GRS] Connecting via proxy ${s.hostname}:${a} to ${n}:${i}`);let g=Wt.request({host:s.hostname,port:a,method:"CONNECT",path:`${n}:${i}`,headers:l});o.onDestroy(()=>g.destroy()),g.on("connect",(h,S)=>{if(h.statusCode!==200){S.destroy(),o.settle(new Error(`[GRS] Proxy CONNECT failed: ${h.statusCode} ${h.statusMessage||""}`));return}o.onDestroy(()=>S.destroy()),this.startTlsOverTunnel(e,S,o,n)}),g.on("error",h=>{o.settle(new Error(`[GRS] Proxy connection failed: ${h.message}`))}),g.end()}startTlsOverTunnel(e,t,n,i){p(()=>"[GRS] Proxy tunnel established, starting TLS handshake");let o=We.connect({...e,socket:t,rejectUnauthorized:!1});n.onDestroy(()=>o.destroy()),this.attachTlsVerification(o,n,i)}buildProxyHeaders(e,t,n){let i={Host:`${t}:${n}`};if(e.username||e.password){let o=`${decodeURIComponent(e.username)}:${decodeURIComponent(e.password)}`;i["Proxy-Authorization"]=`Basic ${Buffer.from(o).toString("base64")}`}return i}attachTlsVerification(e,t,n){e.once("secureConnect",()=>{let i=cr(e,n);i?(e.destroy(i),t.settle(i)):t.settle(null,e)}),e.once("error",i=>{t.settle(i)})}},ae=new oe({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"}],w=class extends Error{kind;constructor(e,t){super(t),this.name="GrsError",this.kind=e}};var pr=["https://grs.dbankcloud.com/grs/2.0/router","https://grs.dbankcloud.cn/grs/2.0/router","https://grs.dbankcloud.asia/grs/2.0/router","https://grs.platform.dbankcloud.ru/grs/2.0/router"],dr="com.huawei.deveco.common-grs/0.1 (Windows;Linux;Mac) Deveco-grs/-1",fr="devecostudio",mr=8e3;async function ue(r){let e=[],t="";for(let o of pr){let s=await gr(o,r);if(s.outcome==="ok")return s.services;e.push(s.outcome),s.detail&&(t=s.detail)}if(e.some(o=>o==="incomplete"))throw new w("no-config",`GRS returned no valid configuration for country code ${r} (this region may not be supported)`);let n=process.env.HTTPS_PROXY||process.env.HTTP_PROXY,i=n?`Current proxy: ${n}. Verify the proxy is running and allows CONNECT to grs.dbankcloud.com:443. If the proxy inspects TLS, set NODE_EXTRA_CA_CERTS to a PEM file with your corporate CA \u2014 untrusted GRS certificates are rejected.`:"No proxy configured (HTTP_PROXY/HTTPS_PROXY). If you are behind a corporate firewall, set HTTPS_PROXY=http://your-proxy:port.";throw new w("network",`GRS endpoints unreachable (grs.dbankcloud.com is globally reachable). ${i}${t?` Last endpoint error: ${t}`:""}`)}async function gr(r,e){let t=`${r}?issue_country=${encodeURIComponent(e)}&app_name=${fr}`;p(()=>`[GRS] POST ${t}`);try{let n=await ne.post(t,{headers:{"User-Agent":dr},httpsAgent:ae,timeout:mr}),i=ne.parseJson(n);return i.resultCode!==0?(p(()=>`[GRS] ${r} resultCode=${i.resultCode}, skipping`),{outcome:"incomplete",detail:`resultCode=${i.resultCode}`}):hr(i.services)?(p(()=>`[GRS] hit ${r}, received ${Object.keys(i.services).length} service groups`),{outcome:"ok",services:i.services}):(p(()=>`[GRS] ${r} returned incomplete config (missing required service keys), skipping`),{outcome:"incomplete",detail:"missing required service keys"})}catch(n){let i=n instanceof Error?n.message:String(n);return p(()=>`[GRS] ${r} request failed: ${i}`),{outcome:"network",detail:i}}}function hr(r){return ce.every(({group:e,key:t})=>typeof r[e]?.[t]=="string")}import Qe from"fs";import yr from"path";var vr="com.huawei.devecostudio.region",Er={[vr]:{spaceintroduce:"https://cn.devecostudio.huawei.com",userinfo:"https://gopenuser-drcn.platform.dbankcloud.cn",agcsign:"https://connect-api.cloud.huawei.com",agcups:"https://connect-api.cloud.huawei.com",agreementservice:"https://terms-drcn.platform.dbankcloud.cn",agcdeveloper:"https://developer.huawei.com"}},Sr=1440*60*1e3,et=new Set(["CN","HK","MO"]),le=class{countryCode="";services={};resolved=!1;isCN(){return this.countryCode==="CN"}isOnlineAllowed(){return et.has(this.countryCode)}getService(e,t){let n=this.services[e]?.[t];if(!n)throw new Error(`GRS service ${e}.${t} not available`);return n}setCountryCode(e){this.countryCode=e}async resolve(){if(!this.countryCode)throw new Error("Country code not set, cannot resolve GRS");if(this.countryCode==="CN"){this.services=Er,this.resolved=!0,p(()=>"[GRS] CN uses hardcoded services, skipping GRS request");return}let e=await br(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 ue(this.countryCode);this.services=t,this.resolved=!0,await Tr(this.countryCode,t)}},E=new le;function tt(r){return yr.join(C(),`grs_${r}.json`)}async function br(r){try{let e=await Qe.promises.readFile(tt(r),"utf8"),t=JSON.parse(e);return t.countryCode!==r||Date.now()-t.fetchedAt>Sr?null:t}catch{return null}}async function Tr(r,e){let t={services:e,fetchedAt:Date.now(),countryCode:r};try{await Qe.promises.writeFile(tt(r),JSON.stringify(t),"utf8")}catch{}}var _=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 N;storageDir="";failedDir="";installId="";get disabled(){return $()||!E.isCN()}traceFileKey=Buffer.alloc(0);sessionId=rt.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){f.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=y.join(e,"failed"),this.cliVersion="1.3.12",this.nodeVersion=process.version,this.installId=Ue(e).replace(/-/g,""),this.traceFileKey=Ae(e),m.mkdirSync(e,{recursive:!0}),m.mkdirSync(this.failedDir,{recursive:!0}),f.debug(`[telemetry] init: dir=${e}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(e){this.devecoStudioVersion=e,f.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,f.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,f.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)return f.debug("[telemetry] track skipped: telemetry not initialized"),typeof t=="function"?t():void 0;if(!t){await this.record(e,0,!0,null);return}if(typeof t!="function"){let o=t;await this.record(e,o.duration_ms,o.success,o.error_code);return}let n=t,i=Date.now();try{let o=await n(),s=Date.now()-i;return await this.record(e,s,!0,null),o}catch(o){let s=Date.now()-i,a=this.toErrorCode(o);throw await this.record(e,s,!1,a),o}}async record(e,t,n,i){let o=this.buildTraceEvent(e,t,n,i);try{let s=we(JSON.stringify(o),this.traceFileKey);await m.promises.appendFile(this.currentFile(),s+`
|
|
40
40
|
`,"utf8"),ke(this.storageDir)}catch{}}buildTraceEvent(e,t,n,i){let o=`${r.EVENT_PREFIX}${e.event}`,s=be.toObject(e);return s&&typeof s=="object"&&delete s.event,{countryCode:r.COUNTRY_CODE,event:o,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:rt.randomUUID(),trace_os_version:r.TRACE_OS_VERSION,os_arch:this.resolveOsArch(),action:o,trace_os_name:this.resolveOsName(),version:`${this.cliVersion}_${this.resolveOsSuffix()}`,deveco_studio_version:this.formatVersion(this.devecoStudioVersion),command_line_version:this.formatVersion(this.cltVersion),source_type:this.sourceType,session_id:this.sessionId,node_version:this.nodeVersion,ram:this.resolveTotalRam(),duration_ms:t,success:n,error_code:i,event_detail:s}}}toErrorCode(e){return e instanceof Error?e.code??e.name:"UnknownError"}resolveOsArch(){let e=V.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=V.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 V.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(V.totalmem()/1024)}KB`}formatVersion(e){return e?`${e}_${this.resolveOsSuffix()}`:""}dateString(){let e=new Date,t=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0");return`${e.getFullYear()}-${t}-${n}`}currentFile(){return y.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){f.debug("[telemetry] scheduler not started (telemetry disabled)");return}f.debug(`[telemetry] scheduler started (flush every ${F/1e3}s, retry failed every ${B/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},F)},F),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},B)},B)}stopScheduler(){this.initialTimer&&(clearTimeout(this.initialTimer),this.initialTimer=null),this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null),this.retryInitialTimer&&(clearTimeout(this.retryInitialTimer),this.retryInitialTimer=null),this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),f.debug("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)return f.debug("[telemetry] flush skipped: telemetry not initialized"),!0;let e=await this.listPendingFiles(),t=!0;for(let n of e)await this.flushFile(n)||(t=!1);return Oe(this.storageDir),t}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)return f.debug("[telemetry] retryFailed skipped: telemetry not initialized"),!0;await this.reclaimStalePending();let e=Date.now(),t;try{t=await m.promises.readdir(this.failedDir)}catch{return!0}let n=t.filter(o=>o.startsWith("telemetry-")&&o.endsWith(".txt")).map(o=>y.join(this.failedDir,o)),i=!0;for(let o of n){let s=y.basename(o),a=Fe(s);if(a!==null){if(e-a>_e){try{await m.promises.unlink(o)}catch{}continue}await this.flushFile(o)||(i=!1)}}return i||f.warn("[telemetry] retry failed"),Me(this.storageDir),i}async reclaimStalePending(){let e=Date.now();for(let t of[this.storageDir,this.failedDir]){let n;try{n=await m.promises.readdir(t)}catch{continue}for(let i of n)Be(i)&&await this.reclaimOrphan(y.join(t,i),e)}}async reclaimOrphan(e,t){let n;try{let g=await m.promises.stat(e);if(t-g.mtimeMs<Ne)return;n=g.size}catch{return}let i=y.dirname(e),o=Q(y.basename(e));if(o===null)return;let s=await this.claimOrphan(e,i,o);if(s===null)return;let a=y.join(i,o),l=A-await this.fileSize(a);if(n>l){try{await m.promises.unlink(s)}catch{}f.warn(`[telemetry] dropped stale orphan pending: ${s} (${n} bytes > budget ${l})`);return}if(await this.mergeOrphanInto(s,a)){f.warn(`[telemetry] reclaimed orphan pending: ${s} (${n} bytes)`);return}f.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${n} bytes)`)}async claimOrphan(e,t,n){let i=y.join(t,`${n}.pending.reclaim-${process.pid}-${Date.now()}`);try{await m.promises.rename(e,i)}catch{return null}return await this.touch(i),i}async mergeOrphanInto(e,t){try{await m.promises.appendFile(t,await m.promises.readFile(e))}catch(n){return f.warn(`[telemetry] merge orphan pending failed: ${e} -> ${t}: ${n instanceof Error?n.message:String(n)}`),!1}try{await m.promises.unlink(e)}catch(n){f.warn(`[telemetry] merged but failed to remove orphan pending: ${e}: ${n instanceof Error?n.message:String(n)}`)}return!0}async fileSize(e){try{return(await m.promises.stat(e)).size}catch{return 0}}async touch(e){let t=new Date;try{await m.promises.utimes(e,t,t)}catch{}}runExclusive(e){let t=()=>e(),n=this.flushChain.then(t,t);return this.flushChain=n.then(()=>{},()=>{}),n}async listPendingFiles(){let e;try{e=await m.promises.readdir(this.storageDir)}catch{return[]}return e.filter(t=>t.startsWith("telemetry-")&&t.endsWith(".txt")).map(t=>y.join(this.storageDir,t)).sort()}async flushFile(e){let t=await this.fileSize(e);if(t>A){f.warn(`[telemetry] ${y.basename(e)} is ${t} bytes (> ${A}), dropped without uploading`);try{await m.promises.unlink(e)}catch{}return!0}let n=e+".pending";try{await m.promises.rename(e,n)}catch{return!1}await this.touch(n);let i;try{i=await m.promises.readFile(n,"utf8")}catch{return!1}let o=i.split(`
|
|
41
41
|
`).map(s=>s.trim()).filter(Boolean);if(o.length===0){try{await m.promises.unlink(n)}catch{}return!0}return this.uploadInBatches(n,o)}collectDecryptBatch(e,t){let n=[],i=16,o=t;for(;o<e.length&&n.length<r.MAX_BATCH;){let s=xe(e[o],this.traceFileKey);if(s===null){o++;continue}let a=Buffer.byteLength(s,"utf8")+1;if(n.length>0&&i+a>r.MAX_PAYLOAD_BYTES)break;n.push(s),i+=a,o++}return{batch:n,next:o}}async uploadInBatches(e,t){let n=0;for(;n<t.length;){let i=n,{batch:o,next:s}=this.collectDecryptBatch(t,n);n=s;let a=this.buildPayloadItems(o);if(a.length===0)continue;let l=JSON.stringify(a),g=!1;try{g=await this.uploader.upload(l,this.installId)}catch{}if(!g){f.warn("[telemetry] upload failed");let h=t.slice(i).join(`
|
|
42
42
|
`)+`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@deveco/deveco-cli-common",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.12",
|
|
4
4
|
"description": "HarmonyOS application development command line tool",
|
|
5
5
|
"supportedDocsApi": 1,
|
|
6
6
|
"license": "MIT",
|
|
@@ -67,7 +67,7 @@
|
|
|
67
67
|
"ui-verification-mcp": "0.0.20",
|
|
68
68
|
"xpath": "^0.0.35",
|
|
69
69
|
"zod": "^4.4.3",
|
|
70
|
-
"@deveco/deveco-cli-knowledgebase": "1.3.
|
|
70
|
+
"@deveco/deveco-cli-knowledgebase": "1.3.12"
|
|
71
71
|
},
|
|
72
72
|
"devDependencies": {
|
|
73
73
|
"@types/adm-zip": "^0.5.8",
|
package/skills/index.json
CHANGED