@deveco-test/deveco-cli-common 0.1.7 → 1.3.6-Test.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,94 +1,109 @@
1
1
  #!/usr/bin/env node
2
- var yS=Object.defineProperty;var vS=(r,e)=>{for(var t in e)yS(r,t,{get:e[t],enumerable:!0})};import*as Lc from"path";import{program as de}from"commander";import{red as LM}from"colorette";var Eo={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},Yi={USER_AGENT:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",ACCEPT_LANGUAGE:"zh-CN"};var Ee={APP_ID:"1009",CONFIG_DIR_NAME:".config",APP_NAME:"deveco-cli",TOKEN_FILE_NAME:"token.enc",KEY_FILE_NAME:"token.dek",API_VERSION:"1.0.0",AUTH_SOURCE_DEVECO_CODE:"deveco-code"},X={LOGIN_URL:"https://devecostudio.huawei.com",CN_LOGIN_URL:"https://cn.devecostudio.huawei.com",AUTH_APPLY_PATH:"console/DevEcoIDE/apply",TEMP_TOKEN_CHECK_PATH:"authrouter/auth/api/temptoken/check",JWT_TOKEN_CHECK_PATH:"authrouter/auth/api/jwToken/check",LOGIN_SUCCESS_PATH:"console/DevEcoCLI/loginSuccess",LOGIN_FAILED_PATH:"console/DevEcoCLI/loginFailed",LOGOUT_PATH:"authrouter/auth/api/logout",AGC_TEAM_LIST_URL:"https://connect-api.cloud.huawei.com/api/ups/user-permission-service/v1/user-team-list"},Ur={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},Co={TMS_URL:"https://terms-drcn.platform.dbankcloud.cn/agreementservice/user",PRIVACY_ID:"20000257",PRIVACY_URL:"https://legal.cloud.huawei.com/terms/scope/huawei/deveco-cli/privacy-statement.htm?code=CN&language=zh-CN&branchid=0&contenttag=default"},Po={baseUrl:X.LOGIN_URL,authUrl:X.AUTH_APPLY_PATH,tempTokenCheckUrl:X.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:X.JWT_TOKEN_CHECK_PATH,successRedirectUrl:X.LOGIN_SUCCESS_PATH,failedRedirectUrl:X.LOGIN_FAILED_PATH,logoutUrl:X.LOGOUT_PATH,agcTeamListUrl:X.AGC_TEAM_LIST_URL,appId:Ee.APP_ID,timeout:Eo.LOGIN_TIMEOUT_MS,countryCode:"CN"};import{Command as rE}from"commander";import{green as sl,red as hm,yellow as al}from"colorette";import Q from"fs";import*as j from"path";import It from"json5";import*as Mc from"fs";import*as Ce from"path";function m(r){if(process.env.DEVECO_CLI_DEBUG){let e=typeof r=="function"?r():r;console.log(`[DEBUG] ${e}`)}}var E=class r{static ASCII_CONTROL_MAX=31;static ASCII_DELETE=127;static parsePositiveInteger(e,t="value"){let n=e.trim();if(!/^\d+$/.test(n))throw new Error(`${t} must be a positive integer`);let o=Number.parseInt(n,10);if(!Number.isInteger(o)||o<=0)throw new Error(`${t} must be a positive integer`);return o}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
3
- `)}static parseDurationToSeconds(e,t="value"){let o=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!o)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported).`);let i=o[1];if((o[2]??"s")==="s")return r.parsePositiveInteger(i,t);if(!/^\d+(?:\.\d)?$/.test(i))throw new Error(`${t} supports a maximum of 1 decimal place for minutes (e.g. 2.5m).`);let a=Number.parseFloat(i);if(!Number.isFinite(a)||a<=0)throw new Error(`${t} must be a positive duration.`);return Math.round(a*60)}static filterLogsByRelativeWindow(e,t,n,o=new Date){if(!t&&!n)return e;let[i,s]=r.resolveTimeBounds(t,n,o),a=e.split(/\r?\n/),c=[],l=!1;for(let d of a){let g=r.extractTimestampFromLogLine(d,o);g&&(l=r.isWithinBounds(g,i,s)),l&&c.push(d)}return c.join(`
4
- `)}static resolveTimeBounds(e,t,n){let o=e?new Date(n.getTime()-e*1e3):null,i=t?new Date(n.getTime()-t*1e3):null;return o&&i?o<i?[o,i]:[i,o]:o?[o,n]:i?[null,i]:[null,null]}static isWithinBounds(e,t,n){let o=e.getTime(),i=t?Math.floor(t.getTime()/1e3)*1e3:null,s=n?Math.floor(n.getTime()/1e3)*1e3+999:null;return!(i!==null&&o<i||s!==null&&o>s)}static extractTimestampFromLogLine(e,t){let n=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!n)return null;let o=t.getFullYear(),i=Number.parseInt(n[1],10)-1,s=Number.parseInt(n[2],10),a=Number.parseInt(n[3],10),c=Number.parseInt(n[4],10),l=Number.parseInt(n[5],10),d=n[6]??"0",g=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),y=new Date(o,i,s,a,c,l,g);return y.getTime()>t.getTime()+1440*60*1e3&&y.setFullYear(o-1),y}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertBundleNameStrict(e){if(e.length<7||e.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${e.length}`);if(e.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let t=e.split(".");if(t.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let n=/^[a-zA-Z0-9_]+$/;for(let o=0;o<t.length;o++){let i=t[o];if(!n.test(i))throw new Error(`Segment "${i}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(o===0){if(!/^[a-zA-Z]/.test(i))throw new Error(`First segment "${i}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(i))throw new Error(`Segment "${i}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(i))throw new Error(`Segment "${i}" must end with a letter or digit.`)}}static assertModuleName(e){this.assertSafeName(e,"module name")}static assertAbilityName(e){this.assertSafeName(e,"ability name")}static assertSafeName(e,t){if(!/^[A-Za-z0-9_.]+$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(n=>{let o=n.charCodeAt(0);return o<=r.ASCII_CONTROL_MAX||o===r.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let n=`'${e.replace(/'/g,"'\\''")}'`;return m(`quotePosixShellArg: ${e} -> ${n}`),n}static assertCrashFilename(e){if(!/^\w+-[\w.]+-\d+-\d+$/.test(e))throw new Error(`Invalid crash log filename: ${JSON.stringify(e)}`)}static assertHilogLevel(e){if(!/^[DIWEF]$/.test(e))throw new Error(`Invalid log level: ${e}`)}static resolvePathWithinRoot(e,t){if(Ce.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let n=Ce.resolve(Ce.normalize(e),t);return r.ensurePathWithinRoot(e,n)}static ensurePathWithinRoot(e,t){let n=Ce.normalize(e),o=Ce.relative(n,t);if(o.split(Ce.sep)[0]===".."||Ce.isAbsolute(o))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||Ce.isAbsolute(e)}static isPathContained(e,t){let n=Ce.resolve(t,e),o=Ce.relative(t,n);return r.isPathEscaping(o)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){let n=r.isPathContained(e,t);if(!n.contained)return n;let o;try{o=Mc.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let i=Ce.resolve(o,e),s;try{s=Mc.realpathSync(i)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${i}`}}return r.isPathContained(s,o)}};import _p from"crypto";import rt from"fs";import qc from"os";import qr from"path";import SS from"https";var dp={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var Ki=class r{static ENDPOINT=dp.devecoApiTraceUpload;static SENDER="deveco-cli";async upload(e,t){let n={"Content-Type":"application/json",sender:r.SENDER,deviceid:t.replace(/-/g,""),"Content-Length":String(Buffer.byteLength(e,"utf8"))};try{let{body:o}=await this.httpPost(r.ENDPOINT,n,Buffer.from(e,"utf8"),6e4);return r.isSuccess(o)}catch{return!1}}static isSuccess(e){try{let t=JSON.parse(e),n=t?.code??t?.errorCode;return String(n)==="200"}catch{return!1}}async httpPost(e,t,n,o){let i=new URL(e);return new Promise((s,a)=>{let c=SS.request({protocol:i.protocol,hostname:i.hostname,port:i.port||(i.protocol==="https:"?443:80),path:i.pathname+i.search,method:"POST",headers:t,timeout:o},l=>{let d=[];l.on("data",g=>d.push(g)),l.on("end",()=>{s({code:l.statusCode??0,body:Buffer.concat(d).toString("utf8")})})});c.on("timeout",()=>{c.destroy(new Error("request timeout"))}),c.on("error",a),c.write(n),c.end()})}};var up={identity:r=>r,camelCase:r=>r,snakeCase:r=>r.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()},_c=class{constructor(e={}){this.config=e}serialize(e){let t=this.transform(e);return this.config.pretty?JSON.stringify(t,null,2):JSON.stringify(t)}toObject(e){return this.transform(e)}transform(e){if(e==null)return e;if(Array.isArray(e))return e.map(i=>this.transform(i));if(typeof e!="object")return e;let t=this.config.namingStrategy??up.identity,n=this.config.fieldNames??{},o={};for(let[i,s]of Object.entries(e)){let a=n[i]??t(i);o[a]=this.transform(s)}return o}},pp=new _c({namingStrategy:up.snakeCase,fieldNames:{}});import Ao from"crypto";import Xi from"fs";import bS from"path";var Zi="aes-256-gcm",ES=12,CS="deveco-cli-trace-file",PS="trace-file-secret",fp=32;function mp(r){try{let e=Xi.readFileSync(r,"utf8").trim();return e&&Buffer.from(e,"base64").length===fp?e:null}catch{return null}}function hp(r){let e=bS.join(r,PS),t=mp(e);if(t)return Fc(t);let n=Ao.randomBytes(fp).toString("base64");try{Xi.mkdirSync(r,{recursive:!0});try{Xi.writeFileSync(e,n,{flag:"wx"})}catch{let o=mp(e);if(o)return Fc(o);Xi.writeFileSync(e,n)}}catch{}return Fc(n)}function Fc(r){return Ao.createHash("sha256").update(CS).update(r).digest()}function jc(r,e){let t=Ao.randomBytes(ES),n=Ao.createCipheriv(Zi,e,t),o=Buffer.concat([n.update(r,"utf8"),n.final()]),i={version:1,algorithm:Zi,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:n.getAuthTag().toString("base64")};return JSON.stringify(i)}function gp(r,e){let t;try{t=JSON.parse(r)}catch{return null}if(!AS(t))return r;try{let n=Ao.createDecipheriv(Zi,e,Buffer.from(t.iv,"base64"));return n.setAuthTag(Buffer.from(t.authTag,"base64")),Buffer.concat([n.update(Buffer.from(t.ciphertext,"base64")),n.final()]).toString("utf8")}catch{return null}}function AS(r){if(!r||typeof r!="object")return!1;let e=r;return e.version===1&&e.algorithm===Zi&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as H from"fs";import*as is from"path";import Z from"fs";import*as Qi from"os";import*as _ from"path";import IS from"json5";var $c="Huawei";var wp=3;function es(r){if(!Z.existsSync(r)||!Z.statSync(r).isDirectory())return!1;let e=Z.existsSync(_.join(r,"build-profile.json5")),t=Z.existsSync(_.join(r,"hvigorfile.js"))||Z.existsSync(_.join(r,"hvigorfile.ts"));if(!e||!t)return!1;try{let n=Z.readFileSync(_.join(r,"build-profile.json5"),"utf-8");return IS.parse(n).app!==void 0}catch{return!1}}function Hc(r,e,t){if(e>=t)return null;let n=kS(r),o=DS(n);if(o)return o;for(let i of n){let s=Hc(i,e+1,t);if(s)return s}return null}function kS(r){try{let e=Z.readdirSync(r,{withFileTypes:!0}),t=[];for(let n of e)n.isDirectory()&&t.push(_.join(r,n.name));return t}catch{return[]}}function DS(r){for(let e of r)if(es(e))return e;return null}function _t(r){if(!r||r.trim()==="")return null;let e=_.resolve(r),t;try{t=Z.realpathSync(e)}catch{t=e}if(!Z.existsSync(t))return null;if(es(t))return t;let n=t;for(let o=1;o<=3;o++){let i=_.dirname(n);if(i===n)break;if(es(i))return i;n=i}if(Z.statSync(t).isDirectory()){let o=Hc(t,0,wp);if(o)return o}return null}function ts(r){if(!r||r.trim()==="")return null;let e=_.resolve(r),t;try{t=Z.realpathSync(e)}catch{t=e}return!Z.existsSync(t)||!Z.statSync(t).isDirectory()?null:es(t)?t:Hc(t,0,wp)}var yp="DevEco Studio";function Sp(){if(process.platform==="win32"){let r=[_.join("C:\\Program Files",$c,yp),_.join("C:\\Program Files (x86)",$c,yp)];return vp(r)}if(process.platform==="darwin"){let r=["/Applications/DevEco Studio.app",_.join(process.env.HOME??"","Applications","DevEco Studio.app")];return vp(r)}return null}function vp(r){for(let e of r)if(Z.existsSync(e))return e;return null}function Io(r,e){let t=e?_.join("standardIndex","index.js"):"index.js";return Z.existsSync(_.join(r,"ace-server"))?_.join(r,"ace-server","out",t):_.join(r,"out",t)}function rs(r){return Z.existsSync(Io(r,!0))}var TS=[".idea",".deveco","cxx","compile_commands.json"];function Wr(r){return _.join(r,...TS)}function bp(r){return new Promise(e=>setTimeout(e,r))}var RS=new Set(["c","cc","cpp","cxx","h","hh","hpp","hxx"]);function Vr(r){let e=_.extname(r).replace(/^\./,"").toLowerCase();return e.length>0&&RS.has(e)}function ns(r){return _.extname(r).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function ve(r){let e=r.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function xS(r){return ve(r)}function Gr(r){let e=xS(r);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function rr(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??_.join(Qi.homedir(),"AppData","Local");return _.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?_.join(Qi.homedir(),"Library","Logs","devecocli-mcp-server"):_.join(Qi.homedir(),".local","share","devecocli-mcp-server","logs")}function Ep(r,e){let t=LS(e),n=NS(t,r);if(n!==null)return n;let o=Date.now(),s=`${r.replace(/:/g,"\\:")}=${o}`,a=OS(t,r,s);return MS(e,a),o}function LS(r){let e;try{e=Z.readFileSync(r,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function NS(r,e){for(let t of r){let n=t.indexOf("=");if(n<=0||t.slice(0,n).replace(/\\:/g,":")!==e)continue;let i=parseInt(t.slice(n+1),10);return Number.isFinite(i)&&i>0?i:null}return null}function OS(r,e,t){let n=!1,o=r.map(i=>{if(n)return i;let s=i.indexOf("=");return s<=0?i:i.slice(0,s).replace(/\\:/g,":")===e?(n=!0,t):i});return n||o.push(t),o}function MS(r,e){try{Z.mkdirSync(_.dirname(r),{recursive:!0})}catch{}try{Z.writeFileSync(r,e.join(`
2
+ var YP=Object.defineProperty;var KP=(n,e)=>{for(var t in e)YP(n,t,{get:e[t],enumerable:!0})};import*as Bd from"path";import{program as se}from"commander";import{red as pU}from"colorette";var Ro={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},ua={USER_AGENT:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",ACCEPT_LANGUAGE:"zh-CN"};var be={APP_ID:"1009",CONFIG_DIR_NAME:".config",APP_NAME:"deveco-cli",TOKEN_FILE_NAME:"token.enc",KEY_FILE_NAME:"token.dek",API_VERSION:"1.0.0",AUTH_SOURCE_DEVECO_CODE:"deveco-code"},oe={LOGIN_URL:"https://devecostudio.huawei.com",CN_LOGIN_URL:"https://cn.devecostudio.huawei.com",AUTH_APPLY_PATH:"console/DevEcoIDE/apply",TEMP_TOKEN_CHECK_PATH:"authrouter/auth/api/temptoken/check",JWT_TOKEN_CHECK_PATH:"authrouter/auth/api/jwToken/check",LOGIN_SUCCESS_PATH:"console/DevEcoCLI/loginSuccess",LOGIN_FAILED_PATH:"console/DevEcoCLI/loginFailed",LOGOUT_PATH:"authrouter/auth/api/logout",AGC_TEAM_LIST_URL:"https://connect-api.cloud.huawei.com/api/ups/user-permission-service/v1/user-team-list"},Dn={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},Do={TMS_URL:"https://terms-drcn.platform.dbankcloud.cn/agreementservice/user",PRIVACY_ID:"20000257",PRIVACY_URL:"https://legal.cloud.huawei.com/terms/scope/huawei/deveco-cli/privacy-statement.htm?code=CN&language=zh-CN&branchid=0&contenttag=default"},xo={baseUrl:oe.LOGIN_URL,authUrl:oe.AUTH_APPLY_PATH,tempTokenCheckUrl:oe.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:oe.JWT_TOKEN_CHECK_PATH,successRedirectUrl:oe.LOGIN_SUCCESS_PATH,failedRedirectUrl:oe.LOGIN_FAILED_PATH,logoutUrl:oe.LOGOUT_PATH,agcTeamListUrl:oe.AGC_TEAM_LIST_URL,appId:be.APP_ID,timeout:Ro.LOGIN_TIMEOUT_MS,countryCode:"CN"};import{Command as Xk}from"commander";import{green as Va,red as bg,yellow as Ga}from"colorette";import wg from"json5";import*as Fo from"fs";import*as Sg from"path";import Y from"fs";import*as F from"path";import Vt from"json5";import*as Wd from"fs";import*as Oe from"path";function m(n){if(process.env.DEVECO_CLI_DEBUG){let e=typeof n=="function"?n():n;console.log(`[DEBUG] ${e}`)}}var E=class n{static ASCII_CONTROL_MAX=31;static ASCII_DELETE=127;static parsePositiveInteger(e,t="value"){let r=e.trim();if(!/^\d+$/.test(r))throw new Error(`${t} must be a positive integer`);let i=Number.parseInt(r,10);if(!Number.isInteger(i)||i<=0)throw new Error(`${t} must be a positive integer`);return i}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
3
+ `)}static parseDurationToSeconds(e,t="value"){let i=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!i)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported).`);let o=i[1];if((i[2]??"s")==="s")return n.parsePositiveInteger(o,t);if(!/^\d+(?:\.\d)?$/.test(o))throw new Error(`${t} supports a maximum of 1 decimal place for minutes (e.g. 2.5m).`);let a=Number.parseFloat(o);if(!Number.isFinite(a)||a<=0)throw new Error(`${t} must be a positive duration.`);return Math.round(a*60)}static filterLogsByRelativeWindow(e,t,r,i=new Date){if(!t&&!r)return e;let[o,s]=n.resolveTimeBounds(t,r,i),a=e.split(/\r?\n/),c=[],l=!1;for(let d of a){let g=n.extractTimestampFromLogLine(d,i);g&&(l=n.isWithinBounds(g,o,s)),l&&c.push(d)}return c.join(`
4
+ `)}static resolveTimeBounds(e,t,r){let i=e?new Date(r.getTime()-e*1e3):null,o=t?new Date(r.getTime()-t*1e3):null;return i&&o?i<o?[i,o]:[o,i]:i?[i,r]:o?[null,o]:[null,null]}static isWithinBounds(e,t,r){let i=e.getTime(),o=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(o!==null&&i<o||s!==null&&i>s)}static extractTimestampFromLogLine(e,t){let r=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!r)return null;let i=t.getFullYear(),o=Number.parseInt(r[1],10)-1,s=Number.parseInt(r[2],10),a=Number.parseInt(r[3],10),c=Number.parseInt(r[4],10),l=Number.parseInt(r[5],10),d=r[6]??"0",g=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),w=new Date(i,o,s,a,c,l,g);return w.getTime()>t.getTime()+1440*60*1e3&&w.setFullYear(i-1),w}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertBundleNameStrict(e){if(e.length<7||e.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${e.length}`);if(e.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let t=e.split(".");if(t.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let r=/^[a-zA-Z0-9_]+$/;for(let i=0;i<t.length;i++){let o=t[i];if(!r.test(o))throw new Error(`Segment "${o}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(i===0){if(!/^[a-zA-Z]/.test(o))throw new Error(`First segment "${o}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(o))throw new Error(`Segment "${o}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(o))throw new Error(`Segment "${o}" must end with a letter or digit.`)}}static assertModuleName(e){this.assertSafeName(e,"module name")}static assertAbilityName(e){this.assertSafeName(e,"ability name")}static assertSafeName(e,t){if(!/^[A-Za-z0-9_.]+$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(r=>{let i=r.charCodeAt(0);return i<=n.ASCII_CONTROL_MAX||i===n.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let r=`'${e.replace(/'/g,"'\\''")}'`;return m(`quotePosixShellArg: ${e} -> ${r}`),r}static assertCrashFilename(e){if(!/^\w+-[\w.]+-\d+-\d+$/.test(e))throw new Error(`Invalid crash log filename: ${JSON.stringify(e)}`)}static assertHilogLevel(e){if(!/^[DIWEF]$/.test(e))throw new Error(`Invalid log level: ${e}`)}static resolvePathWithinRoot(e,t){if(Oe.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=Oe.resolve(Oe.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=Oe.normalize(e),i=Oe.relative(r,t);if(i.split(Oe.sep)[0]===".."||Oe.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||Oe.isAbsolute(e)}static isPathContained(e,t){let r=Oe.resolve(t,e),i=Oe.relative(t,r);return n.isPathEscaping(i)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){let r=n.isPathContained(e,t);if(!r.contained)return r;let i;try{i=Wd.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=Oe.resolve(i,e),s;try{s=Wd.realpathSync(o)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${o}`}}return n.isPathContained(s,i)}};import _h from"crypto";import ae from"fs";import Ca from"os";import ct from"path";import ZP from"https";var oh={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var pa=class n{static ENDPOINT=oh.devecoApiTraceUpload;static SENDER="deveco-cli";async upload(e,t){let r={"Content-Type":"application/json",sender:n.SENDER,deviceid:t.replace(/-/g,""),"Content-Length":String(Buffer.byteLength(e,"utf8"))};try{let{body:i}=await this.httpPost(n.ENDPOINT,r,Buffer.from(e,"utf8"),6e4);return n.isSuccess(i)}catch{return!1}}static isSuccess(e){try{let t=JSON.parse(e),r=t?.code??t?.errorCode;return String(r)==="200"}catch{return!1}}async httpPost(e,t,r,i){let o=new URL(e);return new Promise((s,a)=>{let c=ZP.request({protocol:o.protocol,hostname:o.hostname,port:o.port||(o.protocol==="https:"?443:80),path:o.pathname+o.search,method:"POST",headers:t,timeout:i},l=>{let d=[];l.on("data",g=>d.push(g)),l.on("end",()=>{s({code:l.statusCode??0,body:Buffer.concat(d).toString("utf8")})})});c.on("timeout",()=>{c.destroy(new Error("request timeout"))}),c.on("error",a),c.write(r),c.end()})}};var sh={identity:n=>n,camelCase:n=>n,snakeCase:n=>n.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()},Vd=class{constructor(e={}){this.config=e}serialize(e){let t=this.transform(e);return this.config.pretty?JSON.stringify(t,null,2):JSON.stringify(t)}toObject(e){return this.transform(e)}transform(e){if(e==null)return e;if(Array.isArray(e))return e.map(o=>this.transform(o));if(typeof e!="object")return e;let t=this.config.namingStrategy??sh.identity,r=this.config.fieldNames??{},i={};for(let[o,s]of Object.entries(e)){let a=r[o]??t(o);i[a]=this.transform(s)}return i}},ah=new Vd({namingStrategy:sh.snakeCase,fieldNames:{}});import Ao from"crypto";import ma from"fs";import QP from"path";var fa="aes-256-gcm",eC=12,tC="deveco-cli-trace-file",rC="trace-file-secret",lh=32;function ch(n){try{let e=ma.readFileSync(n,"utf8").trim();return e&&Buffer.from(e,"base64").length===lh?e:null}catch{return null}}function dh(n){let e=QP.join(n,rC),t=ch(e);if(t)return Gd(t);let r=Ao.randomBytes(lh).toString("base64");try{ma.mkdirSync(n,{recursive:!0});try{ma.writeFileSync(e,r,{flag:"wx"})}catch{let i=ch(e);if(i)return Gd(i);ma.writeFileSync(e,r)}}catch{}return Gd(r)}function Gd(n){return Ao.createHash("sha256").update(tC).update(n).digest()}function uh(n,e){let t=Ao.randomBytes(eC),r=Ao.createCipheriv(fa,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o={version:1,algorithm:fa,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:r.getAuthTag().toString("base64")};return JSON.stringify(o)}function ph(n,e){let t;try{t=JSON.parse(n)}catch{return null}if(!nC(t))return n;try{let r=Ao.createDecipheriv(fa,e,Buffer.from(t.iv,"base64"));return r.setAuthTag(Buffer.from(t.authTag,"base64")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"base64")),r.final()]).toString("utf8")}catch{return null}}function nC(n){if(!n||typeof n!="object")return!1;let e=n;return e.version===1&&e.algorithm===fa&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as J from"fs";import*as Sa from"path";import re from"fs";import{spawn as iC}from"child_process";import*as ha from"os";import*as H from"path";import oC from"json5";var qd="Huawei";var yh=3;function ga(n){if(!re.existsSync(n)||!re.statSync(n).isDirectory())return!1;let e=re.existsSync(H.join(n,"build-profile.json5")),t=re.existsSync(H.join(n,"hvigorfile.js"))||re.existsSync(H.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=re.readFileSync(H.join(n,"build-profile.json5"),"utf-8");return oC.parse(r).app!==void 0}catch{return!1}}function zd(n,e,t){if(e>=t)return null;let r=sC(n),i=aC(r);if(i)return i;for(let o of r){let s=zd(o,e+1,t);if(s)return s}return null}function sC(n){try{let e=re.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(H.join(n,r.name));return t}catch{return[]}}function aC(n){for(let e of n)if(ga(e))return e;return null}function lr(n){if(!n||n.trim()==="")return null;let e=H.resolve(n),t;try{t=re.realpathSync(e)}catch{t=e}if(!re.existsSync(t))return null;if(ga(t))return t;let r=t;for(let i=1;i<=3;i++){let o=H.dirname(r);if(o===r)break;if(ga(o))return o;r=o}if(re.statSync(t).isDirectory()){let i=zd(t,0,yh);if(i)return i}return null}function ya(n){if(!n||n.trim()==="")return null;let e=H.resolve(n),t;try{t=re.realpathSync(e)}catch{t=e}return!re.existsSync(t)||!re.statSync(t).isDirectory()?null:ga(t)?t:zd(t,0,yh)}var mh="DevEco Studio";function wh(){if(process.platform==="win32"){let n=[H.join("C:\\Program Files",qd,mh),H.join("C:\\Program Files (x86)",qd,mh)];return fh(n)}if(process.platform==="darwin"){let n=["/Applications/DevEco Studio.app",H.join(process.env.HOME??"","Applications","DevEco Studio.app")];return fh(n)}return null}function fh(n){for(let e of n)if(re.existsSync(e))return e;return null}function mi(n,e){let t=e?H.join("standardIndex","index.js"):"index.js";return re.existsSync(H.join(n,"ace-server"))?H.join(n,"ace-server","out",t):H.join(n,"out",t)}function wa(n){return re.existsSync(mi(n,!0))}var cC=5e3,lC=64*1024,hh=new Map;function vh(n,e){let t=dC(n),r=hh.get(t);if(r)return r;let i=uC(n,e).catch(()=>!1);return hh.set(t,i),i}function dC(n){let e=H.resolve(n).replace(/\\/g,"/");return process.platform==="win32"?e.toLowerCase():e}function gh(n){try{let e=JSON.parse(n.trim());return Array.isArray(e.protocols)?e.protocols.includes("--socket"):null}catch{return null}}function uC(n,e){let t=mi(n,!0);if(!re.existsSync(t))return Promise.resolve(!1);let r=e||process.execPath||"node",i=[t,"--list-protocols"];return h.debug(`Executing: ${r} ${i.join(" ")}`),new Promise(o=>{let s=iC(r,i,{stdio:["ignore","pipe","ignore"],windowsHide:!0}),a="",c=!1,l=g=>{c||(c=!0,clearTimeout(d),s.exitCode===null&&s.signalCode===null&&s.kill(),o(g))},d=setTimeout(()=>l(!1),cC);s.stdout?.on("data",g=>{a=(a+g.toString("utf8")).slice(-lC);let w=gh(a);w!==null&&l(w)}),s.on("error",()=>l(!1)),s.on("close",()=>l(gh(a)??!1))})}var pC=[".idea",".deveco","cxx","compile_commands.json"];function xn(n){return H.join(n,...pC)}function bh(n){return new Promise(e=>setTimeout(e,n))}var mC=new Set(["c","cc","cpp","cxx","h","hh","hpp","hxx"]);function An(n){let e=H.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&mC.has(e)}function va(n){return H.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function De(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function fC(n){return De(n)}function Rt(n){let e=fC(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function Lr(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??H.join(ha.homedir(),"AppData","Local");return H.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?H.join(ha.homedir(),"Library","Logs","devecocli-mcp-server"):H.join(ha.homedir(),".local","share","devecocli-mcp-server","logs")}function Sh(n,e){let t=hC(e),r=gC(t,n);if(r!==null)return r;let i=Date.now(),s=`${n.replace(/:/g,"\\:")}=${i}`,a=yC(t,n,s);return wC(e,a),i}function hC(n){let e;try{e=re.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function gC(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let o=parseInt(t.slice(r+1),10);return Number.isFinite(o)&&o>0?o:null}return null}function yC(n,e,t){let r=!1,i=n.map(o=>{if(r)return o;let s=o.indexOf("=");return s<=0?o:o.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):o});return r||i.push(t),i}function wC(n,e){try{re.mkdirSync(H.dirname(n),{recursive:!0})}catch{}try{re.writeFileSync(n,e.join(`
5
5
  `)+`
6
- `,"utf8")}catch{}}function Bc(r,e,t="[Cleanup]"){try{let n=_.dirname(r);if(!Z.existsSync(n))return;let o=Date.now();for(let i of Z.readdirSync(n,{withFileTypes:!0}))i.isDirectory()&&_S(_.join(n,i.name),o,e,t)}catch{}}function _S(r,e,t,n){try{let{mtimeMs:o}=Z.statSync(r);if(e-o<=t)return;Z.rmSync(r,{recursive:!0,force:!0});let i=Math.floor((e-o)/1e3);console.error(`${n} Removed expired dir (age ${Math.floor(i/86400)}d ${Math.floor(i%86400/3600)}h): ${r}`)}catch(o){console.error(`${n} Failed to remove expired dir ${r}: ${o}`)}}var Cp="mcp-server.log",FS="mcp-server",jS={maxSize:10*1024*1024,maxFiles:4},Uc=class r{fd=null;logDir=null;currentLogFile=null;mode;rotationOptions;currentFileSize=0;currentDate="";isRotating=!1;minLevel;static LEVEL_ORDER={debug:0,info:1,warn:2,error:3};constructor(e,t){this.rotationOptions={...jS,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=rr(),this.currentLogFile=is.join(this.logDir,Cp),H.existsSync(this.logDir)||H.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0");return`${t}-${n}-${o}`}getRotatedFileName(e,t){return is.join(this.logDir,`${FS}-${e}.log.${t}`)}fileExists(e){try{return H.accessSync(e,H.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=H.readdirSync(this.logDir),t=[];for(let o of e)if(o===Cp||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(o)){let i=is.join(this.logDir,o),s=H.statSync(i);t.push({name:o,mtime:s.mtime,path:i})}t.sort((o,i)=>i.mtime.getTime()-o.mtime.getTime());let n=1+this.rotationOptions.maxFiles;for(let o=n;o<t.length;o++)try{H.unlinkSync(t[o].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&H.unlinkSync(t);for(let o=this.rotationOptions.maxFiles-1;o>=1;o--){let i=this.getRotatedFileName(e,o),s=this.getRotatedFileName(e,o+1);this.fileExists(i)&&H.renameSync(i,s)}let n=this.getRotatedFileName(e,1);H.renameSync(this.currentLogFile,n),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let e=H.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=H.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{H.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...n){if(this.mode==="silent"||r.LEVEL_ORDER[e]<r.LEVEL_ORDER[this.minLevel])return;let o=n.map(c=>c instanceof Error?`${c.name}: ${c.message}`:typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),i=o?`${t} ${o}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] ${i}
7
- `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);H.writeSync(this.fd,c),this.checkRotation(c.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{H.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},tt=null;function zr(r=!1){tt&&tt.dispose(),tt=new Uc(r)}function Pp(){tt&&(tt.dispose(),tt=null)}function Ap(){tt&&tt.flush()}function Ip(){return tt?.getLogFilePath()??null}function kp(){return tt?.getLogDirectory()??null}function os(){return tt||zr(!1),tt}var h={debug:(r,...e)=>os().debug(r,...e),info:(r,...e)=>os().info(r,...e),warn:(r,...e)=>os().warn(r,...e),error:(r,...e)=>os().error(r,...e)};import Wc from"fs";import Dp from"path";var ko=300*1e3,Do=3600*1e3,Vc=10080*60*1e3;function At(){let r=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return r==="1"||r==="true"}var $S="upload-state.json";function Tp(r){return Dp.join(r,$S)}function HS(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function ss(r){try{let e=Wc.readFileSync(Tp(r),"utf8"),t=JSON.parse(e);return{firstEventAt:typeof t.firstEventAt=="number"?t.firstEventAt:null,lastUploadAt:typeof t.lastUploadAt=="number"?t.lastUploadAt:null,lastRetryAt:typeof t.lastRetryAt=="number"?t.lastRetryAt:null}}catch{return HS()}}function Gc(r,e){try{Wc.writeFileSync(Tp(r),JSON.stringify(e),"utf8")}catch{}}function Rp(r){let e=ss(r);e.firstEventAt===null&&(e.firstEventAt=Date.now(),Gc(r,e))}function xp(r){let e=ss(r);e.lastUploadAt=Date.now(),e.firstEventAt=null,Gc(r,e)}function Lp(r){let e=ss(r);e.lastRetryAt=Date.now(),Gc(r,e)}function zc(r){let e=r.match(/^telemetry-(\d{4})-(\d{2})-(\d{2})\.txt$/);if(!e)return null;let t=Date.parse(`${e[1]}-${e[2]}-${e[3]}T00:00:00`);return Number.isFinite(t)?t:null}function BS(r,e=Date.now()){let t=Dp.join(r,"failed"),n;try{n=Wc.readdirSync(t)}catch{return!1}for(let o of n){if(!o.startsWith("telemetry-")||!o.endsWith(".txt"))continue;let i=zc(o);if(i!==null&&e-i<=Vc)return!0}return!1}function Np(r,e=Date.now()){let t=ss(r);return!!(t.firstEventAt!==null&&e-t.firstEventAt>=ko||BS(r,e)&&(t.lastRetryAt===null||e-t.lastRetryAt>=Do))}import US from"crypto";import as from"fs";import WS from"path";var VS="install-id";function GS(r){return WS.join(r,VS)}function Op(r){try{let e=as.readFileSync(r,"utf8").trim();return zS(e)?e:null}catch{return null}}function zS(r){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(r)}function Mp(r){let e=GS(r),t=Op(e);if(t)return t;let n=US.randomUUID();try{as.mkdirSync(r,{recursive:!0});try{as.writeFileSync(e,n,{flag:"wx"})}catch{let o=Op(e);if(o)return o;as.writeFileSync(e,n)}}catch{}return n}var To=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 Ki;storageDir="";failedDir="";installId="";disabled=At();traceFileKey=Buffer.alloc(0);sessionId=_p.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){h.info(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=qr.join(e,"failed"),this.cliVersion="0.1.7",this.nodeVersion=process.version,this.installId=Mp(e).replace(/-/g,""),this.traceFileKey=hp(e),rt.mkdirSync(e,{recursive:!0}),rt.mkdirSync(this.failedDir,{recursive:!0}),h.info(`[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.info(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,h.info(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,h.info(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");if(!t){await this.record(e,0,!0,null);return}if(typeof t!="function"){let i=t;await this.record(e,i.duration_ms,i.success,i.error_code);return}let n=t,o=Date.now();try{let i=await n(),s=Date.now()-o;return await this.record(e,s,!0,null),i}catch(i){let s=Date.now()-o,a=this.toErrorCode(i);throw await this.record(e,s,!1,a),i}}async record(e,t,n,o){let i=this.buildTraceEvent(e,t,n,o);try{let s=jc(JSON.stringify(i),this.traceFileKey);await rt.promises.appendFile(this.currentFile(),s+`
8
- `,"utf8"),Rp(this.storageDir)}catch{}}buildTraceEvent(e,t,n,o){let i=`${r.EVENT_PREFIX}${e.event}`,s=pp.toObject(e);return s&&typeof s=="object"&&delete s.event,{countryCode:r.COUNTRY_CODE,event:i,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:_p.randomUUID(),trace_os_version:r.TRACE_OS_VERSION,os_arch:this.resolveOsArch(),action:i,trace_os_name:this.resolveOsName(),version:`${this.cliVersion}_${this.resolveOsSuffix()}`,deveco_studio_version:this.formatVersion(this.devecoStudioVersion),command_line_version:this.formatVersion(this.cltVersion),source_type:this.sourceType,session_id:this.sessionId,node_version:this.nodeVersion,duration_ms:t,success:n,error_code:o,event_detail:s}}}toErrorCode(e){return e instanceof Error?e.code??e.name:"UnknownError"}resolveOsArch(){let e=qc.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=qc.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 qc.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}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 qr.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){h.info("[telemetry] scheduler not started (telemetry disabled)");return}h.info(`[telemetry] scheduler started (flush every ${ko/1e3}s, retry failed every ${Do/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},ko)},ko),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},Do)},Do)}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.info("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");let e=await this.listPendingFiles(),t=!0;for(let n of e)await this.flushFile(n)||(t=!1);return xp(this.storageDir),t}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");let e=Date.now(),t;try{t=await rt.promises.readdir(this.failedDir)}catch{return!0}let n=t.filter(i=>i.startsWith("telemetry-")&&i.endsWith(".txt")).map(i=>qr.join(this.failedDir,i)),o=!0;for(let i of n){let s=qr.basename(i),a=zc(s);if(a!==null){if(e-a>Vc){try{await rt.promises.unlink(i)}catch{}continue}await this.flushFile(i)||(o=!1)}}return o||h.warn("[telemetry] retry failed"),Lp(this.storageDir),o}runExclusive(e){let t=()=>e(),n=this.flushChain.then(t,t);return this.flushChain=n.then(()=>{},()=>{}),n}async listPendingFiles(){let e;try{e=await rt.promises.readdir(this.storageDir)}catch{return[]}return e.filter(t=>t.startsWith("telemetry-")&&t.endsWith(".txt")).map(t=>qr.join(this.storageDir,t)).sort()}async flushFile(e){let t=e+".pending";try{await rt.promises.rename(e,t)}catch{return!1}let n;try{n=await rt.promises.readFile(t,"utf8")}catch{return!1}let o=n.split(`
9
- `).map(s=>s.trim()).filter(Boolean),i=[];for(let s of o){let a=gp(s,this.traceFileKey);a!==null&&i.push(a)}if(i.length===0){try{await rt.promises.unlink(t)}catch{}return!0}return this.uploadInBatches(t,i)}async uploadInBatches(e,t){let n=0;for(;n<t.length;){let o=n,i=[],s=16;for(;n<t.length&&i.length<r.MAX_BATCH;){let d=t[n],g=Buffer.byteLength(d,"utf8")+1;if(i.length>0&&s+g>r.MAX_PAYLOAD_BYTES)break;i.push(d),s+=g,n++}let a=this.buildPayloadItems(i),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(o).join(`
6
+ `,"utf8")}catch{}}function Jd(n,e,t="[Cleanup]"){try{let r=H.dirname(n);if(!re.existsSync(r))return;let i=Date.now();for(let o of re.readdirSync(r,{withFileTypes:!0}))o.isDirectory()&&vC(H.join(r,o.name),i,e,t)}catch{}}function vC(n,e,t,r){try{let{mtimeMs:i}=re.statSync(n);if(e-i<=t)return;re.rmSync(n,{recursive:!0,force:!0});let o=Math.floor((e-i)/1e3);console.error(`${r} Removed expired dir (age ${Math.floor(o/86400)}d ${Math.floor(o%86400/3600)}h): ${n}`)}catch(i){console.error(`${r} Failed to remove expired dir ${n}: ${i}`)}}var Eh="mcp-server.log",bC="mcp-server",SC={maxSize:10*1024*1024,maxFiles:4},Yd=class n{fd=null;logDir=null;currentLogFile=null;mode;rotationOptions;currentFileSize=0;currentDate="";isRotating=!1;minLevel;static LEVEL_ORDER={debug:0,info:1,warn:2,error:3};constructor(e,t){this.rotationOptions={...SC,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Lr(),this.currentLogFile=Sa.join(this.logDir,Eh),J.existsSync(this.logDir)||J.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${i}`}getRotatedFileName(e,t){return Sa.join(this.logDir,`${bC}-${e}.log.${t}`)}fileExists(e){try{return J.accessSync(e,J.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=J.readdirSync(this.logDir),t=[];for(let i of e)if(i===Eh||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=Sa.join(this.logDir,i),s=J.statSync(o);t.push({name:i,mtime:s.mtime,path:o})}t.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let i=r;i<t.length;i++)try{J.unlinkSync(t[i].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&J.unlinkSync(t);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(e,i),s=this.getRotatedFileName(e,i+1);this.fileExists(o)&&J.renameSync(o,s)}let r=this.getRotatedFileName(e,1);J.renameSync(this.currentLogFile,r),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let e=J.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=J.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{J.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...r){if(this.mode==="silent"||n.LEVEL_ORDER[e]<n.LEVEL_ORDER[this.minLevel])return;let i=r.map(c=>c instanceof Error?`${c.name}: ${c.message}`:typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),o=i?`${t} ${i}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] [pid=${process.pid}] ${o}
7
+ `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);J.writeSync(this.fd,c),this.checkRotation(c.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{J.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},ht=null;function In(n=!1){ht&&ht.dispose(),ht=new Yd(n)}function Ph(){ht&&(ht.dispose(),ht=null)}function Ch(){ht&&ht.flush()}function kh(){return ht?.getLogFilePath()??null}function Rh(){return ht?.getLogDirectory()??null}function ba(){return ht||In(!1),ht}var h={debug:(n,...e)=>ba().debug(n,...e),info:(n,...e)=>ba().info(n,...e),warn:(n,...e)=>ba().warn(n,...e),error:(n,...e)=>ba().error(n,...e)};import Io from"fs";import Kd from"path";var To=300*1e3,Oo=3600*1e3,Xd=10080*60*1e3,fi=8*1024*1024,Zd=3600*1e3,Dh=".pending",EC=/\.reclaim-\d+-\d+$/;function Ye(){let n=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return n==="1"||n==="true"}var PC="upload-state.json";function Ah(n){return Kd.join(n,PC)}function CC(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function Ea(n){try{let e=Io.readFileSync(Ah(n),"utf8"),t=JSON.parse(e);return{firstEventAt:typeof t.firstEventAt=="number"?t.firstEventAt:null,lastUploadAt:typeof t.lastUploadAt=="number"?t.lastUploadAt:null,lastRetryAt:typeof t.lastRetryAt=="number"?t.lastRetryAt:null}}catch{return CC()}}function Qd(n,e){try{Io.writeFileSync(Ah(n),JSON.stringify(e),"utf8")}catch{}}function Ih(n){let e=Ea(n);e.firstEventAt===null&&(e.firstEventAt=Date.now(),Qd(n,e))}function Th(n){let e=Ea(n);e.lastUploadAt=Date.now(),e.firstEventAt=null,Qd(n,e)}function Oh(n){let e=Ea(n);e.lastRetryAt=Date.now(),Qd(n,e)}function eu(n){let e=n.match(/^telemetry-(\d{4})-(\d{2})-(\d{2})\.txt$/);if(!e)return null;let t=Date.parse(`${e[1]}-${e[2]}-${e[3]}T00:00:00`);return Number.isFinite(t)?t:null}function tu(n){if(!n.startsWith("telemetry-"))return null;let e=EC.exec(n),t=e?n.slice(0,e.index):n;if(!t.endsWith(Dh))return null;let r=t.slice(0,-Dh.length);return r.endsWith(".txt")?r:null}function ru(n){return tu(n)!==null}function kC(n,e=Date.now()){try{return e-Io.statSync(n).mtimeMs>=Zd}catch{return!1}}function xh(n,e=Date.now()){let t;try{t=Io.readdirSync(n)}catch{return!1}return t.some(r=>ru(r)&&kC(Kd.join(n,r),e))}function RC(n,e=Date.now()){if(xh(n,e))return!0;let t=Kd.join(n,"failed");if(xh(t,e))return!0;let r;try{r=Io.readdirSync(t)}catch{return!1}for(let i of r){if(!i.startsWith("telemetry-")||!i.endsWith(".txt"))continue;let o=eu(i);if(o!==null&&e-o<=Xd)return!0}return!1}function Mh(n,e=Date.now()){let t=Ea(n);return!!(t.firstEventAt!==null&&e-t.firstEventAt>=To||RC(n,e)&&(t.lastRetryAt===null||e-t.lastRetryAt>=Oo))}import DC from"crypto";import Pa from"fs";import xC from"path";var AC="install-id";function IC(n){return xC.join(n,AC)}function Nh(n){try{let e=Pa.readFileSync(n,"utf8").trim();return TC(e)?e:null}catch{return null}}function TC(n){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n)}function Lh(n){let e=IC(n),t=Nh(e);if(t)return t;let r=DC.randomUUID();try{Pa.mkdirSync(n,{recursive:!0});try{Pa.writeFileSync(e,r,{flag:"wx"})}catch{let i=Nh(e);if(i)return i;Pa.writeFileSync(e,r)}}catch{}return r}var Mo=class n{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 pa;storageDir="";failedDir="";installId="";disabled=Ye();traceFileKey=Buffer.alloc(0);sessionId=_h.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=ct.join(e,"failed"),this.cliVersion="1.3.6-Test.1",this.nodeVersion=process.version,this.installId=Lh(e).replace(/-/g,""),this.traceFileKey=dh(e),ae.mkdirSync(e,{recursive:!0}),ae.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)throw new Error("Telemetry not initialized. Call init() first.");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 r=t,i=Date.now();try{let o=await r(),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,r,i){let o=this.buildTraceEvent(e,t,r,i);try{let s=uh(JSON.stringify(o),this.traceFileKey);await ae.promises.appendFile(this.currentFile(),s+`
8
+ `,"utf8"),Ih(this.storageDir)}catch{}}buildTraceEvent(e,t,r,i){let o=`${n.EVENT_PREFIX}${e.event}`,s=ah.toObject(e);return s&&typeof s=="object"&&delete s.event,{countryCode:n.COUNTRY_CODE,event:o,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:_h.randomUUID(),trace_os_version:n.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:r,error_code:i,event_detail:s}}}toErrorCode(e){return e instanceof Error?e.code??e.name:"UnknownError"}resolveOsArch(){let e=Ca.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=Ca.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 Ca.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(Ca.totalmem()/1024)}KB`}formatVersion(e){return e?`${e}_${this.resolveOsSuffix()}`:""}dateString(){let e=new Date,t=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return`${e.getFullYear()}-${t}-${r}`}currentFile(){return ct.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 ${To/1e3}s, retry failed every ${Oo/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},To)},To),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},Oo)},Oo)}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)throw new Error("Telemetry not initialized. Call init() first.");let e=await this.listPendingFiles(),t=!0;for(let r of e)await this.flushFile(r)||(t=!1);return Th(this.storageDir),t}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");await this.reclaimStalePending();let e=Date.now(),t;try{t=await ae.promises.readdir(this.failedDir)}catch{return!0}let r=t.filter(o=>o.startsWith("telemetry-")&&o.endsWith(".txt")).map(o=>ct.join(this.failedDir,o)),i=!0;for(let o of r){let s=ct.basename(o),a=eu(s);if(a!==null){if(e-a>Xd){try{await ae.promises.unlink(o)}catch{}continue}await this.flushFile(o)||(i=!1)}}return i||h.warn("[telemetry] retry failed"),Oh(this.storageDir),i}async reclaimStalePending(){let e=Date.now();for(let t of[this.storageDir,this.failedDir]){let r;try{r=await ae.promises.readdir(t)}catch{continue}for(let i of r)ru(i)&&await this.reclaimOrphan(ct.join(t,i),e)}}async reclaimOrphan(e,t){let r;try{let l=await ae.promises.stat(e);if(t-l.mtimeMs<Zd)return;r=l.size}catch{return}let i=ct.dirname(e),o=tu(ct.basename(e));if(o===null)return;let s=await this.claimOrphan(e,i,o);if(s===null)return;let a=ct.join(i,o),c=fi-await this.fileSize(a);if(r>c){try{await ae.promises.unlink(s)}catch{}h.warn(`[telemetry] dropped stale orphan pending: ${s} (${r} bytes > budget ${c})`);return}if(await this.mergeOrphanInto(s,a)){h.warn(`[telemetry] reclaimed orphan pending: ${s} (${r} bytes)`);return}h.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${r} bytes)`)}async claimOrphan(e,t,r){let i=ct.join(t,`${r}.pending.reclaim-${process.pid}-${Date.now()}`);try{await ae.promises.rename(e,i)}catch{return null}return await this.touch(i),i}async mergeOrphanInto(e,t){try{await ae.promises.appendFile(t,await ae.promises.readFile(e))}catch(r){return h.warn(`[telemetry] merge orphan pending failed: ${e} -> ${t}: ${r instanceof Error?r.message:String(r)}`),!1}try{await ae.promises.unlink(e)}catch(r){h.warn(`[telemetry] merged but failed to remove orphan pending: ${e}: ${r instanceof Error?r.message:String(r)}`)}return!0}async fileSize(e){try{return(await ae.promises.stat(e)).size}catch{return 0}}async touch(e){let t=new Date;try{await ae.promises.utimes(e,t,t)}catch{}}runExclusive(e){let t=()=>e(),r=this.flushChain.then(t,t);return this.flushChain=r.then(()=>{},()=>{}),r}async listPendingFiles(){let e;try{e=await ae.promises.readdir(this.storageDir)}catch{return[]}return e.filter(t=>t.startsWith("telemetry-")&&t.endsWith(".txt")).map(t=>ct.join(this.storageDir,t)).sort()}async flushFile(e){let t=await this.fileSize(e);if(t>fi){h.warn(`[telemetry] ${ct.basename(e)} is ${t} bytes (> ${fi}), dropped without uploading`);try{await ae.promises.unlink(e)}catch{}return!0}let r=e+".pending";try{await ae.promises.rename(e,r)}catch{return!1}await this.touch(r);let i;try{i=await ae.promises.readFile(r,"utf8")}catch{return!1}let o=i.split(`
9
+ `).map(s=>s.trim()).filter(Boolean);if(o.length===0){try{await ae.promises.unlink(r)}catch{}return!0}return this.uploadInBatches(r,o)}collectDecryptBatch(e,t){let r=[],i=16,o=t;for(;o<e.length&&r.length<n.MAX_BATCH;){let s=ph(e[o],this.traceFileKey);if(s===null){o++;continue}let a=Buffer.byteLength(s,"utf8")+1;if(r.length>0&&i+a>n.MAX_PAYLOAD_BYTES)break;r.push(s),i+=a,o++}return{batch:r,next:o}}async uploadInBatches(e,t){let r=0;for(;r<t.length;){let i=r,{batch:o,next:s}=this.collectDecryptBatch(t,r);r=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(`
10
10
  `)+`
11
- `;return await this.moveToFailed(e,d),!1}}try{await rt.promises.unlink(e)}catch{}return!0}buildPayloadItems(e){let t=[];for(let n of e)try{let o=JSON.parse(n);t.push({action:o.event,detail:JSON.stringify(o.properties),timestamp:Number(o.eventtime)||Date.now()})}catch{}return t}async moveToFailed(e,t){let n=qr.basename(e,".pending"),o=qr.join(this.failedDir,n);try{let i=t.split(`
12
- `).filter(Boolean).map(s=>jc(s,this.traceFileKey)).join(`
11
+ `;return await this.moveToFailed(e,d),!1}}try{await ae.promises.unlink(e)}catch{}return!0}buildPayloadItems(e){let t=[];for(let r of e)try{let i=JSON.parse(r);t.push({action:i.event,detail:JSON.stringify(i.properties),timestamp:Number(i.eventtime)||Date.now()})}catch{}return t}async moveToFailed(e,t){let r=ct.basename(e,".pending"),i=ct.join(this.failedDir,r),o=t.split(`
12
+ `).filter(Boolean),s=fi-await this.fileSize(i),a=this.takeNewestWithinBudget(o,s);a.length<o.length&&h.warn(`[telemetry] failed file capped at ${fi} bytes, dropped ${o.length-a.length} older events`);try{a.length>0&&await ae.promises.appendFile(i,a.join(`
13
13
  `)+`
14
- `;await rt.promises.appendFile(o,i,"utf8")}catch{return}try{await rt.promises.unlink(e)}catch{}}};var I=new To;import{spawn as qS}from"child_process";import{existsSync as JS}from"fs";import{dirname as YS,join as KS}from"path";import{fileURLToPath as XS}from"url";function ZS(){let r=YS(XS(import.meta.url)),e=KS(r,"internal","telemetry-upload-background.js");return JS(e)?e:null}function Jc(r){if(At()||!Np(r))return;let e=ZS();if(!e){h.warn("[telemetry] background upload script not found, skipping spawn");return}try{qS(process.execPath,[e],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1",DEVECO_CLI_TELEMETRY_UPLOAD:"1"}}).unref()}catch(t){h.warn("[telemetry] failed to spawn background upload:",t)}}var w=class extends Error{traceMessage;constructor(e,t,n){super(e,n),this.name="TraceError",this.traceMessage=t??e}};function q(r){if(r instanceof w)return r.traceMessage;if(r instanceof Error){let e=r.code;return typeof e=="string"&&e!==""?e:r.name}return"UnknownError"}var S={CommandExecuted:"Command_executed",McpToolCall:"serve_mcp",SkillOperation:"skills",Init:"mcp_config_operation",SkillConfigOperation:"skill_config_operation",DocOperation:"docs",ServeLsp:"serve_lsp",CheckCommand:"check"};var Re={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json",LOCK_JSON5_PATH:"oh_modules/.ohpm/lock.json5"};var V=class r{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let n=r.tryLoadProjectProfile(t);if(n)return new r(t,n);let o=j.dirname(t);if(o===t)break;t=o}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=j.join(e,"build-profile.json5");if(!Q.existsSync(t))return null;try{let n=Q.readFileSync(t,"utf-8"),o=It.parse(n);return o.app?o:null}catch(n){return console.error(`Error parsing ${t}:`,n),null}}getRunnableModuleNames(){return this.profile.modules.map(e=>e.name).filter(e=>this.getModuleType(e)!=="har").join(", ")}getModuleType(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)throw new w(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let n=E.resolvePathWithinRoot(this.rootDir,t.srcPath),o=j.join(n,"src","main","module.json5");if(!Q.existsSync(o))return"entry";try{let i=Q.readFileSync(o,"utf-8");return It.parse(i)?.module?.type||"entry"}catch(i){return console.warn(`Warning: Failed to parse ${o}:`,i),"entry"}}findOwningModule(e){let t=j.normalize(e);for(let n of this.profile.modules){let o=j.normalize(j.join(this.rootDir,n.srcPath)),i=o+j.sep;if(t.startsWith(i)||t===o)return n.name}return null}getModuleProfile(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)throw new w(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let n=E.resolvePathWithinRoot(this.rootDir,t.srcPath),o=j.join(n,"build-profile.json5");if(!Q.existsSync(o))throw new w(`Build profile for module '${e}' not found at ${o}.`,"Build profile for module not found at ${profilePath}.");try{let i=Q.readFileSync(o,"utf-8");return It.parse(i)}catch(i){throw new Error(`Failed to parse module build profile at ${o}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}getBundleName(e){if(e){let n=this.profile.app.products?.find(o=>o.name===e);if(n?.bundleName)return n.bundleName}let t=j.join(this.rootDir,"AppScope","app.json5");if(Q.existsSync(t))try{let n=Q.readFileSync(t,"utf-8"),o=It.parse(n);if(o?.app?.bundleName)return o.app.bundleName}catch(n){console.warn(`Warning: Failed to parse ${t}:`,n)}throw new Error("Could not find bundleName in AppScope/app.json5.")}isAtomicService(){let e=j.join(this.rootDir,"AppScope","app.json5");if(!Q.existsSync(e))return!1;try{let t=Q.readFileSync(e,"utf-8");return It.parse(t)?.app?.bundleType==="atomicService"}catch{return!1}}getMainAbility(e,t){if(t)return t;let n=this.profile.modules.find(s=>s.name===e);if(!n)return"EntryAbility";let o=E.resolvePathWithinRoot(this.rootDir,n.srcPath),i=j.join(o,"src","main","module.json5");if(!Q.existsSync(i))return"EntryAbility";try{let s=Q.readFileSync(i,"utf-8"),c=It.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let l=c.find(d=>d.name==="EntryAbility");return l?l.name:c[0].name}catch(s){return console.warn(`Warning: Failed to parse ${i}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new w(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`,"Invalid product name.");if(!this.profile.app.products?.some(n=>n.name===e)){let n=this.profile.app.products?.map(o=>o.name).join(", ")||"none";throw new w(`Product '${e}' not found in project configuration. Available products: ${n}`,"Productnot found in project configuration.")}}getModuleDependencies(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)return[];let n=this.readLockFinalLocalModuleDeps(e);return n!==null?n:this.readOhPackageLocalModuleDeps(t)}readLockFinalLocalModuleDeps(e){let t=j.join(this.rootDir,Re.LOCK_JSON5_PATH);if(!Q.existsSync(t))return null;let n;try{n=It.parse(Q.readFileSync(t,"utf-8"))}catch(d){return m(`Failed to parse lock.json5: ${d instanceof Error?d.message:String(d)}`),null}let o=n,i=o?.modules;if(!i||typeof i!="object")return null;let s=Object.values(i).find(d=>typeof d=="object"&&d!==null&&d.name===e);if(!s)return null;let a=this.buildOverrideMap(o.overrides),c=[],l=new Set;for(let d of["dependencies","dynamicDependencies"]){let g=s[d];!g||typeof g!="object"||this.collectLocalDeps(g,a,y=>this.resolveLockDepByVersion(y),c,l)}return c}resolveLockDepByVersion(e){if(typeof e!="object"||e===null)return null;let t=e.version;return typeof t=="string"?this.resolveLocalDepToModule(t):null}resolveDepModule(e,t,n){if(t?.has(e)){let o=t.get(e);if(o){let i=this.resolveLocalDepToModule(o);if(i)return i}}return n()}buildOverrideMap(e){if(!e||typeof e!="object")return null;let t=new Map;for(let[n,o]of Object.entries(e))typeof o=="string"&&t.set(n,o);return t.size>0?t:null}resolveLocalDepToModule(e){let t=r.stripLocalDep(e);if(!t)return null;let n=j.resolve(this.rootDir,t),o;try{o=E.ensurePathWithinRoot(this.rootDir,n)}catch{return null}let i=this.profile.modules.find(s=>j.resolve(this.rootDir,s.srcPath)===o);return i?i.name:null}static stripLocalDep(e){return!e.startsWith("file:")&&!e.startsWith(".")&&!e.startsWith("..")?null:e.startsWith("file:")?e.substring(5):e}readOhPackageLocalModuleDeps(e){let t=j.join(E.resolvePathWithinRoot(this.rootDir,e.srcPath),Re.OH_PACKAGE_JSON5);if(!Q.existsSync(t))return[];let n=this.readRootOverrideMap(),o=[],i=new Set;try{let s=It.parse(Q.readFileSync(t,"utf-8"));for(let a of["dependencies","dynamicDependencies"]){let c=s?.[a];!c||typeof c!="object"||this.collectLocalDeps(c,n,l=>this.resolveOhPackageDepByValue(l,e),o,i)}}catch(s){m(`Failed to get module dependencies: ${s instanceof Error?s.message:String(s)}`)}return o}readRootOverrideMap(){let e=j.join(this.rootDir,Re.OH_PACKAGE_JSON5);if(!Q.existsSync(e))return null;try{let t=It.parse(Q.readFileSync(e,"utf-8"));return this.buildOverrideMap(t?.overrides)}catch{return null}}resolveOhPackageDepByValue(e,t){return typeof e=="string"?this.resolveLocalDepModuleName(e,t):null}collectLocalDeps(e,t,n,o,i){for(let[s,a]of Object.entries(e)){let c=this.resolveDepModule(s,t,()=>n(a));c&&!i.has(c)&&(i.add(c),o.push(c))}}resolveLocalDepModuleName(e,t){let n=r.stripLocalDep(e);if(!n)return null;let o=j.join(t.srcPath,n),i=E.resolvePathWithinRoot(this.rootDir,o),s=this.profile.modules.find(a=>j.resolve(this.rootDir,a.srcPath)===i);return s?s.name:null}collectNonHarDependentModuleList(e){let t=[],n=[],o=new Set;for(n.push(e),o.add(e);n.length>0;){let i=n.shift();this.getModuleType(i)!=="har"&&t.push(i);let a=this.getModuleDependencies(i);for(let c of a)o.has(c)||(n.push(c),o.add(c))}return t}resolveModuleMetadata(e,t,n){this.validateProduct(n);let o=this.profile.modules.find(l=>l.name===e);if(!o){let l=this.getRunnableModuleNames();throw new w(`Module '${e}' not found. Available modules: ${l}`,"Module not found.")}let i=this.getModuleType(e)==="shared",s=i?"hspName":"hapName",a=this.buildOutputPath(o.srcPath,n,["intermediates",i?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!Q.existsSync(a))throw new w(`Build metadata not found for module '${e}' at ${a}. Build the project first.`,"Build metadata not found for module. Build the project first.");let c=this.parseOutputMetadata(a,s);return{moduleNode:o,isShared:i,metadataPath:a,metadata:c}}findArtifactPath(e,t,n,o="default"){let{moduleNode:i,isShared:s,metadata:a}=this.resolveModuleMetadata(e,t,o),{packageName:c,isSigned:l}=a,d=c;if(!l){let b=this.getSignedHapName(c,i.srcPath,o,t);b&&(d=b)}let g=s?"-signed.hsp":"-signed.hap";if(!n&&!d.endsWith(g))throw new w(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`,"Target device is a real device, but the artifact is not signed.");let y=this.buildOutputPath(i.srcPath,o,["outputs",t,d]);if(!Q.existsSync(y))throw new w(`Generated package file not found in ${y}.`,"Generated package file not found.");return y}findRemoteHspPaths(e,t,n="default"){let{moduleNode:o,metadata:i}=this.resolveModuleMetadata(e,t,n),s=[],a=new Set;for(let{hspPath:c}of i.dependRemoteHsps){if(a.has(c))continue;a.add(c);let l=j.isAbsolute(c)?c:this.buildOutputPath(o.srcPath,n,["outputs",t,c]);if(!Q.existsSync(l))throw new w(`Remote HSP dependency not found: ${l}`,"Remote HSP dependency not found.");s.push(l)}return s}getSignedHapName(e,t,n,o){let i=null;if(e.endsWith("-unsigned.hap")?i=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(i=e.replace("-unsigned.hsp","-signed.hsp")),!i)return null;let s=this.buildOutputPath(t,n,["outputs",o,i]);return Q.existsSync(s)?i:null}buildOutputPath(e,t,n){let o=E.resolvePathWithinRoot(this.rootDir,e),i=j.resolve(o,"build",t,...n);return E.ensurePathWithinRoot(this.rootDir,i)}collectRemoteHsps(e){return e.flatMap(t=>{let n=t.dependRemoteHsps;return Array.isArray(n)?n.filter(o=>!!(o.hspName&&o.hspPath)).map(o=>({hspName:o.hspName,hspPath:o.hspPath})):[]})}parseOutputMetadata(e,t){let n;try{let c=Q.readFileSync(e,"utf-8");n=It.parse(c)}catch(c){throw new Error(`Failed to parse output metadata at ${e}: ${c instanceof Error?c.message:String(c)}`,{cause:c})}let o,i=!1,s=Array.isArray(n)?n:[n];for(let c of s)o||(o=c[t]),i||(i=c.isSigned===!0);if(!o)throw new w(`Could not find ${t} in output_metadata.json at ${e}`,"Could not find metadataKey in output_metadata.json at metadataPath.");this.validatePackageName(o);let a=this.collectRemoteHsps(s);return{packageName:o,isSigned:i,dependRemoteHsps:a}}validatePackageName(e){let t=j.basename(e);if(t!==e)throw new w(`Invalid traversal name: '${e}'. It must contain path characters.`,"Invalid traversal name.");if(!t.endsWith(".hap")&&!t.endsWith(".hsp"))throw new w(`Invalid package name '${t}'.It must be a .hap or .hsp file.`,"Invalid package name.")}};import xe from"fs";import*as Ye from"os";import*as P from"path";import ls from"fs";import*as ds from"os";import*as Ro from"path";import rb from"regedit";import{execFileSync as eb}from"child_process";import jp from"fs";import*as $p from"os";import*as Yc from"path";import{compare as QS}from"semver";function Fp(r,e){return QS(r,e)}function Sn(r,e){let t=Math.max(r.split(".").length,e.split(".").length);for(let n=0;n<t;n++){let o=Number(r.split(".")[n]??0)-Number(e.split(".")[n]??0);if(o)return o}return 0}function cs(r,e){let t=Yc.join(r,"Contents","Info.plist");if(!jp.existsSync(t)){m(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[n,o]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let i=eb(n,o,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(i&&!i.includes("Does Not Exist"))return i}catch{}}function tb(r){let e=cs(r,"CFBundleShortVersionString");if(!e)return cs(r,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),n=[cs(r,"CFBundleVersion"),cs(r,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let o of n){let i=o?.split(".").at(-1)?.replace(new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`),"");if(i&&/^\d+$/.test(i))return`${e}.${i}`}return e}function nr(r){if($p.platform()==="darwin")return tb(r);let e=Yc.join(r,"product-info.json");try{let t=JSON.parse(jp.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}var nb="DevEco Studio",ob=["Contents","Resources","product-info.json"],ib="name";function sb(r){return r.filter(e=>{try{return ls.statSync(e).isDirectory()}catch{return!1}})}function ab(r){let e=Ro.join(r,...ob);if(ls.existsSync(e))try{let n=JSON.parse(ls.readFileSync(e,"utf8"))[ib];return typeof n=="string"&&n.trim()?n.trim():void 0}catch{return}}function cb(r){return ab(r)===nb}function lb(){let r=[];for(let e of[Ro.join(ds.homedir(),"Applications"),"/Applications"])try{r.push(...ls.readdirSync(e).filter(t=>t.endsWith(".app")).map(t=>Ro.join(e,t)).filter(cb))}catch{}return r}function Hp(r){return new Promise((e,t)=>rb.list(r,(n,o)=>n?t(n):e(o)))}async function Bp(r,e,t){let o=((await Hp([r]))[r]?.keys??[]).filter(e).map(s=>`${r}\\${s}`);if(o.length===0)return[];let i=await Hp(o);return o.flatMap(s=>{let a=i[s]?.values?.[t]?.value;return a?[a]:[]})}async function db(){let r=[Ro.join("C:","Program Files","Huawei","DevEco Studio")];for(let e of["HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall","HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"])try{r.push(...await Bp(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 Bp(e,()=>!0,""))}catch{}return r}async function Up(){let r=ds.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"?lb():await db(),t=sb(e).flatMap(n=>{let o=nr(n);return o?(m(`[ToolProvider] ${n} => version ${o}`),[{root:n,version:o}]):(m(`[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,o)=>Sn(o.version,n.version)>0?o:n)}import*as Wp from"fs";import*as Fe from"path";function xo(r,e){let t=Fe.relative(e,r);return t===""||!Fe.isAbsolute(t)&&!t.startsWith(`..${Fe.sep}`)&&t!==".."}function kt(r){let e=Fe.resolve(r),t=[],n=e;for(;;)try{let o=Wp.realpathSync(n);return t.length===0?o:Fe.join(o,...t.reverse())}catch(o){if(o.code!=="ENOENT")throw o;let i=Fe.dirname(n);if(i===n)return e;t.push(Fe.basename(n)),n=i}}function us(r,e){let t=kt(e),n=kt(r);return xo(n,t)?n:null}function Kc(r){let e=r.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function ps(r){let e=Kc(r);if(!e)throw new Error("Path must not be empty.");return kt(e)}var Xc="https://matrix.openharmony.cn",nt={TAGS_API_URL:`${Xc}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${Xc}/api/registry/skill/skills`,SKILL_API_BASE:`${Xc}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,DEFAULT_MAX_PAGES:100,SUCCESS_CODE:"20000"},ht={"trae-cn":{path:".trae-cn/skills",displayName:"trae-cn"},opencode:{path:".config/opencode/skills",displayName:"opencode"},pi:{path:".pi/agent/skills",displayName:"pi"},deveco:{path:".config/deveco/skills",displayName:"deveco"},cursor:{path:".cursor/skills",displayName:"cursor"},codebuddy:{path:".codebuddy/skills",displayName:"codebuddy"},qoder:{path:".qoder/skills",displayName:"qoder"},"claude-code":{path:".claude/skills",projectPath:".claude/skills",displayName:"claude-code"},codex:{path:".codex/skills",displayName:"codex"},atomcode:{path:".atomcode/skills",displayName:"atomcode"},dsh:{path:".dsh/skills",projectPath:".dsh/skills",displayName:"deepseek harness"}};import{homedir as Dt}from"os";import je from"path";var Tt="deveco-mcp";var or={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:je.join(Dt(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},pi:{name:"pi",displayName:"Pi Coding Agent",supportsGlobal:!0,globalConfigPath:je.join(Dt(),".pi","agent","mcp.json"),projectConfigPath:".pi/mcp.json",mcpServersKey:"mcpServers",format:"standard"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:je.join(process.platform==="win32"?je.join(process.env.APPDATA??je.join(Dt(),"AppData","Roaming"),"Trae CN","User"):je.join(Dt(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:je.join(Dt(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:je.join(Dt(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:je.join(process.platform==="win32"?je.join(process.env.APPDATA??je.join(Dt(),"AppData","Roaming"),"Qoder","SharedClientCache"):je.join(Dt(),"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:je.join(Dt(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:je.join(Dt(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function Gp(r){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:r??"."},enabled:!0}}function Vp(r){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:r??"."},enabled:!0}}function zp(r){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:r??"${workspaceFolder}"}}}function ms(r,e){return r.format==="opencode"?Gp(e):r.format==="claude-code"||r.format==="codex"?Vp(e):zp(e)}var Zc="https://developer.huawei.com/consumer/cn/download/";var ub=/^#\s*Version:\s*(\S+)/,pb="26.0.0.810";function mb(r){try{let e=JSON.parse(xe.readFileSync(r,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch(e){m(`[ToolProvider] Failed to parse API level from ${r}: ${e instanceof Error?e.message:String(e)}`);return}}function fb(r){let e=P.join(r,"default","openharmony");return[P.join(r,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>P.join(e,t,"oh-uni-package.json"))]}var k=class r{constructor(e,t,n,o,i,s,a,c,l,d){this._sourceType=e;this._toolchainRoot=t;this._devecoStudioPath=n;this._nodePath=o;this._ohpmJsPath=i;this._hvigorJsPath=s;this._javaPath=a;this._sdkPath=c;this._hdcPath=l;this._emulatorPath=d}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(xe.existsSync(t.marker))return t.root;return null}get clangdPath(){let e=r.buildToolPaths(this._toolchainRoot,this._sourceType).clangdPath;return xe.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 emulatorLauncherPath(){return this.emulatorPath}assertJava(){if(this._sourceType==="clt"&&!this._javaPath&&(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 Sn(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 getStudioVersion(){try{let e=await r.resolveInstallSource();return nr(e.toolchainRoot)}catch{return}}static async getCltVersion(){try{let e=await r.resolveInstallSource();return r.readCltVersion(e.toolchainRoot)}catch{return}}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)}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)}assertVersion(){if(this._sourceType==="clt"){this.assertCltVersion();return}this.assertIdeVersion()}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(nr(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,o,i){if(!e)throw new w(`Failed to determine ${t} version from ${n} at ${i}`,`Failed to determine ${t} version from ${n}`);if(!/^\d+(?:\.\d+){1,3}$/.test(e))throw new w(`Invalid ${t} version "${e}" from ${n} at ${i}`,`Invalid ${t} version "${e}" from ${n}`);if(Sn(e,o)<0)throw new Error(`The detected ${t} version is ${e}, which is below the minimum required version ${o}. Upgrade before using deveco-cli:
15
- ${Zc}`)}static resolveCodelinterPath(e,t){let n=r.buildToolPaths(e,t).codelinterCandidates,o=n.find(r.isFile);if(!o){let a=t==="studio"?"Code Linter not found in DevEco Studio.":"Code Linter not found in DevEco Command Line Tools.";throw new w(`${a}
14
+ `,"utf8")}catch{return}try{await ae.promises.unlink(e)}catch{}}takeNewestWithinBudget(e,t){if(t<=0)return[];let r=[],i=0;for(let o=e.length-1;o>=0;o--){let s=Buffer.byteLength(e[o],"utf8")+1;if(i+s>t)break;i+=s,r.push(e[o])}return r.reverse(),r}};var D=new Mo;import{spawn as OC}from"child_process";import{existsSync as MC}from"fs";import{dirname as NC,join as LC}from"path";import{fileURLToPath as _C}from"url";function $C(){let n=NC(_C(import.meta.url)),e=LC(n,"internal","telemetry-upload-background.js");return MC(e)?e:null}function nu(n){if(Ye()||!Mh(n))return;let e=$C();if(!e){h.warn("[telemetry] background upload script not found, skipping spawn");return}try{OC(process.execPath,[e],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1",DEVECO_CLI_TELEMETRY_UPLOAD:"1"}}).unref()}catch(t){h.warn("[telemetry] failed to spawn background upload:",t)}}var y=class extends Error{traceMessage;constructor(e,t,r){super(e,r),this.name="TraceError",this.traceMessage=t??e}};function X(n){if(n instanceof y)return n.traceMessage;if(n instanceof Error){let e=n.code;return typeof e=="string"&&e!==""?e:n.name}return"UnknownError"}var v={CommandExecuted:"Command_executed",McpToolCall:"serve_mcp",SkillOperation:"skills",Init:"mcp_config_operation",SkillConfigOperation:"skill_config_operation",DocOperation:"docs",ServeLsp:"serve_lsp",CheckCommand:"check"};var Pe={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json",LOCK_JSON5_PATH:"oh_modules/.ohpm/lock.json5",HVIGOR_CONFIG:"hvigor/hvigor-config.json5"};var B=class n{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let r=n.tryLoadProjectProfile(t);if(r)return new n(t,r);let i=F.dirname(t);if(i===t)break;t=i}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=F.join(e,"build-profile.json5");if(!Y.existsSync(t))return null;try{let r=Y.readFileSync(t,"utf-8"),i=Vt.parse(r);return i.app?i:null}catch(r){return console.error(`Error parsing ${t}:`,r),null}}getRunnableModuleNames(){return this.profile.modules.map(e=>e.name).filter(e=>this.getModuleType(e)!=="har").join(", ")}getModuleType(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new y(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=E.resolvePathWithinRoot(this.rootDir,t.srcPath),i=F.join(r,"src","main","module.json5");if(!Y.existsSync(i))return"entry";try{let o=Y.readFileSync(i,"utf-8");return Vt.parse(o)?.module?.type||"entry"}catch(o){return console.warn(`Warning: Failed to parse ${i}:`,o),"entry"}}findOwningModule(e){let t=F.normalize(e);for(let r of this.profile.modules){let i=F.normalize(F.join(this.rootDir,r.srcPath)),o=i+F.sep;if(t.startsWith(o)||t===i)return r.name}return null}getModuleProfile(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new y(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=E.resolvePathWithinRoot(this.rootDir,t.srcPath),i=F.join(r,"build-profile.json5");if(!Y.existsSync(i))throw new y(`Build profile for module '${e}' not found at ${i}.`,"Build profile for module not found at ${profilePath}.");try{let o=Y.readFileSync(i,"utf-8");return Vt.parse(o)}catch(o){throw new Error(`Failed to parse module build profile at ${i}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}}getBundleName(e){if(e){let r=this.profile.app.products?.find(i=>i.name===e);if(r?.bundleName)return r.bundleName}let t=F.join(this.rootDir,"AppScope","app.json5");if(Y.existsSync(t))try{let r=Y.readFileSync(t,"utf-8"),i=Vt.parse(r);if(i?.app?.bundleName)return i.app.bundleName}catch(r){console.warn(`Warning: Failed to parse ${t}:`,r)}throw new Error("Could not find bundleName in AppScope/app.json5.")}isAtomicService(){let e=F.join(this.rootDir,"AppScope","app.json5");if(!Y.existsSync(e))return!1;try{let t=Y.readFileSync(e,"utf-8");return Vt.parse(t)?.app?.bundleType==="atomicService"}catch{return!1}}getMainAbility(e,t){if(t)return t;let r=this.profile.modules.find(s=>s.name===e);if(!r)return"EntryAbility";let i=E.resolvePathWithinRoot(this.rootDir,r.srcPath),o=F.join(i,"src","main","module.json5");if(!Y.existsSync(o))return"EntryAbility";try{let s=Y.readFileSync(o,"utf-8"),c=Vt.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let l=c.find(d=>d.name==="EntryAbility");return l?l.name:c[0].name}catch(s){return console.warn(`Warning: Failed to parse ${o}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new y(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`,"Invalid product name.");if(!this.profile.app.products?.some(r=>r.name===e)){let r=this.profile.app.products?.map(i=>i.name).join(", ")||"none";throw new y(`Product '${e}' not found in project configuration. Available products: ${r}`,"Productnot found in project configuration.")}}getModuleDependencies(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)return[];let r=this.readLockFinalLocalModuleDeps(e);return r!==null?r:this.readOhPackageLocalModuleDeps(t)}readLockFinalLocalModuleDeps(e){let t=F.join(this.rootDir,Pe.LOCK_JSON5_PATH);if(!Y.existsSync(t))return null;let r;try{r=Vt.parse(Y.readFileSync(t,"utf-8"))}catch(d){return m(`Failed to parse lock.json5: ${d instanceof Error?d.message:String(d)}`),null}let i=r,o=i?.modules;if(!o||typeof o!="object")return null;let s=Object.values(o).find(d=>typeof d=="object"&&d!==null&&d.name===e);if(!s)return null;let a=this.buildOverrideMap(i.overrides),c=[],l=new Set;for(let d of["dependencies","dynamicDependencies"]){let g=s[d];!g||typeof g!="object"||this.collectLocalDeps(g,a,w=>this.resolveLockDepByVersion(w),c,l)}return c}resolveLockDepByVersion(e){if(typeof e!="object"||e===null)return null;let t=e.version;return typeof t=="string"?this.resolveLocalDepToModule(t):null}resolveDepModule(e,t,r){if(t?.has(e)){let i=t.get(e);if(i){let o=this.resolveLocalDepToModule(i);if(o)return o}}return r()}buildOverrideMap(e){if(!e||typeof e!="object")return null;let t=new Map;for(let[r,i]of Object.entries(e))typeof i=="string"&&t.set(r,i);return t.size>0?t:null}resolveLocalDepToModule(e){let t=n.stripLocalDep(e);if(!t)return null;let r=F.resolve(this.rootDir,t),i;try{i=E.ensurePathWithinRoot(this.rootDir,r)}catch{return null}let o=this.profile.modules.find(s=>F.resolve(this.rootDir,s.srcPath)===i);return o?o.name:null}static stripLocalDep(e){return!e.startsWith("file:")&&!e.startsWith(".")&&!e.startsWith("..")?null:e.startsWith("file:")?e.substring(5):e}readOhPackageLocalModuleDeps(e){let t=F.join(E.resolvePathWithinRoot(this.rootDir,e.srcPath),Pe.OH_PACKAGE_JSON5);if(!Y.existsSync(t))return[];let r=this.readRootOverrideMap(),i=[],o=new Set;try{let s=Vt.parse(Y.readFileSync(t,"utf-8"));for(let a of["dependencies","dynamicDependencies"]){let c=s?.[a];!c||typeof c!="object"||this.collectLocalDeps(c,r,l=>this.resolveOhPackageDepByValue(l,e),i,o)}}catch(s){m(`Failed to get module dependencies: ${s instanceof Error?s.message:String(s)}`)}return i}readRootOverrideMap(){let e=F.join(this.rootDir,Pe.OH_PACKAGE_JSON5);if(!Y.existsSync(e))return null;try{let t=Vt.parse(Y.readFileSync(e,"utf-8"));return this.buildOverrideMap(t?.overrides)}catch{return null}}resolveOhPackageDepByValue(e,t){return typeof e=="string"?this.resolveLocalDepModuleName(e,t):null}collectLocalDeps(e,t,r,i,o){for(let[s,a]of Object.entries(e)){let c=this.resolveDepModule(s,t,()=>r(a));c&&!o.has(c)&&(o.add(c),i.push(c))}}resolveLocalDepModuleName(e,t){let r=n.stripLocalDep(e);if(!r)return null;let i=F.join(t.srcPath,r),o=E.resolvePathWithinRoot(this.rootDir,i),s=this.profile.modules.find(a=>F.resolve(this.rootDir,a.srcPath)===o);return s?s.name:null}collectNonHarDependentModuleList(e){let t=[],r=[],i=new Set;for(r.push(e),i.add(e);r.length>0;){let o=r.shift();this.getModuleType(o)!=="har"&&t.push(o);let a=this.getModuleDependencies(o);for(let c of a)i.has(c)||(r.push(c),i.add(c))}return t}resolveModuleMetadata(e,t,r){this.validateProduct(r);let i=this.profile.modules.find(l=>l.name===e);if(!i){let l=this.getRunnableModuleNames();throw new y(`Module '${e}' not found. Available modules: ${l}`,"Module not found.")}let o=this.getModuleType(e)==="shared",s=o?"hspName":"hapName",a=this.buildOutputPath(i.srcPath,r,["intermediates",o?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!Y.existsSync(a))throw new y(`Build metadata not found for module '${e}' at ${a}. Build the project first.`,"Build metadata not found for module. Build the project first.");let c=this.parseOutputMetadata(a,s);return{moduleNode:i,isShared:o,metadataPath:a,metadata:c}}findArtifactPath(e,t,r,i="default"){let{moduleNode:o,isShared:s,metadata:a}=this.resolveModuleMetadata(e,t,i),{packageName:c,isSigned:l}=a,d=c;if(!l){let R=this.getSignedHapName(c,o.srcPath,i,t);R&&(d=R)}let g=s?"-signed.hsp":"-signed.hap";if(!r&&!d.endsWith(g))throw new y(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`,"Target device is a real device, but the artifact is not signed.");let w=this.buildOutputPath(o.srcPath,i,["outputs",t,d]);if(!Y.existsSync(w))throw new y(`Generated package file not found in ${w}.`,"Generated package file not found.");return w}findRemoteHspPaths(e,t,r="default"){let{moduleNode:i,metadata:o}=this.resolveModuleMetadata(e,t,r),s=[],a=new Set;for(let{hspPath:c}of o.dependRemoteHsps){if(a.has(c))continue;a.add(c);let l=F.isAbsolute(c)?c:this.buildOutputPath(i.srcPath,r,["outputs",t,c]);if(!Y.existsSync(l))throw new y(`Remote HSP dependency not found: ${l}`,"Remote HSP dependency not found.");s.push(l)}return s}resolveModuleSpecsForProduct(e){let t=[];for(let r of this.profile.modules){let i=r.targets;if(!i||i.length===0){t.push(`${r.name}@default`);continue}let o=i.filter(s=>!s.applyToProducts||s.applyToProducts.includes(e));if(o.length!==0)for(let s of o)t.push(`${r.name}@${s.name}`)}return t}listBuildArtifacts(e,t){let r=[];for(let i of e){let o=i.indexOf("@"),s=o!==-1?i.substring(0,o):i,a=o!==-1?i.substring(o+1):"default",c=this.profile.modules.find(d=>d.name===s);if(!c)continue;let l=this.buildOutputPath(c.srcPath,t,["outputs",a]);if(Y.existsSync(l))for(let d of Y.readdirSync(l))(d.endsWith(".hap")||d.endsWith(".hsp")||d.endsWith(".har"))&&r.push(F.join(l,d))}return r}listProjectAppArtifacts(e){let t=E.ensurePathWithinRoot(this.rootDir,F.resolve(this.rootDir,"build","outputs",e));if(!Y.existsSync(t))return[];let r=[],i=o=>{for(let s of Y.readdirSync(o,{withFileTypes:!0})){let a=F.join(o,s.name);s.isDirectory()?i(a):s.name.endsWith(".app")&&r.push(a)}};return i(t),r}collectBuildArtifacts(e,t,r){let i=t;if(!e){let s=new Set(t);i=[...t,...this.profile.modules.map(a=>`${a.name}@default`).filter(a=>!s.has(a))]}let o=this.listBuildArtifacts(i,r);return e&&o.push(...this.listProjectAppArtifacts(r)),o}getSignedHapName(e,t,r,i){let o=null;if(e.endsWith("-unsigned.hap")?o=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(o=e.replace("-unsigned.hsp","-signed.hsp")),!o)return null;let s=this.buildOutputPath(t,r,["outputs",i,o]);return Y.existsSync(s)?o:null}buildOutputPath(e,t,r){let i=E.resolvePathWithinRoot(this.rootDir,e),o=F.resolve(i,"build",t,...r);return E.ensurePathWithinRoot(this.rootDir,o)}collectRemoteHsps(e){return e.flatMap(t=>{let r=t.dependRemoteHsps;return Array.isArray(r)?r.filter(i=>!!(i.hspName&&i.hspPath)).map(i=>({hspName:i.hspName,hspPath:i.hspPath})):[]})}parseOutputMetadata(e,t){let r;try{let c=Y.readFileSync(e,"utf-8");r=Vt.parse(c)}catch(c){throw new Error(`Failed to parse output metadata at ${e}: ${c instanceof Error?c.message:String(c)}`,{cause:c})}let i,o=!1,s=Array.isArray(r)?r:[r];for(let c of s)i||(i=c[t]),o||(o=c.isSigned===!0);if(!i)throw new y(`Could not find ${t} in output_metadata.json at ${e}`,"Could not find metadataKey in output_metadata.json at metadataPath.");this.validatePackageName(i);let a=this.collectRemoteHsps(s);return{packageName:i,isSigned:o,dependRemoteHsps:a}}validatePackageName(e){let t=F.basename(e);if(t!==e)throw new y(`Invalid traversal name: '${e}'. It must contain path characters.`,"Invalid traversal name.");if(!t.endsWith(".hap")&&!t.endsWith(".hsp"))throw new y(`Invalid package name '${t}'.It must be a .hap or .hsp file.`,"Invalid package name.")}};import{spawnSync as zh}from"child_process";import Me from"fs";import*as Ze from"os";import*as A from"path";import Ra from"fs";import*as Da from"os";import*as No from"path";import UC from"regedit";import{execFileSync as jC}from"child_process";import $h from"fs";import*as Fh from"os";import*as iu from"path";import{compare as FC}from"semver";function _r(n,e){return FC(n,e)}function hi(n,e){let t=Math.max(n.split(".").length,e.split(".").length);for(let r=0;r<t;r++){let i=Number(n.split(".")[r]??0)-Number(e.split(".")[r]??0);if(i)return i}return 0}function ka(n,e){let t=iu.join(n,"Contents","Info.plist");if(!$h.existsSync(t)){m(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[r,i]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let o=jC(r,i,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(o&&!o.includes("Does Not Exist"))return o}catch{}}function HC(n){let e=ka(n,"CFBundleShortVersionString");if(!e)return ka(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[ka(n,"CFBundleVersion"),ka(n,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let i of r){let o=i?.split(".").at(-1)?.replace(new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`),"");if(o&&/^\d+$/.test(o))return`${e}.${o}`}return e}function $r(n){if(Fh.platform()==="darwin")return HC(n);let e=iu.join(n,"product-info.json");try{let t=JSON.parse($h.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}var BC="DevEco Studio",WC=["Contents","Resources","product-info.json"],VC="name";function GC(n){return n.filter(e=>{try{return Ra.statSync(e).isDirectory()}catch{return!1}})}function qC(n){let e=No.join(n,...WC);if(Ra.existsSync(e))try{let r=JSON.parse(Ra.readFileSync(e,"utf8"))[VC];return typeof r=="string"&&r.trim()?r.trim():void 0}catch{return}}function zC(n){return qC(n)===BC}function JC(){let n=[];for(let e of[No.join(Da.homedir(),"Applications"),"/Applications"])try{n.push(...Ra.readdirSync(e).filter(t=>t.endsWith(".app")).map(t=>No.join(e,t)).filter(zC))}catch{}return n}function jh(n){return new Promise((e,t)=>UC.list(n,(r,i)=>r?t(r):e(i)))}async function Hh(n,e,t){let i=((await jh([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(i.length===0)return[];let o=await jh(i);return i.flatMap(s=>{let a=o[s]?.values?.[t]?.value;return a?[a]:[]})}async function YC(){let n=[No.join("C:","Program Files","Huawei","DevEco Studio")];for(let e of["HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall","HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"])try{n.push(...await Hh(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{n.push(...await Hh(e,()=>!0,""))}catch{}return n}async function Uh(){let n=Da.platform();if(n==="linux")throw new Error("DevEco Studio is not available on Linux. Set DEVECO_CLI_CLT_PATH to a Command Line Tools installation.");let e=n==="darwin"?JC():await YC(),t=GC(e).flatMap(r=>{let i=$r(r);return i?(m(`[ToolProvider] ${r} => version ${i}`),[{root:r,version:i}]):(m(`[ToolProvider] Skipping ${r}: 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((r,i)=>hi(i.version,r.version)>0?i:r)}import*as Bh from"fs";import*as Ke from"path";function ou(n,e){let t=Ke.relative(e,n);return t===""||!Ke.isAbsolute(t)&&!t.startsWith(`..${Ke.sep}`)&&t!==".."}function Fr(n){let e=Ke.resolve(n),t=[],r=e;for(;;)try{let i=Bh.realpathSync(r);return t.length===0?i:Ke.join(i,...t.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=Ke.dirname(r);if(o===r)return e;t.push(Ke.basename(r)),r=o}}function Wh(n,e){let t=Fr(e),r=Fr(n);return ou(r,t)?r:null}function su(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function xa(n){let e=su(n);if(!e)throw new Error("Path must not be empty.");return Fr(e)}var au="https://matrix.openharmony.cn",gt={TAGS_API_URL:`${au}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${au}/api/registry/skill/skills`,SKILL_API_BASE:`${au}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,DEFAULT_MAX_PAGES:100,SUCCESS_CODE:"20000"},Dt={"trae-cn":{path:".trae-cn/skills",displayName:"trae-cn"},opencode:{path:".config/opencode/skills",displayName:"opencode"},pi:{path:".pi/agent/skills",displayName:"pi"},deveco:{path:".config/deveco/skills",displayName:"deveco"},cursor:{path:".cursor/skills",displayName:"cursor"},codebuddy:{path:".codebuddy/skills",displayName:"codebuddy"},qoder:{path:".qoder/skills",displayName:"qoder"},"claude-code":{path:".claude/skills",projectPath:".claude/skills",displayName:"claude-code"},codex:{path:".codex/skills",displayName:"codex"},atomcode:{path:".atomcode/skills",displayName:"atomcode"},dsh:{path:".dsh/skills",projectPath:".dsh/skills",displayName:"deepseek harness"}};import{homedir as Gt}from"os";import Xe from"path";var qt="deveco-mcp";var jr={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:Xe.join(Gt(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},pi:{name:"pi",displayName:"Pi Coding Agent",supportsGlobal:!0,globalConfigPath:Xe.join(Gt(),".pi","agent","mcp.json"),projectConfigPath:".pi/mcp.json",mcpServersKey:"mcpServers",format:"standard"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:Xe.join(process.platform==="win32"?Xe.join(process.env.APPDATA??Xe.join(Gt(),"AppData","Roaming"),"Trae CN","User"):Xe.join(Gt(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:Xe.join(Gt(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:Xe.join(Gt(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"codebuddy"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:Xe.join(process.platform==="win32"?Xe.join(process.env.APPDATA??Xe.join(Gt(),"AppData","Roaming"),"Qoder","SharedClientCache"):Xe.join(Gt(),"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:Xe.join(Gt(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:Xe.join(Gt(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function Gh(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function Vh(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function KC(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."}}}function qh(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function Aa(n,e){return n.format==="opencode"?Gh(e):n.format==="claude-code"||n.format==="codex"?Vh(e):n.format==="codebuddy"?KC(e):qh(e)}var cu="https://developer.huawei.com/consumer/cn/download/";var XC=/^#\s*Version:\s*(\S+)/,ZC="26.0.0.810";function QC(n){try{let e=JSON.parse(Me.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch(e){m(`[ToolProvider] Failed to parse API level from ${n}: ${e instanceof Error?e.message:String(e)}`);return}}function ek(n){let e=A.join(n,"default","openharmony");return[A.join(n,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>A.join(e,t,"oh-uni-package.json"))]}var P=class n{constructor(e,t,r,i,o,s,a,c,l,d){this._sourceType=e;this._toolchainRoot=t;this._devecoStudioPath=r;this._nodePath=i;this._ohpmJsPath=o;this._hvigorJsPath=s;this._javaPath=a;this._sdkPath=c;this._hdcPath=l;this._emulatorPath=d}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 n.resolveCodelinterPath(this._toolchainRoot,this._sourceType)}get arktsLangServerPath(){let e=n.buildToolPaths(this._toolchainRoot,this._sourceType).arktsLangServerCandidates;for(let t of e)if(Me.existsSync(t.marker))return t.root;return null}get clangdPath(){let e=n.buildToolPaths(this._toolchainRoot,this._sourceType).clangdPath;return Me.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 emulatorLauncherPath(){return this.emulatorPath}assertJava(){if(this._sourceType==="clt"&&(this._javaPath=n.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 hi(e,t)}static async checkVersion(){let e=await n.resolveInstallSource();(e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)).assertVersion()}static async new(){let e=await n.resolveInstallSource();return e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)}static fromCLT(e){let t=n.buildToolPaths(e,"clt");return n.assertBuiltPathsInsideRoot(e,t,!1),new n("clt",e,void 0,t.nodePath,t.ohpmJsPath,t.hvigorJsPath,n.resolveCltJava(!1),t.sdkPath,t.hdcPath,t.emulatorPath)}static fromIDE(e,t="studio"){let r=n.buildToolPaths(e,"studio");return n.assertBuiltPathsInsideRoot(e,r,!0),new n(t,e,e,r.nodePath,r.ohpmJsPath,r.hvigorJsPath,r.javaPath,r.sdkPath,r.hdcPath,r.emulatorPath)}assertVersion(){if(this._sourceType==="clt"){this.assertCltVersion();return}this.assertIdeVersion()}readVersion(){return this._sourceType==="clt"?n.readCltVersion(this._toolchainRoot):$r(this._toolchainRoot)}assertCltVersion(e="26.0.0"){if(this._sourceType!=="clt")throw new Error("This operation requires Command Line Tools.");n.assertMinimumVersion(n.readCltVersion(this._toolchainRoot),"Command Line Tools","version.txt",e,this._toolchainRoot)}assertIdeVersion(e="6.0.0"){this.assertStudio(),n.assertMinimumVersion($r(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,r,i,o){if(!e)throw new y(`Failed to determine ${t} version from ${r} at ${o}`,`Failed to determine ${t} version from ${r}`);if(!/^\d+(?:\.\d+){1,3}$/.test(e))throw new y(`Invalid ${t} version "${e}" from ${r} at ${o}`,`Invalid ${t} version "${e}" from ${r}`);if(hi(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:
15
+ ${cu}`)}static resolveCodelinterPath(e,t){let r=n.buildToolPaths(e,t).codelinterCandidates,i=r.find(n.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 y(`${a}
16
16
  Searched paths:
17
- ${n.join(`
18
- `)}`,a)}let i=kt(e),s=kt(o);return r.assertInsideRoot(s,i,"codelinter"),s}static isValidRoot(e,t){if(!r.isDirectory(e))return!1;if(t==="clt")return xe.existsSync(P.join(e,"version.txt"));let n=Ye.platform()==="darwin"?P.join(e,"Contents"):e,o=Ye.platform()==="darwin"?P.join(n,"Info.plist"):P.join(n,"product-info.json");if(!xe.existsSync(o))return!1;let i=r.buildToolPaths(e,"studio");return[i.nodePath,i.ohpmJsPath,i.hvigorJsPath].every(xe.existsSync)}static buildToolPaths(e,t){return t==="clt"?r.buildCltToolPaths(e):r.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=Ye.platform()==="win32",n=t?".exe":"",o=P.join(e,"sdk");return{nodePath:t?P.join(e,"tool","node","node.exe"):P.join(e,"tool","node","bin","node"),ohpmJsPath:P.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:P.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:o,hdcPath:P.join(o,"default","openharmony","toolchains",`hdc${n}`),emulatorPath:P.join(e,"emulator",t?"Emulator.exe":"Emulator"),clangdPath:r.clangdPathFor(o),arktsLangServerCandidates:[{root:P.join(e,"arkts-lsp","lib"),marker:P.join(e,"arkts-lsp","lib","out","index.js")}],codelinterCandidates:r.codelinterCandidatesFor(e,"clt")}}static buildStudioToolPaths(e){let t=Ye.platform()==="darwin",n=Ye.platform()==="win32",o=t?P.join(e,"Contents"):e,i=P.join(o,"tools"),s=P.join(o,"sdk"),a=n?".exe":"";return{nodePath:n?P.join(i,"node","node.exe"):P.join(i,"node","bin","node"),ohpmJsPath:P.join(i,"ohpm","bin","pm-cli.js"),hvigorJsPath:P.join(i,"hvigor","bin","hvigorw.js"),javaPath:n?P.join(e,"jbr","bin","java.exe"):t?P.join(o,"jbr","Contents","Home","bin","java"):P.join(o,"jbr","bin","java"),sdkPath:s,hdcPath:P.join(s,"default","openharmony","toolchains",`hdc${a}`),emulatorPath:P.join(i,"emulator",n?"Emulator.exe":"Emulator"),clangdPath:r.clangdPathFor(s),arktsLangServerCandidates:r.studioArktsLangServerCandidates(e),codelinterCandidates:r.codelinterCandidatesFor(e,"studio")}}static codelinterCandidatesFor(e,t){if(t==="clt")return[P.join(e,"codelinter","index.js"),P.join(e,"codelinter","run","index.js"),P.join(e,"tool","codelinter","bin","codelinter.js"),P.join(e,"tool","codelinter","codelinter.js")];let n=Ye.platform()==="darwin"?["Contents"]:[];return[P.join(e,...n,"plugins","codelinter","run","index.js"),P.join(e,...n,"plugins","codelinter","index.js"),P.join(e,...n,"tools","codelinter","bin","codelinter.js"),P.join(e,...n,"tools","codelinter","codelinter.js")]}static studioArktsLangServerCandidates(e){if(Ye.platform()==="linux")return[];let t=Ye.platform()==="darwin"?["Contents"]:[],n=P.join(e,...t,"plugins","openharmony");return[{root:n,marker:P.join(n,"ace-server","out","index.js")}]}static clangdPathFor(e){return P.join(e,"default","openharmony","native","llvm","bin",Ye.platform()==="win32"?"clangd.exe":"clangd")}static isFile(e){try{return xe.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return xe.existsSync(e)&&xe.statSync(e).isDirectory()}catch{return!1}}static resolveInstallSource(){return r.installSourcePromise||(r.installSourcePromise=r.resolveInstallSourceUncached()),r.installSourcePromise}static async resolveInstallSourceUncached(){let e=[["DEVECO_CLI_STUDIO_PATH","studio","studio"],["DEVECO_CLI_CLT_PATH","clt","clt"],["DEVECO_HOME","studio","studio"],["DEVECO_PATH","studio","studio"]];for(let[n,o,i]of e){let s=process.env[n]?.trim();if(s){let a=r.resolveExplicitRoot(s,o,n);return m(`[ToolProvider] Using ${n} \u2192 ${a}`),{sourceType:i,toolchainRoot:a}}}let t=await Up();return m(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,n){let o;try{o=ps(e)}catch(i){throw new Error(`Invalid ${n}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return t==="studio"&&Ye.platform()==="darwin"&&(o=r.normalizeMacStudioRoot(o)),r.isValidRoot(o,t)?o:r.throwInvalidSource(o,t,n,e)}static assertBuiltPathsInsideRoot(e,t,n){let o=kt(e),i=[["node",t.nodePath],["ohpm",t.ohpmJsPath],["hvigor",t.hvigorJsPath],["sdk",t.sdkPath],["hdc",t.hdcPath],["emulator",t.emulatorPath]];n&&t.javaPath&&i.push(["java",t.javaPath]);for(let[s,a]of i)r.assertInsideRoot(a,o,s)}static assertInsideRoot(e,t,n){if(us(e,t)===null)throw new Error(`Unsafe toolchain path: ${n} resolves outside the toolchain root`)}static throwInvalidSource(e,t,n,o){throw t==="clt"&&r.isValidRoot(e,"studio")?new Error(`${n} must point to Command Line Tools, not a DevEco Studio installation; use DEVECO_CLI_STUDIO_PATH instead`):t==="studio"&&r.isValidRoot(e,"clt")?new Error(`${n} must point to a DevEco Studio installation, not Command Line Tools; use DEVECO_CLI_CLT_PATH instead`):new Error(`Invalid ${n}: ${o}`)}static normalizeMacStudioRoot(e){let t=`${P.sep}Contents`,n=P.normalize(e);return n.endsWith(t)?n.slice(0,-t.length):n}static readCltVersion(e){try{return xe.readFileSync(P.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(ub)?.[1]?.trim()).find(Boolean)}catch{return}}static resolveCltJava(e){let t=process.env.JAVA_HOME?.trim(),n=t&&(r.javaIn(P.join(t,"bin"))??r.javaIn(t)),o=(process.env.Path??process.env.PATH??"").split(P.delimiter).map(s=>r.javaIn(s.trim())).find(Boolean),i=n??o;if(i)return xe.realpathSync(i);if(e)throw new Error("No Java runtime found in CLT mode. Set JAVA_HOME to a JDK/JBR installation directory (or point JAVA_HOME at the JDK bin directory), or add the JDK bin directory to PATH.");return""}static javaIn(e){return(Ye.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(n=>P.join(e,n)).find(xe.existsSync)}getMaxApiLevel(){for(let e of fb(this.sdkPath)){let t=mb(e);if(t!==void 0)return t}return 23}getSdkPlatformVersion(){let e=P.join(this.sdkPath,"default","sdk-pkg.json"),t;try{t=JSON.parse(xe.readFileSync(e,"utf8"))}catch(i){throw new Error(`Failed to read SDK metadata: ${e}`,{cause:i})}let n=t.data?.platformVersion,o=typeof n=="string"?n.trim():"";if(!o)throw new Error(`Missing data.platformVersion in SDK metadata: ${e}`);return o}detectApiLevel(){return this.getMaxApiLevel()}_apiscanPaths;getApiscanPaths(){if(this._apiscanPaths)return this._apiscanPaths;let e=Ye.platform();if(e!=="darwin"&&e!=="win32")throw new Error(`Unsupported platform: ${e}. compat only supports macOS and Windows.`);if(!this._devecoStudioPath)throw new Error("DevEco Studio is required for compatibility checking. Set DEVECO_CLI_STUDIO_PATH or install DevEco Studio.");let t=e==="darwin"?"Contents":"",n=P.join(this._devecoStudioPath,t,"plugins","harmony","arkanalyzer-apiscan"),o=P.join(n,"resources","apiChange"),i=P.join(n,"api-change-scan.js");if(!xe.existsSync(o)||!xe.existsSync(i)){let s=nr(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${pb}. Upgrade before using 'check compat' at ${Zc}`)}return this._apiscanPaths={apiChangeDir:o,scriptPath:i},this._apiscanPaths}};import{execa as Sb}from"execa";import*as Xp from"net";import*as ir from"path";import*as fs from"fs";import*as Zp from"os";import{execFile as Jp}from"child_process";import{existsSync as hb}from"fs";var Yp="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",Qc;function gb(){return Qc===void 0&&(Qc=hb(Yp)),Qc}function $e(r){return new Promise(e=>{let t=process.platform==="win32",n=t?"tasklist":"ps",o=t?["/fi",`PID eq ${r}`,"/fo","csv","/nh"]:["-o","rss=","-p",String(r)];m(`Executing: ${n} ${o.join(" ")}`),Jp(n,o,{timeout:5e3,windowsHide:!0},(i,s)=>{if(i){e(null);return}e(t?wb(s):vb(s))})})}async function yb(r){return new Promise(e=>{let t=process.platform==="win32",n,o;if(t){if(!gb()){e([]);return}n=Yp,o=["-NoProfile","-Command",`Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq ${r} } | Select-Object -ExpandProperty ProcessId`]}else n="ps",o=["-o","pid=","--ppid",String(r)];Jp(n,o,{timeout:5e3,windowsHide:!0},(i,s)=>{if(i){e([]);return}let a=[],c=s.trim().split(`
19
- `);for(let l of c){let d=l.trim();d&&/^\d+$/.test(d)&&a.push(Number(d))}e(a)})})}async function Kp(r){let e=0,t=await $e(r);t&&(e+=Number(t)*1024);let n=await yb(r);for(let o of n)e+=await Kp(o);return e}function te(r){return`${(r/1024/1024).toFixed(2)}MB`}async function qp(r,e){if(!r)return process.memoryUsage().rss;if(e)return Kp(r);let t=await $e(r);return t?Number(t)*1024:0}function bn(r,e=500,t=!1){let n=0,o=!1,i=setInterval(async()=>{if(o)return;let s=await qp(r,t);s>n&&(n=s)},e);return{stop:async()=>{o=!0,clearInterval(i);let s=await qp(r,t);return Math.max(n,s)}}}function vb(r){let e=r.trim().match(/^(\d+)$/);return e?e[1]:null}function wb(r){let e=r.match(/"([^"]+?)\s*K"/i);return e&&e[1].replace(/\D/g,"")||null}var Ke=class{toolProvider;projectRoot;env;silent;constructor(e,t,n=!1){this.toolProvider=e,this.projectRoot=t,this.silent=n;let o=ir.dirname(e.javaPath),i=`${o}${ir.delimiter}${process.env.PATH||""}`,s={...process.env,PATH:i,DEVECO_SDK_HOME:e.sdkPath};e.sourceType==="clt"&&e.javaPath&&(s.JAVA_HOME=ir.dirname(o)),this.env=s}async sync(e,t){let n=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(n)}async buildProduct(e,t){let n=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(n)}async buildModules(e,t,n,o){let i=[...Array.from(o),"--mode","module","-p",`module=${n.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(i)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];return this.runHvigor(e)}async stopDaemon(){return this.runHvigor(["--stop-daemon"])}async ensureDaemonRunning(){if(this.findProjectDaemon()){m("[HvigorAdapter] Daemon already running.");return}m("[HvigorAdapter] No daemon running, starting via --sync --daemon (no hap build)."),await this.runHvigor(["--sync","--daemon"])}isDaemonRunning(e){return this.findProjectDaemon(e)!==null}async isDaemonAlive(e){let t=this.findProjectDaemon(e);return t?this.isPortListening(t.port):!1}isPortListening(e){return new Promise(t=>{let n=new Xp.Socket;n.setTimeout(2e3),n.once("connect",()=>{n.destroy(),t(!0)}),n.once("error",()=>t(!1)),n.once("timeout",()=>{n.destroy(),t(!1)}),n.connect(e,"127.0.0.1")})}findProjectDaemon(e){let t=this.getDaemonRegistryPath();if(!fs.existsSync(t))return null;try{let n=fs.readFileSync(t,"utf-8"),o=JSON.parse(n),i=e??this.projectRoot,s=Object.values(o).filter(a=>a.cwdPath===i&&(a.state==="idle"||a.state==="half_busy"||a.state==="busy")&&this.isProcessAlive(a.pid));return s.length>0?s[s.length-1]:null}catch{return null}}getDaemonRegistryPath(){let e=process.env.HVIGOR_USER_HOME||ir.join(Zp.homedir(),".hvigor");return ir.join(e,"daemon","cache","daemon-sec.json")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}async compileNative(e,t){let n=["--mode","module"];return t&&n.push("-p",`module=${t}`),n.push("-p",`product=${e}`,"compileNative","--analyze=normal"),this.runHvigor(n)}async runHvigor(e){let t=this.toolProvider.nodePath,n=[this.toolProvider.hvigorJsPath,...e];m(`Executing: ${t} ${n.join(" ")}`);let o=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit",i=Sb(t,n,{cwd:this.projectRoot,env:this.env,stdout:o,stderr:o}),s=bn(i.pid,500,!0),a="";try{await i}finally{let c=await s.stop();c>0&&(a=te(c),m(`Hvigor peak memory: ${a}`))}return a}};import{execa as bb}from"execa";var En=class{toolProvider;projectRoot;peakMemoryMb="";constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=[this.toolProvider.ohpmJsPath,"install","--all"];m(`Executing: ${e} ${t.join(" ")}`);let n=bb(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"}),o=bn(n.pid);try{await n}finally{let i=await o.stop();i>0&&(this.peakMemoryMb=te(i))}}};import{mkdir as Eb}from"fs/promises";import{dirname as Cb,resolve as Pb}from"path";import{execa as Ab}from"execa";import{lock as el,check as I0}from"proper-lockfile";function tl(r){return Pb(r,".hvigor",".build-lock")}function Ib(r){let e=!1;return()=>{e||(e=!0,r?.())}}async function Qp(r){let e=Cb(tl(r));if(await Eb(e,{recursive:!0}),process.platform==="win32")try{await Ab("attrib",["+h",e])}catch{}}async function kb(r,e){let t=new AbortController,n=Ib(e);await Qp(r);let o={lockfilePath:tl(r),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await el(r,{...o,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return n(),{release:await el(r,{...o,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Jr(r,e,t){let{release:n,signal:o}=await kb(r,t);try{return await e(o)}finally{await n()}}async function hs(r,e){let t=new AbortController;await Qp(r);let n={lockfilePath:tl(r),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},o;try{o=await el(r,{...n,retries:0})}catch(i){if(i&&typeof i=="object"&&"code"in i&&i.code==="ELOCKED")return{acquired:!1};throw i}try{return{acquired:!0,result:await e(t.signal)}}finally{await o()}}import*as sr from"fs";import*as Yr from"path";import Db from"json5";var Tb=1e3;function ys(r){m(`[ProjectCheck] Checking sync required at project root: ${r}`);let e=Yr.join(r,Re.SYNC_OUTPUT_PATH);if(!sr.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return m(`[ProjectCheck] ${l.reason}`),l}let t=sr.statSync(e).mtimeMs;m(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let n=Rb(r);if(n===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return m(`[ProjectCheck] ${l.reason}`),l}let o=Yr.join(r,Re.OH_PACKAGE_JSON5),i=gs(o,t,"root");if(i.required)return m(`[ProjectCheck] Root check: ${i.reason}`),i;let s=Yr.join(r,Re.BUILD_PROFILE_JSON5),a=gs(s,t,"build-profile");if(a.required)return m(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of n){let d=Yr.join(r,l.srcPath,Re.OH_PACKAGE_JSON5),g=gs(d,t,l.name);if(g.required)return m(`[ProjectCheck] Module '${l.name}' check: ${g.reason}`),g;let y=Yr.join(r,l.srcPath,Re.BUILD_PROFILE_JSON5),b=gs(y,t,l.name);if(b.required)return m(`[ProjectCheck] Module '${l.name}' build-profile check: ${b.reason}`),b}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return m(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function gs(r,e,t){if(!sr.existsSync(r))return{required:!1,reason:`${t}: source not found, skip`};let n=sr.statSync(r).mtimeMs;return n-e>Tb?{required:!0,reason:`${t}: source mtime (${new Date(n).toISOString()}) is newer than sync baseline (${new Date(e).toISOString()})`}:{required:!1,reason:`${t}: up-to-date`}}function Rb(r){let e=Yr.join(r,Re.BUILD_PROFILE_JSON5);try{let t=sr.readFileSync(e,"utf-8");if(!t.trim())return null;let n=Db.parse(t);if(typeof n!="object"||n===null)return null;let o=n.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}import*as ee from"fs";import*as ae from"path";import*as em from"util";var rl="";function ws(r){if(!r||r==="auto"||r==="stdout"||r==="none"){rl="";return}rl=r}function tm(){return rl||(kp()??"")}function vs(r,...e){if(e.length===0)return r;try{return em.format(r,...e)}catch{return[r,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var f={info(r,...e){h.info(`[lsp] ${vs(r,...e)}`)},warn(r,...e){h.warn(`[lsp] ${vs(r,...e)}`)},error(r,...e){h.error(`[lsp] ${vs(r,...e)}`)},debug(r,...e){h.debug(`[lsp] ${vs(r,...e)}`)}};import*as Lo from"fs";import*as No from"os";import*as Cn from"path";import xb from"json5";var v={INITIALIZE:"initialize",INITIALIZED:"initialized",SHUTDOWN:"shutdown",EXIT:"exit",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",DID_CLOSE:"textDocument/didClose",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",DECLARATION:"textDocument/declaration",REFERENCES:"textDocument/references",IMPLEMENTATION:"textDocument/implementation",COMPLETION:"textDocument/completion",COMPLETION_ITEM_RESOLVE:"completionItem/resolve",SIGNATURE_HELP:"textDocument/signatureHelp",CODE_ACTION:"textDocument/codeAction",PREPARE_RENAME:"textDocument/prepareRename",RENAME:"textDocument/rename",DOCUMENT_HIGHLIGHT:"textDocument/documentHighlight",DOCUMENT_LINK:"textDocument/documentLink",INLAY_HINT:"textDocument/inlayHint",DOCUMENT_SYMBOL:"textDocument/documentSymbol",WORKSPACE_SYMBOL:"workspace/symbol",DIAGNOSTIC:"textDocument/diagnostic",WORKSPACE_DIAGNOSTIC:"workspace/diagnostic",PREPARE_CALL_HIERARCHY:"textDocument/prepareCallHierarchy",INCOMING_CALLS:"callHierarchy/incomingCalls",OUTGOING_CALLS:"callHierarchy/outgoingCalls",PREPARE_TYPE_HIERARCHY:"textDocument/prepareTypeHierarchy",SUPERTYPES:"typeHierarchy/supertypes",SUBTYPES:"typeHierarchy/subtypes",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",DID_CREATE_FILES:"workspace/didCreateFiles",DID_DELETE_FILES:"workspace/didDeleteFiles",PROGRESS:"$/progress",WINDOW_SHOW_MESSAGE:"window/showMessage",WINDOW_LOG_MESSAGE:"window/logMessage",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing",ARKTS_ERROR:"arkts/error",CPP_INITIALIZED:"cpp/initialized",CPP_INITIALIZATION_FAILED:"cpp/initializationFailed",CPP_INDEXING_PROGRESS:"cpp/indexingProgress",CPP_SYNC_PROJECT:"cpp/syncProject",CPP_SYNC_COMPLETED:"cpp/syncCompleted",CPP_REINITIALIZING:"cpp/reinitializing",CPP_ERROR:"cpp/error",BROADCAST:"lsp/broadcast"},R="2.0";var rm=8192,nl=100,nm=.03,om=.7,ot=900*1e3;function Xe(r){if(!Lo.existsSync(r))return null;try{let e=Lo.readFileSync(r,"utf-8");return e.trim()?xb.parse(e):null}catch{return null}}function Ss(r,e){let t=Math.floor(No.totalmem()/1048576),n=Math.floor(t*om),o,i;e!==void 0&&Number.isFinite(e)&&e>0?(o=e,i=`override(${e})`):(o=rm,r>nl&&(o+=(r-nl)*nm*1024),i=`formula(moduleCount=${r})`);let s=n>0&&o>n;s&&(o=n);let a=Math.round(o);return f.info(`[computeLspServerMaxSize] source=${i}, physicalTotal=${t}MB, physicalCap(70%)=${n}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function gt(r){if(r.startsWith("file:"))return r;try{let e=Cn.resolve(r),t=new URL(`file://${e}`).toString();if(No.platform()==="win32"){let n=t.match(/^file:\/\/\/([A-Za-z]):/);if(n){let o=n[1].toUpperCase(),i=t.substring(`file:///${n[1]}:`.length);t=`file:///${o}%3A${i}`}}return t}catch{return r}}function Pn(r){return r&&r.replace(/\\/g,"/")}function J(r){let e=Cn.normalize(r).replace(/\\/g,"/");if(No.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function im(r){return Cn.join(r,"build-profile.json5")}var Ft=class{constructor(e){this.projectRoot=e}getAllModuleInfo(){let e=im(this.projectRoot);try{let t=Xe(e);if(typeof t!="object"||t===null)return[];let n=t.modules;return Array.isArray(n)?n.filter(o=>{if(typeof o!="object"||o===null)return!1;let i=o;return typeof i.name=="string"&&typeof i.srcPath=="string"}):[]}catch(t){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};import{spawn as Lb}from"child_process";import*as Es from"fs";var Nb=600*1e3;function Ob(r,e,t){let n=t.split(/\s+/).filter(o=>o.length>0);return[r,[e,...n]]}function Mb(r){let e=[],t=[];return r.stdout?.on("data",n=>{e.push(n.toString())}),r.stderr?.on("data",n=>{let o=n.toString();t.push(o),o.split(/\r?\n/).filter(Boolean).forEach(i=>f.info("[hvigor:err] %s",i))}),{stdout:e,stderr:t}}function bs(r){return r.join("")}function _b(r,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
17
+ ${r.join(`
18
+ `)}`,a)}let o=Fr(e),s=Fr(i);return n.assertInsideRoot(s,o,"codelinter"),s}static isValidRoot(e,t){if(!n.isDirectory(e))return!1;if(t==="clt")return Me.existsSync(A.join(e,"version.txt"));let r=Ze.platform()==="darwin"?A.join(e,"Contents"):e,i=Ze.platform()==="darwin"?A.join(r,"Info.plist"):A.join(r,"product-info.json");if(!Me.existsSync(i))return!1;let o=n.buildToolPaths(e,"studio");return[o.nodePath,o.ohpmJsPath,o.hvigorJsPath].every(Me.existsSync)}static buildToolPaths(e,t){return t==="clt"?n.buildCltToolPaths(e):n.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=Ze.platform()==="win32",r=t?".exe":"",i=A.join(e,"sdk");return{nodePath:t?A.join(e,"tool","node","node.exe"):A.join(e,"tool","node","bin","node"),ohpmJsPath:A.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:A.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:i,hdcPath:A.join(i,"default","openharmony","toolchains",`hdc${r}`),emulatorPath:A.join(e,"emulator",t?"Emulator.exe":"Emulator"),clangdPath:n.clangdPathFor(i),arktsLangServerCandidates:[{root:A.join(e,"arkts-lsp","lib"),marker:A.join(e,"arkts-lsp","lib","out","index.js")}],codelinterCandidates:n.codelinterCandidatesFor(e,"clt")}}static buildStudioToolPaths(e){let t=Ze.platform()==="darwin",r=Ze.platform()==="win32",i=t?A.join(e,"Contents"):e,o=A.join(i,"tools"),s=A.join(i,"sdk"),a=r?".exe":"";return{nodePath:r?A.join(o,"node","node.exe"):A.join(o,"node","bin","node"),ohpmJsPath:A.join(o,"ohpm","bin","pm-cli.js"),hvigorJsPath:A.join(o,"hvigor","bin","hvigorw.js"),javaPath:r?A.join(e,"jbr","bin","java.exe"):t?A.join(i,"jbr","Contents","Home","bin","java"):A.join(i,"jbr","bin","java"),sdkPath:s,hdcPath:A.join(s,"default","openharmony","toolchains",`hdc${a}`),emulatorPath:A.join(o,"emulator",r?"Emulator.exe":"Emulator"),clangdPath:n.clangdPathFor(s),arktsLangServerCandidates:n.studioArktsLangServerCandidates(e),codelinterCandidates:n.codelinterCandidatesFor(e,"studio")}}static codelinterCandidatesFor(e,t){if(t==="clt")return[A.join(e,"codelinter","index.js"),A.join(e,"codelinter","run","index.js"),A.join(e,"tool","codelinter","bin","codelinter.js"),A.join(e,"tool","codelinter","codelinter.js")];let r=Ze.platform()==="darwin"?["Contents"]:[];return[A.join(e,...r,"plugins","codelinter","run","index.js"),A.join(e,...r,"plugins","codelinter","index.js"),A.join(e,...r,"tools","codelinter","bin","codelinter.js"),A.join(e,...r,"tools","codelinter","codelinter.js")]}static studioArktsLangServerCandidates(e){if(Ze.platform()==="linux")return[];let t=Ze.platform()==="darwin"?["Contents"]:[],r=A.join(e,...t,"plugins","openharmony");return[{root:r,marker:A.join(r,"ace-server","out","index.js")}]}static clangdPathFor(e){return A.join(e,"default","openharmony","native","llvm","bin",Ze.platform()==="win32"?"clangd.exe":"clangd")}static isFile(e){try{return Me.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return Me.existsSync(e)&&Me.statSync(e).isDirectory()}catch{return!1}}static resolveInstallSource(){return n.installSourcePromise||(n.installSourcePromise=n.resolveInstallSourceUncached()),n.installSourcePromise}static async resolveInstallSourceUncached(){let e=[["DEVECO_CLI_STUDIO_PATH","studio","studio"],["DEVECO_CLI_CLT_PATH","clt","clt"],["DEVECO_HOME","studio","studio"],["DEVECO_PATH","studio","studio"]];for(let[r,i,o]of e){let s=process.env[r]?.trim();if(s){let a=n.resolveExplicitRoot(s,i,r);return m(`[ToolProvider] Using ${r} \u2192 ${a}`),{sourceType:o,toolchainRoot:a}}}let t=await Uh();return m(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,r){let i;try{i=xa(e)}catch(o){throw new Error(`Invalid ${r}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}return t==="studio"&&Ze.platform()==="darwin"&&(i=n.normalizeMacStudioRoot(i)),n.isValidRoot(i,t)?i:n.throwInvalidSource(i,t,r,e)}static assertBuiltPathsInsideRoot(e,t,r){let i=Fr(e),o=[["node",t.nodePath],["ohpm",t.ohpmJsPath],["hvigor",t.hvigorJsPath],["sdk",t.sdkPath],["hdc",t.hdcPath],["emulator",t.emulatorPath]];r&&t.javaPath&&o.push(["java",t.javaPath]);for(let[s,a]of o)n.assertInsideRoot(a,i,s)}static assertInsideRoot(e,t,r){if(Wh(e,t)===null)throw new Error(`Unsafe toolchain path: ${r} resolves outside the toolchain root`)}static throwInvalidSource(e,t,r,i){throw t==="clt"&&n.isValidRoot(e,"studio")?new Error(`${r} must point to Command Line Tools, not a DevEco Studio installation; use DEVECO_CLI_STUDIO_PATH instead`):t==="studio"&&n.isValidRoot(e,"clt")?new Error(`${r} must point to a DevEco Studio installation, not Command Line Tools; use DEVECO_CLI_CLT_PATH instead`):new Error(`Invalid ${r}: ${i}`)}static normalizeMacStudioRoot(e){let t=`${A.sep}Contents`,r=A.normalize(e);return r.endsWith(t)?r.slice(0,-t.length):r}static readCltVersion(e){try{return Me.readFileSync(A.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(XC)?.[1]?.trim()).find(Boolean)}catch{return}}static resolveCltJava(e){let t=process.env.JAVA_HOME?.trim(),i=[t&&(n.javaIn(A.join(t,"bin"))??n.javaIn(t)),...n.locateJavaFromPath()].filter(o=>!!o);if(!e)return i[0]?Me.realpathSync(i[0]):"";for(let o of i)if(n.isUsableJava(o))return Me.realpathSync(o);throw new Error("No Java runtime found in CLT mode. Set JAVA_HOME to a JDK/JBR installation directory (or point JAVA_HOME at the JDK bin directory), or add the JDK bin directory to PATH.")}static locateJavaFromPath(){let e=Ze.platform()==="win32",t=e?"where.exe":"which",r=e?["java"]:["-a","java"];m(`Executing: ${t} ${r.join(" ")}`);let i=zh(t,r,{encoding:"utf8",stdio:"pipe",timeout:2e3,windowsHide:!0});return i.error||i.status!==0?[]:i.stdout.split(/\r?\n/).map(o=>o.trim()).filter(Boolean)}static javaIn(e){return(Ze.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(r=>A.join(e,r)).find(Me.existsSync)}static isUsableJava(e){let t=["-version"];m(`Executing: ${e} ${t.join(" ")}`);let r=zh(e,t,{encoding:"utf8",stdio:"pipe",timeout:2e3,windowsHide:!0});return!r.error&&r.status===0}getMaxApiLevel(){for(let e of ek(this.sdkPath)){let t=QC(e);if(t!==void 0)return t}return 23}getSdkPlatformVersion(){let e=A.join(this.sdkPath,"default","sdk-pkg.json"),t;try{t=JSON.parse(Me.readFileSync(e,"utf8"))}catch(o){throw new Error(`Failed to read SDK metadata: ${e}`,{cause:o})}let r=t.data?.platformVersion,i=typeof r=="string"?r.trim():"";if(!i)throw new Error(`Missing data.platformVersion in SDK metadata: ${e}`);return i}detectApiLevel(){return this.getMaxApiLevel()}_apiscanPaths;getApiscanPaths(){if(this._apiscanPaths)return this._apiscanPaths;let e=Ze.platform();if(e!=="darwin"&&e!=="win32")throw new Error(`Unsupported platform: ${e}. compat only supports macOS and Windows.`);if(!this._devecoStudioPath)throw new Error("DevEco Studio is required for compatibility checking. Set DEVECO_CLI_STUDIO_PATH or install DevEco Studio.");let t=e==="darwin"?"Contents":"",r=A.join(this._devecoStudioPath,t,"plugins","harmony","arkanalyzer-apiscan"),i=A.join(r,"resources","apiChange"),o=A.join(r,"api-change-scan.js");if(!Me.existsSync(i)||!Me.existsSync(o)){let s=$r(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${ZC}. Upgrade before using 'check compat' at ${cu}`)}return this._apiscanPaths={apiChangeDir:i,scriptPath:o},this._apiscanPaths}};import{execa as fk}from"execa";import*as eg from"net";import*as Hr from"path";import*as Oa from"fs";import*as Ma from"os";import{execFile as uu,spawn as Jh}from"child_process";import{existsSync as tk,readdirSync as rk,readFileSync as nk}from"fs";var Ta="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",lu,du="---MEMORY-SAMPLE-DELIMITER---";function Kh(){return lu===void 0&&(lu=tk(Ta)),lu}function lt(n){return new Promise(e=>{let t=process.platform==="win32",r=t?"tasklist":"ps",i=t?["/fi",`PID eq ${n}`,"/fo","csv","/nh"]:["-o","rss=","-p",String(n)];m(`Executing: ${r} ${i.join(" ")}`),uu(r,i,{timeout:5e3,windowsHide:!0},(o,s)=>{if(o){e(null);return}e(t?mk(s):pk(s))})})}async function ik(){return process.platform==="linux"?Ia():process.platform==="darwin"?ok():process.platform==="win32"?sk():[]}function Ia(){let n=[],e;try{e=rk("/proc")}catch{return n}for(let t of e){if(!/^\d+$/.test(t))continue;let r=Number(t);try{let i=nk(`/proc/${r}/status`,"utf8"),o=i.match(/VmRSS:\s+(\d+)\s+kB/),s=i.match(/^PPid:\s+(\d+)/m);if(!o||!s)continue;n.push({pid:r,ppid:Number(s[1]),rssBytes:Number(o[1])*1024})}catch{}}return n}function ok(){return new Promise(n=>{uu("ps",["-ax","-o","pid=,ppid=,rss="],{timeout:5e3,windowsHide:!0},(e,t)=>{if(e){n([]);return}n(Xh(t))})})}function Xh(n){let e=[];for(let t of n.trim().split(`
19
+ `)){let r=t.trim().split(/\s+/);if(r.length<3)continue;let i=Number(r[0]),o=Number(r[1]),s=Number(r[2]);isNaN(i)||isNaN(o)||isNaN(s)||e.push({pid:i,ppid:o,rssBytes:s*1024})}return e}function sk(){return new Promise(n=>{if(!Kh()){n([]);return}uu(Ta,["-NoProfile","-Command",'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId),$($_.ParentProcessId),$($_.WorkingSetSize)" }'],{timeout:5e3,windowsHide:!0},(t,r)=>{if(t){n([]);return}n(Zh(r))})})}function Zh(n){let e=[];for(let t of n.trim().split(`
20
+ `)){let r=t.trim();if(!r)continue;let i=r.split(",");if(i.length<3)continue;let o=Number(i[0]),s=Number(i[1]),a=Number(i[2]);isNaN(o)||isNaN(s)||isNaN(a)||e.push({pid:o,ppid:s,rssBytes:a})}return e}function Qh(n,e){let t=new Map,r=new Map;for(let a of n){t.set(a.pid,a.rssBytes);let c=r.get(a.ppid);c?c.push(a.pid):r.set(a.ppid,[a.pid])}let i=0,o=new Set,s=[e];for(;s.length>0;){let a=s.shift();if(o.has(a))continue;o.add(a),i+=t.get(a)??0;let c=r.get(a);c&&s.push(...c)}return i}async function ak(n){let e=await ik();return Qh(e,n)}function ck(n){if(process.platform==="darwin"){let e=(n/1e3).toFixed(1),t=`while true; do ps -ax -o pid=,ppid=,rss=; echo '${du}'; sleep ${e}; done`;return m(`Executing: sh -c ${t}`),Jh("sh",["-c",t],{stdio:["ignore","pipe","ignore"],windowsHide:!0})}if(process.platform==="win32"&&Kh()){let e=`while ($true) { Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId),$($_.ParentProcessId),$($_.WorkingSetSize)" }; Write-Output '${du}'; Start-Sleep -Milliseconds ${n} }`;return m(`Executing: ${Ta} -NoProfile -Command ${e}`),Jh(Ta,["-NoProfile","-Command",e],{stdio:["ignore","pipe","ignore"],windowsHide:!0})}return null}function ce(n){return`${(n/1024/1024).toFixed(2)}MB`}async function Yh(n,e){if(!n)return process.memoryUsage().rss;if(e)return ak(n);let t=await lt(n);return t?Number(t)*1024:0}function gi(n,e=2e3,t=!1){let r=0,i=!1,o=a=>{if(i||!n)return;let c=t?Qh(a,n):a.find(l=>l.pid===n)?.rssBytes??0;c>r&&(r=c)};if(!n)return dk(e);if(process.platform==="linux")return uk(e,o,()=>r);let s=ck(e);return s?(lk(s,o),{stop:async()=>{i=!0;try{s.kill()}catch{}let a=await Yh(n,t);return Math.max(r,a)}}):{stop:async()=>{i=!0;let a=await Yh(n,t);return Math.max(r,a)}}}function lk(n,e){let t=process.platform==="darwin"?Xh:Zh,r="";n.stdout?.on("data",i=>{r+=i.toString();let o=r.split(du);r=o.pop()??"";for(let s of o)e(t(s))}),n.on("error",()=>{})}function dk(n){let e=process.memoryUsage().rss,t=setInterval(()=>{let r=process.memoryUsage().rss;r>e&&(e=r)},n);return{stop:async()=>(clearInterval(t),Math.max(e,process.memoryUsage().rss))}}function uk(n,e,t){e(Ia());let r=setInterval(()=>e(Ia()),n);return{stop:async()=>(clearInterval(r),e(Ia()),t())}}function pk(n){let e=n.trim().match(/^(\d+)$/);return e?e[1]:null}function mk(n){let e=n.match(/"([^"]+?)\s*K"/i);return e&&e[1].replace(/\D/g,"")||null}var Na="module",dt=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let i=Hr.dirname(e.javaPath),o=`${i}${Hr.delimiter}${process.env.PATH||""}`,s={...process.env,PATH:o,DEVECO_SDK_HOME:e.sdkPath},a=Ma.platform()==="darwin"&&e.javaPath==="/usr/bin/java";e.sourceType==="clt"&&e.javaPath&&!a&&(s.JAVA_HOME=Hr.dirname(i)),this.env=s}async sync(e,t){let r=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`];return this.runHvigor(r)}async buildProduct(e,t){let r=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`];return this.runHvigor(r)}async buildModules(e,t,r,i){let o=[...Array.from(i),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`];return this.runHvigor(o)}async clean(e,t){let r=["clean","--mode",e??Na];return t&&t.length>0&&r.push("-p",`module=${t.join(",")}`),this.runHvigor(r)}async stopDaemon(){return this.runHvigor(["--stop-daemon"])}async ensureDaemonRunning(){if(this.findProjectDaemon()){m("[HvigorAdapter] Daemon already running.");return}m("[HvigorAdapter] No daemon running, starting via --sync --daemon (no hap build)."),await this.runHvigor(["--sync","--daemon"])}isDaemonRunning(e){return this.findProjectDaemon(e)!==null}async isDaemonAlive(e){let t=this.findProjectDaemon(e);return t?this.isPortListening(t.port):!1}isPortListening(e){return new Promise(t=>{let r=new eg.Socket;r.setTimeout(2e3),r.once("connect",()=>{r.destroy(),t(!0)}),r.once("error",()=>t(!1)),r.once("timeout",()=>{r.destroy(),t(!1)}),r.connect(e,"127.0.0.1")})}findProjectDaemon(e){let t=this.getDaemonRegistryPath();if(!Oa.existsSync(t))return null;try{let r=Oa.readFileSync(t,"utf-8"),i=JSON.parse(r),o=e??this.projectRoot,s=Object.values(i).filter(a=>a.cwdPath===o&&(a.state==="idle"||a.state==="half_busy"||a.state==="busy")&&this.isProcessAlive(a.pid));return s.length>0?s[s.length-1]:null}catch{return null}}getDaemonRegistryPath(){let e=process.env.HVIGOR_USER_HOME||Hr.join(Ma.homedir(),".hvigor");return Hr.join(e,"daemon","cache","daemon-sec.json")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}async compileNative(e,t){let r=["--mode","module"];return t&&r.push("-p",`module=${t}`),r.push("-p",`product=${e}`,"compileNative"),this.runHvigor(r)}async runHvigor(e){let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];m(`Executing: ${t} ${r.join(" ")}`);let i=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit",o=fk(t,r,{cwd:this.projectRoot,env:this.env,stdout:i,stderr:i}),s=Ye()?void 0:gi(o.pid,2e3,!0),a="";try{await o}finally{if(s){let c=await s.stop();c>0&&(a=ce(c),m(`Hvigor peak memory: ${a}`))}}return a}};import{execa as hk}from"execa";var yi=class{toolProvider;projectRoot;peakMemoryMb="";constructor(e,t){this.toolProvider=e,this.projectRoot=t}async install(){let e=this.toolProvider.nodePath,t=[this.toolProvider.ohpmJsPath,"install"];m(`Executing: ${e} ${t.join(" ")}`);let r=hk(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"}),i=Ye()?void 0:gi(r.pid,2e3,!1);try{await r}finally{if(i){let o=await i.stop();o>0&&(this.peakMemoryMb=ce(o))}}}};import{mkdir as gk}from"fs/promises";import{dirname as yk,resolve as wk}from"path";import{execa as vk}from"execa";import{lock as pu,check as pW}from"proper-lockfile";function mu(n){return wk(n,".hvigor",".build-lock")}function bk(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function tg(n){let e=yk(mu(n));if(await gk(e,{recursive:!0}),process.platform==="win32")try{await vk("attrib",["+h",e])}catch{}}async function Sk(n,e){let t=new AbortController,r=bk(e);await tg(n);let i={lockfilePath:mu(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await pu(n,{...i,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return r(),{release:await pu(n,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Tn(n,e,t){let{release:r,signal:i}=await Sk(n,t);try{return await e(i)}finally{await r()}}async function La(n,e){let t=new AbortController;await tg(n);let r={lockfilePath:mu(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await pu(n,{...r,retries:0})}catch(o){if(o&&typeof o=="object"&&"code"in o&&o.code==="ELOCKED")return{acquired:!1};throw o}try{return{acquired:!0,result:await e(t.signal)}}finally{await i()}}import*as dr from"fs";import*as zt from"path";import Ek from"json5";var Pk=1e3;function wi(n,e,t){let r=Ck(n,e,t);return r.required?(m(`[ProjectCheck] ${t} check: ${r.reason}`),r):null}function _a(n){m(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=zt.join(n,Pe.SYNC_OUTPUT_PATH);if(!dr.existsSync(e)){let a={required:!0,reason:`sync baseline file not found: ${e}`};return m(`[ProjectCheck] ${a.reason}`),a}let t=dr.statSync(e).mtimeMs,r=zt.join(n,Pe.LOCK_JSON5_PATH);if(!dr.existsSync(r)){let a={required:!0,reason:`oh_modules lock not found: ${r}`};return m(`[ProjectCheck] ${a.reason}`),a}let i=kk(n);if(i===null)return{required:!0,reason:"failed to parse build-profile.json5"};let o=wi(zt.join(n,Pe.OH_PACKAGE_JSON5),t,"root");if(o||(o=wi(zt.join(n,Pe.BUILD_PROFILE_JSON5),t,"build-profile"),o)||(o=wi(zt.join(n,Pe.HVIGOR_CONFIG),t,"hvigor-config"),o)||(o=wi(zt.join(n,Pe.HVIGOR_CONFIG),t,"hvigor-config"),o))return o;for(let a of i)if(o=wi(zt.join(n,a.srcPath,Pe.OH_PACKAGE_JSON5),t,a.name),o||(o=wi(zt.join(n,a.srcPath,Pe.BUILD_PROFILE_JSON5),t,a.name),o))return o;let s=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return m(`[ProjectCheck] ${s}`),{required:!1,reason:s}}function Ck(n,e,t){if(!dr.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=dr.statSync(n).mtimeMs;return r-e>Pk?{required:!0,reason:`${t}: source mtime (${new Date(r).toISOString()}) is newer than sync baseline (${new Date(e).toISOString()})`}:{required:!1,reason:`${t}: up-to-date`}}function kk(n){let e=zt.join(n,Pe.BUILD_PROFILE_JSON5);try{let t=dr.readFileSync(e,"utf-8");if(!t.trim())return null;let r=Ek.parse(t);if(typeof r!="object"||r===null)return null;let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}import*as Z from"fs";import*as G from"path";import*as rg from"util";var fu="";function Fa(n){if(!n||n==="auto"||n==="stdout"||n==="none"){fu="";return}fu=n}function ng(){return fu||(Rh()??"")}function $a(n,...e){if(e.length===0)return n;try{return rg.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var f={info(n,...e){h.info(`[lsp] ${$a(n,...e)}`)},warn(n,...e){h.warn(`[lsp] ${$a(n,...e)}`)},error(n,...e){h.error(`[lsp] ${$a(n,...e)}`)},debug(n,...e){h.debug(`[lsp] ${$a(n,...e)}`)}};import*as Lo from"fs";import*as _o from"os";import*as bi from"path";import Rk from"json5";var b={INITIALIZE:"initialize",INITIALIZED:"initialized",SHUTDOWN:"shutdown",EXIT:"exit",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",DID_CLOSE:"textDocument/didClose",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",DECLARATION:"textDocument/declaration",REFERENCES:"textDocument/references",IMPLEMENTATION:"textDocument/implementation",COMPLETION:"textDocument/completion",COMPLETION_ITEM_RESOLVE:"completionItem/resolve",SIGNATURE_HELP:"textDocument/signatureHelp",CODE_ACTION:"textDocument/codeAction",PREPARE_RENAME:"textDocument/prepareRename",RENAME:"textDocument/rename",DOCUMENT_HIGHLIGHT:"textDocument/documentHighlight",DOCUMENT_LINK:"textDocument/documentLink",INLAY_HINT:"textDocument/inlayHint",DOCUMENT_SYMBOL:"textDocument/documentSymbol",WORKSPACE_SYMBOL:"workspace/symbol",DIAGNOSTIC:"textDocument/diagnostic",WORKSPACE_DIAGNOSTIC:"workspace/diagnostic",PREPARE_CALL_HIERARCHY:"textDocument/prepareCallHierarchy",INCOMING_CALLS:"callHierarchy/incomingCalls",OUTGOING_CALLS:"callHierarchy/outgoingCalls",PREPARE_TYPE_HIERARCHY:"textDocument/prepareTypeHierarchy",SUPERTYPES:"typeHierarchy/supertypes",SUBTYPES:"typeHierarchy/subtypes",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",DID_CREATE_FILES:"workspace/didCreateFiles",DID_DELETE_FILES:"workspace/didDeleteFiles",PROGRESS:"$/progress",WINDOW_SHOW_MESSAGE:"window/showMessage",WINDOW_LOG_MESSAGE:"window/logMessage",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing",ARKTS_ERROR:"arkts/error",CPP_INITIALIZED:"cpp/initialized",CPP_INITIALIZATION_FAILED:"cpp/initializationFailed",CPP_INDEXING_PROGRESS:"cpp/indexingProgress",CPP_SYNC_PROJECT:"cpp/syncProject",CPP_SYNC_COMPLETED:"cpp/syncCompleted",CPP_REINITIALIZING:"cpp/reinitializing",CPP_ERROR:"cpp/error",BROADCAST:"lsp/broadcast"},L="2.0",vi={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate"};var ig=8192,hu=100,og=.03,sg=.7,Qe=900*1e3;function ut(n){if(!Lo.existsSync(n))return null;try{let e=Lo.readFileSync(n,"utf-8");return e.trim()?Rk.parse(e):null}catch{return null}}function ja(n,e){let t=Math.floor(_o.totalmem()/1048576),r=Math.floor(t*sg),i,o;e!==void 0&&Number.isFinite(e)&&e>0?(i=e,o=`override(${e})`):(i=ig,n>hu&&(i+=(n-hu)*og*1024),o=`formula(moduleCount=${n})`);let s=r>0&&i>r;s&&(i=r);let a=Math.round(i);return f.info(`[computeLspServerMaxSize] source=${o}, physicalTotal=${t}MB, physicalCap(70%)=${r}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function xt(n){if(n.startsWith("file:"))return n;try{let e=bi.resolve(n),t=new URL(`file://${e}`).toString();if(_o.platform()==="win32"){let r=t.match(/^file:\/\/\/([A-Za-z]):/);if(r){let i=r[1].toUpperCase(),o=t.substring(`file:///${r[1]}:`.length);t=`file:///${i}%3A${o}`}}return t}catch{return n}}function Si(n){return n&&n.replace(/\\/g,"/")}function he(n){let e=bi.normalize(n).replace(/\\/g,"/");if(_o.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function On(n){return n||process.execPath||"node"}function $o(n){let e=he(n.lspLogPath),t=["--expose-gc",`--max-old-space-size=${n.serverMaxSize}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${e}`,n.serverPath,n.transportFlag??"--stdio",`--logger-path=${e}`,"--logger-level=TRACE"];return n.projectPath&&t.push(`--projectPath=${he(n.projectPath)}`),n.sdkPath&&t.push(`--sdkPath=${he(n.sdkPath)}`),t}function ag(n){return bi.join(n,"build-profile.json5")}var ur=class{constructor(e){this.projectRoot=e}getAllModuleInfo(){let e=ag(this.projectRoot);try{let t=ut(e);if(typeof t!="object"||t===null)return[];let r=t.modules;return Array.isArray(r)?r.filter(i=>{if(typeof i!="object"||i===null)return!1;let o=i;return typeof o.name=="string"&&typeof o.srcPath=="string"}):[]}catch(t){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};import{spawn as Dk}from"child_process";import*as Ua from"fs";var xk=600*1e3;function Ak(n,e,t){let r=t.split(/\s+/).filter(i=>i.length>0);return[n,[e,...r]]}function Ik(n,e){let t=[],r=[],i="",o="";return n.stdout?.on("data",s=>{let a=s.toString();t.push(a),i=cg(i+a,e)}),n.stderr?.on("data",s=>{let a=s.toString();r.push(a),o=cg(o+a,c=>{f.info("[hvigor:err] %s",c),e?.(c)})}),{stdout:t,stderr:r,flush:()=>{i&&e?.(i),o&&(f.info("[hvigor:err] %s",o),e?.(o))}}}function cg(n,e){let t=n.split(/\r?\n/),r=t.pop()??"";for(let i of t)i&&e?.(i);return r}function Ha(n){return n.join("")}function Tk(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
20
21
  Output so far:
21
- `+t,exitCode:-1};let n=r??-1;return{success:n===0,output:t,exitCode:n}}function Fb(r,e,t){return new Promise(n=>{let o=Lb(r[0],r[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:i,stderr:s}=Mb(o),a=setTimeout(()=>{o.kill();let c=[bs(i),bs(s)].filter(Boolean).join(`
22
- `).trim();n({success:!1,output:`Build process timeout after 10 minutes.
22
+ `+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function Ok(n,e,t,r){return new Promise(i=>{let o=Dk(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:s,stderr:a,flush:c}=Ik(o,r),l=setTimeout(()=>{o.kill(),c();let d=[Ha(s),Ha(a)].filter(Boolean).join(`
23
+ `).trim();i({success:!1,output:`Build process timeout after 10 minutes.
23
24
  Output so far:
24
- `+c,exitCode:-1})},Nb);o.on("close",(c,l)=>{clearTimeout(a);let d=[bs(i),bs(s)].filter(Boolean).join(`
25
- `).trim()||"";n(_b(c,l,d))}),o.on("error",c=>{clearTimeout(a),n({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function ol(r,e,t,n,o){let i={...process.env,DEVECO_SDK_HOME:n},s=Ob(e,t,o);return await Fb(s,r,i)}function jb(r,e,t){return{node_path:e,hvigor_path:t,sdk_path:r}}function $b(r){return!r.node_path||!Es.existsSync(r.node_path)?`Node path not found or invalid: ${r.node_path}`:!r.hvigor_path||!Es.existsSync(r.hvigor_path)?`Hvigor path not found or invalid: ${r.hvigor_path}`:!r.sdk_path||!Es.existsSync(r.sdk_path)?`SDK path not found or invalid: ${r.sdk_path}`:null}var Hb="--sync -p product=default --analyze=normal --parallel --incremental --no-daemon";async function sm(r,e,t,n){try{let o=jb(e,t,n),i=$b(o);if(i!=null)return f.info(`Config validation failed: ${i}`),!1;let s=await ol(r,o.node_path,o.hvigor_path,e,Hb);return f.info(`[hvigor] sync finished: success=${s.success}, exitCode=${s.exitCode}`),s.success}catch(o){return f.info(`syncProject failed: ${JSON.stringify(o)}`),!1}}function Bb(r){let e=ae.extname(r).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh"].includes(e)}function Ub(r,e){let t=ae.join(r,e.name);return e.isDirectory()?e.name===".cxx"||cm(t):Bb(t)}function cm(r){if(!ee.existsSync(r))return!1;try{return ee.readdirSync(r,{withFileTypes:!0}).some(t=>Ub(r,t))}catch{}return!1}function ar(r){try{let t=new Ft(r).getAllModuleInfo(),n=[];for(let o of t){let i=ae.resolve(r,o.srcPath);cm(i)&&n.push(o)}return n}catch(e){throw h.error(`[CppCompile] findCppModules threw: ${e instanceof Error?e.message:String(e)}`),e}}function Wb(r){let e=[],n=new Ft(r).getAllModuleInfo();for(let o of n){let i=ae.resolve(r,o.srcPath),s=ae.join(i,".cxx");ee.existsSync(s)&&lm(s,e)}return e}function lm(r,e){try{let t=ee.readdirSync(r,{withFileTypes:!0});for(let n of t){let o=ae.join(r,n.name);n.isDirectory()?lm(o,e):n.name==="compile_commands.json"&&e.push(o)}}catch{}}function Vb(r){let e=[];for(let t of r)try{let n=ee.readFileSync(t,"utf8"),o=JSON.parse(n);e.push(...o)}catch{}return e}function Gb(r,e){let t=ae.join(r,...zb.slice(0,-1));ee.mkdirSync(t,{recursive:!0});let n=ae.join(t,"compile_commands.json");ee.writeFileSync(n,JSON.stringify(e,null,2),"utf8")}function il(r){let e=Wb(r);if(e.length>0){let t=Vb(e);Gb(r,t),h.info(`[CppCompile] compile_commands.json generated, ${t.length} compile commands`)}else h.warn("[CppCompile] No compile_commands.json files found")}var zb=[".idea",".deveco","cxx","compile_commands.json"];async function qb(r,e,t,n,o){if(!n){h.warn(`[CppCompile] hvigorw.js path not injected (sdk '${e}')`);return}h.info(`[CppCompile] sdkPath: ${e}, hvigorPath: ${n}`);for(let i of o){let s=i.name;try{E.assertModuleName(s)}catch{h.warn(`[CppCompile] Skipping module with invalid name: ${s}`);continue}let a=["--mode","module","-p",`module=${i.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"].join(" ");h.info(`[CppCompile] Running compileNative for module: ${i.name}`);let c=await ol(r,t,n,e,a);c.success?h.info(`[CppCompile] compileNative ${i.name} succeeded`):h.warn(`[CppCompile] compileNative ${i.name} failed: ${c.output}`)}}async function dm(r,e,t,n){let o=ar(r);if(o.length===0){h.info("[CppCompile] No C++ modules found, skipping initialization");return}h.info(`[CppCompile] Found ${o.length} C++ module(s): ${o.map(i=>i.name).join(", ")}`),await qb(r,e,t,n,o),il(r),eE(r,o)}var Jb=1e3,Yb=["src","main","cpp","CMakeLists.txt"],Kb=new Set([".cxx","build","node_modules",".preview",".hvigor",".idea"]),Xb=new Set(["c","cpp","cxx","cc"]),Zb="cpp-source-manifest.json";function Qb(r){let e=ae.extname(r).replace(/^\./,"").toLowerCase();return Xb.has(e)}function am(r,e){return ee.existsSync(r)?ee.statSync(r).mtimeMs-e>Jb:!1}function um(r){return ae.join(ae.dirname(Wr(r)),Zb)}function pm(r,e,t){let n;try{n=ee.readdirSync(r,{withFileTypes:!0})}catch{return}for(let o of n){let i=ae.join(r,o.name);if(o.isDirectory()){if(Kb.has(o.name))continue;pm(i,e,t)}else Qb(o.name)&&t.push(ae.relative(e,i).replace(/\\/g,"/"))}}function mm(r,e){let t=[];for(let n of e){let o=E.resolvePathWithinRoot(r,n.srcPath);pm(o,r,t)}return t.sort()}function eE(r,e){let t=mm(r,e),n={files:t,updatedAt:Date.now()},o=um(r);try{ee.mkdirSync(ae.dirname(o),{recursive:!0}),ee.writeFileSync(o,JSON.stringify(n,null,2),"utf8"),h.info(`[CppCompile] C++ source manifest written, ${t.length} files`)}catch(i){h.warn(`[CppCompile] Failed to write C++ source manifest: ${i}`)}}function tE(r,e){let t=um(r);if(!ee.existsSync(t))return{required:!0,reason:"C++ source manifest not found, needs initialization"};let n;try{let i=JSON.parse(ee.readFileSync(t,"utf8"));n=Array.isArray(i.files)?i.files:[]}catch{return{required:!0,reason:"C++ source manifest corrupted, needs initialization"}}let o=mm(r,e);return o.length!==n.length||o.some((i,s)=>i!==n[s])?{required:!0,reason:`C++ source file set changed (recorded=${n.length}, actual=${o.length})`}:null}function fm(r){let e=Wr(r);if(!ee.existsSync(e))return{required:!0,reason:"C++ baseline (compile_commands.json) not found, needs initialization"};let t=ee.statSync(e).mtimeMs,n=ar(r);if(n.length===0)return{required:!1,reason:"no C++ modules, skip compileNative"};for(let i of n){let s=E.resolvePathWithinRoot(r,i.srcPath);if(am(ae.join(s,"build-profile.json5"),t))return{required:!0,reason:`module '${i.name}': build-profile.json5 newer than baseline`};let a=ae.join(s,...Yb);if(am(a,t))return{required:!0,reason:`module '${i.name}': CMakeLists.txt newer than baseline`}}let o=tE(r,n);return o||{required:!1,reason:`C++ project up-to-date (baseline: ${new Date(t).toISOString()})`}}function nE(r,e){if(e.product&&r.validateProduct(e.product),e.buildMode){let t=["debug","release"],n=(r.profile.app.buildModeSet?.map(i=>i.name)??[]).filter(i=>!t.includes(i)),o=[...t,...n];if(!o.includes(e.buildMode))throw new Error(`Build mode '${e.buildMode}' not found. Available modes: ${o.join(", ")}`)}}function oE(r,e){let t=r.profile.modules.map(o=>o.name),n=new Set(t);for(let o of e){let i=o.split("@",1)[0];if(!n.has(i))throw new Error(`Module '${i}' not found in project-level build-profile.json5. Available modules: ${t.join(", ")||"none"}`)}}function iE(r,e){let t;if(e.modules&&e.modules.length>0)t=e.modules,oE(r,t);else{let o=r.profile.modules,i=o.filter(s=>r.getModuleType(s.name)==="entry");if(o.length===1)t=[o[0].name];else if(i.length===1)t=[i[0].name];else throw i.length>1?new w(`Multiple entry modules found (${i.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`,"Multiple entry modules found."):new w(`No entry module found and multiple modules available (${o.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`,"No entry module found and multiple modules available.")}let n=new Set;for(let o of t){let i=o.indexOf("@"),s=i!==-1?o.substring(0,i):o,a=i!==-1?o.substring(i+1):"default";n.add(`${s}@${a}`)}return Array.from(n)}function cl(r,e){let t=new Set;for(let n of e){let o=n.indexOf("@"),i=o!==-1?n.substring(0,o):n,s=r.getModuleType(i);s==="shared"?t.add("assembleHsp"):s==="har"?t.add("assembleHar"):t.add("assembleHap")}return t}function Oo(r,e){let t=e,n=`${r} failed`;console.error(hm(n));let o=t.stdout||t.message;throw o&&console.error(o),t.stderr&&console.error(t.stderr),new Error(n,{cause:e})}async function ll(r,e,t,n,o,i){let s=ys(i);console.log(`
26
- [ohpm install] Running...`);try{await r.installAll()}catch(l){Oo("ohpm install",l)}let a="";if(s.required){console.log(`
27
- [hvigor sync] Running...`);try{a=await e.sync(t,n)}catch(l){Oo("hvigor sync",l)}}else console.log(`
28
- [hvigor sync] Skipped (configurations unchanged)`);console.log(`
29
- [hvigor build] Running...`);let c="";try{o.type==="product"?c=await e.buildProduct(t,n):c=await e.buildModules(t,n,o.modulesToBuild,o.moduleTasks)}catch(l){Oo("hvigor build",l)}return sE(i),{ohpmMemoryMb:r.peakMemoryMb,syncMemoryMb:a,buildMemoryMb:c}}function sE(r){try{if(ar(r).length===0)return;il(r),console.log(sl(`
30
- Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(al(`
31
- Failed to merge compile_commands.json: ${e.message}`))}}async function gm(r,e){let t=Date.now(),n=!0,o=null;try{await e()}catch(i){n=!1,o=q(i),console.error(hm(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:n,error_code:o};await I.track(r,i)}}function aE(r){let e={event:S.CommandExecuted,args:["build",...r.product?["--product"]:[],...r.modules?["--modules"]:[],...r.buildMode?["--build-mode"]:[]]};return r.buildMode&&(e.build_mode=r.buildMode),r.modules&&(e.module_count=r.modules.length),e}function cE(){return{event:S.CommandExecuted,args:["build","clean"]}}async function lE(r){let e=process.cwd(),t=V.discover(e);console.warn(al("Ensure the project source is trustworthy before proceeding."));let n=await k.new();n.assertJava(),nE(t,r);let o=r.product||"default",i=r.buildMode||"debug",s;if(r.product&&!r.modules)s={type:"product"};else{let d=iE(t,r),g=cl(t,d);s={type:"modules",modulesToBuild:d,moduleTasks:g}}let a=new En(n,t.rootDir),c=new Ke(n,t.rootDir),l=await Jr(t.rootDir,async()=>ll(a,c,o,i,s,t.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")});return console.log(`
32
- `+sl("Build completed successfully")),{bundleName:t.getBundleName(),ohpmMemoryMb:l.ohpmMemoryMb,syncMemoryMb:l.syncMemoryMb,buildMemoryMb:l.buildMemoryMb}}async function dE(){let r=process.cwd(),e=V.discover(r);console.warn(al("Ensure the project source is trusted before proceeding."));let t=await k.new();t.assertJava();let n=new Ke(t,e.rootDir);return await Jr(e.rootDir,async()=>{console.log(`
33
- [1/2] Running hvigor clean...`);try{await n.clean()}catch(o){Oo("hvigor clean",o)}console.log(`
34
- [2/2] Running hvigor --stop-daemon...`);try{await n.stopDaemon()}catch(o){Oo("hvigor --stop-daemon",o)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
35
- `+sl("Clean completed successfully.")),e.getBundleName()}var ym=new rE("build").description("Build HarmonyOS project").option("--product <product>","Product name defined in build-profile.json5 (default: default)").option("--modules <modules...>","Modules to build (format: module or module@target)").option("--build-mode <mode>","Build mode (buildModeSet in build-profile.json5; e.g. debug, release; default: debug)").action(async r=>{let e=aE(r);await gm(e,async()=>{let t=await lE(r);e.bundle_name=t.bundleName,t.ohpmMemoryMb&&(e.ohpm_install_memory=t.ohpmMemoryMb),t.syncMemoryMb&&(e.hvigor_sync_memory=t.syncMemoryMb),t.buildMemoryMb&&(e.hvigor_build_memory=t.buildMemoryMb)})});ym.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{let r=cE();await gm(r,async()=>{r.bundle_name=await dE()})});var vm=ym;import{Command as kC}from"commander";import{green as Wo,red as DC,yellow as Bs}from"colorette";import*as Vo from"path";import{randomUUID as PE}from"crypto";import{execa as Im}from"execa";import{execa as CE}from"execa";import{execFile as uE,spawn as pE}from"child_process";import{promisify as mE}from"util";var fE=mE(uE);function wm(r,e,t){let o=r.replace(/\r\n/g,`
25
+ `+d,exitCode:-1})},xk);o.on("close",(d,g)=>{clearTimeout(l),c();let w=[Ha(s),Ha(a)].filter(Boolean).join(`
26
+ `).trim()||"";i(Tk(d,g,w))}),o.on("error",d=>{clearTimeout(l),i({success:!1,output:`Build execution exception: ${d.message}`,exitCode:-1})})})}async function gu(n,e,t,r,i,o){let s={...process.env,DEVECO_SDK_HOME:r},a=Ak(e,t,i);return await Ok(a,n,s,o)}function Mk(n,e,t){return{node_path:e,hvigor_path:t,sdk_path:n}}function Nk(n){return!n.node_path||!Ua.existsSync(n.node_path)?`Node path not found or invalid: ${n.node_path}`:!n.hvigor_path||!Ua.existsSync(n.hvigor_path)?`Hvigor path not found or invalid: ${n.hvigor_path}`:!n.sdk_path||!Ua.existsSync(n.sdk_path)?`SDK path not found or invalid: ${n.sdk_path}`:null}var Lk="--sync -p product=default";async function lg(n,e,t,r,i){try{let o=Mk(e,t,r),s=Nk(o);if(s!=null)return f.info(`Config validation failed: ${s}`),!1;let a=await gu(n,o.node_path,o.hvigor_path,e,Lk,i);return f.info(`[hvigor] sync finished: success=${a.success}, exitCode=${a.exitCode}`),a.success}catch(o){return f.info(`syncProject failed: ${JSON.stringify(o)}`),!1}}function _k(n){let e=G.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh"].includes(e)}function $k(n,e){let t=G.join(n,e.name);return e.isDirectory()?e.name===".cxx"||ug(t):_k(t)}function ug(n){if(!Z.existsSync(n))return!1;try{return Z.readdirSync(n,{withFileTypes:!0}).some(t=>$k(n,t))}catch{}return!1}function Ur(n){try{let t=new ur(n).getAllModuleInfo(),r=[];for(let i of t){let o=G.resolve(n,i.srcPath);ug(o)&&r.push(i)}return r}catch(e){throw h.error(`[CppCompile] findCppModules threw: ${e instanceof Error?e.message:String(e)}`),e}}function Fk(n){let e=[],r=new ur(n).getAllModuleInfo();for(let i of r){let o=G.resolve(n,i.srcPath),s=G.join(o,".cxx");Z.existsSync(s)&&pg(s,e)}return e}function pg(n,e){try{let t=Z.readdirSync(n,{withFileTypes:!0});for(let r of t){let i=G.join(n,r.name);r.isDirectory()?pg(i,e):r.name==="compile_commands.json"&&e.push(i)}}catch{}}function jk(n){let e=[];for(let t of n)try{let r=Z.readFileSync(t,"utf8"),i=JSON.parse(r);e.push(...i)}catch{}return e}function Hk(n,e){let t=G.join(n,...Uk.slice(0,-1));Z.mkdirSync(t,{recursive:!0});let r=G.join(t,"compile_commands.json");Z.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function yu(n){let e=Fk(n);if(e.length>0){let t=jk(e);Hk(n,t),h.info(`[CppCompile] compile_commands.json generated, ${t.length} compile commands`)}else h.warn("[CppCompile] No compile_commands.json files found")}var Uk=[".idea",".deveco","cxx","compile_commands.json"];async function Bk(n,e,t,r,i){if(!r){h.warn(`[CppCompile] hvigorw.js path not injected (sdk '${e}')`);return}h.info(`[CppCompile] sdkPath: ${e}, hvigorPath: ${r}`);for(let o of i){let s=o.name;try{E.assertModuleName(s)}catch{h.warn(`[CppCompile] Skipping module with invalid name: ${s}`);continue}let a=["--mode","module","-p",`module=${o.name}`,"-p","product=default","compileNative"].join(" ");h.info(`[CppCompile] Running compileNative for module: ${o.name}`);let c=await gu(n,t,r,e,a);c.success?h.info(`[CppCompile] compileNative ${o.name} succeeded`):h.warn(`[CppCompile] compileNative ${o.name} failed: ${c.output}`)}}async function mg(n,e,t,r){let i=Ur(n);if(i.length===0){h.info("[CppCompile] No C++ modules found, skipping initialization");return}h.info(`[CppCompile] Found ${i.length} C++ module(s): ${i.map(o=>o.name).join(", ")}`),await Bk(n,e,t,r,i),yu(n),Yk(n,i)}function Ba(n,e){let t=n?.trim()??"";if(!t)return null;let r=t;if(/\{workspace\}/i.test(r)){if(!e)return h.warn("[CppCompile] {workspace} placeholder in compile_commands path but no project root resolved, falling back to default sync"),null;r=r.replace(/\{workspace\}/gi,e)}else if(!G.isAbsolute(r)){if(!e)return h.warn(`[CppCompile] Relative compile_commands path '${r}' requires a project root, falling back to default sync`),null;r=G.join(e,r)}let i=G.resolve(r);try{if(!Z.existsSync(i)||!Z.statSync(i).isFile())return h.warn(`[CppCompile] Custom compile_commands.json not found: ${i}, falling back to default sync`),null;let o=JSON.parse(Z.readFileSync(i,"utf8"));if(!Array.isArray(o))return h.warn(`[CppCompile] Custom compile_commands.json is not a JSON array: ${i}, falling back to default sync`),null}catch(o){return h.warn(`[CppCompile] Failed to read custom compile_commands.json (${i}): ${o}, falling back to default sync`),null}return G.dirname(i)}var Wk=1e3,Vk=["src","main","cpp","CMakeLists.txt"],Gk=new Set([".cxx","build","node_modules",".preview",".hvigor",".idea"]),qk=new Set(["c","cpp","cxx","cc"]),zk="cpp-source-manifest.json";function Jk(n){let e=G.extname(n).replace(/^\./,"").toLowerCase();return qk.has(e)}function dg(n,e){return Z.existsSync(n)?Z.statSync(n).mtimeMs-e>Wk:!1}function fg(n){return G.join(G.dirname(xn(n)),zk)}function hg(n,e,t){let r;try{r=Z.readdirSync(n,{withFileTypes:!0})}catch{return}for(let i of r){let o=G.join(n,i.name);if(i.isDirectory()){if(Gk.has(i.name))continue;hg(o,e,t)}else Jk(i.name)&&t.push(G.relative(e,o).replace(/\\/g,"/"))}}function gg(n,e){let t=[];for(let r of e){let i=G.resolve(n,r.srcPath);hg(i,n,t)}return t.sort()}function Yk(n,e){let t=gg(n,e),r={files:t,updatedAt:Date.now()},i=fg(n);try{Z.mkdirSync(G.dirname(i),{recursive:!0}),Z.writeFileSync(i,JSON.stringify(r,null,2),"utf8"),h.info(`[CppCompile] C++ source manifest written, ${t.length} files`)}catch(o){h.warn(`[CppCompile] Failed to write C++ source manifest: ${o}`)}}function Kk(n,e){let t=fg(n);if(!Z.existsSync(t))return{required:!0,reason:"C++ source manifest not found, needs initialization"};let r;try{let o=JSON.parse(Z.readFileSync(t,"utf8"));r=Array.isArray(o.files)?o.files:[]}catch{return{required:!0,reason:"C++ source manifest corrupted, needs initialization"}}let i=gg(n,e);return i.length!==r.length||i.some((o,s)=>o!==r[s])?{required:!0,reason:`C++ source file set changed (recorded=${r.length}, actual=${i.length})`}:null}function yg(n){let e=xn(n);if(!Z.existsSync(e))return{required:!0,reason:"C++ baseline (compile_commands.json) not found, needs initialization"};let t=Z.statSync(e).mtimeMs,r=Ur(n);if(r.length===0)return{required:!1,reason:"no C++ modules, skip compileNative"};for(let o of r){let s=G.resolve(n,o.srcPath);if(dg(G.join(s,"build-profile.json5"),t))return{required:!0,reason:`module '${o.name}': build-profile.json5 newer than baseline`};let a=G.join(s,...Vk);if(dg(a,t))return{required:!0,reason:`module '${o.name}': CMakeLists.txt newer than baseline`}}let i=Kk(n,r);return i||{required:!1,reason:`C++ project up-to-date (baseline: ${new Date(t).toISOString()})`}}var vg=["assembleHap","assembleApp","assembleHsp","assembleHar"];function Zk(n,e){if(e.product&&n.validateProduct(e.product),e.buildMode){let t=["debug","release"],r=(n.profile.app.buildModeSet?.map(o=>o.name)??[]).filter(o=>!t.includes(o)),i=[...t,...r];if(!i.includes(e.buildMode))throw new Error(`Build mode '${e.buildMode}' not found. Available modes: ${i.join(", ")}`)}if(e.assembleType&&!vg.includes(e.assembleType))throw new Error(`Invalid assemble type '${e.assembleType}'. Valid types: ${vg.join(", ")}`);if(e.signingConfig){if(!/^[\da-zA-Z_-]+$/.test(e.signingConfig))throw new Error(`Invalid signing config name '${e.signingConfig}'. Only letters, digits, hyphens and underscores are allowed.`);let t=n.profile.app.signingConfigs?.map(r=>r.name)??[];if(!t.includes(e.signingConfig)){let r=t.length>0?`Available configs: ${t.join(", ")}.`:"No signing configs found in build-profile.json5.",i=e.signingConfig.endsWith("_release")?"Run `devecocli signature generate --type release` to generate release signing materials.":"Run `devecocli signature generate` to generate signing materials.";throw new Error(`Signing config '${e.signingConfig}' not found in build-profile.json5. ${r} ${i}`)}}}function Eg(n,e){let t=n.profile.modules.map(i=>i.name),r=new Set(t);for(let i of e){let o=i.split("@",1)[0];if(!r.has(o))throw new Error(`Module '${o}' not found in project-level build-profile.json5. Available modules: ${t.join(", ")||"none"}`)}}function Qk(n,e){let t;if(e.modules&&e.modules.length>0)t=e.modules,Eg(n,t);else{let i=n.profile.modules,o=i.filter(s=>n.getModuleType(s.name)==="entry");if(i.length===1)t=[i[0].name];else if(o.length===1)t=[o[0].name];else throw o.length>1?new y(`Multiple entry modules found (${o.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`,"Multiple entry modules found."):new y(`No entry module found and multiple modules available (${i.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`,"No entry module found and multiple modules available.")}let r=new Set;for(let i of t){let o=i.indexOf("@"),s=o!==-1?i.substring(0,o):i,a=o!==-1?i.substring(o+1):"default";r.add(`${s}@${a}`)}return Array.from(r)}function wu(n,e,t){let r=new Set;for(let i of e){let o=i.indexOf("@"),s=o!==-1?i.substring(0,o):i;if(t){let a=n.getModuleType(s),c=a==="shared"?"assembleHsp":a==="har"?"assembleHar":"assembleHap";t!==c&&t!=="assembleApp"&&console.warn(Ga(`Warning: --assemble-type ${t} may not be compatible with module '${s}' (type: ${a}, expected: ${c}).`)),r.add(t)}else{let a=n.getModuleType(s);a==="shared"?r.add("assembleHsp"):a==="har"?r.add("assembleHar"):r.add("assembleHap")}}return r}function Wa(n,e){let t=e,r=`${n} failed`;console.error(bg(r));let i=t.stdout||t.message;throw i&&console.error(i),t.stderr&&console.error(t.stderr),new Error(r,{cause:e})}async function eR(n,e,t,r,i){if(!_a(i).required)return console.log(`
27
+ [ohpm install] Skipped (configurations unchanged)`),console.log(`
28
+ [hvigor sync] Skipped (configurations unchanged)`),"";console.log(`
29
+ [ohpm install] Running...`);try{await n.install()}catch(s){Wa("ohpm install",s)}console.log(`
30
+ [hvigor sync] Running...`);try{return await e.sync(t,r)}catch(s){Wa("hvigor sync",s)}return""}async function vu(n,e,t,r,i,o){let s=await eR(n,e,t,r,o);console.log(`
31
+ [hvigor build] Running...`);let a="";try{i.type==="product"?a=await e.buildProduct(t,r):a=await e.buildModules(t,r,i.modulesToBuild,i.moduleTasks)}catch(c){Wa("hvigor build",c)}return tR(o),{ohpmMemoryMb:n.peakMemoryMb,syncMemoryMb:s,buildMemoryMb:a}}function tR(n){try{if(Ur(n).length===0)return;yu(n),console.log(Va(`
32
+ Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(Ga(`
33
+ Failed to merge compile_commands.json: ${e.message}`))}}async function Pg(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=X(o),console.error(bg(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await D.track(n,o)}}function rR(n){let e={event:v.CommandExecuted,args:["build",...n.product?["--product"]:[],...n.modules?["--modules"]:[],...n.buildMode?["--build-mode"]:[],...n.assembleType?["--assemble-type"]:[],...n.signingConfig?["--signing-config"]:[]]};return n.buildMode&&(e.build_mode=n.buildMode),n.modules&&(e.module_count=n.modules.length),n.assembleType&&(e.assemble_type=n.assembleType),n.signingConfig&&(e.signing_config=n.signingConfig),e}function nR(n){let e={event:v.CommandExecuted,args:["build","clean",...n.mode?["--mode"]:[],...n.modules?["--modules"]:[]]};return n.modules&&(e.module_count=n.modules.length),n.mode&&(e.clean_mode=n.mode),e}async function iR(n){let e=B.discover(process.cwd());console.warn(Ga("Ensure the project source is trustworthy before proceeding."));let t=await P.new();t.assertJava(),Zk(e,n);let r=n.product||"default",i=n.buildMode||"debug",o=oR(e,n),s=new yi(t,e.rootDir),a=new dt(t,e.rootDir),c=n.signingConfig?sR(e.rootDir,r,n.signingConfig):void 0;try{let l=await Tn(e.rootDir,async()=>vu(s,a,r,i,o,e.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")});return console.log(`
34
+ `+Va("Build completed successfully")),aR(e,o,r),{bundleName:e.getBundleName(),ohpmMemoryMb:l.ohpmMemoryMb,syncMemoryMb:l.syncMemoryMb,buildMemoryMb:l.buildMemoryMb}}finally{c?.()}}function oR(n,e){if(e.assembleType==="assembleApp"||e.product&&!e.modules&&!e.assembleType)return{type:"product"};let t=Qk(n,e),r=wu(n,t,e.assembleType);return{type:"modules",modulesToBuild:t,moduleTasks:r}}function sR(n,e,t){let r=Sg.join(n,"build-profile.json5"),i=Fo.readFileSync(r,"utf-8"),o=wg.parse(i),s=o?.app?.products??[],a=s.findIndex(c=>c.name===e);return a>=0?s[a].signingConfig=t:s.push({name:e,signingConfig:t}),m(`[build] temporarily setting product '${e}' signingConfig to '${t}'`),Fo.writeFileSync(r,wg.stringify(o,null,2),"utf-8"),()=>{Fo.writeFileSync(r,i,"utf-8"),m("[build] restored original build-profile.json5")}}function aR(n,e,t){let r=e.type==="product"?n.resolveModuleSpecsForProduct(t):e.modulesToBuild,i=n.collectBuildArtifacts(e.type==="product",r,t);if(i.length!==0){console.log(Va("Build artifacts:"));for(let o of i)console.log(` ${o}`)}}async function cR(n){let e=process.cwd(),t=B.discover(e);console.warn(Ga("Ensure the project source is trusted before proceeding."));let r=await P.new();r.assertJava();let i;n.modules&&n.modules.length>0&&(Eg(t,n.modules),i=n.modules.map(s=>s.split("@",1)[0]));let o=new dt(r,t.rootDir);return await Tn(t.rootDir,async()=>{let s=i&&i.length>0?`mode=${n.mode??Na}, modules=${i.join(",")}`:`mode=${n.mode??Na}`;console.log(`
35
+ Running hvigor clean (${s})...`);try{await o.clean(n.mode,i)}catch(a){Wa("hvigor clean",a)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
36
+ `+Va("Clean completed successfully.")),t.getBundleName()}var Cg=new Xk("build").description("Build HarmonyOS project").option("--product <product>","Product name defined in build-profile.json5 (default: default)").option("--modules <modules...>","Modules to build (format: module or module@target)").option("--build-mode <mode>","Build mode (buildModeSet in build-profile.json5; e.g. debug, release; default: debug)").option("--assemble-type <type>","Assemble task type: assembleHap, assembleApp, assembleHsp, assembleHar (default: auto-detect by module type)").option("--signing-config <name>","Signing config name defined in build-profile.json5 (overrides product default)").action(async n=>{let e=rR(n);await Pg(e,async()=>{let t=await iR(n);e.bundle_name=t.bundleName,t.ohpmMemoryMb&&(e.ohpm_install_memory=t.ohpmMemoryMb),t.syncMemoryMb&&(e.hvigor_sync_memory=t.syncMemoryMb),t.buildMemoryMb&&(e.hvigor_build_memory=t.buildMemoryMb)})});Cg.command("clean").description("Clean HarmonyOS project build outputs").option("--mode <mode>","hvigor --mode value (default: module)").option("--modules <modules...>","Scope clean to specific modules").action(async(n,e)=>{let t=e.parent?.opts()??{},r={mode:n.mode,modules:n.modules??t.modules},i=nR(r);await Pg(i,async()=>{i.bundle_name=await cR(r)})});var kg=Cg;import{Command as _x}from"commander";import{green as Qo,red as $x,yellow as Ec}from"colorette";import*as es from"path";import{randomUUID as ER}from"crypto";import{execa as Mg}from"execa";import{execa as SR}from"execa";import{execFile as lR,spawn as dR}from"child_process";import{promisify as uR}from"util";var pR=uR(lR);function Rg(n,e,t){let i=n.replace(/\r\n/g,`
36
37
  `).split(`
37
- `),i=o.pop()??"",s=o.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),i}function Sm(r,e,t){let n=r.endsWith("\r")?r.slice(0,-1):r;n.length>0&&t.onData([n],e)}function hE(r,e){return{stdout:r.stdoutChunks.join(""),stderr:r.stderrChunks.join(""),exitCode:e??-1}}function gE(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function yE(r,e,t,n,o){r.stdout?.on("data",i=>{let s=i.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=wm(e.stdoutLineBuffer+s,"stdout",t)}),r.stderr?.on("data",i=>{let s=i.toString();e.stderrChunks.push(s),e.stderrLineBuffer=wm(e.stderrLineBuffer+s,"stderr",t)}),r.on("error",i=>{e.settled||(e.settled=!0,t.onError(i),o(i))}),r.on("close",i=>{if(e.settled)return;e.settled=!0,Sm(e.stdoutLineBuffer,"stdout",t),Sm(e.stderrLineBuffer,"stderr",t),t.onClose(i);let s=hE(e,i);n(s)})}async function Mo(r,e=[],t={}){try{let{stdout:n,stderr:o}=await fE(r,e,t);return{stdout:typeof n=="string"?n.trim():"",stderr:typeof o=="string"?o.trim():"",exitCode:0}}catch(n){let o=n;return{stdout:o.stdout?.trim()||"",stderr:o.stderr?.trim()??o.message,exitCode:typeof o.code=="number"?o.code:1}}}async function bm(r,e,t){return await new Promise((n,o)=>{let i=pE(r,e,{stdio:["inherit","pipe","pipe"]}),s=gE();yE(i,s,t,n,o)})}function Em(r){let e=r.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var vE=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],wE=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function cr(r){return r?vE.some(e=>e.test(r))?"transient":wE.some(e=>e.test(r))?"fatal":"ok":"ok"}var SE=/(?:^|\s)(\d{2,})(?:\s|$)/;function Cm(r){let e=r.stdout.trim(),t=r.stderr.trim();return cr(e)!=="ok"||cr(t)!=="ok"?"query-failed":r.exitCode===0?e&&SE.test(e)?"alive":"dead":r.exitCode===1&&!e&&!t?"dead":"query-failed"}var dl=[800,1500,2500];function bE(r){return new Promise(e=>setTimeout(e,r))}async function re(r,e){let t=1+dl.length,n={stdout:"",stderr:"",exitCode:-1};for(let o=0;o<t;o++){if(n=await Mo(r,e),n.exitCode===0||cr(n.stderr)!=="transient"||o>=t-1)return n;m(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${dl[o]}ms`),await bE(dl[o])}return n}var Pm=/^[\w.-]+$/;async function Cs(r,e,t){if(!Pm.test(t)){m(`Skipping invalid param key: ${JSON.stringify(t)}`);return}let n=["-t",e,"shell","param","get",t];m(`Executing: ${r} ${n.join(" ")}`);let o=await re(r,n);if(o.exitCode!==0)return;let i=o.stdout.trim();if(!(!i||cr(i)!=="ok"))return Em(i)}var ul="__DEVECO_PARAM_DELIM__";function EE(r,e){let t=new Map,n=r.split(ul);for(let o=0;o<e.length;o++){let i=(n[o]??"").trim();if(!i||cr(i)!=="ok")continue;let s=Em(i);s&&t.set(e[o],s)}return t}async function An(r,e,t){let n=t.filter(a=>Pm.test(a)?!0:(m(`Skipping invalid param key: ${JSON.stringify(a)}`),!1));if(n.length===0)return new Map;if(n.length===1){let a=new Map,c=await Cs(r,e,n[0]);return c&&a.set(n[0],c),a}let o=n.map(a=>`param get ${a}`).join(`; echo ${ul}; `)+`; echo ${ul}`,i=await re(r,["-t",e,"shell",o]);if(i.exitCode===0){let a=EE(i.stdout,n);if(a.size>0)return a}m(`Batched param fetch failed (exit=${i.exitCode}), falling back to individual calls for ${e}`);let s=new Map;for(let a of n){let c=await Cs(r,e,a);c&&s.set(a,c)}return s}function Rt(r){return r.startsWith("127.0.0.1:")}var Am=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],ue=class r{hdcPath;constructor(e){this.hdcPath=e}static from(e){return new r(e.hdcPath)}static withHdcPath(e){return new r(e)}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}stripBrandPrefix(e,t){let n=e.trim(),o=t?.trim();if(!n||!o)return n;let i=new RegExp(`^${this.escapeRegExp(o)}(\\s+|[-_]+)?`,"i");return n.replace(i,"").trim()||n}async executeHdc(e){return m(`Executing: ${this.hdcPath} ${e.join(" ")}`),CE(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let n of e.split(`
38
- `)){let o=n.trim();if(!o||o.startsWith("[Empty]"))continue;let i=o.split(/\s+/),s=i[0];if(!s||s.startsWith("[Empty]"))continue;let a=i.length>=2?i[1]:"device";if(a.toLowerCase()==="unauthorized"){m(`[DeviceManager] Skipping unauthorized device: ${s}`);continue}t.push({serial:s,status:a})}return t}extractDisplayName(e){let t=e.get("ohos.qemu.hvd.name");if(t)return t;let n=e.get("const.product.name");if(n&&n!=="emulator")return n;let o=e.get("const.product.model");if(o&&o!=="emulator"){let s=e.get("const.product.brand");return this.stripBrandPrefix(o,s)}let i=e.get("const.build.product");if(i&&i!=="emulator")return i}async getDeviceName(e){let t=await An(this.hdcPath,e,[...Am]);return this.extractDisplayName(t)??e}async getDeviceInfo(e,t){if(e.length===0)return null;if(t){let n=e.find(s=>s.serial===t);if(n)return n;let o=t.toLowerCase(),i=[];for(let s of e){let a=await this.getDeviceName(s.serial);a.toLowerCase()===o&&i.push({device:s,name:a})}if(i.length===1)return i[0].device;throw i.length>1?new w(`Multiple devices match "${t}". Use a serial instead:
39
- `+i.map(s=>` - ${s.name} (${s.device.serial})`).join(`
40
- `),"Multiple devices match."):new w(`Device "${t}" not found. Use \`devecocli device list\` to see available targets.`,"Device not found.")}return e[0]}async getDeviceDetail(e){let t={serial:e,status:"device"};try{let n=await An(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=n.get("const.product.devicetype");let o=n.get("const.ohos.apiversion"),i=n.get("const.ohos.releasetype");o&&(t.osVersion=i?`API ${o} (${i})`:`API ${o}`)}catch{}return t}async listDevicesWithName(){let e=await this.listDevices();return Promise.all(e.map(async t=>({serial:t.serial,name:await this.getDeviceName(t.serial)})))}async getConnectedEntries(){let e=await this.listDevices();return Promise.all(e.map(t=>this.buildConnectedEntry(t.serial)))}async buildConnectedEntry(e){let t=Rt(e),n,o;try{let i=await An(this.hdcPath,e,[...Am]);n=this.extractDisplayName(i),o=i.get("const.product.devicetype")}catch{}return{serial:e,name:n,isEmulator:t,deviceType:o}}};var Ze=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=ue.from(e)}async runHdc(e,t=!0){let n=this.toolProvider.hdcPath;m(`Executing: ${n} ${e.join(" ")}`);try{let{stdout:o}=await Im(n,e,{env:{...process.env}});return o}catch(o){if(t)throw o;return o.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){E.assertBundleNameStrict(t);let n=await this.runHdc(["-t",e,"shell","bm","uninstall","-n",t],!1);if(n.includes("uninstall bundle successfully"))return!0;if(n.includes("uninstall missing installed bundle"))return!1;throw new Error(`Uninstall failed: ${n}`)}async installApp(e,t){if(t.length===0)return;let o=`/data/local/tmp/${PE()}`;try{await this.runHdc(["-t",e,"shell","mkdir",o]);for(let s of t){let a=await this.runHdc(["-t",e,"file","send",s,o+"/"]);if(!a.startsWith("FileTransfer finish"))throw new Error(a)}let i=await this.runHdc(["-t",e,"shell","bm","install","-p",o]);if(!i.includes("install bundle successfully."))throw new Error(i);console.log("App installed successfully")}finally{await this.runHdc(["-t",e,"shell","rm","-rf",o],!1)}}async launchApp(e,t,n){E.assertBundleNameStrict(t),E.assertAbilityName(n);let o=["-t",e,"shell","aa","start","-a",n,"-b",t];return await this.runHdc(o)}async pidofBundle(e,t){E.assertBundleNameStrict(t);let n=["-t",e,"shell","pidof",t],o=this.toolProvider.hdcPath;m(`Executing: ${o} ${n.join(" ")}`);let i=await re(o,n),s=Cm(i);if(s==="query-failed"){let a=[i.stdout,i.stderr].map(c=>c.trim()).filter(Boolean).join(" ");throw new Error(`pidof query failed for '${t}': ${a||`exit ${i.exitCode}`}`)}return s==="alive"}async forceStopApp(e,t){E.assertBundleNameStrict(t);let n=["-t",e,"shell","aa","force-stop",t];return await this.runHdc(n,!1)}async transferFile(e,t,n,o){let i=["-t",e,"file",t,n,o],s=await this.runHdc(i,!1);if(!s.includes("FileTransfer finish"))throw new Error(`File ${t} failed: ${s.trim()||"hdc returned no output"}`);return s.trim()}async runSqlite3(e,t,n=[]){let o=["-t",e,"shell","sqlite3",t,...n];await Im(this.toolProvider.hdcPath,o,{stdio:"inherit",env:{...process.env}})}};import pl from"fs";import*as Kr from"path";function _o(r,e){if(!pl.existsSync(r))throw new Error(`Apply file list not found: ${r}`);let n=pl.readFileSync(r,"utf-8").split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("#"));if(n.length===0)throw new Error("Apply file list is empty (no valid entries)");let o=Kr.resolve(e),i=new Set,s=[];for(let a of n){let c=Kr.resolve(o,a),l=Kr.isAbsolute(a)?Kr.relative(o,a):a;if(l.startsWith(".."))throw new Error(`File path is outside the project directory: ${a}`);let d=E.isPathContainedWithSymlink(l,o);if(!d.contained){if(!pl.existsSync(c))throw new Error(`File not found: ${a}`);let g=d.reason?`; ${d.reason}`:"";throw new Error(`File path is outside the project directory: ${a}${g}`)}i.has(c)||(i.add(c),s.push(c))}return s}import ml from"fs";import Fo from"path";import{execa as kE}from"execa";import km from"fs";import*as Dm from"path";import AE from"json5";function IE(r,e){try{let n=AE.parse(km.readFileSync(r,"utf-8")).modules?.find(o=>o.name===e);return n?.srcPath?n.srcPath.replace(/^\.\//,""):null}catch(t){return m(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function xt(r,e){let t=Dm.join(r,"build-profile.json5");return km.existsSync(t)?IE(t,e)??e:e}async function Tm(r,e,t,n){let o=Fo.dirname(r.javaPath),i={...process.env,PATH:`${o}${Fo.delimiter}${process.env.PATH||""}`,DEVECO_SDK_HOME:r.sdkPath},s=[r.hvigorJsPath,"--mode","module","-p",`module=${t.join(",")}@${n}`,"-p",`product=${n}`,"-p","debuggable=true","assembleDevHqf","--analyze=normal","--parallel","--incremental","--no-daemon"];m(`[buildSignedHqf] ${r.nodePath} ${s.join(" ")}`);let a=await kE(r.nodePath,s,{cwd:e,env:i,stdout:"inherit",stderr:"inherit",reject:!1}),c=(a.exitCode??0)|0;if(c===-1)throw new Error("hvigor hot compile produced invalid abc (exit code -1)");if(c!==0)throw new Error(`hvigor assembleDevHqf failed with exit code ${a.exitCode}`);return t.map(l=>TE(e,l,n))}function Rm(r,e,t){let n=xt(r,e);return Fo.join(r,n,"build",t,"outputs")}function DE(r,e,t){return Fo.join(Rm(r,e,t),`${e}-${t}-signed.hqf`)}function TE(r,e,t){let n=Rm(r,e,t),o=DE(r,e,t);if(ml.existsSync(o))return o;let i=fl(n,"-signed.hqf")??fl(n,".hqf");if(!i)throw new Error(`Signed hqf not found at ${o} (and no *.hqf under ${n})`);return m(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${i}`),i}function fl(r,e){if(!ml.existsSync(r))return null;for(let t of ml.readdirSync(r,{withFileTypes:!0})){let n=Fo.join(r,t.name);if(t.isDirectory()){let o=fl(n,e);if(o)return o}else if(t.isFile()&&t.name.endsWith(e))return n}return null}import ne from"fs";import*as O from"path";import hl from"json5";var xm="default",In=class r{static writeChangedFileLists(e,t,n,o){let i=t||xm,s=r.loadBuildProfile(e);if(!s)return{writtenModules:[],skippedFiles:n};let a=s.modules,c=r.filterRunnableModules(e,a);if(c.length===0)return{writtenModules:[],skippedFiles:n};let l=r.buildReverseDependencyMap(e,a),d=r.createCollectors(c),g=r.collectChanges(n,e,a,l,d);return{writtenModules:r.flushCollectors(e,i,c,d,o),skippedFiles:g}}static initEmptyChangedFileLists(e,t,n){let o=t||xm,i=r.loadBuildProfile(e);if(!i)return[];let s=i.modules,a=[];for(let c of s){let l=r.getModuleType(e,c.srcPath);if(l!=="entry"&&l!=="shared")continue;let d=!n||c.name===n;r.initEmptyForModule(e,o,c.srcPath,d),a.push(c.name)}return a}static filterRunnableModules(e,t){return t.filter(n=>{let o=r.getModuleType(e,n.srcPath);return o==="entry"||o==="shared"})}static createCollectors(e){let t=new Map;for(let n of e)t.set(n.name,{hotReloadEntries:[],patchEtsFiles:[],patchRawFiles:[],patchResFiles:[],nativeFiles:[]});return t}static collectChanges(e,t,n,o,i){let s=[];for(let a of e){let c=O.normalize(a),l=r.classifyFile(c,t,n);if(l.fileClass==="unknown"){s.push(c);continue}let d=r.findModuleByFilePath(c,t,n);if(!d){s.push(c);continue}let g=r.resolveTargetModules(d,t,n,o);if(g.length===0){s.push(c);continue}r.dispatchToCollectors(g,i,c,l,d.srcPath,t)}return s}static resolveTargetModules(e,t,n,o){let i=r.getModuleType(t,e.srcPath);return i==="entry"||i==="shared"?[e.name]:Array.from(r.findTopLevelConsumers(e.name,o,t,n))}static dispatchToCollectors(e,t,n,o,i,s){for(let a of e){let c=t.get(a);c&&r.addFileToCollector(c,n,o.fileClass,i,s)}}static flushCollectors(e,t,n,o,i){let s=[];for(let a of n){let c=o.get(a.name);if(!c||!r.hasAnyChange(c))continue;(!i||a.name===i)&&c.hotReloadEntries.length>0&&r.writeApplyFile(e,a.srcPath,t,c.hotReloadEntries),r.writePatchFile(e,a.srcPath,t,c.patchEtsFiles,c.patchRawFiles,c.patchResFiles),s.push(a.name)}return s}static hasAnyChange(e){return e.hotReloadEntries.length>0||e.patchEtsFiles.length>0||e.patchRawFiles.length>0||e.patchResFiles.length>0||e.nativeFiles.length>0}static initEmptyForModule(e,t,n,o){let i=O.join(e,n,"build",t,"intermediates","patch","default"),s=O.join(i,"changedFileList.json");if(ne.existsSync(s)||(ne.mkdirSync(i,{recursive:!0}),ne.writeFileSync(s,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!o)return;let a=O.join(e,n,"build",t,"intermediates","hotReload"),c=O.join(a,"changedFileList.json");ne.existsSync(c)||(ne.mkdirSync(a,{recursive:!0}),ne.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=O.join(e,"build-profile.json5");if(!ne.existsSync(t))return null;try{let n=ne.readFileSync(t,"utf-8");return hl.parse(n)}catch{return null}}static classifyFile(e,t,n){let o=O.extname(e).toLowerCase();if(o===".ets"||o===".ts")return{fileClass:"ets_ts",moduleSrcPath:r.findModuleByFilePath(e,t,n)?.srcPath??""};if(o===".cpp"||o===".cc"||o===".c"||o===".h"||o===".hpp")return{fileClass:"native",moduleSrcPath:r.findModuleByFilePath(e,t,n)?.srcPath??""};let i=e.replace(/\\/g,"/");return i.includes("/resources/rawfile/")?{fileClass:"raw_file",moduleSrcPath:r.findModuleByFilePath(e,t,n)?.srcPath??""}:i.includes("/resources/resfile/")?{fileClass:"res_file",moduleSrcPath:r.findModuleByFilePath(e,t,n)?.srcPath??""}:{fileClass:"unknown",moduleSrcPath:""}}static findModuleByFilePath(e,t,n){let o=O.normalize(e);for(let i of n){let s=O.normalize(O.join(t,i.srcPath)),a=s+O.sep;if(o.startsWith(a)||o===s)return i}return null}static getModuleType(e,t){let n=O.join(e,t,"src","main","module.json5");if(!ne.existsSync(n))return"entry";try{let o=ne.readFileSync(n,"utf-8");return hl.parse(o)?.module?.type||"entry"}catch{return"entry"}}static buildReverseDependencyMap(e,t){let n=new Map;for(let o of t){let i=r.readLocalDependencies(e,o.srcPath);for(let s of i){let a=n.get(s)||[];a.includes(o.name)||a.push(o.name),n.set(s,a)}}return n}static readLocalDependencies(e,t){let n=O.join(e,t,"oh-package.json5");if(!ne.existsSync(n))return[];try{let o=ne.readFileSync(n,"utf-8"),i=hl.parse(o);return r.resolveDepModuleNames(e,t,i.dependencies||{})}catch{return[]}}static resolveDepModuleNames(e,t,n){let o=r.loadBuildProfile(e);if(!o)return[];let i=o.modules,s=[];for(let a of Object.values(n)){if(typeof a!="string")continue;let c=r.tryResolveDepModule(e,t,a,i);c&&s.push(c)}return s}static tryResolveDepModule(e,t,n,o){let i=n;if(!(i.startsWith("file:")||i.startsWith(".")||i.startsWith("..")))return null;i.startsWith("file:")&&(i=i.substring(5));let a=O.resolve(e,t,i);return o.find(l=>O.resolve(e,l.srcPath)===a)?.name??null}static findTopLevelConsumers(e,t,n,o){let i=new Set,s=new Set,a=[e];for(;a.length>0;){let c=a.shift();s.has(c)||(s.add(c),r.processDependents(c,t,n,o,i,a))}return i}static processDependents(e,t,n,o,i,s){let a=t.get(e)||[];for(let c of a){let l=o.find(g=>g.name===c);if(!l)continue;let d=r.getModuleType(n,l.srcPath);(d==="entry"||d==="shared")&&i.add(c),d==="har"&&s.push(c)}}static addFileToCollector(e,t,n,o,i){let s=O.join(i,o,"src","main","resources");n==="ets_ts"?(e.hotReloadEntries.push({filePath:t,belongProjectPath:i}),e.patchEtsFiles.push(t)):n==="raw_file"?e.patchRawFiles.push({filePath:t,resourcePath:s}):n==="res_file"?e.patchResFiles.push({filePath:t,resourcePath:s}):n==="native"&&e.nativeFiles.push(t)}static writeApplyFile(e,t,n,o){let i=t.replace(/^\.\//,""),s=O.join(e,i,"build",n,"intermediates","hotReload","changedFileList.json"),a=r.readExistingApply(s),c=r.mergeApplyEntries(a,o),l=O.dirname(s);ne.existsSync(l)||ne.mkdirSync(l,{recursive:!0}),ne.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),m(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!ne.existsSync(e))return[];try{let t=ne.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,n,o,i,s){let a=t.replace(/^\.\//,""),c=O.join(e,a,"build",n,"intermediates","patch","default","changedFileList.json"),l=r.readExistingPatch(c),d=O.join(e,a,"src","main","ets"),g=o.map(me=>r.resolveRelativePathForPatch(me,d)),y=r.mergeStrings(l.modifiedFiles,g),b=r.mergePatchResources(l.rawFile,i),N=r.mergePatchResources(l.resFile,s),$=O.dirname(c);ne.existsSync($)||ne.mkdirSync($,{recursive:!0}),ne.writeFileSync(c,JSON.stringify({resources:{resFile:N,rawFile:b},modifiedFiles:y}),"utf-8"),m(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!ne.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=ne.readFileSync(e,"utf-8"),n=JSON.parse(t);return{modifiedFiles:n?.modifiedFiles||[],rawFile:n?.resources?.rawFile||[],resFile:n?.resources?.resFile||[]}}catch{return{modifiedFiles:[],rawFile:[],resFile:[]}}}static resolveRelativePathForPatch(e,t){return O.relative(O.normalize(t),O.normalize(e)).replace(/\\/g,"/")}static mergeApplyEntries(e,t){let n=new Set,o=[];for(let i of[...e,...t])n.has(i.filePath)||(n.add(i.filePath),o.push(i));return o}static mergeStrings(e,t){let n=new Set,o=[];for(let i of[...e,...t])n.has(i)||(n.add(i),o.push(i));return o}static mergePatchResources(e,t){let n=new Set,o=[];for(let i of[...e,...t])n.has(i.filePath)||(n.add(i.filePath),o.push(i));return o}};import RE from"fs";import{randomUUID as xE}from"crypto";import{execa as LE}from"execa";var kn=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,n){for(let a of t)if(!RE.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}E.assertBundleName(n);let i=`/data/local/tmp/${xE()}`,s=[];try{for(let a=0;a<t.length;a++){let c=`${i}/${n}_${a}.hqf`;s.push(c),await this.pushHqf(e,t[a],i,c)}return await this.executeQuickfix(e,s)}catch(a){let c=`hqf install error: ${a.message}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}finally{await this.runHdc(["-t",e,"shell","rm","-rf",i],!1)}}async pushHqf(e,t,n,o){console.log(`[Apply] Pushing hqf to device ${e}: ${t}`),await this.runHdc(["-t",e,"shell","mkdir","-p",n]);let i=await this.runHdc(["-t",e,"file","send",t,o]);if(!i.startsWith("FileTransfer finish"))throw new Error(`Failed to send hqf: ${i}`)}async executeQuickfix(e,t){console.log(`[Apply] Installing ${t.length} hqf patch(es) via quickfix...`);let n=["-t",e,"shell","bm","quickfix","-a","-f",...t,"-d"];await this.getApiVersion(e)>17&&n.push("-o");let i=await this.runHdc(n,!1);if(m(`[InstallHqf] quickfix output: ${i}`),/succe(?:ed|ss)/i.test(i))return console.log("[Apply] hqf installed successfully."),{success:!0,message:"hqf quickfix installed successfully."};let s=`hqf quickfix install failed. Device response: ${i||"(empty)"}. Please try reinstalling the application.`;return console.error(`[Apply] ${s}`),{success:!1,message:s}}async getApiVersion(e){try{let t=await this.runHdc(["-t",e,"shell","param","get","const.ohos.apiversion"],!1),n=parseInt(t.trim(),10);if(!isNaN(n))return console.log(`[InstallHqf] device API version: ${n}`),n}catch{}return 0}async runHdc(e,t=!0){let n=this.toolProvider.hdcPath;m(`[InstallHqf] Executing: ${n} ${e.join(" ")}`);try{let{stdout:o}=await LE(n,e,{env:{...process.env}});return o}catch(o){if(t)throw o;return o.stdout||""}}};var NE="6.1.1",Ps=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}async execute(e){await Jr(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(NE);let t=_o(e.applyFile,this.projectRoot);console.log(`[Apply] Parsed ${t.length} changed file(s)`);let n=this.writeChangeFileList(e,t);await this.stopApp(e);let o=await this.buildHqf(e,n);await this.installHqf(e,o),await this.launchApp(e),console.log("[Apply] Apply complete")}writeChangeFileList(e,t){let n=In.writeChangedFileLists(this.projectRoot,e.productName,t);if(n.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");return console.log(`[Apply] changeFileList written for: ${n.writtenModules.join(", ")}`),n.writtenModules}async buildHqf(e,t){return m(`[Apply] hvigor assembleDevHqf --no-daemon (modules=${t.join(",")})`),await Tm(this.toolProvider,this.projectRoot,t,e.productName)}async installHqf(e,t){console.log(`[Apply] Installing ${t.length} hqf(s) to ${e.targetDeviceId}`);let o=await new kn(this.toolProvider).install(e.targetDeviceId,t,e.bundleName);if(!o.success)throw new Error(`hqf install failed: ${o.message}`);console.log("[Apply] hqf installed")}async stopApp(e){let t=new Ze(this.toolProvider);try{await t.forceStopApp(e.targetDeviceId,e.bundleName),console.log("[Apply] app stopped")}catch(n){console.warn(`[Apply] stop app failed: ${n.message}`)}}async launchApp(e){let t=new Ze(this.toolProvider);try{await t.launchApp(e.targetDeviceId,e.bundleName,e.abilityName),console.log("[Apply] app launched")}catch(n){throw new Error(`[Apply] launch app failed: ${n.message}`,{cause:n})}}};import gl from"fs";import*as B from"path";var As=class r{static generate(e,t,n,o){let i=xt(e,t),s=B.join(e,i),a=B.join(s,"build","config"),c=r.buildConfig(e,s,n,o);gl.mkdirSync(a,{recursive:!0}),gl.writeFileSync(B.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[BuildConfigManager] buildConfig.json written to ${a}`);let l=B.join(s,"build",n,"intermediates","loader_out",n,"ets");gl.mkdirSync(l,{recursive:!0})}static buildConfig(e,t,n,o){let i=B.dirname(o.nodePath)+B.sep,s=B.join(t,"build",n),a=B.join(s,"intermediates"),c=B.join(a,"loader_out",n),l=B.join(a,"res",n);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:i,projectProfilePath:B.join(e,"build-profile.json5"),localPropertiesPath:B.join(e,"local.properties"),appResource:B.join(l,"ResourceTable.txt"),cachePath:B.join(s,"cache",n,`${n}@CompileArkTS`,"esmodule","debug"),aceBuildJson:B.join(a,"loader",n,"loader.json"),aceModuleJsonPath:B.join(l,"module.json"),aceSoPath:B.join(c,"nativeDependencies.txt"),aceModuleRoot:B.join(t,"src","main","ets"),aceModuleBuild:B.join(c,"ets"),aceProfilePath:B.join(l,"resources","base","profile"),aceSuperVisualPath:B.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"false",mode:"hotReload",oldMapFilePath:B.join(c,"ets"),changedFileList:B.join(a,"patch",n,"changedFileList.json"),patchAbcPath:B.join(a,"patch",n,"ets"),removeChangedFileListInSdk:"true"}}}};import Lm from"fs";import*as W from"path";var Is=class r{static generate(e,t,n,o){let i=xt(e,t),s=W.join(e,i),a=W.join(s,"build","config"),c=r.buildConfig(e,s,n,o);Lm.mkdirSync(a,{recursive:!0}),Lm.writeFileSync(W.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[HotReloadBuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,n,o){let i=W.dirname(o.nodePath)+W.sep,s=W.join(t,"build",n),a=W.join(s,"intermediates"),c=W.join(a,"loader_out",n),l=W.join(a,"res",n);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:i,projectProfilePath:W.join(e,"build-profile.json5"),localPropertiesPath:W.join(e,"local.properties"),appResource:W.join(l,"ResourceTable.txt"),cachePath:W.join(s,"cache",n,`${n}@CompileArkTS`,"esmodule","debug"),aceBuildJson:W.join(a,"loader",n,"loader.json"),aceModuleJsonPath:W.join(l,"module.json"),aceSoPath:W.join(c,"nativeDependencies.txt"),aceModuleRoot:W.join(t,"src","main","ets"),aceModuleBuild:W.join(c,"ets"),aceProfilePath:W.join(l,"resources","base","profile"),aceSuperVisualPath:W.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:W.join(c,"ets"),changedFileList:W.join(a,"hotReload","changedFileList.json"),patchAbcPath:W.join(a,"hotReload","patchAbcPath","ets"),removeChangedFileListInSdk:"true"}}}};import Nm from"crypto";import it from"fs";import st from"path";import Om from"os";import{io as OE}from"socket.io-client";var ME=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Dn=class r{projectRoot;toolProvider;cachedSocket=null;cachedDaemonPort=0;constructor(e,t){this.projectRoot=e,this.toolProvider=t}async sendHotCompile(e){await this.waitForDaemonReady();let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Run `devecocli run --hotreload` first.");return this.sendViaSocket(t,e)}async startWatchSession(e){await this.waitForDaemonReady(),console.log(`[DaemonClient] Compiling, build with: ${JSON.stringify(e)}`);let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Build the hap first.");let n=await this.getOrCreateSocket(t),o=this.watchLogPath;it.mkdirSync(st.dirname(o),{recursive:!0}),it.writeFileSync(o,"");let i=this.createWatchLogBuffer(o);n.on("WatchLog",i.onWatchLog),n.on("WatchResult",i.onWatchResult),await this.awaitInitialBuild(n,e)}createWatchLogBuffer(e){let n=[];return{onWatchLog:s=>{let a=r.extractText(s);a.trim()&&(n.push(a.endsWith(`
38
+ `),o=i.pop()??"",s=i.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),o}function Dg(n,e,t){let r=n.endsWith("\r")?n.slice(0,-1):n;r.length>0&&t.onData([r],e)}function mR(n,e){return{stdout:n.stdoutChunks.join(""),stderr:n.stderrChunks.join(""),exitCode:e??-1}}function fR(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function hR(n,e,t,r,i){n.stdout?.on("data",o=>{let s=o.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=Rg(e.stdoutLineBuffer+s,"stdout",t)}),n.stderr?.on("data",o=>{let s=o.toString();e.stderrChunks.push(s),e.stderrLineBuffer=Rg(e.stderrLineBuffer+s,"stderr",t)}),n.on("error",o=>{e.settled||(e.settled=!0,t.onError(o),i(o))}),n.on("close",o=>{if(e.settled)return;e.settled=!0,Dg(e.stdoutLineBuffer,"stdout",t),Dg(e.stderrLineBuffer,"stderr",t),t.onClose(o);let s=mR(e,o);r(s)})}async function jo(n,e=[],t={}){try{let{stdout:r,stderr:i}=await pR(n,e,t);return{stdout:typeof r=="string"?r.trim():"",stderr:typeof i=="string"?i.trim():"",exitCode:0}}catch(r){let i=r;return{stdout:i.stdout?.trim()||"",stderr:i.stderr?.trim()??i.message,exitCode:typeof i.code=="number"?i.code:1}}}async function xg(n,e,t){return await new Promise((r,i)=>{let o=dR(n,e,{stdio:["inherit","pipe","pipe"]}),s=fR();hR(o,s,t,r,i)})}function Ag(n){let e=n.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var gR=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],yR=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function At(n){return n?gR.some(e=>e.test(n))?"transient":yR.some(e=>e.test(n))?"fatal":"ok":"ok"}var wR=/(?:^|\s)(\d{2,})(?:\s|$)/;function Ig(n){let e=n.stdout.trim(),t=n.stderr.trim();return At(e)!=="ok"||At(t)!=="ok"?"query-failed":n.exitCode===0?e&&wR.test(e)?"alive":"dead":n.exitCode===1&&!e&&!t?"dead":"query-failed"}var bu=[800,1500,2500];function vR(n){return new Promise(e=>setTimeout(e,n))}async function C(n,e){let t=1+bu.length,r={stdout:"",stderr:"",exitCode:-1};for(let i=0;i<t;i++){if(r=await jo(n,e),r.exitCode===0||At(r.stderr)!=="transient"||i>=t-1)return r;m(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${bu[i]}ms`),await vR(bu[i])}return r}var Tg=/^[\w.-]+$/;async function qa(n,e,t){if(!Tg.test(t)){m(`Skipping invalid param key: ${JSON.stringify(t)}`);return}let r=["-t",e,"shell","param","get",t];m(`Executing: ${n} ${r.join(" ")}`);let i=await C(n,r);if(i.exitCode!==0)return;let o=i.stdout.trim();if(!(!o||At(o)!=="ok"))return Ag(o)}var Su="__DEVECO_PARAM_DELIM__";function bR(n,e){let t=new Map,r=n.split(Su);for(let i=0;i<e.length;i++){let o=(r[i]??"").trim();if(!o||At(o)!=="ok")continue;let s=Ag(o);s&&t.set(e[i],s)}return t}async function Ei(n,e,t){let r=t.filter(a=>Tg.test(a)?!0:(m(`Skipping invalid param key: ${JSON.stringify(a)}`),!1));if(r.length===0)return new Map;if(r.length===1){let a=new Map,c=await qa(n,e,r[0]);return c&&a.set(r[0],c),a}let i=r.map(a=>`param get ${a}`).join(`; echo ${Su}; `)+`; echo ${Su}`,o=await C(n,["-t",e,"shell",i]);if(o.exitCode===0){let a=bR(o.stdout,r);if(a.size>0)return a}m(`Batched param fetch failed (exit=${o.exitCode}), falling back to individual calls for ${e}`);let s=new Map;for(let a of r){let c=await qa(n,e,a);c&&s.set(a,c)}return s}function Jt(n){return n.startsWith("127.0.0.1:")}var Og=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],le=class n{hdcPath;constructor(e){this.hdcPath=e}static from(e){return new n(e.hdcPath)}static withHdcPath(e){return new n(e)}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}stripBrandPrefix(e,t){let r=e.trim(),i=t?.trim();if(!r||!i)return r;let o=new RegExp(`^${this.escapeRegExp(i)}(\\s+|[-_]+)?`,"i");return r.replace(o,"").trim()||r}async executeHdc(e){return m(`Executing: ${this.hdcPath} ${e.join(" ")}`),SR(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let r of e.split(`
39
+ `)){let i=r.trim();if(!i||i.startsWith("[Empty]"))continue;let o=i.split(/\s+/),s=o[0];if(!s||s.startsWith("[Empty]"))continue;let a=o.length>=2?o[1]:"device";if(a.toLowerCase()==="unauthorized"){m(`[DeviceManager] Skipping unauthorized device: ${s}`);continue}t.push({serial:s,status:a})}return t}extractDisplayName(e){let t=e.get("ohos.qemu.hvd.name");if(t)return t;let r=e.get("const.product.name");if(r&&r!=="emulator")return r;let i=e.get("const.product.model");if(i&&i!=="emulator"){let s=e.get("const.product.brand");return this.stripBrandPrefix(i,s)}let o=e.get("const.build.product");if(o&&o!=="emulator")return o}async getDeviceName(e){let t=await Ei(this.hdcPath,e,[...Og]);return this.extractDisplayName(t)??e}async getDeviceInfo(e,t){if(e.length===0)return null;if(t){let r=e.find(s=>s.serial===t);if(r)return r;let i=t.toLowerCase(),o=[];for(let s of e){let a=await this.getDeviceName(s.serial);a.toLowerCase()===i&&o.push({device:s,name:a})}if(o.length===1)return o[0].device;throw o.length>1?new y(`Multiple devices match "${t}". Use a serial instead:
40
+ `+o.map(s=>` - ${s.name} (${s.device.serial})`).join(`
41
+ `),"Multiple devices match."):new y(`Device "${t}" not found. Use \`devecocli device list\` to see available targets.`,"Device not found.")}return e[0]}async getDeviceDetail(e){let t={serial:e,status:"device"};try{let r=await Ei(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=r.get("const.product.devicetype");let i=r.get("const.ohos.apiversion"),o=r.get("const.ohos.releasetype");i&&(t.osVersion=o?`API ${i} (${o})`:`API ${i}`)}catch{}return t}async listDevicesWithName(){let e=await this.listDevices();return Promise.all(e.map(async t=>({serial:t.serial,name:await this.getDeviceName(t.serial)})))}async getConnectedEntries(){let e=await this.listDevices();return Promise.all(e.map(t=>this.buildConnectedEntry(t.serial)))}async buildConnectedEntry(e){let t=Jt(e),r,i;try{let o=await Ei(this.hdcPath,e,[...Og]);r=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:i}}};function PR(n,e,t,r){let i=["-t",n,"shell","bm","install"];return r?.replace&&i.push("-r"),e&&i.push("-p",e),t&&i.push("-s",t),r?.wait!==void 0&&i.push("-w",String(r.wait)),r?.user&&i.push("-u",r.user),i}var de=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=le.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;m(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await Mg(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){E.assertBundleNameStrict(t);let r=await this.runHdc(["-t",e,"shell","bm","uninstall","-n",t],!1);if(r.includes("uninstall bundle successfully"))return!0;if(r.includes("uninstall missing installed bundle"))return!1;throw new Error(`Uninstall failed: ${r}`)}async installApp(e,t,r){let i=!!r?.shared?.length;if(t.length===0&&!i)return;let o=ER(),s=t.length?`/data/local/tmp/${o}`:null,a=i?`/data/local/tmp/${o}-shared`:null;try{s&&await this.runHdc(["-t",e,"shell","mkdir",s]),a&&await this.runHdc(["-t",e,"shell","mkdir",a]),s&&await this.pushFiles(e,t,s),a&&r?.shared&&await this.pushFiles(e,r.shared,a);let c=PR(e,s,a,r),l=await this.runHdc(c);if(!l.includes("install bundle successfully."))throw new Error(l)}finally{s&&await this.runHdc(["-t",e,"shell","rm","-rf",s],!1),a&&await this.runHdc(["-t",e,"shell","rm","-rf",a],!1)}}async pushFiles(e,t,r){for(let i of t){let o=await this.runHdc(["-t",e,"file","send",i,r+"/"]);if(!o.startsWith("FileTransfer finish"))throw new Error(o)}}async launchApp(e,t,r){E.assertBundleNameStrict(t),E.assertAbilityName(r);let i=["-t",e,"shell","aa","start","-a",r,"-b",t];return await this.runHdc(i)}async pidofBundle(e,t){E.assertBundleNameStrict(t);let r=["-t",e,"shell","pidof",t],i=this.toolProvider.hdcPath;m(`Executing: ${i} ${r.join(" ")}`);let o=await C(i,r),s=Ig(o);if(s==="query-failed"){let a=[o.stdout,o.stderr].map(c=>c.trim()).filter(Boolean).join(" ");throw new Error(`pidof query failed for '${t}': ${a||`exit ${o.exitCode}`}`)}return s==="alive"}async forceStopApp(e,t){E.assertBundleNameStrict(t);let r=["-t",e,"shell","aa","force-stop",t];return await this.runHdc(r,!1)}async transferFile(e,t,r,i){let o=["-t",e,"file",t,r,i],s=await this.runHdc(o,!1);if(!s.includes("FileTransfer finish"))throw new Error(`File ${t} failed: ${s.trim()||"hdc returned no output"}`);return s.trim()}async runSqlite3(e,t,r=[]){let i=["-t",e,"shell","sqlite3",t,...r];await Mg(this.toolProvider.hdcPath,i,{stdio:"inherit",env:{...process.env}})}};import Eu from"fs";import*as Mn from"path";function Ho(n,e){if(!Eu.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=Eu.readFileSync(n,"utf-8").split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("#"));if(r.length===0)throw new Error("Apply file list is empty (no valid entries)");let i=Mn.resolve(e),o=new Set,s=[];for(let a of r){let c=Mn.resolve(i,a),l=Mn.isAbsolute(a)?Mn.relative(i,a):a;if(l.startsWith(".."))throw new Error(`File path is outside the project directory: ${a}`);let d=E.isPathContainedWithSymlink(l,i);if(!d.contained){if(!Eu.existsSync(c))throw new Error(`File not found: ${a}`);let g=d.reason?`; ${d.reason}`:"";throw new Error(`File path is outside the project directory: ${a}${g}`)}o.has(c)||(o.add(c),s.push(c))}return s}import Pu from"fs";import Uo from"path";import{execa as RR}from"execa";import Ng from"fs";import*as Lg from"path";import CR from"json5";function kR(n,e){try{let r=CR.parse(Ng.readFileSync(n,"utf-8")).modules?.find(i=>i.name===e);return r?.srcPath?r.srcPath.replace(/^\.\//,""):null}catch(t){return m(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function Yt(n,e){let t=Lg.join(n,"build-profile.json5");return Ng.existsSync(t)?kR(t,e)??e:e}async function _g(n,e,t,r){let i=Uo.dirname(n.javaPath),o={...process.env,PATH:`${i}${Uo.delimiter}${process.env.PATH||""}`,DEVECO_SDK_HOME:n.sdkPath},s=[n.hvigorJsPath,"--mode","module","-p",`module=${t.join(",")}@${r}`,"-p",`product=${r}`,"-p","debuggable=true","assembleDevHqf"];m(`[buildSignedHqf] ${n.nodePath} ${s.join(" ")}`);let a=await RR(n.nodePath,s,{cwd:e,env:o,stdout:"inherit",stderr:"inherit",reject:!1}),c=(a.exitCode??0)|0;if(c===-1)throw new Error("hvigor hot compile produced invalid abc (exit code -1)");if(c!==0)throw new Error(`hvigor assembleDevHqf failed with exit code ${a.exitCode}`);return t.map(l=>xR(e,l,r))}function $g(n,e,t){let r=Yt(n,e);return Uo.join(n,r,"build",t,"outputs")}function DR(n,e,t){return Uo.join($g(n,e,t),`${e}-${t}-signed.hqf`)}function xR(n,e,t){let r=$g(n,e,t),i=DR(n,e,t);if(Pu.existsSync(i))return i;let o=Cu(r,"-signed.hqf")??Cu(r,".hqf");if(!o)throw new Error(`Signed hqf not found at ${i} (and no *.hqf under ${r})`);return m(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${o}`),o}function Cu(n,e){if(!Pu.existsSync(n))return null;for(let t of Pu.readdirSync(n,{withFileTypes:!0})){let r=Uo.join(n,t.name);if(t.isDirectory()){let i=Cu(r,e);if(i)return i}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import ue from"fs";import*as j from"path";import ku from"json5";var Fg="default",Pi=class n{static writeChangedFileLists(e,t,r,i){let o=t||Fg,s=n.loadBuildProfile(e);if(!s)return{writtenModules:[],skippedFiles:r};let a=s.modules,c=n.filterRunnableModules(e,a);if(c.length===0)return{writtenModules:[],skippedFiles:r};let l=n.buildReverseDependencyMap(e,a),d=n.createCollectors(c),g=n.collectChanges(r,e,a,l,d);return{writtenModules:n.flushCollectors(e,o,c,d,i),skippedFiles:g}}static initEmptyChangedFileLists(e,t,r){let i=t||Fg,o=n.loadBuildProfile(e);if(!o)return[];let s=o.modules,a=[];for(let c of s){let l=n.getModuleType(e,c.srcPath);if(l!=="entry"&&l!=="shared")continue;let d=!r||c.name===r;n.initEmptyForModule(e,i,c.srcPath,d),a.push(c.name)}return a}static filterRunnableModules(e,t){return t.filter(r=>{let i=n.getModuleType(e,r.srcPath);return i==="entry"||i==="shared"})}static createCollectors(e){let t=new Map;for(let r of e)t.set(r.name,{hotReloadEntries:[],patchEtsFiles:[],patchRawFiles:[],patchResFiles:[],nativeFiles:[]});return t}static collectChanges(e,t,r,i,o){let s=[];for(let a of e){let c=j.normalize(a),l=n.classifyFile(c,t,r);if(l.fileClass==="unknown"){s.push(c);continue}let d=n.findModuleByFilePath(c,t,r);if(!d){s.push(c);continue}let g=n.resolveTargetModules(d,t,r,i);if(g.length===0){s.push(c);continue}n.dispatchToCollectors(g,o,c,l,d.srcPath,t)}return s}static resolveTargetModules(e,t,r,i){let o=n.getModuleType(t,e.srcPath);return o==="entry"||o==="shared"?[e.name]:Array.from(n.findTopLevelConsumers(e.name,i,t,r))}static dispatchToCollectors(e,t,r,i,o,s){for(let a of e){let c=t.get(a);c&&n.addFileToCollector(c,r,i.fileClass,o,s)}}static flushCollectors(e,t,r,i,o){let s=[];for(let a of r){let c=i.get(a.name);if(!c||!n.hasAnyChange(c))continue;(!o||a.name===o)&&c.hotReloadEntries.length>0&&n.writeApplyFile(e,a.srcPath,t,c.hotReloadEntries),n.writePatchFile(e,a.srcPath,t,c.patchEtsFiles,c.patchRawFiles,c.patchResFiles),s.push(a.name)}return s}static hasAnyChange(e){return e.hotReloadEntries.length>0||e.patchEtsFiles.length>0||e.patchRawFiles.length>0||e.patchResFiles.length>0||e.nativeFiles.length>0}static initEmptyForModule(e,t,r,i){let o=j.join(e,r,"build",t,"intermediates","patch","default"),s=j.join(o,"changedFileList.json");if(ue.existsSync(s)||(ue.mkdirSync(o,{recursive:!0}),ue.writeFileSync(s,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!i)return;let a=j.join(e,r,"build",t,"intermediates","hotReload"),c=j.join(a,"changedFileList.json");ue.existsSync(c)||(ue.mkdirSync(a,{recursive:!0}),ue.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=j.join(e,"build-profile.json5");if(!ue.existsSync(t))return null;try{let r=ue.readFileSync(t,"utf-8");return ku.parse(r)}catch{return null}}static classifyFile(e,t,r){let i=j.extname(e).toLowerCase();if(i===".ets"||i===".ts")return{fileClass:"ets_ts",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};if(i===".cpp"||i===".cc"||i===".c"||i===".h"||i===".hpp")return{fileClass:"native",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};let o=e.replace(/\\/g,"/");return o.includes("/resources/rawfile/")?{fileClass:"raw_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:o.includes("/resources/resfile/")?{fileClass:"res_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:{fileClass:"unknown",moduleSrcPath:""}}static findModuleByFilePath(e,t,r){let i=j.normalize(e);for(let o of r){let s=j.normalize(j.join(t,o.srcPath)),a=s+j.sep;if(i.startsWith(a)||i===s)return o}return null}static getModuleType(e,t){let r=j.join(e,t,"src","main","module.json5");if(!ue.existsSync(r))return"entry";try{let i=ue.readFileSync(r,"utf-8");return ku.parse(i)?.module?.type||"entry"}catch{return"entry"}}static buildReverseDependencyMap(e,t){let r=new Map;for(let i of t){let o=n.readLocalDependencies(e,i.srcPath);for(let s of o){let a=r.get(s)||[];a.includes(i.name)||a.push(i.name),r.set(s,a)}}return r}static readLocalDependencies(e,t){let r=j.join(e,t,"oh-package.json5");if(!ue.existsSync(r))return[];try{let i=ue.readFileSync(r,"utf-8"),o=ku.parse(i);return n.resolveDepModuleNames(e,t,o.dependencies||{})}catch{return[]}}static resolveDepModuleNames(e,t,r){let i=n.loadBuildProfile(e);if(!i)return[];let o=i.modules,s=[];for(let a of Object.values(r)){if(typeof a!="string")continue;let c=n.tryResolveDepModule(e,t,a,o);c&&s.push(c)}return s}static tryResolveDepModule(e,t,r,i){let o=r;if(!(o.startsWith("file:")||o.startsWith(".")||o.startsWith("..")))return null;o.startsWith("file:")&&(o=o.substring(5));let a=j.resolve(e,t,o);return i.find(l=>j.resolve(e,l.srcPath)===a)?.name??null}static findTopLevelConsumers(e,t,r,i){let o=new Set,s=new Set,a=[e];for(;a.length>0;){let c=a.shift();s.has(c)||(s.add(c),n.processDependents(c,t,r,i,o,a))}return o}static processDependents(e,t,r,i,o,s){let a=t.get(e)||[];for(let c of a){let l=i.find(g=>g.name===c);if(!l)continue;let d=n.getModuleType(r,l.srcPath);(d==="entry"||d==="shared")&&o.add(c),d==="har"&&s.push(c)}}static addFileToCollector(e,t,r,i,o){let s=j.join(o,i,"src","main","resources");r==="ets_ts"?(e.hotReloadEntries.push({filePath:t,belongProjectPath:o}),e.patchEtsFiles.push(t)):r==="raw_file"?e.patchRawFiles.push({filePath:t,resourcePath:s}):r==="res_file"?e.patchResFiles.push({filePath:t,resourcePath:s}):r==="native"&&e.nativeFiles.push(t)}static writeApplyFile(e,t,r,i){let o=t.replace(/^\.\//,""),s=j.join(e,o,"build",r,"intermediates","hotReload","changedFileList.json"),a=n.readExistingApply(s),c=n.mergeApplyEntries(a,i),l=j.dirname(s);ue.existsSync(l)||ue.mkdirSync(l,{recursive:!0}),ue.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),m(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!ue.existsSync(e))return[];try{let t=ue.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,r,i,o,s){let a=t.replace(/^\.\//,""),c=j.join(e,a,"build",r,"intermediates","patch","default","changedFileList.json"),l=n.readExistingPatch(c),d=j.join(e,a,"src","main","ets"),g=i.map(at=>n.resolveRelativePathForPatch(at,d)),w=n.mergeStrings(l.modifiedFiles,g),R=n.mergePatchResources(l.rawFile,o),z=n.mergePatchResources(l.resFile,s),ie=j.dirname(c);ue.existsSync(ie)||ue.mkdirSync(ie,{recursive:!0}),ue.writeFileSync(c,JSON.stringify({resources:{resFile:z,rawFile:R},modifiedFiles:w}),"utf-8"),m(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!ue.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=ue.readFileSync(e,"utf-8"),r=JSON.parse(t);return{modifiedFiles:r?.modifiedFiles||[],rawFile:r?.resources?.rawFile||[],resFile:r?.resources?.resFile||[]}}catch{return{modifiedFiles:[],rawFile:[],resFile:[]}}}static resolveRelativePathForPatch(e,t){return j.relative(j.normalize(t),j.normalize(e)).replace(/\\/g,"/")}static mergeApplyEntries(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o.filePath)||(r.add(o.filePath),i.push(o));return i}static mergeStrings(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o)||(r.add(o),i.push(o));return i}static mergePatchResources(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o.filePath)||(r.add(o.filePath),i.push(o));return i}};import AR from"fs";import{randomUUID as IR}from"crypto";import{execa as TR}from"execa";var Ci=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!AR.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}E.assertBundleName(r);let o=`/data/local/tmp/${IR()}`,s=[];try{for(let a=0;a<t.length;a++){let c=`${o}/${r}_${a}.hqf`;s.push(c),await this.pushHqf(e,t[a],o,c)}return await this.executeQuickfix(e,s)}catch(a){let c=`hqf install error: ${a.message}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}finally{await this.runHdc(["-t",e,"shell","rm","-rf",o],!1)}}async pushHqf(e,t,r,i){console.log(`[Apply] Pushing hqf to device ${e}: ${t}`),await this.runHdc(["-t",e,"shell","mkdir","-p",r]);let o=await this.runHdc(["-t",e,"file","send",t,i]);if(!o.startsWith("FileTransfer finish"))throw new Error(`Failed to send hqf: ${o}`)}async executeQuickfix(e,t){console.log(`[Apply] Installing ${t.length} hqf patch(es) via quickfix...`);let r=["-t",e,"shell","bm","quickfix","-a","-f",...t,"-d"];await this.getApiVersion(e)>17&&r.push("-o");let o=await this.runHdc(r,!1);if(m(`[InstallHqf] quickfix output: ${o}`),/succe(?:ed|ss)/i.test(o))return console.log("[Apply] hqf installed successfully."),{success:!0,message:"hqf quickfix installed successfully."};let s=`hqf quickfix install failed. Device response: ${o||"(empty)"}. Please try reinstalling the application.`;return console.error(`[Apply] ${s}`),{success:!1,message:s}}async getApiVersion(e){try{let t=await this.runHdc(["-t",e,"shell","param","get","const.ohos.apiversion"],!1),r=parseInt(t.trim(),10);if(!isNaN(r))return console.log(`[InstallHqf] device API version: ${r}`),r}catch{}return 0}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;m(`[InstallHqf] Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await TR(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}};var OR="6.1.1",za=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}async execute(e){await Tn(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(OR);let t=Ho(e.applyFile,this.projectRoot);console.log(`[Apply] Parsed ${t.length} changed file(s)`);let r=this.writeChangeFileList(e,t);await this.stopApp(e);let i=await this.buildHqf(e,r);await this.installHqf(e,i),await this.launchApp(e),console.log("[Apply] Apply complete")}writeChangeFileList(e,t){let r=Pi.writeChangedFileLists(this.projectRoot,e.productName,t);if(r.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");return console.log(`[Apply] changeFileList written for: ${r.writtenModules.join(", ")}`),r.writtenModules}async buildHqf(e,t){return m(`[Apply] hvigor assembleDevHqf --no-daemon (modules=${t.join(",")})`),await _g(this.toolProvider,this.projectRoot,t,e.productName)}async installHqf(e,t){console.log(`[Apply] Installing ${t.length} hqf(s) to ${e.targetDeviceId}`);let i=await new Ci(this.toolProvider).install(e.targetDeviceId,t,e.bundleName);if(!i.success)throw new Error(`hqf install failed: ${i.message}`);console.log("[Apply] hqf installed")}async stopApp(e){let t=new de(this.toolProvider);try{await t.forceStopApp(e.targetDeviceId,e.bundleName),console.log("[Apply] app stopped")}catch(r){console.warn(`[Apply] stop app failed: ${r.message}`)}}async launchApp(e){let t=new de(this.toolProvider);try{await t.launchApp(e.targetDeviceId,e.bundleName,e.abilityName),console.log("[Apply] app launched")}catch(r){throw new Error(`[Apply] launch app failed: ${r.message}`,{cause:r})}}};import Ru from"fs";import*as K from"path";var Ja=class n{static generate(e,t,r,i){let o=Yt(e,t),s=K.join(e,o),a=K.join(s,"build","config"),c=n.buildConfig(e,s,r,i);Ru.mkdirSync(a,{recursive:!0}),Ru.writeFileSync(K.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[BuildConfigManager] buildConfig.json written to ${a}`);let l=K.join(s,"build",r,"intermediates","loader_out",r,"ets");Ru.mkdirSync(l,{recursive:!0})}static buildConfig(e,t,r,i){let o=K.dirname(i.nodePath)+K.sep,s=K.join(t,"build",r),a=K.join(s,"intermediates"),c=K.join(a,"loader_out",r),l=K.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:K.join(e,"build-profile.json5"),localPropertiesPath:K.join(e,"local.properties"),appResource:K.join(l,"ResourceTable.txt"),cachePath:K.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:K.join(a,"loader",r,"loader.json"),aceModuleJsonPath:K.join(l,"module.json"),aceSoPath:K.join(c,"nativeDependencies.txt"),aceModuleRoot:K.join(t,"src","main","ets"),aceModuleBuild:K.join(c,"ets"),aceProfilePath:K.join(l,"resources","base","profile"),aceSuperVisualPath:K.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"false",mode:"hotReload",oldMapFilePath:K.join(c,"ets"),changedFileList:K.join(a,"patch",r,"changedFileList.json"),patchAbcPath:K.join(a,"patch",r,"ets"),removeChangedFileListInSdk:"true"}}}};import jg from"fs";import*as Q from"path";var Ya=class n{static generate(e,t,r,i){let o=Yt(e,t),s=Q.join(e,o),a=Q.join(s,"build","config"),c=n.buildConfig(e,s,r,i);jg.mkdirSync(a,{recursive:!0}),jg.writeFileSync(Q.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[HotReloadBuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,i){let o=Q.dirname(i.nodePath)+Q.sep,s=Q.join(t,"build",r),a=Q.join(s,"intermediates"),c=Q.join(a,"loader_out",r),l=Q.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:Q.join(e,"build-profile.json5"),localPropertiesPath:Q.join(e,"local.properties"),appResource:Q.join(l,"ResourceTable.txt"),cachePath:Q.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:Q.join(a,"loader",r,"loader.json"),aceModuleJsonPath:Q.join(l,"module.json"),aceSoPath:Q.join(c,"nativeDependencies.txt"),aceModuleRoot:Q.join(t,"src","main","ets"),aceModuleBuild:Q.join(c,"ets"),aceProfilePath:Q.join(l,"resources","base","profile"),aceSuperVisualPath:Q.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:Q.join(c,"ets"),changedFileList:Q.join(a,"hotReload","changedFileList.json"),patchAbcPath:Q.join(a,"hotReload","patchAbcPath","ets"),removeChangedFileListInSdk:"true"}}}};import Hg from"crypto";import yt from"fs";import wt from"path";import Ug from"os";import{io as MR}from"socket.io-client";var NR=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),ki=class n{projectRoot;toolProvider;cachedSocket=null;cachedDaemonPort=0;constructor(e,t){this.projectRoot=e,this.toolProvider=t}async sendHotCompile(e){await this.waitForDaemonReady();let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Run `devecocli run --hotreload` first.");return this.sendViaSocket(t,e)}async startWatchSession(e){await this.waitForDaemonReady(),console.log(`[DaemonClient] Compiling, build with: ${JSON.stringify(e)}`);let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Build the hap first.");let r=await this.getOrCreateSocket(t),i=this.watchLogPath;yt.mkdirSync(wt.dirname(i),{recursive:!0}),yt.writeFileSync(i,"");let o=this.createWatchLogBuffer(i);r.on("WatchLog",o.onWatchLog),r.on("WatchResult",o.onWatchResult),await this.awaitInitialBuild(r,e)}createWatchLogBuffer(e){let r=[];return{onWatchLog:s=>{let a=n.extractText(s);a.trim()&&(r.push(a.endsWith(`
41
42
  `)?a:a+`
42
- `),n.length>100&&n.shift())},onWatchResult:s=>{let a=r.extractText(s);if(!a.trim())return;let c=`[WatchResult] ${a}`;console.log(c),it.writeFileSync(e,[...n,c+`
43
- `].join("")),n.length=0}}}awaitInitialBuild(e,t){return new Promise((n,o)=>{let i=!1,s=this.createOutputHandler(),a=l=>{!l?.status||i||(l.status==="finish"?(i=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),n()):(l.status==="reject"||l.status==="close")&&(i=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),this.invalidateSocket(),o(new Error(l.reason||`Watch-session build ${l.status}`))))},c=l=>{i||(i=!0,o(new Error(`Socket disconnected: ${l}`)))};e.on("disconnect",c),e.on("Output",s),e.on("BuildStatus",a),e.emit("CommonBuild",this.buildStartOptions(t)),console.log("[DaemonClient] Compiling, waiting for build to finish...")})}getWatchLogPath(){return this.watchLogPath}get watchLogPath(){return st.join(this.projectRoot,".hvigor","hotreload-watch.log")}buildStartOptions(e){let t={_:["assembleHap"],daemon:!0,watch:!0,hotReloadBuild:!0,mode:"module",prop:[`module=${e.moduleSpecs.join(",")}`,`product=${e.productName}`,"debuggable=true","hotReload=true","requiredDeviceType=phone"],parallel:!0,incremental:!0,analyze:"normal",env:{DEVECO_SDK_HOME:this.toolProvider.sdkPath}};return console.log("[DaemonClient] buildStartOptions:",JSON.stringify(t,null,2)),t}disconnect(){this.invalidateSocket()}onSocketDisconnect(e){this.cachedSocket&&this.cachedSocket.on("disconnect",e)}async getOrCreateSocket(e){if(this.cachedSocket&&this.cachedDaemonPort===e.port){if(this.cachedSocket.connected)return this.cachedSocket;this.invalidateSocket()}let t=this.decryptSessionId(e.sessionId);console.log(`[DaemonClient] Socket.IO connect: ws://127.0.0.1:${e.port} (${e.state})`);let n=OE(`ws://127.0.0.1:${e.port}`,{transports:["websocket"],path:`/${t}`});return await new Promise((o,i)=>{let s=setTimeout(()=>{i(new Error("Socket connect timeout (10s)"))},1e4);n.once("connect",()=>{clearTimeout(s),o()}),n.once("connect_error",a=>{clearTimeout(s),i(new Error(`Socket connect error: ${a.message}`))})}),this.cachedSocket=n,this.cachedDaemonPort=e.port,n}invalidateSocket(){this.cachedSocket&&(this.cachedSocket.removeAllListeners(),this.cachedSocket.disconnect(),this.cachedSocket=null,this.cachedDaemonPort=0)}async sendViaSocket(e,t){let n=await this.getOrCreateSocket(e);return new Promise((o,i)=>{let s=!1,a=Date.now(),c=this.createHotCompileHandlers(n,()=>s,d=>s=d,i),l=d=>{!d?.status||s||(d.status==="finish"?(s=!0,c.detach(),n.off("BuildStatus",l),console.log(`[Timing] abc compile: ${Date.now()-a}ms`),o(d.exitCode??0)):(d.status==="reject"||d.status==="close")&&(s=!0,c.detach(),n.off("BuildStatus",l),this.invalidateSocket(),i(new Error(`Hot compile ${d.status}: ${d.reason||"see WatchLog/Output above for compile errors"}`))))};n.on("disconnect",c.onDisconnect),n.on("Output",c.onOutput),n.on("BuildStatus",l),n.on("WatchLog",c.onWatchLog),n.on("WatchResult",c.onWatchResult),n.on("WatchCompileResult",c.onWatchCompileResult),n.on("WatchCompileData",c.onWatchCompileData),n.emit("CommonBuild",this.buildCompileOptions(t)),console.log("[DaemonClient] Compiling, waiting for hot compile to finish...")})}static extractText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="object"){let t=e;if(typeof t.text=="string")return t.text;if(typeof t.msg=="string")return t.msg;if(typeof t.message=="string")return t.message}return JSON.stringify(e)}createHotCompileHandlers(e,t,n,o){let i=y=>{t()||(n(!0),g(),this.invalidateSocket(),o(new Error(`Socket disconnected: ${y}`)))},s=this.createOutputHandler(),{onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d}=this.getDataHandler(),g=()=>{e.off("disconnect",i),e.off("Output",s),e.off("WatchLog",a),e.off("WatchResult",c),e.off("WatchCompileResult",l),e.off("WatchCompileData",d)};return{onDisconnect:i,onOutput:s,onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d,detach:g}}getDataHandler(){let e=r.extractText;return{onWatchLog:s=>{let a=e(s);a.trim()&&process.stdout.write(a+(a.endsWith(`
43
+ `),r.length>100&&r.shift())},onWatchResult:s=>{let a=n.extractText(s);if(!a.trim())return;let c=`[WatchResult] ${a}`;console.log(c),yt.writeFileSync(e,[...r,c+`
44
+ `].join("")),r.length=0}}}awaitInitialBuild(e,t){return new Promise((r,i)=>{let o=!1,s=this.createOutputHandler(),a=l=>{!l?.status||o||(l.status==="finish"?(o=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),r()):(l.status==="reject"||l.status==="close")&&(o=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),this.invalidateSocket(),i(new Error(l.reason||`Watch-session build ${l.status}`))))},c=l=>{o||(o=!0,i(new Error(`Socket disconnected: ${l}`)))};e.on("disconnect",c),e.on("Output",s),e.on("BuildStatus",a),e.emit("CommonBuild",this.buildStartOptions(t)),console.log("[DaemonClient] Compiling, waiting for build to finish...")})}getWatchLogPath(){return this.watchLogPath}get watchLogPath(){return wt.join(this.projectRoot,".hvigor","hotreload-watch.log")}buildStartOptions(e){let t={_:["assembleHap"],daemon:!0,watch:!0,hotReloadBuild:!0,mode:"module",prop:[`module=${e.moduleSpecs.join(",")}`,`product=${e.productName}`,"debuggable=true","hotReload=true","requiredDeviceType=phone"],parallel:!0,incremental:!0,analyze:"normal",env:{DEVECO_SDK_HOME:this.toolProvider.sdkPath}};return console.log("[DaemonClient] buildStartOptions:",JSON.stringify(t,null,2)),t}disconnect(){this.invalidateSocket()}onSocketDisconnect(e){this.cachedSocket&&this.cachedSocket.on("disconnect",e)}async getOrCreateSocket(e){if(this.cachedSocket&&this.cachedDaemonPort===e.port){if(this.cachedSocket.connected)return this.cachedSocket;this.invalidateSocket()}let t=this.decryptSessionId(e.sessionId);console.log(`[DaemonClient] Socket.IO connect: ws://127.0.0.1:${e.port} (${e.state})`);let r=MR(`ws://127.0.0.1:${e.port}`,{transports:["websocket"],path:`/${t}`});return await new Promise((i,o)=>{let s=setTimeout(()=>{o(new Error("Socket connect timeout (10s)"))},1e4);r.once("connect",()=>{clearTimeout(s),i()}),r.once("connect_error",a=>{clearTimeout(s),o(new Error(`Socket connect error: ${a.message}`))})}),this.cachedSocket=r,this.cachedDaemonPort=e.port,r}invalidateSocket(){this.cachedSocket&&(this.cachedSocket.removeAllListeners(),this.cachedSocket.disconnect(),this.cachedSocket=null,this.cachedDaemonPort=0)}async sendViaSocket(e,t){let r=await this.getOrCreateSocket(e);return new Promise((i,o)=>{let s=!1,a=Date.now(),c=this.createHotCompileHandlers(r,()=>s,d=>s=d,o),l=d=>{!d?.status||s||(d.status==="finish"?(s=!0,c.detach(),r.off("BuildStatus",l),console.log(`[Timing] abc compile: ${Date.now()-a}ms`),i(d.exitCode??0)):(d.status==="reject"||d.status==="close")&&(s=!0,c.detach(),r.off("BuildStatus",l),this.invalidateSocket(),o(new Error(`Hot compile ${d.status}: ${d.reason||"see WatchLog/Output above for compile errors"}`))))};r.on("disconnect",c.onDisconnect),r.on("Output",c.onOutput),r.on("BuildStatus",l),r.on("WatchLog",c.onWatchLog),r.on("WatchResult",c.onWatchResult),r.on("WatchCompileResult",c.onWatchCompileResult),r.on("WatchCompileData",c.onWatchCompileData),r.emit("CommonBuild",this.buildCompileOptions(t)),console.log("[DaemonClient] Compiling, waiting for hot compile to finish...")})}static extractText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="object"){let t=e;if(typeof t.text=="string")return t.text;if(typeof t.msg=="string")return t.msg;if(typeof t.message=="string")return t.message}return JSON.stringify(e)}createHotCompileHandlers(e,t,r,i){let o=w=>{t()||(r(!0),g(),this.invalidateSocket(),i(new Error(`Socket disconnected: ${w}`)))},s=this.createOutputHandler(),{onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d}=this.getDataHandler(),g=()=>{e.off("disconnect",o),e.off("Output",s),e.off("WatchLog",a),e.off("WatchResult",c),e.off("WatchCompileResult",l),e.off("WatchCompileData",d)};return{onDisconnect:o,onOutput:s,onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d,detach:g}}getDataHandler(){let e=n.extractText;return{onWatchLog:s=>{let a=e(s);a.trim()&&process.stdout.write(a+(a.endsWith(`
44
45
  `)?"":`
45
- `))},onWatchResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchResult] ${a}`)},onWatchCompileResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileResult] ${a}`)},onWatchCompileData:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileData] ${a}`)}}}createOutputHandler(){return e=>{let t=typeof e.text=="string"?e.text:Buffer.from(e.text).toString(e.encoding??"utf-8");t.trim()&&(e.type==="stderr"?process.stderr.write(t):process.stdout.write(t))}}buildCompileOptions(e){let t={_:["assembleDevHqf"],daemon:!0,hotCompile:!0,mode:"module",prop:[`module=${e.moduleSpecs.join(",")}`,`product=${e.productName}`,"debuggable=true","hotReload=true","requiredDeviceType=phone"],parallel:!0,incremental:!0,analyze:"normal",env:{DEVECO_SDK_HOME:this.toolProvider.sdkPath}};return console.log("[DaemonClient] buildCompileOptions:",JSON.stringify(t,null,2)),t}async waitForDaemonReady(){let n=Date.now();for(;Date.now()-n<3e4;){let o=this.findProjectDaemon();if(o&&(o.state==="half_busy"||o.state==="idle"))return;await new Promise(i=>setTimeout(i,1e3))}throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first.")}findProjectDaemon(){let e=this.getRegistryPath();if(!it.existsSync(e))return null;try{let t=it.readFileSync(e,"utf-8"),n=JSON.parse(t),o=Object.values(n).filter(i=>i.cwdPath===this.projectRoot&&(i.state==="idle"||i.state==="half_busy"||i.state==="busy")&&this.isProcessAlive(i.pid));return o.length>0?o[o.length-1]:null}catch{return null}}decryptSessionId(e){let t=this.getMetaDir(),n=st.join(t,"fd"),o=st.join(t,"ac"),i=st.join(t,"ce"),s=this.readComponents(n),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(ME)]),c=this.readSingleFile(o),l=Nm.pbkdf2Sync(Buffer.from(a).toString(),c,1e4,16,"sha256"),d=this.readSingleFile(i),g=this.aesGcmDecrypt(l,d),y=Buffer.from(e,"hex");return this.aesGcmDecrypt(g,y).toString("utf-8")}aesGcmDecrypt(e,t){let n=0,o=t.readUInt32BE(n);n+=4;let i=t.subarray(n,n+12);n+=12;let s=o-16,a=t.subarray(n,n+s);n+=s;let c=t.subarray(n,n+16),l=Nm.createDecipheriv("aes-128-gcm",e,i);return l.setAuthTag(c),Buffer.concat([l.update(a),l.final()])}readComponents(e){let t=it.readdirSync(e).map(n=>st.join(e,n)).filter(n=>it.statSync(n).isDirectory()).sort();if(t.length<3)throw new Error(`Expected 3 subdirectories in ${e}, found ${t.length}`);return t.slice(0,3).map(n=>{let o=it.readdirSync(n);if(o.length===0)throw new Error(`No file in ${n}`);return it.readFileSync(st.join(n,o[0]))})}readSingleFile(e){let t=it.readdirSync(e).map(n=>st.join(e,n)).filter(n=>it.statSync(n).isFile());if(t.length===0)throw new Error(`No file in ${e}`);return it.readFileSync(t[0])}xorBuffers(e){let t=Buffer.alloc(e[0].length);t.set(e[0]);for(let n=1;n<e.length;n++){let o=Buffer.isBuffer(e[n])?e[n]:Buffer.from(e[n]);for(let i=0;i<t.length;i++)t[i]^=o[i]}return t}getRegistryPath(){let e=process.env.HVIGOR_USER_HOME||st.join(Om.homedir(),".hvigor");return st.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||st.join(Om.homedir(),".hvigor");return st.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import Fm from"fs";import*as jt from"path";import{green as Rs,yellow as yl}from"colorette";import Xr from"fs";import*as Zr from"path";import _E from"json5";var FE=2e6,jE=1e6,$E="hotreload",ks=class r{static generateOrUpdate(e,t,n){let o=r.readAppConfig(e),i=Zr.resolve(e,t),s=Zr.join(i,"patch.json"),a;return Xr.existsSync(s)?(m(`[PatchManager] patch.json found at ${s}, incrementing patchVersionCode`),a=r.readExistingPatch(s),a.app.patchVersionCode+=1):(m(`[PatchManager] patch.json not found, generating new one at ${s}`),a={app:{bundleName:o.bundleName,patchVersionCode:FE,versionCode:o.versionCode},module:{name:n,type:$E}}),r.writePatchJson(s,a),a}static readAppConfig(e){let t=Zr.join(e,"AppScope","app.json5");if(!Xr.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let n=Xr.readFileSync(t,"utf-8"),o=_E.parse(n),i=o?.app?.bundleName;if(!i)throw new Error("bundleName is missing in AppScope/app.json5");let s=o?.app?.versionCode??jE;return{bundleName:i,versionCode:s}}static readExistingPatch(e){let t=Xr.readFileSync(e,"utf-8"),n=JSON.parse(t);if(!n?.app?.patchVersionCode)throw new Error(`Invalid patch.json at ${e}: missing app.patchVersionCode`);return n}static writePatchJson(e,t){let n=Zr.dirname(e);Xr.existsSync(n)||Xr.mkdirSync(n,{recursive:!0});let o=JSON.stringify(t,null,2);Xr.writeFileSync(e,o,"utf-8"),m(`[PatchManager] patch.json written to ${e}`),m(`[PatchManager] Content: ${o}`)}};import we from"fs";import*as G from"path";import Mm from"crypto";import HE from"json5";import{execa as _m}from"execa";var Ds=class r{static COMPONENT=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]);static DIRS=["fd","ac","ce"];static decryptPwd(e,t,n){if(t.length<32||t.length%2!==0)throw new Error(`Invalid encrypted password for ${n}`);m(`[DecipherUtil] Decrypting ${n}, encrypted length: ${t.length}`);let o=G.resolve(e,"material"),i=r.getKey(o,n),s=new Int8Array(Buffer.from(t,"hex"));return m(`[DecipherUtil] Data length: ${s.length}, key length: ${i.length}`),r.decrypt(i,s).toString("utf-8")}static getKey(e,t){let n=G.resolve(e,r.DIRS[0]),o=r.readFd(n,t),i=r.readDirBytes(G.resolve(e,r.DIRS[1]),t),s=r.getRootKey(o,i,t),a=r.readDirBytes(G.resolve(e,r.DIRS[2]),t);return new Int8Array(r.decrypt(s,a))}static getRootKey(e,t,n){if(!e.every(a=>a.length===16))throw new Error(`Signing material data error for ${n}`);let o=[...e,r.COMPONENT],i=r.xor(o[0],o[1],n);for(let a=2;a<o.length;a++)i=r.xor(i,o[a],n);let s=Mm.pbkdf2Sync(Buffer.from(i).toString(),Buffer.from(t),1e4,16,"sha256");return new Int8Array(s)}static xor(e,t,n){if(e.byteLength!==t.byteLength)throw new Error(`Signing material data error for ${n}`);let o=new Int8Array(e.byteLength);for(let i=0;i<e.byteLength;i++)o[i]=e[i]^t[i];return o}static decrypt(e,t){let n=(255&t[0])<<24|(255&t[1])<<16|(255&t[2])<<8|255&t[3],o=t.length-4-n,i=t.slice(4,4+o),s=t.slice(t.length-16),a=Mm.createDecipheriv("aes-128-gcm",Buffer.from(e),Buffer.from(i));a.setAuthTag(Buffer.from(s));let c=a.update(Buffer.from(t.subarray(4+o,t.length-16))),l=a.final();return Buffer.concat([c,l])}static readFd(e,t){let n=we.readdirSync(e).filter(i=>i!==".DS_Store");if(n.length!==3)throw new Error(`fd directory must have 3 entries for ${t}`);let o=[];for(let i of n){let s=G.join(e,i);o.push(r.readDirBytes(s,t))}return o}static readDirBytes(e,t){if(we.statSync(e).isDirectory()){let o=we.readdirSync(e).filter(i=>i!==".DS_Store");if(o.length!==1)throw new Error(`Expected exactly 1 file in ${e} for ${t}`);return new Int8Array(we.readFileSync(G.join(e,o[0])))}return new Int8Array(we.readFileSync(e))}},Ts=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let o=`${G.dirname(e.javaPath)}${G.delimiter}${process.env.PATH||""}`;this.env={...process.env,PATH:o,DEVECO_SDK_HOME:e.sdkPath}}async generateAndSign(e,t,n,o,i=!1){let s=this.checkAbcExists(t);if(!s.exists)return{signedHqfPaths:[],message:s.message};let a=this.resolveHqfPaths(e,o);return await this.generateHqf(n,s.abcPath,a.unsignedHqfPath)?i?{success:!0,signedHqfPaths:[a.unsignedHqfPath],unsignedHqfPath:a.unsignedHqfPath,message:"Unsigned hqf generated (signing skipped for emulator)."}:this.signHqfDirect(a.unsignedHqfPath,a.signedHqfPath):{signedHqfPaths:[],unsignedHqfPath:a.unsignedHqfPath,message:"Failed to generate unsigned hqf."}}checkAbcExists(e){let t=G.join(e,"ets","modules.abc");if(we.existsSync(t))return{exists:!0,abcPath:t,message:"abc file exists."};let n=this.findFirstAbc(e);return n?{exists:!0,abcPath:n,message:"abc file exists."}:{exists:!1,abcPath:"",message:`abc file not found in ${e}.`}}findFirstAbc(e){if(!we.existsSync(e))return null;let t=we.readdirSync(e,{withFileTypes:!0});for(let n of t){let o=G.join(e,n.name);if(n.isDirectory()){let i=this.findFirstAbc(o);if(i)return i}else if(n.isFile()&&n.name.endsWith(".abc"))return o}return null}resolveHqfPaths(e,t){let n=xt(this.projectRoot,e),o=G.join(this.projectRoot,n,"build",t,"outputs","default");return we.existsSync(o)||we.mkdirSync(o,{recursive:!0}),{unsignedHqfPath:G.join(o,`${e}-default-unsigned.hqf`),signedHqfPath:G.join(o,`${e}-default-signed.hqf`)}}async generateHqf(e,t,n){let o=this.resolvePackingTool();if(!o)return console.error("[HotReload] app_packing_tool.jar not found in SDK."),!1;let i=G.dirname(t),s=this.toolProvider.javaPath,a=["-jar",o,"--mode","hqf","--json-path",e,"--ets-path",i,"--out-path",n,"--force","true"];m(`[GenSignHqf] Packing: ${s} ${a.join(" ")}`);try{let c=Date.now(),l=await _m(s,a,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] pack (JVM#1): ${Date.now()-c}ms`),l.stdout&&console.log(l.stdout),l.stderr&&console.error(l.stderr),l.exitCode!==0?(console.error(`[HotReload] app_packing_tool failed with exit code ${l.exitCode}`),!1):we.existsSync(n)?(console.log(`[HotReload] Unsigned hqf generated: ${n}`),!0):(console.error(`[HotReload] hqf not generated at ${n}`),!1)}catch(c){return console.error(`[HotReload] Packing hqf failed: ${c.message}`),!1}}async signHqfDirect(e,t){let n=this.resolveSignConfig();if(!n)return this.signFailResult(e,"Signing prerequisites not met.");let o=this.buildSignArgs(n,e,t),i=this.toolProvider.javaPath,s=o.map((a,c)=>c>0&&["-keyPwd","-keystorePwd"].includes(o[c-1])?"******":a);m(`[GenSignHqf] Signing: ${i} ${s.join(" ")}`);try{let a=Date.now(),c=await _m(i,o,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] sign (JVM#2): ${Date.now()-a}ms`),c.stdout&&console.log(c.stdout),c.stderr&&console.error(c.stderr),c.exitCode!==0?this.signFailResult(e,`hqf signing failed with exit code ${c.exitCode}`):we.existsSync(t)?(console.log(`[HotReload] Signed hqf generated: ${t}`),{success:!0,signedHqfPaths:[t],unsignedHqfPath:e,message:"hqf generated and signed successfully."}):this.signFailResult(e,`Signed hqf not generated at ${t}`)}catch(a){return this.signFailResult(e,`hqf signing failed: ${a.message}`)}}resolveSignConfig(){let e=this.resolveSignTool();if(!e)return null;let t=this.readSigningConfig("default");if(!t?.storeFile||!t?.certpath||!t?.profile)return null;let n=this.resolveMaterialDir();if(!n)return null;try{let o=Ds.decryptPwd(n,t.storePassword,"storePassword"),i=Ds.decryptPwd(n,t.keyPassword,"keyPassword");return{signToolPath:e,storePwd:o,keyPwd:i,signingConfig:t}}catch{return null}}buildSignArgs(e,t,n){return["-jar",e.signToolPath,"sign-app","-mode","localSign","-keyAlias",e.signingConfig.keyAlias||"debugKey","-keyPwd",e.keyPwd,"-keystoreFile",e.signingConfig.storeFile,"-keystorePwd",e.storePwd,"-appCertFile",e.signingConfig.certpath,"-profileFile",e.signingConfig.profile,"-inFile",t,"-outFile",n,"-signAlg",e.signingConfig.signAlg||"SHA256withECDSA"]}resolveMaterialDir(){let e=this.readSigningConfig("default");if(!e?.storeFile)return null;let t=G.resolve(e.storeFile,".."),n=G.join(t,"material");return we.existsSync(n)?t:null}readSigningConfig(e){let t=G.join(this.projectRoot,"build-profile.json5");if(!we.existsSync(t))return null;try{let n=we.readFileSync(t,"utf-8"),o=HE.parse(n),s=o.app?.products?.find(a=>a.name===e)?.signingConfig;return s?o.app?.signingConfigs?.find(a=>a.name===s)?.material??null:null}catch{return null}}resolveSignTool(){let e=this.toolProvider.sdkPath,t=[G.join(e,"default","openharmony","toolchains","lib","hap-sign-tool.jar"),G.join(e,"toolchains","lib","hap-sign-tool.jar")];for(let n of t)if(we.existsSync(n))return n;return null}signFailResult(e,t){return console.error(`[HotReload] ${t}`),{success:!1,signedHqfPaths:[],unsignedHqfPath:e,message:t}}resolvePackingTool(){let e=this.toolProvider.sdkPath,t=[G.join(e,"default","openharmony","toolchains","lib","app_packing_tool.jar"),G.join(e,"toolchains","lib","app_packing_tool.jar")];for(let n of t)if(we.existsSync(n))return n;return null}};async function jm(r){let e=Date.now(),t=xt(r.projectPath,r.moduleName),n=BE(r);console.log(yl("[HotReload] Ensure the project source is trusted before proceeding."));let o=UE(r),i=_o(n,r.projectPath);console.log(`[HotReload] Parsed ${i.length} changed file(s) from ${r.applyFileName}`),WE(r,i),VE(r,t),await GE(r,o);let s=jt.join(r.projectPath,t,"patch.json"),a=await qE(r,t,s);return await JE(r,a),console.log(Rs("[HotReload] hot reload applied successfully (app not restarted).")),console.log(`[Timing] TOTAL executeHotReloadApply: ${Date.now()-e}ms`),{success:!0,message:"Hot reload applied successfully."}}function BE(r){if(jt.basename(r.applyFileName)!==r.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r.applyFileName}`);return jt.join(r.projectPath,".hvigor",r.applyFileName)}function UE(r){let{projectPath:e,toolProvider:t}=r,n=new Dn(e,t);if(!n.findProjectDaemon())throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first to start the daemon.");return n}function WE(r,e){let t=In.writeChangedFileLists(r.projectPath,r.productName,e,r.moduleName);if(t.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");console.log(Rs(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn(yl(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function VE(r,e){let t=ks.generateOrUpdate(r.projectPath,e,r.moduleName);console.log(Rs(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function GE(r,e){let t=Date.now(),n=e.getWatchLogPath();try{console.log("[HotReload] Daemon hot compile (socket short connection)...");let o=await e.sendHotCompile({moduleSpecs:r.moduleSpecs,productName:r.productName});if(o!==0){let i=zE(n);throw new Error(`Daemon hot compile exited with code ${o}`+(i?`
46
+ `))},onWatchResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchResult] ${a}`)},onWatchCompileResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileResult] ${a}`)},onWatchCompileData:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileData] ${a}`)}}}createOutputHandler(){return e=>{let t=typeof e.text=="string"?e.text:Buffer.from(e.text).toString(e.encoding??"utf-8");t.trim()&&(e.type==="stderr"?process.stderr.write(t):process.stdout.write(t))}}buildCompileOptions(e){let t={_:["assembleDevHqf"],daemon:!0,hotCompile:!0,mode:"module",prop:[`module=${e.moduleSpecs.join(",")}`,`product=${e.productName}`,"debuggable=true","hotReload=true","requiredDeviceType=phone"],parallel:!0,incremental:!0,analyze:"normal",env:{DEVECO_SDK_HOME:this.toolProvider.sdkPath}};return console.log("[DaemonClient] buildCompileOptions:",JSON.stringify(t,null,2)),t}async waitForDaemonReady(){let r=Date.now();for(;Date.now()-r<3e4;){let i=this.findProjectDaemon();if(i&&(i.state==="half_busy"||i.state==="idle"))return;await new Promise(o=>setTimeout(o,1e3))}throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first.")}findProjectDaemon(){let e=this.getRegistryPath();if(!yt.existsSync(e))return null;try{let t=yt.readFileSync(e,"utf-8"),r=JSON.parse(t),i=Object.values(r).filter(o=>o.cwdPath===this.projectRoot&&(o.state==="idle"||o.state==="half_busy"||o.state==="busy")&&this.isProcessAlive(o.pid));return i.length>0?i[i.length-1]:null}catch{return null}}decryptSessionId(e){let t=this.getMetaDir(),r=wt.join(t,"fd"),i=wt.join(t,"ac"),o=wt.join(t,"ce"),s=this.readComponents(r),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(NR)]),c=this.readSingleFile(i),l=Hg.pbkdf2Sync(Buffer.from(a).toString(),c,1e4,16,"sha256"),d=this.readSingleFile(o),g=this.aesGcmDecrypt(l,d),w=Buffer.from(e,"hex");return this.aesGcmDecrypt(g,w).toString("utf-8")}aesGcmDecrypt(e,t){let r=0,i=t.readUInt32BE(r);r+=4;let o=t.subarray(r,r+12);r+=12;let s=i-16,a=t.subarray(r,r+s);r+=s;let c=t.subarray(r,r+16),l=Hg.createDecipheriv("aes-128-gcm",e,o);return l.setAuthTag(c),Buffer.concat([l.update(a),l.final()])}readComponents(e){let t=yt.readdirSync(e).map(r=>wt.join(e,r)).filter(r=>yt.statSync(r).isDirectory()).sort();if(t.length<3)throw new Error(`Expected 3 subdirectories in ${e}, found ${t.length}`);return t.slice(0,3).map(r=>{let i=yt.readdirSync(r);if(i.length===0)throw new Error(`No file in ${r}`);return yt.readFileSync(wt.join(r,i[0]))})}readSingleFile(e){let t=yt.readdirSync(e).map(r=>wt.join(e,r)).filter(r=>yt.statSync(r).isFile());if(t.length===0)throw new Error(`No file in ${e}`);return yt.readFileSync(t[0])}xorBuffers(e){let t=Buffer.alloc(e[0].length);t.set(e[0]);for(let r=1;r<e.length;r++){let i=Buffer.isBuffer(e[r])?e[r]:Buffer.from(e[r]);for(let o=0;o<t.length;o++)t[o]^=i[o]}return t}getRegistryPath(){let e=process.env.HVIGOR_USER_HOME||wt.join(Ug.homedir(),".hvigor");return wt.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||wt.join(Ug.homedir(),".hvigor");return wt.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import Vg from"fs";import*as pr from"path";import{green as Qa,yellow as Du}from"colorette";import Nn from"fs";import*as Ln from"path";import LR from"json5";var _R=2e6,$R=1e6,FR="hotreload",Ka=class n{static generateOrUpdate(e,t,r){let i=n.readAppConfig(e),o=Ln.resolve(e,t),s=Ln.join(o,"patch.json"),a;return Nn.existsSync(s)?(m(`[PatchManager] patch.json found at ${s}, incrementing patchVersionCode`),a=n.readExistingPatch(s),a.app.patchVersionCode+=1):(m(`[PatchManager] patch.json not found, generating new one at ${s}`),a={app:{bundleName:i.bundleName,patchVersionCode:_R,versionCode:i.versionCode},module:{name:r,type:FR}}),n.writePatchJson(s,a),a}static readAppConfig(e){let t=Ln.join(e,"AppScope","app.json5");if(!Nn.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let r=Nn.readFileSync(t,"utf-8"),i=LR.parse(r),o=i?.app?.bundleName;if(!o)throw new Error("bundleName is missing in AppScope/app.json5");let s=i?.app?.versionCode??$R;return{bundleName:o,versionCode:s}}static readExistingPatch(e){let t=Nn.readFileSync(e,"utf-8"),r=JSON.parse(t);if(!r?.app?.patchVersionCode)throw new Error(`Invalid patch.json at ${e}: missing app.patchVersionCode`);return r}static writePatchJson(e,t){let r=Ln.dirname(e);Nn.existsSync(r)||Nn.mkdirSync(r,{recursive:!0});let i=JSON.stringify(t,null,2);Nn.writeFileSync(e,i,"utf-8"),m(`[PatchManager] patch.json written to ${e}`),m(`[PatchManager] Content: ${i}`)}};import xe from"fs";import*as ee from"path";import Bg from"crypto";import jR from"json5";import{execa as Wg}from"execa";var Xa=class n{static COMPONENT=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]);static DIRS=["fd","ac","ce"];static decryptPwd(e,t,r){if(t.length<32||t.length%2!==0)throw new Error(`Invalid encrypted password for ${r}`);m(`[DecipherUtil] Decrypting ${r}, encrypted length: ${t.length}`);let i=ee.resolve(e,"material"),o=n.getKey(i,r),s=new Int8Array(Buffer.from(t,"hex"));return m(`[DecipherUtil] Data length: ${s.length}, key length: ${o.length}`),n.decrypt(o,s).toString("utf-8")}static getKey(e,t){let r=ee.resolve(e,n.DIRS[0]),i=n.readFd(r,t),o=n.readDirBytes(ee.resolve(e,n.DIRS[1]),t),s=n.getRootKey(i,o,t),a=n.readDirBytes(ee.resolve(e,n.DIRS[2]),t);return new Int8Array(n.decrypt(s,a))}static getRootKey(e,t,r){if(!e.every(a=>a.length===16))throw new Error(`Signing material data error for ${r}`);let i=[...e,n.COMPONENT],o=n.xor(i[0],i[1],r);for(let a=2;a<i.length;a++)o=n.xor(o,i[a],r);let s=Bg.pbkdf2Sync(Buffer.from(o).toString(),Buffer.from(t),1e4,16,"sha256");return new Int8Array(s)}static xor(e,t,r){if(e.byteLength!==t.byteLength)throw new Error(`Signing material data error for ${r}`);let i=new Int8Array(e.byteLength);for(let o=0;o<e.byteLength;o++)i[o]=e[o]^t[o];return i}static decrypt(e,t){let r=(255&t[0])<<24|(255&t[1])<<16|(255&t[2])<<8|255&t[3],i=t.length-4-r,o=t.slice(4,4+i),s=t.slice(t.length-16),a=Bg.createDecipheriv("aes-128-gcm",Buffer.from(e),Buffer.from(o));a.setAuthTag(Buffer.from(s));let c=a.update(Buffer.from(t.subarray(4+i,t.length-16))),l=a.final();return Buffer.concat([c,l])}static readFd(e,t){let r=xe.readdirSync(e).filter(o=>o!==".DS_Store");if(r.length!==3)throw new Error(`fd directory must have 3 entries for ${t}`);let i=[];for(let o of r){let s=ee.join(e,o);i.push(n.readDirBytes(s,t))}return i}static readDirBytes(e,t){if(xe.statSync(e).isDirectory()){let i=xe.readdirSync(e).filter(o=>o!==".DS_Store");if(i.length!==1)throw new Error(`Expected exactly 1 file in ${e} for ${t}`);return new Int8Array(xe.readFileSync(ee.join(e,i[0])))}return new Int8Array(xe.readFileSync(e))}},Za=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let i=`${ee.dirname(e.javaPath)}${ee.delimiter}${process.env.PATH||""}`;this.env={...process.env,PATH:i,DEVECO_SDK_HOME:e.sdkPath}}async generateAndSign(e,t,r,i,o=!1){let s=this.checkAbcExists(t);if(!s.exists)return{signedHqfPaths:[],message:s.message};let a=this.resolveHqfPaths(e,i);return await this.generateHqf(r,s.abcPath,a.unsignedHqfPath)?o?{success:!0,signedHqfPaths:[a.unsignedHqfPath],unsignedHqfPath:a.unsignedHqfPath,message:"Unsigned hqf generated (signing skipped for emulator)."}:this.signHqfDirect(a.unsignedHqfPath,a.signedHqfPath):{signedHqfPaths:[],unsignedHqfPath:a.unsignedHqfPath,message:"Failed to generate unsigned hqf."}}checkAbcExists(e){let t=ee.join(e,"ets","modules.abc");if(xe.existsSync(t))return{exists:!0,abcPath:t,message:"abc file exists."};let r=this.findFirstAbc(e);return r?{exists:!0,abcPath:r,message:"abc file exists."}:{exists:!1,abcPath:"",message:`abc file not found in ${e}.`}}findFirstAbc(e){if(!xe.existsSync(e))return null;let t=xe.readdirSync(e,{withFileTypes:!0});for(let r of t){let i=ee.join(e,r.name);if(r.isDirectory()){let o=this.findFirstAbc(i);if(o)return o}else if(r.isFile()&&r.name.endsWith(".abc"))return i}return null}resolveHqfPaths(e,t){let r=Yt(this.projectRoot,e),i=ee.join(this.projectRoot,r,"build",t,"outputs","default");return xe.existsSync(i)||xe.mkdirSync(i,{recursive:!0}),{unsignedHqfPath:ee.join(i,`${e}-default-unsigned.hqf`),signedHqfPath:ee.join(i,`${e}-default-signed.hqf`)}}async generateHqf(e,t,r){let i=this.resolvePackingTool();if(!i)return console.error("[HotReload] app_packing_tool.jar not found in SDK."),!1;let o=ee.dirname(t),s=this.toolProvider.javaPath,a=["-jar",i,"--mode","hqf","--json-path",e,"--ets-path",o,"--out-path",r,"--force","true"];m(`[GenSignHqf] Packing: ${s} ${a.join(" ")}`);try{let c=Date.now(),l=await Wg(s,a,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] pack (JVM#1): ${Date.now()-c}ms`),l.stdout&&console.log(l.stdout),l.stderr&&console.error(l.stderr),l.exitCode!==0?(console.error(`[HotReload] app_packing_tool failed with exit code ${l.exitCode}`),!1):xe.existsSync(r)?(console.log(`[HotReload] Unsigned hqf generated: ${r}`),!0):(console.error(`[HotReload] hqf not generated at ${r}`),!1)}catch(c){return console.error(`[HotReload] Packing hqf failed: ${c.message}`),!1}}async signHqfDirect(e,t){let r=this.resolveSignConfig();if(!r)return this.signFailResult(e,"Signing prerequisites not met.");let i=this.buildSignArgs(r,e,t),o=this.toolProvider.javaPath,s=i.map((a,c)=>c>0&&["-keyPwd","-keystorePwd"].includes(i[c-1])?"******":a);m(`[GenSignHqf] Signing: ${o} ${s.join(" ")}`);try{let a=Date.now(),c=await Wg(o,i,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] sign (JVM#2): ${Date.now()-a}ms`),c.stdout&&console.log(c.stdout),c.stderr&&console.error(c.stderr),c.exitCode!==0?this.signFailResult(e,`hqf signing failed with exit code ${c.exitCode}`):xe.existsSync(t)?(console.log(`[HotReload] Signed hqf generated: ${t}`),{success:!0,signedHqfPaths:[t],unsignedHqfPath:e,message:"hqf generated and signed successfully."}):this.signFailResult(e,`Signed hqf not generated at ${t}`)}catch(a){return this.signFailResult(e,`hqf signing failed: ${a.message}`)}}resolveSignConfig(){let e=this.resolveSignTool();if(!e)return null;let t=this.readSigningConfig("default");if(!t?.storeFile||!t?.certpath||!t?.profile)return null;let r=this.resolveMaterialDir();if(!r)return null;try{let i=Xa.decryptPwd(r,t.storePassword,"storePassword"),o=Xa.decryptPwd(r,t.keyPassword,"keyPassword");return{signToolPath:e,storePwd:i,keyPwd:o,signingConfig:t}}catch{return null}}buildSignArgs(e,t,r){return["-jar",e.signToolPath,"sign-app","-mode","localSign","-keyAlias",e.signingConfig.keyAlias||"debugKey","-keyPwd",e.keyPwd,"-keystoreFile",e.signingConfig.storeFile,"-keystorePwd",e.storePwd,"-appCertFile",e.signingConfig.certpath,"-profileFile",e.signingConfig.profile,"-inFile",t,"-outFile",r,"-signAlg",e.signingConfig.signAlg||"SHA256withECDSA"]}resolveMaterialDir(){let e=this.readSigningConfig("default");if(!e?.storeFile)return null;let t=ee.resolve(e.storeFile,".."),r=ee.join(t,"material");return xe.existsSync(r)?t:null}readSigningConfig(e){let t=ee.join(this.projectRoot,"build-profile.json5");if(!xe.existsSync(t))return null;try{let r=xe.readFileSync(t,"utf-8"),i=jR.parse(r),s=i.app?.products?.find(a=>a.name===e)?.signingConfig;return s?i.app?.signingConfigs?.find(a=>a.name===s)?.material??null:null}catch{return null}}resolveSignTool(){let e=this.toolProvider.sdkPath,t=[ee.join(e,"default","openharmony","toolchains","lib","hap-sign-tool.jar"),ee.join(e,"toolchains","lib","hap-sign-tool.jar")];for(let r of t)if(xe.existsSync(r))return r;return null}signFailResult(e,t){return console.error(`[HotReload] ${t}`),{success:!1,signedHqfPaths:[],unsignedHqfPath:e,message:t}}resolvePackingTool(){let e=this.toolProvider.sdkPath,t=[ee.join(e,"default","openharmony","toolchains","lib","app_packing_tool.jar"),ee.join(e,"toolchains","lib","app_packing_tool.jar")];for(let r of t)if(xe.existsSync(r))return r;return null}};async function Gg(n){let e=Date.now(),t=Yt(n.projectPath,n.moduleName),r=HR(n);console.log(Du("[HotReload] Ensure the project source is trusted before proceeding."));let i=UR(n),o=Ho(r,n.projectPath);console.log(`[HotReload] Parsed ${o.length} changed file(s) from ${n.applyFileName}`),BR(n,o),WR(n,t),await VR(n,i);let s=pr.join(n.projectPath,t,"patch.json"),a=await qR(n,t,s);return await zR(n,a),console.log(Qa("[HotReload] hot reload applied successfully (app not restarted).")),console.log(`[Timing] TOTAL executeHotReloadApply: ${Date.now()-e}ms`),{success:!0,message:"Hot reload applied successfully."}}function HR(n){if(pr.basename(n.applyFileName)!==n.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n.applyFileName}`);return pr.join(n.projectPath,".hvigor",n.applyFileName)}function UR(n){let{projectPath:e,toolProvider:t}=n,r=new ki(e,t);if(!r.findProjectDaemon())throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first to start the daemon.");return r}function BR(n,e){let t=Pi.writeChangedFileLists(n.projectPath,n.productName,e,n.moduleName);if(t.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");console.log(Qa(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn(Du(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function WR(n,e){let t=Ka.generateOrUpdate(n.projectPath,e,n.moduleName);console.log(Qa(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function VR(n,e){let t=Date.now(),r=e.getWatchLogPath();try{console.log("[HotReload] Daemon hot compile (socket short connection)...");let i=await e.sendHotCompile({moduleSpecs:n.moduleSpecs,productName:n.productName});if(i!==0){let o=GR(r);throw new Error(`Daemon hot compile exited with code ${i}`+(o?`
46
47
  --- compile output (from watch session) ---
47
- ${i}`:""))}}finally{e.disconnect()}console.log(`[Timing] daemon hot compile: ${Date.now()-t}ms`)}function zE(r){try{return Fm.existsSync(r)?Fm.readFileSync(r,"utf8").split(/\r?\n/).filter(t=>t.trim()).slice(-40).join(`
48
- `):""}catch{return""}}async function qE(r,e,t){let n=jt.join(r.projectPath,e,"build",r.productName,"intermediates"),o=[jt.join(n,"hotReload","patchAbcPath"),jt.join(n,"patch","default")],i=Date.now(),s=new Ts(r.toolProvider,r.projectPath),a=r.targetDeviceId.includes("127.0.0.1")||r.targetDeviceId.includes("localhost"),c=null;for(let l of o){let d=await s.generateAndSign(r.moduleName,l,t,r.productName,a);if(d.success&&d.signedHqfPaths.length>0){c=d;break}c=d}if(console.log(`[Timing] gen+sign hqf: ${Date.now()-i}ms`),!c?.success||c.signedHqfPaths.length===0)throw new Error(`hqf generation/signing failed (no abc found in any candidate). Last: ${c?.message??"unknown"}`);return c.signedHqfPaths}async function JE(r,e){let t=Date.now(),o=await new kn(r.toolProvider).install(r.targetDeviceId,e,r.bundleName);if(console.log(`[Timing] quickfix install: ${Date.now()-t}ms`),!o.success)throw new Error(`hqf install failed: ${o.message}`)}function vl(r,e){if(!r||r.length===0)throw new Error(`Hot reload requires --module <name> (a single target module; har deps are fine). Got: '${e??""}' (no --module passed).`)}function $m(r,e,t){let n=jt.join(r.rootDir,".hvigor",t),o;try{o=_o(n,r.rootDir)}catch{return}let i=new Set;for(let s of o){let a=r.findOwningModule(s);if(!a||a===e)continue;let c=r.getModuleType(a);(c==="feature"||c==="shared")&&i.add(`${a} (${c})`)}i.size>0&&console.warn(yl(`[HotReload] Changed files belong to feature/hsp dependency module(s): ${[...i].join(", ")}. These are NOT hot-reloadable \u2014 run \`devecocli run\` (full redeploy) for them. Only the target module (+ har deps) will be hot-reloaded this time.`))}function Hm(r,e,t,n,o){let i=new Set,s=r.collectNonHarDependentModuleList(e);for(let a of s)i.add(r.findArtifactPath(a,t,n,o));return i.add(r.findArtifactPath(e,t,n,o)),[...i]}async function Bm(r,e){await new Ke(r,e.rootDir).stopDaemon(),console.log(Rs("Hvigor daemon stopped."))}var xs=class{formatPass(e){return e.evidence.processCheckSkipped?"Smoke: PASS (process check unavailable, smoke skipped)":e.evidence.phashBlank===null?"Smoke: PASS (screenshot unavailable, blank check skipped)":"Smoke: PASS"}formatFailure(e,t){let{status:n,reason:o,evidence:i}=e,s=[`Smoke: ${n}`,`${o} (bundle=${t.bundleName}, device=${t.targetDeviceId}).`];return n==="FAIL_CRASH"&&i.crashLogPath&&s.push(`crash_log: ${i.crashLogPath}`),n==="FAIL_BLANK"&&i.screenshotPath&&s.push(`screenshot: ${i.screenshotPath}`),s.join(`
49
- `)}toTraceError(e,t){return new w(this.formatFailure(e,t),e.status)}};import Fs from"fs";import AC from"path";import{yellow as Uo}from"colorette";import{cyan as Ls}from"colorette";function Qr(r,e){if(r.exitCode===0)return null;let t=r.stderr||r.stdout,n=cr(t);return n==="transient"?new Error(`${e}: Device communication channel unavailable. Retry in a few seconds.`):n==="fatal"?new Error(`${e}: ${t.trim()}`):null}var wl=[800,1500,2500];function KE(r){return new Promise(e=>setTimeout(e,r))}var lr=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=ue.from(e)}createFollowLineHandler(){return(e,t)=>{if(t==="stderr"){for(let n of e)console.error(n);return}for(let n of e)console.log(n)}}findDeviceByArg(e,t){return e.find(n=>n.serial===t||n.name===t)}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
50
- `)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let o=t[0];return m(Ls(`Using device serial: ${o}`)),o}if(e&&t.includes(e))return m(Ls(`Using device serial: ${e}`)),e;let n=await this.loadConnectedDevicesByName();if(e){let o=this.findDeviceByArg(n,e);if(o)return m(Ls(`Using device: ${o.name} (${o.serial})`)),o.serial;let i=this.formatConnectedDeviceList(n);throw new w(`Device '${e}' not found.
48
+ ${o}`:""))}}finally{e.disconnect()}console.log(`[Timing] daemon hot compile: ${Date.now()-t}ms`)}function GR(n){try{return Vg.existsSync(n)?Vg.readFileSync(n,"utf8").split(/\r?\n/).filter(t=>t.trim()).slice(-40).join(`
49
+ `):""}catch{return""}}async function qR(n,e,t){let r=pr.join(n.projectPath,e,"build",n.productName,"intermediates"),i=[pr.join(r,"hotReload","patchAbcPath"),pr.join(r,"patch","default")],o=Date.now(),s=new Za(n.toolProvider,n.projectPath),a=n.targetDeviceId.includes("127.0.0.1")||n.targetDeviceId.includes("localhost"),c=null;for(let l of i){let d=await s.generateAndSign(n.moduleName,l,t,n.productName,a);if(d.success&&d.signedHqfPaths.length>0){c=d;break}c=d}if(console.log(`[Timing] gen+sign hqf: ${Date.now()-o}ms`),!c?.success||c.signedHqfPaths.length===0)throw new Error(`hqf generation/signing failed (no abc found in any candidate). Last: ${c?.message??"unknown"}`);return c.signedHqfPaths}async function zR(n,e){let t=Date.now(),i=await new Ci(n.toolProvider).install(n.targetDeviceId,e,n.bundleName);if(console.log(`[Timing] quickfix install: ${Date.now()-t}ms`),!i.success)throw new Error(`hqf install failed: ${i.message}`)}function xu(n,e){if(!n||n.length===0)throw new Error(`Hot reload requires --module <name> (a single target module; har deps are fine). Got: '${e??""}' (no --module passed).`)}function qg(n,e,t){let r=pr.join(n.rootDir,".hvigor",t),i;try{i=Ho(r,n.rootDir)}catch{return}let o=new Set;for(let s of i){let a=n.findOwningModule(s);if(!a||a===e)continue;let c=n.getModuleType(a);(c==="feature"||c==="shared")&&o.add(`${a} (${c})`)}o.size>0&&console.warn(Du(`[HotReload] Changed files belong to feature/hsp dependency module(s): ${[...o].join(", ")}. These are NOT hot-reloadable \u2014 run \`devecocli run\` (full redeploy) for them. Only the target module (+ har deps) will be hot-reloaded this time.`))}function zg(n,e,t,r,i){let o=new Set,s=n.collectNonHarDependentModuleList(e);for(let a of s)o.add(n.findArtifactPath(a,t,r,i));return o.add(n.findArtifactPath(e,t,r,i)),[...o]}async function Jg(n,e){await new dt(n,e.rootDir).stopDaemon(),console.log(Qa("Hvigor daemon stopped."))}var ec=class{formatPass(e){return e.evidence.processCheckSkipped?"Smoke: PASS (process check unavailable, smoke skipped)":e.evidence.phashBlank===null?"Smoke: PASS (screenshot unavailable, blank check skipped)":"Smoke: PASS"}formatFailure(e,t){let{status:r,reason:i,evidence:o}=e,s=[`Smoke: ${r}`,`${i} (bundle=${t.bundleName}, device=${t.targetDeviceId}).`];return r==="FAIL_CRASH"&&o.crashLogPath&&s.push(`crash_log: ${o.crashLogPath}`),r==="FAIL_BLANK"&&o.screenshotPath&&s.push(`screenshot: ${o.screenshotPath}`),s.join(`
50
+ `)}toTraceError(e,t){return new y(this.formatFailure(e,t),e.status)}};import wc from"fs";import Nx from"path";import{yellow as Zo}from"colorette";import{cyan as tc}from"colorette";function _n(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=At(t);return r==="transient"?new Error(`${e}: Device communication channel unavailable. Retry in a few seconds.`):r==="fatal"?new Error(`${e}: ${t.trim()}`):null}var Au=[800,1500,2500];function YR(n){return new Promise(e=>setTimeout(e,n))}var Br=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=le.from(e)}createFollowLineHandler(){return(e,t)=>{if(t==="stderr"){for(let r of e)console.error(r);return}for(let r of e)console.log(r)}}findDeviceByArg(e,t){return e.find(r=>r.serial===t||r.name===t)}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
51
+ `)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let i=t[0];return m(tc(`Using device serial: ${i}`)),i}if(e&&t.includes(e))return m(tc(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let i=this.findDeviceByArg(r,e);if(i)return m(tc(`Using device: ${i.name} (${i.serial})`)),i.serial;let o=this.formatConnectedDeviceList(r);throw new y(`Device '${e}' not found.
51
52
  Available devices:
52
- ${i}`,"Device not found.")}if(n.length===1){let o=n[0];return m(Ls(`Using device: ${o.name} (${o.serial})`)),o.serial}throw new w("Multiple devices found. Specify a target device using `--device <name>` or `--device <serial>`.\nAvailable devices:\n"+this.formatConnectedDeviceList(n),"Multiple devices found.")}async getConnectedDeviceSerials(){let e=await this.deviceManager.listDevices();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e}async getPidForBundle(e,t,n){m(`Retrieving PID for bundle ${n}`),E.assertBundleNameStrict(n);let o=await re(e,["-t",t,"shell","pidof",n]),i=Qr(o,"Failed to look up PID");if(i)throw i;if(o.exitCode===0&&o.stdout.trim()){let s=o.stdout.trim(),a=s.split(/\s+/)[0]||s;return m(`Found PID for ${n}: ${a}`),a}return m(`No PID found for bundle: ${n}`),null}async resizeHilogBuffer(e,t,n){if(m(`Setting hilog buffer size to: ${n}`),!/^\d+[KMG]?$/.test(n))throw new Error(`Invalid hilog buffer size: ${JSON.stringify(n)}. Expected format: <number>[K|M|G], e.g. "4M", "16M"`);let o=await re(e,["-t",t,"shell","hilog","-G",n]),i=Qr(o,"Failed to resize hilog buffer");if(i)throw i;o.exitCode!==0&&console.error(`Failed to resize hilog buffer: ${o.stderr||o.stdout}`)}buildHilogCommand(e,t,n,o){let i=this.buildHilogShellCommand(n,o);return[e,["-t",t,"shell",i]]}buildHilogShellCommand(e,t){let n=["hilog"];return e.isFollow||n.push("-x"),e.tag&&(E.assertHilogToken(e.tag,"tag"),n.push("-T",e.tag)),e.level&&(E.assertHilogLevel(e.level),n.push("-L",e.level)),e.domain&&(E.assertHilogToken(e.domain,"domain"),n.push("-D",e.domain)),t&&n.push("-P",t),e.keyword&&(E.assertHilogKeyword(e.keyword),n.push("-e",E.quotePosixShellArg(e.keyword))),n.join(" ")}async followHilog(e,t,n,o,i){let a=await bm(e,t,{onData:n,onError:o,onClose:i});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}async runHilogWithSpawnRetry(e,t,n,o,i){let s=1+wl.length,a={stdout:"",stderr:"",exitCode:-1};for(let c=0;c<s;c++){if(a=await this.followHilog(e,t,n,o,i),a.exitCode===0||cr(a.stderr)!=="transient"||c>=s-1)return a;m(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${wl[c]}ms`),await KE(wl[c])}return a}async runHilogStreamingCollect(e,t,n){return this.runHilogWithSpawnRetry(e,t,()=>{},o=>{m(`Callback triggered when an error occurs during ${n}: ${o.message}`)},()=>{})}async printTailSnapshotIfNeeded(e,t,n,o){if(!n.tail&&!n.fromSeconds&&!n.toSeconds)return;let i={...n,isFollow:!1},[s,a]=this.buildHilogCommand(e,t,i,o);m(`Ready to run hilog snapshot command: ${s} ${a.join(" ")}`);let c=await this.runHilogStreamingCollect(s,a,"a hilog snapshot streaming read"),l=Qr(c,"Failed to get hilog");if(l)throw l;if(c.exitCode!==0&&c.stderr)throw new Error(`Failed to get hilog: ${c.stderr}`);let d=E.filterLogsByRelativeWindow(c.stdout||c.stderr,n.fromSeconds,n.toSeconds);d=E.getLastLines(d,n.tail),d.trim()&&console.log(d)}async getHilogOnce(e,t,n,o){let[i,s]=this.buildHilogCommand(e,t,n,o);m(`Ready to run hilog command: ${i} ${s.join(" ")}`);let a=await this.runHilogStreamingCollect(i,s,"a single hilog streaming read"),c=Qr(a,"Failed to get hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to get hilog: ${a.stderr}`);let l=a.stdout||a.stderr,d=E.filterLogsByRelativeWindow(l,n.fromSeconds,n.toSeconds);return d=E.getLastLines(d,n.tail),d}async runHilogFollow(e,t,n,o){try{await this.printTailSnapshotIfNeeded(e,t,n,o)}catch(l){console.error(`Warning: Failed to fetch log snapshot, continuing with live stream: ${l.message}`)}let[i,s]=this.buildHilogCommand(e,t,n,o);m(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${i} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(i,s,this.createFollowLineHandler(),l=>{m(`Spawn error during hilog follow: ${l.message}`)},()=>{}),c=Qr(a,"Failed to follow hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to follow hilog: ${a.stderr}`);return""}async getHilog(e,t){let n=this.toolProvider.hdcPath,o=t.bundleName?await this.getPidForBundle(n,e,t.bundleName):void 0;if(t.bundleName&&!o)throw new w(`No running process found for bundle '${t.bundleName}'. Ensure the app is launched on the device before fetching logs.`,"No running process found for bundle.");return t.logSize&&await this.resizeHilogBuffer(n,e,t.logSize),t.isFollow?await this.runHilogFollow(n,e,t,o||""):await this.getHilogOnce(n,e,t,o||"")}async getLatestCrashLog(e,t){m(`Fetching crash logs from device: ${e}`);let n=this.toolProvider.hdcPath,o=await this.listCrashLogs(n,e,t);if(o.length===0)return;let s=[...o].sort((c,l)=>{let d=c.split("-").pop()||"";return(l.split("-").pop()||"").localeCompare(d)})[0],a=await this.fetchCrashLogContent(n,e,s);return`--- Latest Crash Log File: ${s} ---${a}`}async getCrashLog(e,t){let n=await this.getLatestCrashLog(e,t);return n!==void 0?n:t?`No crash logs found for bundle '${t}'.`:"No crash logs found."}async listCrashLogs(e,t,n){let o=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];m(`Running command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log list streaming read"),s=Qr(i,"Failed to list crash logs");if(s)throw s;if(i.exitCode!==0)throw new Error(`Failed to list crash logs: ${i.stderr||i.stdout}`);return m(`Crash logs list output:
53
- ${i.stdout}`),this.parseCrashLogFilenames(i.stdout,n)}parseCrashLogFilenames(e,t){return e.split(`
54
- `).map(n=>n.trim()).filter(n=>n.length>0).filter(n=>{try{return E.assertCrashFilename(n),!0}catch{return!1}}).filter(n=>t?n.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,n){m(`Fetching latest crash log file: ${n}`);let o=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${n}`];m(`Executing command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log streaming read"),s=Qr(i,"Failed to fetch crash log content");if(s)throw s;return i.exitCode!==0&&i.stderr&&console.error(`Warning: Failed to fetch crash logs: ${i.stderr}`),i.stdout+i.stderr}};import{readFileSync as ZE,unlinkSync as QE}from"fs";import{tmpdir as eC}from"os";import{join as tC}from"path";var $t=class{constructor(e,t){this.hdcPath=e;this.serial=t}async listWindows(e){let t=await this.fetchDump(),n=XE(t);return e?.all||(n=n.filter(o=>o.type===1)),n}async fetchDump(){let e=["-t",this.serial,"shell","hidumper","-s","WindowManagerService","-a","-a"];m(`Executing: ${this.hdcPath} ${e.join(" ")}`);let t=await re(this.hdcPath,e);if(t.exitCode!==0)throw new Error(`Failed to query windows: ${(t.stderr||t.stdout).trim()}`);return t.stdout}};function XE(r){let e=r.split(`
55
- `),t=e.findIndex(s=>s.trimStart().startsWith("WindowName"));if(t===-1)return[];let n=[];for(let s=t+1;s<e.length;s++){let a=e[s].trim();if(!a||/^-+$/.test(a)||a.startsWith("Focus window")||a.startsWith("total window"))break;let c=a.split(/\s+/);if(c.length<5)continue;let l=c[0],d=Number(c[1]),g=Number(c[2]),y=Number(c[3]),b=Number(c[4]);Number.isFinite(y)&&Number.isFinite(d)&&Number.isFinite(g)&&n.push({id:y,name:l,pid:g,displayId:d,type:b})}let o=e.find(s=>s.trim().startsWith("Focus window")),i=o?Number(o.replace(/.*:\s*/,"").trim()):NaN;return n.map(s=>({...s,focused:s.id===i}))}function Um(r){if(!(!r||r==="HitTestMode.Default"))return r.startsWith("HitTestMode.")?r.slice(12):r}function jo(r){if(!(r==null||r==="")){if(typeof r=="boolean")return r;if(r==="true")return!0;if(r==="false")return!1}}function Wm(r){if(typeof r!="string")return;let e=r.match(/-?\d+/g);if(!(!e||e.length<4))return[Number(e[0]),Number(e[1]),Number(e[2]),Number(e[3])]}function Vm(r){return r.originalText||void 0}function Tn(r,e){let t=[],n=[...r].reverse();for(;n.length>0;){let o=n.pop();o.id===e&&t.push(o);for(let i=o.children.length-1;i>=0;i--)n.push(o.children[i])}return t}function Gm(r,e){let t=[],n=[{current:r,parent:null,depth:0}];for(;n.length>0;){let{current:o,parent:i,depth:s}=n.pop(),a=i===null,c=!o.id&&!o.text&&!o.clickable&&!o.longClickable&&!o.scrollable&&!o.checkable,l=a||!c,d=i;if(l){let y={...o,children:[]};if(a?t.push(y):i.children.push(y),d=y,e>0&&s+1>=e)continue}if(process.env.DEVECO_CLI_DEBUG){let y=o.type?o.id?`${o.type}#${o.id}`:o.type:"#";m(`collapse ${y} depth=${s} -> ${a?"root":c?"collapsed":"emitted"}`)}let g=l?s+1:s;for(let y=o.children.length-1;y>=0;y--)n.push({current:o.children[y],parent:d,depth:g})}return t}function rC(r){let e=ZE(r,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function nC(r){return r.attributes??{}}function Ns(r,e,t){let n=nC(r),o={id:n.id||void 0,type:n.type||void 0,text:Vm(n),bounds:Wm(n.bounds),clickable:jo(n.clickable)||void 0,longClickable:jo(n.longClickable)||void 0,scrollable:jo(n.scrollable)||void 0,checkable:jo(n.checkable)||void 0,hitTestBehavior:Um(n.hitTestBehavior),children:[]};return e>0&&t+1>=e||r.children&&(o.children=r.children.map(i=>Ns(i,e,t+1))),o}function oC(r,e){if(e){let n=r.find(o=>String(o.id)===e);if(!n){let o=r.map(i=>`${i.id} (${i.name})`).join(", ");throw new w(`Window '${e}' not found. Available windows: ${o||"none"}`,"Window not found.")}return n}let t=r.find(n=>n.focused);if(t)return t;throw new Error("No window id specified and could not detect focused window")}var en=class{hdcPath;constructor(e){this.hdcPath=e}buildRemoteDumpPath(){return`/data/local/tmp/deveco_cli_dump_${Date.now()}_${process.pid}.json`}async fetchRawDump(e,t,n){let o=this.buildRemoteDumpPath(),i=["-t",e,"shell","uitest","dumpLayout","-p",o];n!==void 0&&i.push("-d",String(n)),t&&i.push("-w",t),m(`Executing: ${this.hdcPath} ${i.join(" ")}`);let s=await re(this.hdcPath,i);if(s.exitCode!==0)throw new Error(`Failed to dump layout: ${(s.stderr||s.stdout).trim()}`);return this.recvAndParseDump(e,o)}async recvAndParseDump(e,t){let n=tC(eC(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,n),rC(n)}finally{await this.cleanupDumpArtifacts(e,n,t)}}async recvDumpFile(e,t,n){let o=["-t",e,"file","recv",t,n];m(`Executing: ${this.hdcPath} ${o.join(" ")}`);let i=await re(this.hdcPath,o);if(i.exitCode!==0)throw new Error(`Failed to recv dump file: ${(i.stderr||i.stdout).trim()}`)}async cleanupDumpArtifacts(e,t,n){try{m(`Removing local dump file: ${t}`),QE(t)}catch(i){m(`Failed to clean local dump file ${t}: ${i.message}`)}let o=["-t",e,"shell","rm","-f",n];m(`Executing: ${this.hdcPath} ${o.join(" ")}`),await re(this.hdcPath,o).catch(i=>{m(`Failed to clean remote dump file ${n}: ${i.message}`)})}async dumpRawNodes(e,t,n){let i=await new $t(this.hdcPath,e).listWindows({all:!0});if(n){let a=[...new Set(i.map(l=>l.displayId))],c=[];for(let l of a)c.push(await this.fetchRawDump(e,void 0,l));return c}let s=oC(i,t);return[await this.fetchRawDump(e,String(s.id),s.displayId)]}async dumpFullTree(e,t,n,o){return(await this.dumpRawNodes(e,n,o)).map(s=>Ns(s,t,0))}async dumpFullTreeByDisplays(e,t,n){let o=[];for(let i of n){let s=await this.fetchRawDump(e,void 0,i);o.push({displayId:i,tree:Ns(s,t,0)})}return o}async dumpCollapsedTree(e,t,n,o){return(await this.dumpRawNodes(e,n,o)).flatMap(s=>Gm(Ns(s,0,0),t))}};import He from"fs";import Pe from"path";import{randomUUID as iC}from"crypto";function zm(r,e){let t=["-t",r.serial,"shell","snapshot_display"];return r.display!==void 0&&t.push("-i",r.display),t.push("-f",r.remotePath),e&&t.push("-t",e),t}function qm(r,e){return[r,e].filter(Boolean).join(`
56
- `).trim()}function Jm(r){return r.replace(/(Tips:\s*supported\s+displayIds)\s*:?[ \t]*(?:\r?\n[ \t]*)?(\d+(?:(?:[ \t]*,[ \t]*|[ \t]+|\r?\n[ \t]*)\d+)*)/gi,(e,t,n)=>`${t}: ${n.match(/\d+/g)?.join(", ")??n}`)}function Ym(r){let e=String.raw`invalid|not found|not exist|does not exist|out of range|unsupported`;return new RegExp(String.raw`display(?:\s*id)?.*(?:${e})`,"is").test(r)||new RegExp(String.raw`(?:${e}).*display(?:\s*id)?`,"is").test(r)}function Km(r){let e=r.trim();if(!e||/No such file|not found|cannot access/i.test(e))return;let t=e.split(/\s+/),n=Number(t[4]);return Number.isFinite(n)?n:void 0}function sC(){return String(Date.now())}function Sl(r){let e;try{e=He.statSync(r)}catch(t){let n=t.code;throw n==="ENOENT"?new Error(`Screenshot directory does not exist: ${r}`,{cause:t}):n==="EACCES"||n==="EPERM"?new Error(`Screenshot directory is not writable: ${r}`,{cause:t}):new Error(`Invalid screenshot path: ${t.message}${n?` (${n})`:""}`,{cause:t})}if(!e.isDirectory())throw new Error(`Screenshot parent path is not a directory: ${r}`);try{He.accessSync(r,He.constants.W_OK|He.constants.X_OK)}catch(t){throw new Error(`Screenshot directory is not writable: ${r}`,{cause:t})}}function bl(r,e){try{throw He.lstatSync(r),new Error(`Screenshot file already exists: ${r}`)}catch(t){let n=t.code;if(n==="ENOENT")return;throw n==="EACCES"||n==="EPERM"?new Error(`Screenshot directory is not writable: ${e}`,{cause:t}):t instanceof Error&&!n?t:new Error(`Invalid screenshot path: ${t.message}${n?` (${n})`:""}`,{cause:t})}}function Xm(r){if(!He.existsSync(r))throw new Error(`Screenshot file was not created: ${r}`);let e=He.statSync(r);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${r}`);let t=He.readFileSync(r).subarray(0,8),n=Buffer.from([137,80,78,71,13,10,26,10]);if(!t.equals(n))throw new Error(`Screenshot file is not a valid PNG: ${r}`)}function Zm(r){try{return Xm(r),!0}catch{return!1}}function Qm(r){let e=[];for(let t of He.readdirSync(r,{withFileTypes:!0})){let n=Pe.join(r,t.name);if(t.isDirectory()){e.push(...Qm(n));continue}t.isFile()&&Zm(n)&&e.push(n)}return e}function aC(r,e){let t=Pe.join(r,Pe.basename(e));if(Zm(t))return t;let n=Qm(r);if(n.length===1)return n[0];if(n.length>1)throw new Error(`Multiple screenshot files were received in ${r}.`)}function cC(r,e){try{He.copyFileSync(r,e,He.constants.COPYFILE_EXCL)}catch(t){throw t.code==="EEXIST"?new Error(`Screenshot file already exists: ${e}`,{cause:t}):t}Xm(e)}var tn=class{constructor(e){this.toolProvider=e}resolveDestinationPath(e){if(!e?.trim())throw new Error("--path is required.");let t=e.trim(),n=Pe.resolve(t);try{if(He.statSync(n).isDirectory()){Sl(n);let i=Pe.join(n,`screenshot-${sC()}.png`);return bl(i,n),i}}catch(i){if(i.code!=="ENOENT")throw i}if(Pe.extname(n).toLowerCase()!==".png")throw new Error(`Screenshot path must be an existing directory or a PNG file: ${n}`);let o=Pe.dirname(n);return Sl(o),bl(n,o),n}async captureToPath(e,t,n){let o=Pe.dirname(Pe.resolve(t));Sl(o),bl(Pe.resolve(t),o);let i=`/data/local/tmp/devecocli-${iC()}.png`;await this.capture({hdcPath:this.toolProvider.hdcPath,serial:e,localPath:Pe.resolve(t),remotePath:i,display:n})}async capture(e){try{await this.createRemoteScreenshot(e),await this.receiveScreenshotFile(e)}finally{await this.removeRemoteScreenshot(e)}}async getRemoteScreenshotSize(e){let t=["-t",e.serial,"shell","ls","-l",e.remotePath];m(`Executing: ${e.hdcPath} ${t.join(" ")}`);let n=await re(e.hdcPath,t);return n.exitCode===0?Km(n.stdout):void 0}async tryCreateRemoteScreenshot(e,t){let n=zm(e,t);m(`Executing: ${e.hdcPath} ${n.join(" ")}`);let o=await re(e.hdcPath,n),i=await this.getRemoteScreenshotSize(e);return{created:i!==void 0&&i>0,output:Jm(qm(o.stdout,o.stderr))}}async createRemoteScreenshot(e){let t="";for(let n of[void 0,"png"]){let o=await this.tryCreateRemoteScreenshot(e,n);if(o.created)return;if(e.display!==void 0&&Ym(o.output))throw new Error(`Screenshot was not created on device: ${e.remotePath}.
53
+ ${o}`,"Device not found.")}if(r.length===1){let i=r[0];return m(tc(`Using device: ${i.name} (${i.serial})`)),i.serial}throw new y("Multiple devices found. Specify a target device using `--device <name>` or `--device <serial>`.\nAvailable devices:\n"+this.formatConnectedDeviceList(r),"Multiple devices found.")}async getConnectedDeviceSerials(){let e=await this.deviceManager.listDevices();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e}async getPidForBundle(e,t,r){m(`Retrieving PID for bundle ${r}`),E.assertBundleNameStrict(r);let i=await C(e,["-t",t,"shell","pidof",r]),o=_n(i,"Failed to look up PID");if(o)throw o;if(i.exitCode===0&&i.stdout.trim()){let s=i.stdout.trim(),a=s.split(/\s+/)[0]||s;return m(`Found PID for ${r}: ${a}`),a}return m(`No PID found for bundle: ${r}`),null}async resizeHilogBuffer(e,t,r){if(m(`Setting hilog buffer size to: ${r}`),!/^\d+[KMG]?$/.test(r))throw new Error(`Invalid hilog buffer size: ${JSON.stringify(r)}. Expected format: <number>[K|M|G], e.g. "4M", "16M"`);let i=await C(e,["-t",t,"shell","hilog","-G",r]),o=_n(i,"Failed to resize hilog buffer");if(o)throw o;i.exitCode!==0&&console.error(`Failed to resize hilog buffer: ${i.stderr||i.stdout}`)}buildHilogCommand(e,t,r,i){let o=this.buildHilogShellCommand(r,i);return[e,["-t",t,"shell",o]]}buildHilogShellCommand(e,t){let r=["hilog"];return e.isFollow||r.push("-x"),e.tag&&(E.assertHilogToken(e.tag,"tag"),r.push("-T",e.tag)),e.level&&(E.assertHilogLevel(e.level),r.push("-L",e.level)),e.domain&&(E.assertHilogToken(e.domain,"domain"),r.push("-D",e.domain)),t&&r.push("-P",t),e.keyword&&(E.assertHilogKeyword(e.keyword),r.push("-e",E.quotePosixShellArg(e.keyword))),r.join(" ")}async followHilog(e,t,r,i,o){let a=await xg(e,t,{onData:r,onError:i,onClose:o});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}async runHilogWithSpawnRetry(e,t,r,i,o){let s=1+Au.length,a={stdout:"",stderr:"",exitCode:-1};for(let c=0;c<s;c++){if(a=await this.followHilog(e,t,r,i,o),a.exitCode===0||At(a.stderr)!=="transient"||c>=s-1)return a;m(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${Au[c]}ms`),await YR(Au[c])}return a}async runHilogStreamingCollect(e,t,r){return this.runHilogWithSpawnRetry(e,t,()=>{},i=>{m(`Callback triggered when an error occurs during ${r}: ${i.message}`)},()=>{})}async printTailSnapshotIfNeeded(e,t,r,i){if(!r.tail&&!r.fromSeconds&&!r.toSeconds)return;let o={...r,isFollow:!1},[s,a]=this.buildHilogCommand(e,t,o,i);m(`Ready to run hilog snapshot command: ${s} ${a.join(" ")}`);let c=await this.runHilogStreamingCollect(s,a,"a hilog snapshot streaming read"),l=_n(c,"Failed to get hilog");if(l)throw l;if(c.exitCode!==0&&c.stderr)throw new Error(`Failed to get hilog: ${c.stderr}`);let d=E.filterLogsByRelativeWindow(c.stdout||c.stderr,r.fromSeconds,r.toSeconds);d=E.getLastLines(d,r.tail),d.trim()&&console.log(d)}async getHilogOnce(e,t,r,i){let[o,s]=this.buildHilogCommand(e,t,r,i);m(`Ready to run hilog command: ${o} ${s.join(" ")}`);let a=await this.runHilogStreamingCollect(o,s,"a single hilog streaming read"),c=_n(a,"Failed to get hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to get hilog: ${a.stderr}`);let l=a.stdout||a.stderr,d=E.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return d=E.getLastLines(d,r.tail),d}async runHilogFollow(e,t,r,i){try{await this.printTailSnapshotIfNeeded(e,t,r,i)}catch(l){console.error(`Warning: Failed to fetch log snapshot, continuing with live stream: ${l.message}`)}let[o,s]=this.buildHilogCommand(e,t,r,i);m(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${o} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(o,s,this.createFollowLineHandler(),l=>{m(`Spawn error during hilog follow: ${l.message}`)},()=>{}),c=_n(a,"Failed to follow hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to follow hilog: ${a.stderr}`);return""}async getHilog(e,t){let r=this.toolProvider.hdcPath,i=t.bundleName?await this.getPidForBundle(r,e,t.bundleName):void 0;if(t.bundleName&&!i)throw new y(`No running process found for bundle '${t.bundleName}'. Ensure the app is launched on the device before fetching logs.`,"No running process found for bundle.");return t.logSize&&await this.resizeHilogBuffer(r,e,t.logSize),t.isFollow?await this.runHilogFollow(r,e,t,i||""):await this.getHilogOnce(r,e,t,i||"")}async getLatestCrashLog(e,t){m(`Fetching crash logs from device: ${e}`);let r=this.toolProvider.hdcPath,i=await this.listCrashLogs(r,e,t);if(i.length===0)return;let s=[...i].sort((c,l)=>{let d=c.split("-").pop()||"";return(l.split("-").pop()||"").localeCompare(d)})[0],a=await this.fetchCrashLogContent(r,e,s);return`--- Latest Crash Log File: ${s} ---${a}`}async getCrashLog(e,t){let r=await this.getLatestCrashLog(e,t);return r!==void 0?r:t?`No crash logs found for bundle '${t}'.`:"No crash logs found."}async listCrashLogs(e,t,r){let i=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];m(`Running command: ${e} ${i.join(" ")}`);let o=await this.runHilogStreamingCollect(e,i,"a crash log list streaming read"),s=_n(o,"Failed to list crash logs");if(s)throw s;if(o.exitCode!==0)throw new Error(`Failed to list crash logs: ${o.stderr||o.stdout}`);return m(`Crash logs list output:
54
+ ${o.stdout}`),this.parseCrashLogFilenames(o.stdout,r)}parseCrashLogFilenames(e,t){return e.split(`
55
+ `).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return E.assertCrashFilename(r),!0}catch{return!1}}).filter(r=>t?r.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){m(`Fetching latest crash log file: ${r}`);let i=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];m(`Executing command: ${e} ${i.join(" ")}`);let o=await this.runHilogStreamingCollect(e,i,"a crash log streaming read"),s=_n(o,"Failed to fetch crash log content");if(s)throw s;return o.exitCode!==0&&o.stderr&&console.error(`Warning: Failed to fetch crash logs: ${o.stderr}`),o.stdout+o.stderr}};import{readFileSync as XR,unlinkSync as ZR}from"fs";import{tmpdir as QR}from"os";import{join as eD}from"path";var mr=class{constructor(e,t){this.hdcPath=e;this.serial=t}async listWindows(e){let t=await this.fetchDump(),r=KR(t);return e?.all||(r=r.filter(i=>i.type===1)),r}async fetchDump(){let e=["-t",this.serial,"shell","hidumper","-s","WindowManagerService","-a","-a"];m(`Executing: ${this.hdcPath} ${e.join(" ")}`);let t=await C(this.hdcPath,e);if(t.exitCode!==0)throw new Error(`Failed to query windows: ${(t.stderr||t.stdout).trim()}`);return t.stdout}};function KR(n){let e=n.split(`
56
+ `),t=e.findIndex(s=>s.trimStart().startsWith("WindowName"));if(t===-1)return[];let r=[];for(let s=t+1;s<e.length;s++){let a=e[s].trim();if(!a||/^-+$/.test(a)||a.startsWith("Focus window")||a.startsWith("total window"))break;let c=a.split(/\s+/);if(c.length<5)continue;let l=c[0],d=Number(c[1]),g=Number(c[2]),w=Number(c[3]),R=Number(c[4]);Number.isFinite(w)&&Number.isFinite(d)&&Number.isFinite(g)&&r.push({id:w,name:l,pid:g,displayId:d,type:R})}let i=e.find(s=>s.trim().startsWith("Focus window")),o=i?Number(i.replace(/.*:\s*/,"").trim()):NaN;return r.map(s=>({...s,focused:s.id===o}))}function Yg(n){if(!(!n||n==="HitTestMode.Default"))return n.startsWith("HitTestMode.")?n.slice(12):n}function Bo(n){if(!(n==null||n==="")){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1}}function rc(n){if(typeof n!="string")return;let e=n.match(/-?\d+/g);if(!(!e||e.length<4))return[Number(e[0]),Number(e[1]),Number(e[2]),Number(e[3])]}function Kg(n){return n.originalText||void 0}function Ri(n,e){let t=[],r=[...n].reverse();for(;r.length>0;){let i=r.pop();i.id===e&&t.push(i);for(let o=i.children.length-1;o>=0;o--)r.push(i.children[o])}return t}function Xg(n,e){let t=[],r=[{current:n,parent:null,depth:0}];for(;r.length>0;){let{current:i,parent:o,depth:s}=r.pop(),a=o===null,c=!i.id&&!i.text&&!i.clickable&&!i.longClickable&&!i.scrollable&&!i.checkable,l=a||!c,d=o;if(l){let w={...i,children:[]};if(a?t.push(w):o.children.push(w),d=w,e>0&&s+1>=e)continue}if(process.env.DEVECO_CLI_DEBUG){let w=i.type?i.id?`${i.type}#${i.id}`:i.type:"#";m(`collapse ${w} depth=${s} -> ${a?"root":c?"collapsed":"emitted"}`)}let g=l?s+1:s;for(let w=i.children.length-1;w>=0;w--)r.push({current:i.children[w],parent:d,depth:g})}return t}function tD(n){let e=XR(n,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function rD(n){return n.attributes??{}}function nc(n,e,t){let r=rD(n),i={id:r.id||void 0,type:r.type||void 0,text:Kg(r),bounds:rc(r.bounds),clickable:Bo(r.clickable)||void 0,longClickable:Bo(r.longClickable)||void 0,scrollable:Bo(r.scrollable)||void 0,checkable:Bo(r.checkable)||void 0,hitTestBehavior:Yg(r.hitTestBehavior),children:[]};return e>0&&t+1>=e||n.children&&(i.children=n.children.map(o=>nc(o,e,t+1))),i}function nD(n,e){if(e){let r=n.find(i=>String(i.id)===e);if(!r){let i=n.map(o=>`${o.id} (${o.name})`).join(", ");throw new y(`Window '${e}' not found. Available windows: ${i||"none"}`,"Window not found.")}return r}let t=n.find(r=>r.focused);if(t)return t;throw new Error("No window id specified and could not detect focused window")}var fr=class{hdcPath;constructor(e){this.hdcPath=e}buildRemoteDumpPath(){return`/data/local/tmp/deveco_cli_dump_${Date.now()}_${process.pid}.json`}async fetchRawDump(e,t,r){let i=this.buildRemoteDumpPath(),o=["-t",e,"shell","uitest","dumpLayout","-p",i];r!==void 0&&o.push("-d",String(r)),t&&o.push("-w",t),m(`Executing: ${this.hdcPath} ${o.join(" ")}`);let s=await C(this.hdcPath,o);if(s.exitCode!==0)throw new Error(`Failed to dump layout: ${(s.stderr||s.stdout).trim()}`);return this.recvAndParseDump(e,i)}async recvAndParseDump(e,t){let r=eD(QR(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,r),tD(r)}finally{await this.cleanupDumpArtifacts(e,r,t)}}async recvDumpFile(e,t,r){let i=["-t",e,"file","recv",t,r];m(`Executing: ${this.hdcPath} ${i.join(" ")}`);let o=await C(this.hdcPath,i);if(o.exitCode!==0)throw new Error(`Failed to recv dump file: ${(o.stderr||o.stdout).trim()}`)}async cleanupDumpArtifacts(e,t,r){try{m(`Removing local dump file: ${t}`),ZR(t)}catch(o){m(`Failed to clean local dump file ${t}: ${o.message}`)}let i=["-t",e,"shell","rm","-f",r];m(`Executing: ${this.hdcPath} ${i.join(" ")}`),await C(this.hdcPath,i).catch(o=>{m(`Failed to clean remote dump file ${r}: ${o.message}`)})}async dumpRawNodes(e,t,r){let o=await new mr(this.hdcPath,e).listWindows({all:!0});if(r){let a=[...new Set(o.map(l=>l.displayId))],c=[];for(let l of a)c.push(await this.fetchRawDump(e,void 0,l));return c}let s=nD(o,t);return[await this.fetchRawDump(e,String(s.id),s.displayId)]}async dumpFullTree(e,t,r,i){return(await this.dumpRawNodes(e,r,i)).map(s=>nc(s,t,0))}async dumpFullTreeByDisplays(e,t,r){let i=[];for(let o of r){let s=await this.fetchRawDump(e,void 0,o);i.push({displayId:o,tree:nc(s,t,0)})}return i}async dumpCollapsedTree(e,t,r,i){return(await this.dumpRawNodes(e,r,i)).flatMap(s=>Xg(nc(s,0,0),t))}async dumpRawTree(e,t){return(await this.dumpRawNodes(e,t,!1))[0]}};var je=class extends Error{position;input;constructor(e,t,r){super(`Selector parse error at ${t}: ${e}`),this.name="SelectorParseError",this.position=t,this.input=r}},iD=["*=","^=","$=","/="],oD=/[A-Za-z_]/,sD=/[A-Za-z0-9_]/,Tu=/\s/,aD=/^(.*)\/([gimsuy]+)$/,Ou=class{input;pos=0;constructor(e){this.input=e}eof(){return this.pos>=this.input.length}peek(e=0){let t=this.pos+e;return t>=0&&t<this.input.length?this.input[t]:""}next(){return this.pos<this.input.length?this.input[this.pos++]:""}startsWith(e){return this.input.slice(this.pos,this.pos+e.length)===e}};function hr(n){for(;!n.eof()&&Tu.test(n.peek());)n.next()}function cD(n){let e=n.pos;if(!oD.test(n.peek()))throw new je("expected attribute key",n.pos,n.input);for(;!n.eof()&&sD.test(n.peek());)n.next();return n.input.slice(e,n.pos)}function lD(n,e){for(let t of iD)if(n.startsWith(t))return n.pos+=t.length,t;if(n.peek()==="=")return n.next(),"=";throw new je(`expected operator (=, *=, ^=, $=, /=) after key "${e}"`,n.pos,n.input)}function Zg(n){let e=n.match(aD);return e?{value:e[1],flags:e[2]}:{value:n}}function dD(n,e){n.next();let t="";for(;!n.eof();){let r=n.next();if(r==="\\"){if(n.eof())throw new je("dangling escape in quoted value",n.pos,n.input);t+=n.next();continue}if(r===e)return t;t+=r}throw new je("unterminated quoted value",n.pos,n.input)}function Iu(n){return n==='"'||n==="'"}function uD(n,e){let t=n.peek();if(Iu(t)){let i=dD(n,t);return e==="/="?Zg(i):{value:i}}let r="";for(;!n.eof();){let i=n.peek();if(i===","||i==="["||Iu(i))break;if(Tu.test(i)){let o=n.pos+1;for(;o<n.input.length&&Tu.test(n.input[o]);)o++;let s=o<n.input.length?n.input[o]:"";if(s===""||s===","||s==="["||Iu(s))break;r+=n.next();continue}if(i==="\\"){if(n.next(),n.eof())throw new je("dangling escape in value",n.pos,n.input);r+=n.next();continue}r+=n.next()}return e==="/="?Zg(r):{value:r}}function Qg(n){hr(n);let e=cD(n);hr(n);let t=lD(n,e);if(hr(n),n.eof()||n.peek()===","||n.peek()==="[")throw new je(`missing value for key "${e}"`,n.pos,n.input);let{value:r,flags:i}=uD(n,t);if(t==="/=")try{new RegExp(r,i)}catch(s){throw new je(`invalid regex "${r}"${i?` with flags "${i}"`:""}: ${s.message}`,n.pos,n.input)}let o={key:e,op:t,value:r};return i!==void 0&&(o.flags=i),o}function pD(n){let e="";for(;!n.eof()&&n.peek()!=="]";)e+=n.next();if(e=e.trim(),e==="last")return-1;if(/^-?\d+$/.test(e))return parseInt(e,10);throw new je(`invalid index "${e}" (expected N, -N, or "last")`,n.pos,n.input)}function Wo(n){if(typeof n!="string")throw new je("input must be a string",0,String(n));let e=new Ou(n),t=[];if(hr(e),e.eof())throw new je("empty selector",e.pos,n);for(t.push(Qg(e));hr(e),e.peek()===",";){if(e.next(),hr(e),e.eof()||e.peek()===",")throw new je("expected clause after comma",e.pos,n);t.push(Qg(e))}let r;if(hr(e),e.peek()==="["){if(e.next(),r=pD(e),hr(e),e.peek()!=="]")throw new je("expected ']' after index",e.pos,n);e.next(),hr(e)}if(!e.eof())throw new je(`unexpected trailing input "${e.input.slice(e.pos)}"`,e.pos,n);return{clauses:t,index:r,raw:n}}function mD(n,e){if(n==null)return;if(e==="text"){let r=n.originalText??n.text;return r==null?void 0:String(r)}if(e==="desc"||e==="description"){let r=n.description;return r==null?void 0:String(r)}let t=n[e];return t==null?void 0:String(t)}function fD(n,e){let t=mD(n,e.key);if(t===void 0)return!1;switch(e.op){case"=":return t===e.value;case"*=":return t.includes(e.value);case"^=":return t.startsWith(e.value);case"$=":return t.endsWith(e.value);case"/=":try{return(e.flags?new RegExp(e.value,e.flags):new RegExp(e.value)).test(t)}catch{return!1}default:return!1}}function ic(n,e){let t=[],r=[n];for(;r.length>0;){let i=r.pop(),o=i.attributes??null;e.clauses.every(a=>fD(o,a))&&t.push(i);let s=i.children;if(s)for(let a=s.length-1;a>=0;a--)r.push(s[a])}return t}function Di(n,e){return e===void 0?n[0]:e>=0?n[e]:n[n.length+e]}import{DOMParser as hD}from"@xmldom/xmldom";import{select as gD}from"xpath";var yD=["id","key","originalText","description","enabled","focused","checked","selected","visible","clickable","longClickable","scrollable","checkable","accessibilityLevel","hitTestBehavior","bounds"];function wD(n){if(!n)return"node";let e=n.replace(/[^A-Za-z0-9_-]/g,"_");return/^[0-9]/.test(e)&&(e="_"+e),e||"node"}var vD=/&/g,bD=/</g,SD=/>/g,ED=/"/g,PD=/'/g;function oc(n){return n.replace(vD,"&amp;").replace(bD,"&lt;").replace(SD,"&gt;").replace(ED,"&quot;").replace(PD,"&apos;")}function CD(n){let e=[],t=typeof n.type=="string"?n.type:"";t&&e.push(` type="${oc(t)}"`);let r=n.originalText??n.text;r!=null&&r!==""&&e.push(` text="${oc(String(r))}"`);for(let o of yD){let s=n[o];s==null||s===""||e.push(` ${o}="${oc(String(s))}"`)}let i=n.description;return i!=null&&i!==""&&e.push(` desc="${oc(String(i))}"`),e.join("")}function ey(n){let e=n.attributes??{},t=wD(typeof e.type=="string"?e.type:void 0),r=CD(e),i=n.children??[];return i.length===0?`<${t}${r}/>`:`<${t}${r}>${i.map(ey).join("")}</${t}>`}function kD(n){return`<?xml version="1.0" encoding="UTF-8"?>${ey(n)}`}function RD(n){if(!n)return;let e=n.match(/-?\d+/g);if(!e||e.length<4)return;let[t,r,i,o]=e.map(Number);return[t,r,i,o]}function DD(n){return typeof n!="object"||n===null?!1:n.nodeType===1}function xD(n){let e=i=>{let o=n.getAttribute(i);return o===""||o===null?void 0:o},t={},r=n.attributes;if(r)for(let i=0;i<r.length;i++){let o=r[i];o&&(t[o.name]=o.value)}return{type:e("type")??n.tagName,id:e("id"),key:e("key"),text:e("text"),originalText:e("originalText"),description:e("description")??e("desc"),enabled:e("enabled"),focused:e("focused"),checked:e("checked"),selected:e("selected"),visible:e("visible"),clickable:e("clickable"),longClickable:e("longClickable"),scrollable:e("scrollable"),checkable:e("checkable"),accessibilityLevel:e("accessibilityLevel"),hitTestBehavior:e("hitTestBehavior"),bounds:RD(e("bounds")),attributes:t}}function Mu(n,e){if(typeof e!="string"||e.trim()==="")throw new Error("xpath expression must be a non-empty string");let t=kD(n),r=new hD().parseFromString(t,"text/xml"),i=gD(e,r);if(!Array.isArray(i))throw new Error(`xpath "${e}" did not return a node-set; use a path expression like //Button[@text='\u767B\u5F55']`);let o=[];for(let s of i)DD(s)&&o.push(xD(s));return o}function sc(n){return typeof n=="string"&&n.trimStart().startsWith("xpath=")}function ac(n){return n.trimStart().slice(6)}function cc(n){return new Promise(e=>setTimeout(e,n))}function Nu(n,e){let t=n.attributes??{};return{index:e,id:t.id||void 0,key:t.key||void 0,type:t.type||void 0,text:t.originalText||t.text||void 0,description:t.description||void 0,enabled:t.enabled||void 0,focused:t.focused||void 0,checked:t.checked||void 0,selected:t.selected||void 0,visible:t.visible||void 0,clickable:t.clickable||void 0,longClickable:t.longClickable||void 0,scrollable:t.scrollable||void 0,checkable:t.checkable||void 0,bounds:rc(t.bounds),attributes:t}}function ty(n,e){return{index:e,id:n.id,key:n.key,type:n.type,text:n.text,description:n.description,enabled:n.enabled,focused:n.focused,checked:n.checked,selected:n.selected,visible:n.visible,clickable:n.clickable,longClickable:n.longClickable,scrollable:n.scrollable,checkable:n.checkable,bounds:n.bounds,attributes:n.attributes}}function lc(n){return n.startsWith("base64=")?Buffer.from(n.slice(7).trim(),"base64").toString("utf8"):n}var AD=new Set(["text","desc","description"]),Vo=[];function ny(n,e){if(n.attributes)for(let t of Object.keys(n.attributes))e.add(t);if(n.children)for(let t of n.children)ny(t,e)}function iy(n,e){let t=new Set;ny(n,t);let r=[];for(let i of e)AD.has(i.key)||t.has(i.key)||r.push(i.key);return r}function ry(n,e){let t=iy(n,e);for(let r of t)Vo.push(`WARNING: attribute "${r}" not found in any node of the layout tree. No matches will be returned for this key.`)}function Lu(){return Vo.splice(0)}var xi=class{dumper;constructor(e){this.dumper=new fr(e)}async find(e,t,r){Vo.splice(0);let i=lc(t);if(sc(i))return this.runXpathFind(e,ac(i),r);let o=Wo(i);return this.runFind(e,o,r)}async runFind(e,t,r){let i=r?.timeoutMs??3e3,o=300,s=Date.now(),a=[],c=!1,l=!1;for(;!c;){let g=await this.dumper.dumpRawTree(e,r?.window);if(l||(ry(g,t.clauses),l=!0),a=ic(g,t),c=r?.all?a.length>0:Di(a,t.index)!==void 0,c)break;if(Date.now()-s>=i)throw new Error(`Timed out (${i}ms) waiting for selector: ${t.raw}`);await cc(o)}if(r?.all)return a.map((g,w)=>Nu(g,w));let d=Di(a,t.index);if(!d){let g=a.length,w=t.index===void 0?0:t.index;throw new Error(`Index ${w} out of range (matched ${g} element(s)) for selector: ${t.raw}`)}return[Nu(d,t.index??0)]}async runXpathFind(e,t,r){let i=r?.timeoutMs??3e3,o=300,s=Date.now(),a=[],c=!1;for(;!c;){let l=await this.dumper.dumpRawTree(e,r?.window);if(a=Mu(l,t),c=a.length>0,c)break;if(Date.now()-s>=i)throw new Error(`Timed out (${i}ms) waiting for xpath: ${t}`);await cc(o)}return r?.all?a.map((l,d)=>ty(l,d)):[ty(a[0],0)]}async waitForAppearance(e,t,r,i){Vo.splice(0);let o=lc(t);if(sc(o))return(await this.runXpathFind(e,ac(o),{timeoutMs:r,window:i}))[0];let s=Wo(o);return await this.runWaitFor(e,s,r,i,!0)}async waitForDisappear(e,t,r,i){Vo.splice(0);let o=lc(t);if(sc(o))return this.runXpathWaitFor(e,ac(o),r,i,!1);let s=Wo(o);await this.runWaitFor(e,s,r,i,!1)}async runWaitFor(e,t,r,i,o){let a=Date.now(),c=!1;for(;;){let l=await this.dumper.dumpRawTree(e,i);c||(ry(l,t.clauses),c=!0);let d=ic(l,t),g=Di(d,t.index)!==void 0;if(o&&g){let w=Di(d,t.index);return Nu(w,t.index??0)}if(!o&&!g)return;if(Date.now()-a>=r)throw new Error(`Timed out (${r}ms) waiting for selector to ${o?"appear":"disappear"}: ${t.raw}`);await cc(300)}}async runXpathWaitFor(e,t,r,i,o){let a=Date.now();for(;;){let c=await this.dumper.dumpRawTree(e,i),d=Mu(c,t).length>0;if(o&&d||!o&&!d)return;if(Date.now()-a>=r)throw new Error(`Timed out (${r}ms) waiting for xpath to ${o?"appear":"disappear"}: ${t}`);await cc(300)}}};import et from"fs";import Ne from"path";import{randomUUID as ID}from"crypto";function oy(n,e){let t=["-t",n.serial,"shell","snapshot_display"];return n.display!==void 0&&t.push("-i",n.display),t.push("-f",n.remotePath),e&&t.push("-t",e),t}function sy(n,e){return[n,e].filter(Boolean).join(`
57
+ `).trim()}function ay(n){return n.replace(/(Tips:\s*supported\s+displayIds)\s*:?[ \t]*(?:\r?\n[ \t]*)?(\d+(?:(?:[ \t]*,[ \t]*|[ \t]+|\r?\n[ \t]*)\d+)*)/gi,(e,t,r)=>`${t}: ${r.match(/\d+/g)?.join(", ")??r}`)}function cy(n){let e=String.raw`invalid|not found|not exist|does not exist|out of range|unsupported`;return new RegExp(String.raw`display(?:\s*id)?.*(?:${e})`,"is").test(n)||new RegExp(String.raw`(?:${e}).*display(?:\s*id)?`,"is").test(n)}function ly(n){let e=n.trim();if(!e||/No such file|not found|cannot access/i.test(e))return;let t=e.split(/\s+/),r=Number(t[4]);return Number.isFinite(r)?r:void 0}function TD(){return String(Date.now())}function _u(n){let e;try{e=et.statSync(n)}catch(t){let r=t.code;throw r==="ENOENT"?new Error(`Screenshot directory does not exist: ${n}`,{cause:t}):r==="EACCES"||r==="EPERM"?new Error(`Screenshot directory is not writable: ${n}`,{cause:t}):new Error(`Invalid screenshot path: ${t.message}${r?` (${r})`:""}`,{cause:t})}if(!e.isDirectory())throw new Error(`Screenshot parent path is not a directory: ${n}`);try{et.accessSync(n,et.constants.W_OK|et.constants.X_OK)}catch(t){throw new Error(`Screenshot directory is not writable: ${n}`,{cause:t})}}function $u(n,e){try{throw et.lstatSync(n),new Error(`Screenshot file already exists: ${n}`)}catch(t){let r=t.code;if(r==="ENOENT")return;throw r==="EACCES"||r==="EPERM"?new Error(`Screenshot directory is not writable: ${e}`,{cause:t}):t instanceof Error&&!r?t:new Error(`Invalid screenshot path: ${t.message}${r?` (${r})`:""}`,{cause:t})}}function dy(n){if(!et.existsSync(n))throw new Error(`Screenshot file was not created: ${n}`);let e=et.statSync(n);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${n}`);let t=et.readFileSync(n).subarray(0,8),r=Buffer.from([137,80,78,71,13,10,26,10]);if(!t.equals(r))throw new Error(`Screenshot file is not a valid PNG: ${n}`)}function uy(n){try{return dy(n),!0}catch{return!1}}function py(n){let e=[];for(let t of et.readdirSync(n,{withFileTypes:!0})){let r=Ne.join(n,t.name);if(t.isDirectory()){e.push(...py(r));continue}t.isFile()&&uy(r)&&e.push(r)}return e}function OD(n,e){let t=Ne.join(n,Ne.basename(e));if(uy(t))return t;let r=py(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}function MD(n,e){try{et.copyFileSync(n,e,et.constants.COPYFILE_EXCL)}catch(t){throw t.code==="EEXIST"?new Error(`Screenshot file already exists: ${e}`,{cause:t}):t}dy(e)}var $n=class{constructor(e){this.toolProvider=e}resolveDestinationPath(e){if(!e?.trim())throw new Error("--path is required.");let t=e.trim(),r=Ne.resolve(t);try{if(et.statSync(r).isDirectory()){_u(r);let o=Ne.join(r,`screenshot-${TD()}.png`);return $u(o,r),o}}catch(o){if(o.code!=="ENOENT")throw o}if(Ne.extname(r).toLowerCase()!==".png")throw new Error(`Screenshot path must be an existing directory or a PNG file: ${r}`);let i=Ne.dirname(r);return _u(i),$u(r,i),r}async captureToPath(e,t,r){let i=Ne.dirname(Ne.resolve(t));_u(i),$u(Ne.resolve(t),i);let o=`/data/local/tmp/devecocli-${ID()}.png`;await this.capture({hdcPath:this.toolProvider.hdcPath,serial:e,localPath:Ne.resolve(t),remotePath:o,display:r})}async capture(e){try{await this.createRemoteScreenshot(e),await this.receiveScreenshotFile(e)}finally{await this.removeRemoteScreenshot(e)}}async getRemoteScreenshotSize(e){let t=["-t",e.serial,"shell","ls","-l",e.remotePath];m(`Executing: ${e.hdcPath} ${t.join(" ")}`);let r=await C(e.hdcPath,t);return r.exitCode===0?ly(r.stdout):void 0}async tryCreateRemoteScreenshot(e,t){let r=oy(e,t);m(`Executing: ${e.hdcPath} ${r.join(" ")}`);let i=await C(e.hdcPath,r),o=await this.getRemoteScreenshotSize(e);return{created:o!==void 0&&o>0,output:ay(sy(i.stdout,i.stderr))}}async createRemoteScreenshot(e){let t="";for(let r of[void 0,"png"]){let i=await this.tryCreateRemoteScreenshot(e,r);if(i.created)return;if(e.display!==void 0&&cy(i.output))throw new Error(`Screenshot was not created on device: ${e.remotePath}.
57
58
  snapshot_display output:
58
- ${o.output}`);o.output&&(t=o.output)}throw new Error(t?`Screenshot was not created on device: ${e.remotePath}.
59
+ ${i.output}`);i.output&&(t=i.output)}throw new Error(t?`Screenshot was not created on device: ${e.remotePath}.
59
60
  snapshot_display output:
60
- ${t}`:`Screenshot was not created on device: ${e.remotePath}.`)}async tryReceiveScreenshot(e,t,n){let o=["-t",e.serial,"file","recv",e.remotePath,n];m(`Executing: ${e.hdcPath} ${o.join(" ")}`);let i=await re(e.hdcPath,o);return i.exitCode!==0&&m(`hdc file recv failed: ${i.stderr||i.stdout||`exit code ${i.exitCode}`}`),aC(t,e.remotePath)}async receiveScreenshotFile(e){let t=He.mkdtempSync(Pe.join(Pe.dirname(e.localPath),".devecocli-screenshot-"));try{let n=await this.tryReceiveScreenshot(e,t,Pe.join(t,Pe.basename(e.remotePath)))??await this.tryReceiveScreenshot(e,t,t)??await this.tryReceiveScreenshot(e,t,Pe.join(t,"screenshot.png"));if(!n)throw new Error(`Screenshot file was not created in ${t}.`);cC(n,e.localPath)}finally{He.rmSync(t,{recursive:!0,force:!0})}}async removeRemoteScreenshot(e){let t=["-t",e.serial,"shell","rm","-f",e.remotePath];m(`Executing: ${e.hdcPath} ${t.join(" ")}`),await re(e.hdcPath,t)}};var Os={left:"0",right:"1",up:"2",down:"3"};function Le(r,e){let t=Number(r);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function El(r,e){r!==void 0&&Le(r,e)}function ef(r,e){if(r===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function Ms(r,e){if(r!==void 0&&r.length===0)throw new Error(`${e} must not be empty`)}function $o(r){if(r===void 0)return;let e=Number(r);if(!Number.isInteger(e)||e<200||e>4e4)throw new Error("--speed must be an integer between 200 and 40000");return r}function tf(r){if(r!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(r))throw new Error("--window must consist of letters, digits, - or _")}function rf(r,e,t,n=!0){if(t&&!e)throw new Error("--window must be used with --id");if(r&&e)throw new Error("Coordinates and --id are mutually exclusive");if(n&&!r&&!e)throw new Error("Either provide x y coordinates or use --id")}function Rn(r,e,t,n,o=!0){ef(r,e),Ms(t,"--id"),El(r,"x"),El(e,"y"),tf(n),rf(r!==void 0,!!t,!!n,o)}async function yt(r,e){let n=await new lr(r).selectDevice(e);if(!n)throw new Error("No device selected. Use `devecocli device list` to see targets.");return n}async function Lt(r){let e=await k.new(),t=await yt(e,r);return{hdcPath:e.hdcPath,deviceId:t}}async function xn(r,e,t,n,o,i){if(t!==void 0&&n!==void 0)return{x:t,y:n};if(o===void 0)throw new Error("Either provide x y coordinates or use --id");let a=await new $t(r,e).listWindows({all:!0}),c=new en(r);return lC(c,e,a,o,i)}async function lC(r,e,t,n,o){if(o!==void 0){let i=t.find(a=>String(a.id)===o);if(i&&i.displayId!==0)throw new w(`Window "${o}" is on display ${i.displayId}. The current command only supports operations on the primary display.`,"The current command only supports operations on the primary display.");let s=await r.dumpFullTree(e,0,o,!1);return uC(s,n)}return dC(r,e,t,n)}async function dC(r,e,t,n){let o=[...new Set(t.map(a=>a.displayId))],i=await r.dumpFullTreeByDisplays(e,0,o),s=[];for(let{displayId:a,tree:c}of i)for(let l of Tn([c],n))s.push({node:l,displayId:a});if(s.length===0)throw new w(`Node "${n}" not found.`,"Node not found.");if(s.length>1)throw new w(`Multiple nodes found with id "${n}".`,"Multiple nodes found");if(s[0].displayId!==0)throw new w(`Node "${n}" is on display ${s[0].displayId}. The current command only supports operations on the primary display.`,"The current command only supports operations on the primary display.");return nf(s[0].node,n)}function uC(r,e){let t=Tn(r,e);if(t.length===0)throw new w(`Node "${e}" not found.`,"Node not found.");if(t.length>1)throw new w(`Multiple nodes found with id "${e}".`,"Multiple nodes found");return nf(t[0],e)}function nf(r,e){let t=r.bounds;if(!t)throw new w(`Node "${e}" has no bounds.`,"Node has no bounds.");let[n,o,i,s]=t;return{x:Math.ceil((n+i)/2),y:Math.ceil((o+s)/2)}}async function at(r,e,t){let n=["-t",e,"shell",...t];m(`Executing: ${r} ${n.join(" ")}`);let o=await re(r,n);if(o.exitCode!==0)throw new Error(o.stderr||o.stdout||`uitest exited with code ${o.exitCode}`);let i=o.stdout.toLowerCase();if(["illegal","fail","error","incorrect","please confirm that the coordinate values are correct"].some(a=>i.includes(a))&&!i.includes("no error"))throw new Error(o.stdout.trim()||"uitest command failed")}import{deflateSync as pC,inflateSync as mC}from"zlib";import fC from"fs";var of=8,sf=32,hC=.06,gC=.04,Cl=10,_s=class r{whiteBits=null;blackBits=null;analyzeRgb(e,t,n){if(e<8||t<8||n.length<e*t*3)return null;let o=this.cropChrome(e,t,n),i=this.hashBits(o.width,o.height,o.rgb),s=Math.min(this.hammingDistance(i,this.solidRefBits(255)),this.hammingDistance(i,this.solidRefBits(0)));return{phash:this.bitsToHex(i),hamming:s,isBlank:s<=Cl}}analyzeFile(e){let t;try{t=fC.readFileSync(e)}catch{return null}let n=this.decodePngRgb(t);return n?this.analyzeRgb(n.width,n.height,n.rgb):null}static encodePngRgb(e,t,n){let o=r.pngCrcTable(),i=[Buffer.from(`\x89PNG\r
61
+ ${t}`:`Screenshot was not created on device: ${e.remotePath}.`)}async tryReceiveScreenshot(e,t,r){let i=["-t",e.serial,"file","recv",e.remotePath,r];m(`Executing: ${e.hdcPath} ${i.join(" ")}`);let o=await C(e.hdcPath,i);return o.exitCode!==0&&m(`hdc file recv failed: ${o.stderr||o.stdout||`exit code ${o.exitCode}`}`),OD(t,e.remotePath)}async receiveScreenshotFile(e){let t=et.mkdtempSync(Ne.join(Ne.dirname(e.localPath),".devecocli-screenshot-"));try{let r=await this.tryReceiveScreenshot(e,t,Ne.join(t,Ne.basename(e.remotePath)))??await this.tryReceiveScreenshot(e,t,t)??await this.tryReceiveScreenshot(e,t,Ne.join(t,"screenshot.png"));if(!r)throw new Error(`Screenshot file was not created in ${t}.`);MD(r,e.localPath)}finally{et.rmSync(t,{recursive:!0,force:!0})}}async removeRemoteScreenshot(e){let t=["-t",e.serial,"shell","rm","-f",e.remotePath];m(`Executing: ${e.hdcPath} ${t.join(" ")}`),await C(e.hdcPath,t)}};import qy from"path";import{randomBytes as hx}from"crypto";import*as Go from"fs";import*as fy from"path";import{homedir as ND}from"os";var LD="deveco-cli",my,Fu=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function _D(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":su(n))||fy.join(ND(),".local","share",LD);try{return xa(t)}catch(r){throw new Fu(r instanceof Error?r.message:String(r))}}function W(){if(my!==void 0)return my;let n=_D();try{if(Go.existsSync(n))return Go.realpathSync(n)}catch{}return n}async function T(n,e){let r=await new Br(n).selectDevice(e);if(!r)throw new Error("No device selected. Use `devecocli device list` to see targets.");return r}var qo="com.huawei.hmos.screenrecorder",Fn="com.huawei.hmos.screenrecorder.ServiceExtAbility",hy="/data/local/tmp",S=class extends Error{constructor(t,r=t,i){super(r,i);this.code=t;this.name="ScreenRecordError"}};var ju=/^\s*uri \[([^\]]*)\]\s*$/,$D=/^\s*uri \[/,FD=/AbilityRecord ID\s*[:#]\s*(\d+)/,jD=/start time \[(\d+)\]/,HD=/bundle name \[([^\]]*)\]/,UD=/main name \[([^\]]*)\]/,BD=/\[(?:Fail|E\d{5,})\]|^\s*(?:error|Error)(?::|\s)/m,WD=Fn.slice(Fn.lastIndexOf(".")+1);function VD(n){let e=[],t;for(let r of n.split(/\r?\n/))ju.test(r)?(t=[r],e.push(t)):t&&t.push(r);return e}function GD(n){let e={};for(let t of n){let r=ju.exec(t);if(r){e.uri=r[1].trim();continue}let i=FD.exec(t);if(i&&(e.id=Number(i[1]),!Number.isSafeInteger(e.id)))throw new S("DUMP_PARSE_FAILED",`Unparseable AbilityRecord ID in aa dump output: ${i[1]}`);let o=jD.exec(t);if(o){e.startedAtMs=Number(o[1]);continue}let s=HD.exec(t);if(s){e.bundleName=s[1].trim();continue}let a=UD.exec(t);a&&(e.mainName=a[1].trim())}return e}function gy(n){let e=n.mainName;if((!n.bundleName||!e)&&n.uri){let t=n.uri.split("/").filter(Boolean);t.length>=3&&(n.bundleName??=t[0],e??=t[t.length-1])}return{bundleName:n.bundleName,abilityName:e}}function qD(n){let{bundleName:e,abilityName:t}=gy(n);return e!==qo||!t?!1:t===Fn||t===WD}function zD(n){if(BD.test(n))throw new S("DUMP_PARSE_FAILED",`Unexpected aa dump output: ${n.trim().split(/\r?\n/)[0]??""}`);if(!n.includes("ExtensionRecords")&&!n.includes("AbilityRecord ID"))throw new S("DUMP_PARSE_FAILED","aa dump output has no recognizable extension-record structure");for(let t of n.split(/\r?\n/))if($D.test(t)&&!ju.test(t))throw new S("DUMP_PARSE_FAILED","aa dump output has an unterminated uri line; output may be truncated");let e=VD(n);if(e.length===0&&n.replace(/ExtensionRecords:\s*/,"").trim()!=="")throw new S("DUMP_PARSE_FAILED","aa dump output has no complete ability records; output may be truncated");return e}function yy(n){if(!n.trim())throw new S("DUMP_PARSE_FAILED","aa dump output is empty; the device state is unknown");let e=new Map;for(let t of zD(n)){let r=GD(t);if(!qD(r))continue;if(r.id===void 0)throw new S("DUMP_PARSE_FAILED","Recorder ability block is missing its AbilityRecord ID");let{bundleName:i,abilityName:o}=gy(r);e.set(r.id,{abilityRecordId:r.id,bundleName:i??qo,abilityName:o??Fn,startedAtMs:r.startedAtMs})}return[...e.values()]}function Hu(n,e){if(n.length>1)throw new S("AMBIGUOUS_DEVICE_STATE",`Multiple screen recorder ability records: ${n.map(r=>r.abilityRecordId).join(", ")}`);let t=n[0];return t?{status:e?.abilityRecordId===t.abilityRecordId?"recording":"busy",activeId:t.abilityRecordId,session:e}:{status:"idle",session:e}}function jn(n,e){return!n||!e?n===e:n.fileName===e.fileName&&n.abilityRecordId===e.abilityRecordId&&n.startTime===e.startTime&&n.localPath===e.localPath}function wy(n){return n.status==="recording"?{plan:"error",error:new S("CLI_RECORDING_ACTIVE","A CLI recording session is already running; run stop first")}:n.status==="busy"?{plan:"error",error:new S("EXTERNAL_RECORDING","A recording not started by this CLI is in progress; run stop --force first")}:n.session?{plan:"discard-first",session:n.session}:{plan:"start-new"}}function vy(n){return n.status==="idle"&&!n.session?{plan:"start-new"}:{plan:"error",error:new S("STATE_CHANGED","Device state changed while discarding the interrupted registration; not starting")}}function by(n,e){return n.status==="busy"?e?{plan:"force-stop-external",activeId:n.activeId}:{plan:"error",error:new S("EXTERNAL_RECORDING","Recording was not started by this CLI. Stop it on the device or run stop --force.")}:n.session?{plan:"finalize-session",session:n.session}:{plan:"error",error:new S("NO_CLI_SESSION","No CLI recording session on this device")}}function Sy(n,e,t){return jn(n,e)?{plan:"proceed"}:t==="interactive"?{plan:"completed-elsewhere"}:{plan:"error",error:new S("SESSION_CHANGED","The recording session changed; leaving the current one untouched")}}function Ey(n){return n.status==="busy"?{plan:"error",error:new S("EXTERNAL_RECORDING","A recording not started by this CLI is in progress; not toggling")}:n.status==="recording"?{plan:"stop-recording"}:{plan:"retrieve"}}function Py(n,e){if(n.length===0)return{outcome:"gone"};if(n.length>1)return{outcome:"error",error:new S("STATE_CHANGED","Multiple recorder records while confirming stop; not toggling again")};let t=n[0].abilityRecordId;return t!==e?{outcome:"error",error:new S("STATE_CHANGED",`A different recording (ID ${t}) appeared while stopping; leaving it alone`)}:{outcome:"still-recording",activeId:t}}function Cy(n){return n.length===1?{outcome:"confirmed",record:n[0]}:n.length>1?{outcome:"error",error:new S("AMBIGUOUS_DEVICE_STATE","Multiple recorder records after start; refusing to pick one")}:{outcome:"pending"}}function ky(n,e){if(n.length===0)return{plan:"already-stopped"};if(n.length>1)return{plan:"error",error:new S("AMBIGUOUS_DEVICE_STATE","Multiple recorder records; refusing to force-stop")};let t=n[0];return e!==void 0&&t.abilityRecordId!==e?{plan:"error",error:new S("STATE_CHANGED","The recording changed while stopping; leaving it alone")}:{plan:"stop",currentId:t.abilityRecordId,startedAtMs:t.startedAtMs}}function Ry(n){return n.status==="idle"&&n.session?{status:"idle",note:"interrupted session found; retrievable via ui screenrecord stop"}:{status:n.status}}function Dy(n,e){return!jn(n.session,e)||n.status!=="recording"}function Uu(n,e){return n.startTime+e}function xy(n,e,t){return t+Math.max(0,e-n)}import Wr from"fs";import Ny from"path";import{randomBytes as XD}from"crypto";import{lock as ZD}from"proper-lockfile";import zo from"path";var JD=/^[A-Za-z0-9][A-Za-z0-9.-]*\.mp4$/;function Ai(n){return Buffer.from(n,"utf8").toString("hex")}function Hn(n,e){return String(n).padStart(e,"0")}function Ay(n){return`${Hn(n.getFullYear(),4)}${Hn(n.getMonth()+1,2)}${Hn(n.getDate(),2)}-${Hn(n.getHours(),2)}${Hn(n.getMinutes(),2)}${Hn(n.getSeconds(),2)}${Hn(n.getMilliseconds(),3)}`}function YD(n){return n.replace(/[<>:"/\\|?*\u0000-\u001f]/g,"-").replace(/\s+/g," ").trim().replace(/[. ]+$/,"").replace(/^[. ]+/,"")||"device"}function Iy(n,e){if(!/^[a-z0-9]{4}$/.test(e))throw new S("INVALID_RECORDING_PATH",`Internal: bad random suffix ${JSON.stringify(e)}`);return`devecocli-${Ay(n)}-${e}.mp4`}function Ty(n,e,t){return`${YD(n)}-${Ay(e)}-${t}.mp4`}function Oy(n,e){if(!JD.test(n))throw new S("INVALID_RECORDING_PATH",`Unsafe device file name: ${JSON.stringify(n)}`);return`${hy}/devecocli-${e}-${n}`}var KD=20;function My(n){let e=zo.dirname(n),t=zo.extname(n),r=zo.basename(n,t),i=[n];i.push(zo.join(e,`${r}-recovered${t}`));for(let o=2;o<KD;o++)i.push(zo.join(e,`${r}-recovered-${o}${t}`));return i}var QD=5*6e4,ex=5*6e4,tx=1e4,rx=6e4,Bu=200;function nx(n){if(!Number.isInteger(n)||n<=0)return"unknown";try{return process.kill(n,0),"alive"}catch(e){let t=e.code;return t==="ESRCH"?"dead":t==="EPERM"?"alive":"unknown"}}function Ly(n){return new Promise(e=>setTimeout(e,n))}function ix(){return XD(8).toString("hex")}async function _y(n){let e;try{e=await Wr.promises.readFile(n,"utf8")}catch{return}try{let t=JSON.parse(e);return typeof t.token=="string"?t.token:void 0}catch{return}}var dc=class{constructor(e,t={}){this.recordDir=e;this.releaseGuardWaitMs=t.releaseGuardWaitMs??tx}releaseGuardWaitMs;lockPath(e){return Ny.join(this.recordDir,`${Ai(e)}.lock`)}guardPath(e){return Ny.join(this.recordDir,`${Ai(e)}.guard`)}async withDeviceLock(e,t,r=rx){let i=await this.acquire(e,r),o;try{o=await t(i)}catch(s){try{await this.releaseOwned(e,i)}catch(a){m(`lock release failed after action error: ${a.message}`)}throw s}return await this.releaseOwned(e,i),o}async withGuard(e,t,r=0){let i=Date.now()+r;for(;;){let o;try{o=await ZD(this.guardPath(e),{realpath:!1,stale:QD,update:1e3,retries:0})}catch(s){if(s.code!=="ELOCKED"||Date.now()>=i)throw s;await Ly(Math.min(Bu,i-Date.now()));continue}try{return await t()}finally{await o()}}}async acquire(e,t){await Wr.promises.mkdir(this.recordDir,{recursive:!0});let r=ix(),i=this.lockPath(e),o=Date.now()+t;for(;;){let s=!1;try{await this.withGuard(e,async()=>{s=await this.tryCreateOrReclaim(i,r)})}catch(a){if(a.code!=="ELOCKED")throw a}if(s)return this.buildLease(i,r);if(Date.now()+Bu>o)throw new S("LOCK_BUSY",`Timed out waiting ${t}ms for the device lock (${e})`);await Ly(Bu)}}async tryCreateOrReclaim(e,t){let r;try{r=await Wr.promises.open(e,"wx")}catch(i){if(i.code!=="EEXIST")throw i;return await this.reclaimIfDead(e),!1}try{let i={pid:process.pid,createdAt:Date.now(),token:t};await r.writeFile(JSON.stringify(i)),await r.sync()}finally{await r.close()}return!0}async reclaimIfDead(e){let t,r;try{t=await Wr.promises.readFile(e,"utf8"),r=await Wr.promises.stat(e)}catch(o){if(o.code==="ENOENT")return;throw o}let i;try{let o=JSON.parse(t);typeof o.pid=="number"&&typeof o.createdAt=="number"&&typeof o.token=="string"&&(i=o)}catch{}if(i){nx(i.pid)==="dead"&&await Wr.promises.unlink(e);return}Date.now()-r.mtimeMs>ex&&await Wr.promises.unlink(e)}buildLease(e,t){let r=new AbortController;return{token:t,signal:r.signal,assertOwned:async()=>{if(await _y(e)!==t)throw r.abort(),new S("LOCK_LOST","Lost the device lock; aborting this operation")}}}async releaseOwned(e,t){let r=this.lockPath(e);try{await this.withGuard(e,async()=>{await _y(r)===t.token&&await Wr.promises.unlink(r)},this.releaseGuardWaitMs)}catch(i){throw new S("LOCK_RELEASE_FAILED",`Could not release the device lock (${e}): ${i.message}. The lock stays in place; it is reclaimed by the dead-PID or corrupt-age rule once this process exits.`,{cause:i})}}};import{execa as ox}from"execa";var Wu=15e3,$y=10*6e4,sx=3,Fy=400;function ax(n){return new Promise(e=>setTimeout(e,n))}function cx(n){return async(e,t)=>{m(`Executing: ${n} ${e.join(" ")}`);let r=await ox(n,e,{reject:!1,timeout:t.timeoutMs??Wu,cancelSignal:t.signal,stdout:"pipe",stderr:"pipe"});return{stdout:typeof r.stdout=="string"?r.stdout:"",stderr:typeof r.stderr=="string"?r.stderr:"",exitCode:r.exitCode??-1}}}var uc=class n{runner;constructor(e){this.runner=cx(e)}async runReadOnly(e,t){let r={stdout:"",stderr:"",exitCode:-1},i=t!==void 0?Date.now()+t:void 0;for(let o=0;o<sx;o++){let s=i!==void 0?i-Date.now():void 0;r=await this.runner(e,s===void 0?{}:{timeoutMs:Math.max(1,s)});let a=`${r.stdout}
62
+ ${r.stderr}`;if(r.exitCode===0||At(a)!=="transient")return r;if(i!==void 0&&Date.now()+Fy>i)break;await ax(Fy)}return r}static assertUsable(e,t){let r=`${e.stdout}
63
+ ${e.stderr}`.trim();if(e.exitCode!==0||At(r)!=="ok")throw new S(t,`hdc command failed (exit ${e.exitCode}): ${r.split(`
64
+ `)[0]??""}`)}async observeOnce(e,t){let r=await this.runReadOnly(["-t",e,"shell","aa","dump","-e"],t);return n.assertUsable(r,"DUMP_PARSE_FAILED"),yy(r.stdout)}async readUptimeMs(e,t){let r=await this.runReadOnly(["-t",e,"shell","cat","/proc/uptime"],t);n.assertUsable(r,"DUMP_PARSE_FAILED");let i=Number(/^([\d.]+)/.exec(r.stdout.trim())?.[1]);if(!Number.isFinite(i)||i<=0)throw new S("DUMP_PARSE_FAILED",`Unparseable /proc/uptime output: ${r.stdout.trim().split(`
65
+ `)[0]??""}`);return Math.round(i*1e3)}async toggleOnce(e,t,r,i){await r.assertOwned();let o=["-t",e,"shell","aa","start","-b",qo,"-a",Fn];t!==void 0&&o.push("--ps","CustomizedFileName",t);try{let s=await this.runner(o,{timeoutMs:i??Wu,signal:r.signal});return s.exitCode!==0?(m(`aa start exited ${s.exitCode}: ${s.stderr||s.stdout}`),{transport:"uncertain",stdout:s.stdout,stderr:s.stderr}):{transport:"returned",stdout:s.stdout,stderr:s.stderr}}catch(s){return m(`aa start transport failure: ${s.message}`),{transport:"uncertain",stderr:s.message}}}async queryMediaUri(e,t,r){let i=await this.runReadOnly(["-t",e,"shell","mediatool","query",t,"-u"],r);n.assertUsable(i,"MEDIA_QUERY_FAILED");let o=/find\s+(\d+)\s+result/i.exec(i.stdout);if(!o)throw new S("MEDIA_QUERY_FAILED",`Unparseable mediatool query output: ${i.stdout.trim().split(`
66
+ `)[0]??""}`);let s=[...i.stdout.matchAll(/"(file:\/\/[^"]+)"/g)].map(c=>c[1]),a=Number(o[1]);if(a!==0){if(a>1||s.length>1)throw new S("MEDIA_AMBIGUOUS",`mediatool returned ${a} entries for ${t}`);if(s.length!==1)throw new S("MEDIA_QUERY_FAILED",`mediatool reported 1 entry but no URI for ${t}`);return s[0]}}async exportToStaging(e,t,r){let i=await this.runner(["-t",e,"shell","mediatool","recv",t,r],{timeoutMs:$y});if(n.assertUsable(i,"SAVE_FAILED"),!i.stdout.includes(r))throw new S("SAVE_FAILED",`mediatool recv did not confirm ${r}: ${i.stdout.trim().split(`
67
+ `)[0]??""}`)}async receiveFile(e,t,r,i){let o=await this.runner(["-t",e,"file","recv",t,r],{timeoutMs:$y,signal:i});if(o.exitCode!==0)throw new S("SAVE_FAILED",`hdc file recv failed (exit ${o.exitCode}): ${(o.stderr||o.stdout).split(`
68
+ `)[0]??""}`)}async removeStaging(e,t){return(await this.runReadOnly(["-t",e,"shell","rm","-f",t],Wu)).exitCode===0}};import gr from"fs";import Kt from"path";import{createFile as lx}from"mp4box";var Hy=".devecocli-record-";function Ii(n,e){return new S("INVALID_RECORDING_PATH",e instanceof Error?`${n}: ${e.message}`:n,e instanceof Error?{cause:e}:void 0)}async function Vu(n){try{return{stat:await gr.promises.stat(n)}}catch(e){let t=e.code;return t==="ENOENT"?null:{code:t??"UNKNOWN"}}}async function jy(n){let e=await Vu(n);if(!e)throw Ii(`Directory does not exist: ${n}`);if("code"in e)throw Ii(`Directory is not accessible: ${n}`);if(!e.stat.isDirectory())throw Ii(`Path is not a directory: ${n}`);try{await gr.promises.access(n,gr.constants.W_OK)}catch(t){throw Ii(`Directory is not writable: ${n}`,t)}}async function Gu(n){if(await Vu(n))throw new S("DESTINATION_EXISTS",`Destination already exists: ${n}`)}async function qu(n,e,t,r){if(!n?.trim())throw Ii("--path is required.");let i=Kt.resolve(n.trim()),o=await Vu(i);if(o&&"stat"in o&&o.stat.isDirectory()){await jy(i);let a=Kt.join(i,Ty(e,t,r));return await Gu(a),a}if(o)throw new S("DESTINATION_EXISTS",`Destination already exists: ${i}`);if(Kt.extname(i).toLowerCase()!==".mp4")throw Ii(`Destination must be an existing directory or a new .mp4 file: ${i}`);let s=Kt.dirname(i);return await jy(s),i}async function Uy(n){return gr.promises.mkdtemp(Kt.join(Kt.dirname(n),Hy))}var dx=4*1024*1024;async function ux(n){let e=await gr.promises.open(n,"r");try{let{size:t}=await e.stat(),r=lx(),i=0;for(let s=0;s<t;){let a=Math.min(dx,t-s),c=Buffer.alloc(a),{bytesRead:l}=await e.read(c,0,a,s);if(l<=0)break;let d=c.buffer.slice(c.byteOffset,c.byteOffset+l);d.fileStart=s,i=r.appendBuffer(d,s+l>=t),s+=l}r.flush();let o=r.getBox("moov");return{size:t,complete:i===t,hasMovieHeader:o?.mvhd!==void 0,videoTrackCount:o?.mvhd!==void 0?r.getInfo().videoTracks.length:0}}finally{await e.close()}}async function By(n){let e;try{e=await ux(n)}catch(t){throw new S("SAVE_FAILED",`Cannot inspect received file: ${t.message}`,{cause:t})}if(e.size===0)throw new S("MEDIA_NOT_READY","Received file is empty");if(!e.complete||!e.hasMovieHeader)throw new S("MEDIA_NOT_READY","Received file is not a complete MP4");if(e.videoTrackCount<1)throw new S("MEDIA_NOT_READY","Received file has no video track");return e.size}async function px(n){let e=await gr.promises.open(n,"r+");try{await e.sync()}finally{await e.close()}}async function mx(n){try{let e=await gr.promises.open(Kt.dirname(n),"r");try{await e.sync()}finally{await e.close()}}catch{}}async function Wy(n,e){await px(n);for(let t of My(e))try{return await gr.promises.link(n,t),await mx(t),t}catch(r){if(r.code==="EEXIST")continue;throw new S("SAVE_FAILED",`Cannot publish recording to ${t}: ${r.message}`,{cause:r})}throw new S("DESTINATION_UNAVAILABLE",`All recovery names are taken near ${e}`)}async function Vy(n,e){let t=Kt.dirname(e),r=Kt.basename(n);Kt.dirname(n)!==t||!r.startsWith(Hy)||await gr.promises.rm(n,{recursive:!0,force:!0}).catch(()=>{})}import yr from"fs";import pc from"path";import{randomBytes as fx}from"crypto";function Gy(n,e){let t=n,r=i=>new S("SESSION_CORRUPT",`Invalid recording session ${i} in ${e}`);if(!t||typeof t!="object")throw r("object");if(typeof t.fileName!="string"||t.fileName.length===0||t.fileName!==pc.basename(t.fileName)||t.fileName.includes(".."))throw r("fileName");if(typeof t.abilityRecordId!="number"||!Number.isSafeInteger(t.abilityRecordId)||t.abilityRecordId<=0)throw r("abilityRecordId");if(typeof t.startTime!="number"||!Number.isFinite(t.startTime))throw r("startTime");if(typeof t.localPath!="string"||t.localPath.length===0||!pc.isAbsolute(t.localPath))throw r("localPath");return{fileName:t.fileName,abilityRecordId:t.abilityRecordId,startTime:t.startTime,localPath:t.localPath}}var mc=class{constructor(e){this.recordDir=e}sessionPath(e){return pc.join(this.recordDir,`${Ai(e)}.json`)}async read(e){let t=this.sessionPath(e),r;try{r=await yr.promises.readFile(t,"utf8")}catch(o){if(o.code==="ENOENT")return;throw new S("SESSION_CORRUPT",`Cannot read recording session: ${o.message}`,{cause:o})}let i;try{i=JSON.parse(r)}catch(o){throw new S("SESSION_CORRUPT",`Recording session file is not valid JSON: ${t}`,{cause:o})}return Gy(i,t)}async createAtomic(e,t,r){await yr.promises.mkdir(this.recordDir,{recursive:!0});let i=this.sessionPath(e),o=pc.join(this.recordDir,`${Ai(e)}.${fx(6).toString("hex")}.tmp`),s=JSON.stringify(Gy(t,"input")),a;try{a=await yr.promises.open(o,"wx")}catch(c){throw new S("SESSION_PUBLISH_FAILED",`Cannot create session temp file: ${c.message}`,{cause:c})}try{await a.writeFile(s),await a.sync()}catch(c){throw await a.close().catch(()=>{}),await yr.promises.unlink(o).catch(()=>{}),new S("SESSION_PUBLISH_FAILED",`Cannot write session temp file: ${c.message}`,{cause:c})}await a.close();try{if(await r.assertOwned(),await this.exists(i))throw new S("SESSION_CHANGED",`A recording session was created concurrently for ${e}`);await yr.promises.link(o,i),await this.syncDir()}finally{await yr.promises.unlink(o).catch(()=>{})}}async deleteIfSame(e,t,r){await r.assertOwned();let i=await this.read(e);if(i){if(!jn(i,t))throw new S("SESSION_CHANGED","The recording session changed hands; leaving the new record untouched");await yr.promises.unlink(this.sessionPath(e)),await this.syncDir()}}async exists(e){try{return await yr.promises.lstat(e),!0}catch{return!1}}async syncDir(){try{let e=await yr.promises.open(this.recordDir,"r");try{await e.sync()}finally{await e.close()}}catch{}}};var gx={startConfirmMs:1e4,stopConfirmMs:15e3,stopReadyMs:3e3,observeIntervalMs:250,foregroundPollMs:1e3,mediaReadyMs:3e4,mediaBackoffMs:[250,500,1e3,2e3],mediaRecvAttempts:3,lockWaitMs:6e4,interactiveLockWaitMs:10*6e4,foregroundFailureBudget:3},zy=4e3;function Jo(n){return new Promise(e=>setTimeout(e,n))}function fc(){return hx(2).toString("hex")}var Jy=["SIGINT","SIGTERM","SIGHUP"];function yx(n,e){let t=()=>{n.requested||(n.requested=!0,e?.(),n.wake())};for(let r of Jy)process.on(r,t);return()=>{for(let r of Jy)process.off(r,t)}}var Vr=class{constructor(e,t={}){this.toolProvider=e;let r=qy.join(W(),"record");this.deps={store:t.store??new mc(r),lock:t.lock??new dc(r),device:t.device??new uc(e.hdcPath),timing:{...gx,...t.timing}}}deps;async startDetached(e,t){let r=await this.resolveTarget(e),i=await qu(t,r.name,new Date,fc());return this.startSession(r,i)}async recordInteractively(e,t,r){let i=new Set,o={requested:!1,wake:()=>{for(let a of i)a()}},s=yx(o,r.onStopRequested);try{let a=await this.resolveTarget(e),c=await qu(t,a.name,new Date,fc()),l=await this.startSession(a,c);return r.onStarted(),await this.waitForInteractiveCompletion(l,o,i)}finally{s()}}async waitForInteractiveCompletion(e,t,r){let i,o=()=>(i??=this.deps.lock.withDeviceLock(e.serial,a=>this.finalizeLocked(e.serial,e.session,"interactive",a),this.deps.timing.interactiveLockWaitMs),i),s=0;for(;;){if(t.requested)return await o();let a;try{a=await this.readSnapshot(e.serial),s=0}catch(c){if(s+=1,s>=this.deps.timing.foregroundFailureBudget)throw c;await this.waitPoll(t,r);continue}if(Dy(a,e.session))return await o();await this.waitPoll(t,r)}}async stopRecording(e,t){let r=await this.resolveTarget(e);return this.deps.lock.withDeviceLock(r.serial,async i=>{let o=await this.readSnapshot(r.serial),s=by(o,t);if(s.plan==="force-stop-external")return await this.stopExternal(r.serial,s.activeId,i),{kind:"external-stopped"};if(s.plan==="error")throw s.error;return this.finalizeLocked(r.serial,s.session,"stop-or-recover",i)},this.deps.timing.lockWaitMs)}async getRecordingStatus(e){let t=await this.resolveTarget(e);for(let r=0;r<3;r++){let i=await this.deps.store.read(t.serial),o=await this.deps.device.observeOnce(t.serial),s=await this.deps.store.read(t.serial);if(!jn(i,s))continue;let a=Hu(o,s);return Ry(a)}throw new S("STATE_CHANGING","The recording session keeps changing; try again")}async resolveTarget(e){let t=await le.from(this.toolProvider).getConnectedEntries();if(t.length===0)throw new S("NO_ACTIVE_DEVICES","No active devices found. Connect a physical device; screen recording does not support emulators.");let r=await T(this.toolProvider,e),i=t.find(o=>o.serial===r);if(i?.isEmulator)throw new S("EMULATOR_NOT_SUPPORTED","Screen recording is only supported on physical devices");return{serial:r,name:i?.name??r}}async readSnapshot(e){let t=await this.deps.store.read(e),r=await this.deps.device.observeOnce(e);return Hu(r,t)}async startSession(e,t){return this.deps.lock.withDeviceLock(e.serial,r=>this.startSessionLocked(e,t,r),this.deps.timing.lockWaitMs)}async startSessionLocked(e,t,r){let i=await this.readSnapshot(e.serial),o=wy(i);if(o.plan==="error")throw o.error;if(o.plan==="discard-first"){await this.deps.store.deleteIfSame(e.serial,o.session,r);let s=await this.readSnapshot(e.serial),a=vy(s);if(a.plan==="error")throw a.error}return this.toggleAndRegister(e,t,r)}async toggleAndRegister(e,t,r){await Gu(t);let i=Iy(new Date,fc()),o=Date.now(),s=Date.now()+this.deps.timing.startConfirmMs;await r.assertOwned(),await this.deps.device.toggleOnce(e.serial,i,r,Math.max(1,s-Date.now()));let a=await this.waitForStarted(e.serial,s),c={fileName:i,abilityRecordId:a.abilityRecordId,startTime:o,localPath:t};return await this.registerSession(e.serial,c,r),{serial:e.serial,session:c}}async registerSession(e,t,r){try{await this.deps.store.createAtomic(e,t,r)}catch(i){throw await this.abortUnregistered(e,t,r),new S(i.code??"SESSION_PUBLISH_FAILED",`Recording started on device (file ${t.fileName}) but could not be registered: ${i.message}. Check the device gallery.`,{cause:i})}}async withinDeadline(e,t,r){try{return await r(Math.max(1,e-Date.now()))}catch(i){throw Date.now()>=e?t:i}}async waitForStarted(e,t){for(;;){let r=t-Date.now();if(r<=0)throw new S("START_CONFIRM_TIMEOUT","Device screen may be locked");let i=await this.withinDeadline(t,new S("START_CONFIRM_TIMEOUT","Device screen may be locked"),s=>this.deps.device.observeOnce(e,s)),o=Cy(i);if(o.outcome==="error")throw o.error;if(o.outcome==="confirmed"){if(Date.now()>t)throw new S("START_CONFIRM_TIMEOUT","Device screen may be locked");return o.record}await Jo(Math.min(this.deps.timing.observeIntervalMs,r))}}async observeActiveId(e,t,r){let i=await this.deps.device.observeOnce(e,r),o=Py(i,t);if(o.outcome==="error")throw o.error;return o.outcome==="gone"?void 0:o.activeId}async waitForStopped(e,t,r){for(;;){let i=r-Date.now();if(i<=0)throw new S("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent");if(await this.withinDeadline(r,new S("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent"),s=>this.observeActiveId(e,t,s))===void 0)return;await Jo(Math.min(this.deps.timing.observeIntervalMs,i))}}async awaitStopReady(e,t,r,i){for(;;){let o=i-Date.now();if(o<=0)throw new S("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent");if(await this.withinDeadline(i,new S("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent"),a=>this.observeActiveId(e,t,a))===void 0)return"vanished";if(Date.now()>=r){if(Date.now()>i)throw new S("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent");return"ready"}await Jo(Math.min(this.deps.timing.observeIntervalMs,r-Date.now(),o))}}async abortUnregistered(e,t,r){try{let i=Date.now()+this.deps.timing.stopConfirmMs,o=Uu(t,this.deps.timing.stopReadyMs);await this.awaitStopReady(e,t.abilityRecordId,o,i)==="ready"&&await this.deps.device.toggleOnce(e,void 0,r,Math.max(1,i-Date.now()))}catch(i){m(`abortUnregistered: best-effort stop failed: ${i.message}`)}}async finalizeLocked(e,t,r,i){let o=await this.deps.store.read(e),s=Sy(o,t,r);if(s.plan==="completed-elsewhere")return{kind:"completed-elsewhere"};if(s.plan==="error")throw s.error;let a=await this.readSnapshot(e),c=Ey(a);if(c.plan==="error")throw c.error;if(c.plan==="stop-recording"){let l=Date.now()+this.deps.timing.stopConfirmMs;return this.stopLiveRecording(e,t,i,l)}return this.retrieveAndPublish(e,t,i)}async stopLiveRecording(e,t,r,i){let o=Uu(t,this.deps.timing.stopReadyMs);return await this.awaitStopReady(e,t.abilityRecordId,o,i)==="vanished"?this.retrieveAndPublish(e,t,r):(await r.assertOwned(),await this.deps.device.toggleOnce(e,void 0,r,Math.max(1,i-Date.now())),await this.waitForStopped(e,t.abilityRecordId,i),this.retrieveAndPublish(e,t,r))}async stopExternal(e,t,r){let i=await this.deps.device.observeOnce(e),o=ky(i,t);if(o.plan==="already-stopped")return;if(o.plan==="error")throw o.error;let s=Date.now()+this.deps.timing.stopConfirmMs;o.startedAtMs!==void 0&&!await this.awaitForeignStopReady(e,o.currentId,o.startedAtMs,s)||(await r.assertOwned(),await this.deps.device.toggleOnce(e,void 0,r,Math.max(1,s-Date.now())),await this.waitForStopped(e,o.currentId,s))}async awaitForeignStopReady(e,t,r,i){let o=await this.withinDeadline(i,new S("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent"),c=>this.deps.device.readUptimeMs(e,c)),s=xy(o-r,this.deps.timing.stopReadyMs,Date.now());return await this.awaitStopReady(e,t,s,i)==="ready"}async retrieveAndPublish(e,t,r){let i=[],o=await this.waitForMediaUri(e,t.fileName),s=await Uy(t.localPath);try{let a=await this.receiveUntilValid(e,o,t,s,r,i);await r.assertOwned();let c=await Wy(a,t.localPath);return await this.deleteSessionAfterSave(e,t,r,c),{kind:"saved",localPath:c,warnings:i}}finally{await Vy(s,t.localPath)}}async waitForMediaUri(e,t){let r=Date.now()+this.deps.timing.mediaReadyMs,i=0;for(;;){let o=r-Date.now();if(o<=0)throw new S("MEDIA_NOT_READY",`Timed out waiting for ${t} in the media library; session kept for a later stop`);let s=await this.withinDeadline(r,new S("MEDIA_NOT_READY",`Timed out waiting for ${t} in the media library; session kept for a later stop`),c=>this.deps.device.queryMediaUri(e,t,c));if(s&&Date.now()<=r)return s;let a=Math.min(this.deps.timing.mediaBackoffMs[Math.min(i,this.deps.timing.mediaBackoffMs.length-1)]??zy,zy,o);i+=1,await Jo(a)}}async receiveUntilValid(e,t,r,i,o,s){for(let a=0;a<this.deps.timing.mediaRecvAttempts;a++){await o.assertOwned();let c=Oy(r.fileName,fc()),l=await this.receiveOnce(e,t,c,i,r.fileName,o,s);try{return await By(l),l}catch(d){if(d.code!=="MEDIA_NOT_READY")throw d;m(`Received file incomplete (attempt ${a+1}); retrying export`),await Jo(this.deps.timing.mediaBackoffMs[0]??250)}}throw new S("MEDIA_NOT_READY",`Received file for ${r.fileName} is incomplete after ${this.deps.timing.mediaRecvAttempts} attempts; session kept`)}async receiveOnce(e,t,r,i,o,s,a){let c=qy.join(i,o);try{await this.deps.device.exportToStaging(e,t,r),await this.deps.device.receiveFile(e,r,c,s.signal)}finally{await this.deps.device.removeStaging(e,r)||a.push(`Failed to remove device staging file: ${r}`)}return c}async deleteSessionAfterSave(e,t,r,i){try{await this.deps.store.deleteIfSame(e,t,r)}catch(o){throw new S(o.code??"SESSION_DELETE_FAILED",`Recording saved to ${i}, but the session record could not be removed: ${o.message}. A later stop may create a recovered copy.`,{cause:o})}}async waitPoll(e,t){await new Promise(r=>{let i=setTimeout(()=>{t.delete(o),r()},this.deps.timing.foregroundPollMs),o=()=>{t.delete(o),clearTimeout(i),r()};t.add(o)})}};var hc={left:"0",right:"1",up:"2",down:"3"};function He(n,e){let t=Number(n);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function zu(n,e){n!==void 0&&He(n,e)}function Yy(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function gc(n,e){if(n!==void 0&&n.length===0)throw new Error(`${e} must not be empty`)}function Yo(n){if(n===void 0)return;let e=Number(n);if(!Number.isInteger(e)||e<200||e>4e4)throw new Error("--speed must be an integer between 200 and 40000");return n}function Ky(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function Xy(n,e,t,r=!0){if(t&&!e)throw new Error("--window must be used with --id");if(n&&e)throw new Error("Coordinates and --id are mutually exclusive");if(r&&!n&&!e)throw new Error("Either provide x y coordinates or use --id")}function Ti(n,e,t,r,i=!0){Yy(n,e),gc(t,"--id"),zu(n,"x"),zu(e,"y"),Ky(r),Xy(n!==void 0,!!t,!!r,i)}async function Xt(n){let e=await P.new(),t=await T(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function Oi(n,e,t,r,i,o){if(t!==void 0&&r!==void 0)return{x:t,y:r};if(i===void 0)throw new Error("Either provide x y coordinates or use --id");let a=await new mr(n,e).listWindows({all:!0}),c=new fr(n);return wx(c,e,a,i,o)}async function wx(n,e,t,r,i){if(i!==void 0){let o=t.find(a=>String(a.id)===i);if(o&&o.displayId!==0)throw new y(`Window "${i}" is on display ${o.displayId}. The current command only supports operations on the primary display.`,"The current command only supports operations on the primary display.");let s=await n.dumpFullTree(e,0,i,!1);return bx(s,r)}return vx(n,e,t,r)}async function vx(n,e,t,r){let i=[...new Set(t.map(a=>a.displayId))],o=await n.dumpFullTreeByDisplays(e,0,i),s=[];for(let{displayId:a,tree:c}of o)for(let l of Ri([c],r))s.push({node:l,displayId:a});if(s.length===0)throw new y(`Node "${r}" not found.`,"Node not found.");if(s.length>1)throw new y(`Multiple nodes found with id "${r}".`,"Multiple nodes found");if(s[0].displayId!==0)throw new y(`Node "${r}" is on display ${s[0].displayId}. The current command only supports operations on the primary display.`,"The current command only supports operations on the primary display.");return Zy(s[0].node,r)}function bx(n,e){let t=Ri(n,e);if(t.length===0)throw new y(`Node "${e}" not found.`,"Node not found.");if(t.length>1)throw new y(`Multiple nodes found with id "${e}".`,"Multiple nodes found");return Zy(t[0],e)}function Zy(n,e){let t=n.bounds;if(!t)throw new y(`Node "${e}" has no bounds.`,"Node has no bounds.");let[r,i,o,s]=t;return{x:Math.ceil((r+o)/2),y:Math.ceil((i+s)/2)}}async function vt(n,e,t){let r=["-t",e,"shell",...t];m(`Executing: ${n} ${r.join(" ")}`);let i=await C(n,r);if(i.exitCode!==0)throw new Error(i.stderr||i.stdout||`uitest exited with code ${i.exitCode}`);let o=i.stdout.toLowerCase();if(["illegal","fail","error","incorrect","please confirm that the coordinate values are correct"].some(a=>o.includes(a))&&!o.includes("no error"))throw new Error(i.stdout.trim()||"uitest command failed")}import{deflateSync as Sx,inflateSync as Ex}from"zlib";import Px from"fs";var Qy=8,ew=32,Cx=.06,kx=.04,Ju=10,yc=class n{whiteBits=null;blackBits=null;analyzeRgb(e,t,r){if(e<8||t<8||r.length<e*t*3)return null;let i=this.cropChrome(e,t,r),o=this.hashBits(i.width,i.height,i.rgb),s=Math.min(this.hammingDistance(o,this.solidRefBits(255)),this.hammingDistance(o,this.solidRefBits(0)));return{phash:this.bitsToHex(o),hamming:s,isBlank:s<=Ju}}analyzeFile(e){let t;try{t=Px.readFileSync(e)}catch{return null}let r=this.decodePngRgb(t);return r?this.analyzeRgb(r.width,r.height,r.rgb):null}static encodePngRgb(e,t,r){let i=n.pngCrcTable(),o=[Buffer.from(`\x89PNG\r
61
69
  
62
- `,"binary")],s=Buffer.alloc(13);s.writeUInt32BE(e,0),s.writeUInt32BE(t,4),s[8]=8,s[9]=2,i.push(r.pngChunk("IHDR",s,o));let a=Buffer.alloc((e*3+1)*t);for(let c=0;c<t;c++)a[c*(e*3+1)]=0,Buffer.from(n.buffer,n.byteOffset+c*e*3,e*3).copy(a,c*(e*3+1)+1);return i.push(r.pngChunk("IDAT",pC(a),o)),i.push(r.pngChunk("IEND",Buffer.alloc(0),o)),Buffer.concat(i)}cropChrome(e,t,n){let o=Math.floor(t*hC),i=Math.floor(t*(1-gC));if(i<=o+8)return{width:e,height:t,rgb:n};let s=i-o,a=new Uint8Array(e*s*3);for(let c=0;c<s;c++){let l=(o+c)*e*3;a.set(n.subarray(l,l+e*3),c*e*3)}return{width:e,height:s,rgb:a}}hashBits(e,t,n){let o=this.toGray(e,t,n),i=this.resizeGray(o,sf,sf),s=this.dct2(i),a=[];for(let d=0;d<of;d++)a.push(s[d].slice(0,of));let c=this.stabilizeDct(a),l=this.median(c);return c.map(d=>d>l)}solidRefBits(e){return e===255?this.whiteBits??=this.solidBits(255,255,255):this.blackBits??=this.solidBits(0,0,0)}solidBits(e,t,n){let i=new Uint8Array(12288);for(let s=0;s<4096;s++)i[s*3]=e,i[s*3+1]=t,i[s*3+2]=n;return this.hashBits(64,64,i)}hammingDistance(e,t){let n=Math.min(e.length,t.length),o=Math.abs(e.length-t.length);for(let i=0;i<n;i++)e[i]!==t[i]&&o++;return o}bitsToHex(e){let t=0n;for(let o of e)t=t<<1n|(o?1n:0n);let n=Math.max(1,Math.ceil(e.length/4));return t.toString(16).padStart(n,"0")}toGray(e,t,n){let o=[];for(let i=0;i<t;i++){let s=[];for(let a=0;a<e;a++){let c=(i*e+a)*3;s.push(.299*n[c]+.587*n[c+1]+.114*n[c+2])}o.push(s)}return o}resizeGray(e,t,n){let o=e.length,i=e[0]?.length??0;if(i===t&&o===n)return e;let s=[];for(let a=0;a<n;a++){let c=(a+.5)*o/n-.5,l=Math.max(0,Math.min(o-1,Math.floor(c))),d=Math.max(0,Math.min(o-1,l+1)),g=c-l,y=[];for(let b=0;b<t;b++){let N=(b+.5)*i/t-.5,$=Math.max(0,Math.min(i-1,Math.floor(N))),me=Math.max(0,Math.min(i-1,$+1)),Te=N-$,Pt=e[l][$],lp=e[l][me],Nc=e[d][$],Oc=e[d][me];y.push(Pt*(1-Te)*(1-g)+lp*Te*(1-g)+Nc*(1-Te)*g+Oc*Te*g)}s.push(y)}return s}stabilizeDct(e){let t=e.flat(),n=Math.abs(t[0]??0),o=Math.max(.001,n*1e-8);return t.map(i=>Math.abs(i)<o?0:i)}median(e){if(e.length===0)return 0;let t=[...e].sort((o,i)=>o-i),n=Math.floor(t.length/2);return t.length%2?t[n]:.5*(t[n-1]+t[n])}dct2(e){let t=e.length,n=a=>{let c=new Array(t).fill(0);for(let l=0;l<t;l++){let d=0;for(let g=0;g<t;g++)d+=a[g]*Math.cos(Math.PI*(g+.5)*l/t);c[l]=d}return c},o=e.map(n),i=[];for(let a=0;a<t;a++)i.push(n(o.map(c=>c[a])));let s=[];for(let a=0;a<t;a++){let c=[];for(let l=0;l<t;l++)c.push(i[l][a]);s.push(c)}return s}decodePngRgb(e){let t=this.parsePngChunks(e);if(!t)return null;let n;try{n=mC(Buffer.concat(t.idat))}catch{return null}let o=this.pngScanlinesToRgb(n,t.width,t.height,t.colorType);return{width:t.width,height:t.height,rgb:o}}parsePngChunks(e){if(e.length<8||e.subarray(0,8).toString("binary")!==`\x89PNG\r
70
+ `,"binary")],s=Buffer.alloc(13);s.writeUInt32BE(e,0),s.writeUInt32BE(t,4),s[8]=8,s[9]=2,o.push(n.pngChunk("IHDR",s,i));let a=Buffer.alloc((e*3+1)*t);for(let c=0;c<t;c++)a[c*(e*3+1)]=0,Buffer.from(r.buffer,r.byteOffset+c*e*3,e*3).copy(a,c*(e*3+1)+1);return o.push(n.pngChunk("IDAT",Sx(a),i)),o.push(n.pngChunk("IEND",Buffer.alloc(0),i)),Buffer.concat(o)}cropChrome(e,t,r){let i=Math.floor(t*Cx),o=Math.floor(t*(1-kx));if(o<=i+8)return{width:e,height:t,rgb:r};let s=o-i,a=new Uint8Array(e*s*3);for(let c=0;c<s;c++){let l=(i+c)*e*3;a.set(r.subarray(l,l+e*3),c*e*3)}return{width:e,height:s,rgb:a}}hashBits(e,t,r){let i=this.toGray(e,t,r),o=this.resizeGray(i,ew,ew),s=this.dct2(o),a=[];for(let d=0;d<Qy;d++)a.push(s[d].slice(0,Qy));let c=this.stabilizeDct(a),l=this.median(c);return c.map(d=>d>l)}solidRefBits(e){return e===255?this.whiteBits??=this.solidBits(255,255,255):this.blackBits??=this.solidBits(0,0,0)}solidBits(e,t,r){let o=new Uint8Array(12288);for(let s=0;s<4096;s++)o[s*3]=e,o[s*3+1]=t,o[s*3+2]=r;return this.hashBits(64,64,o)}hammingDistance(e,t){let r=Math.min(e.length,t.length),i=Math.abs(e.length-t.length);for(let o=0;o<r;o++)e[o]!==t[o]&&i++;return i}bitsToHex(e){let t=0n;for(let i of e)t=t<<1n|(i?1n:0n);let r=Math.max(1,Math.ceil(e.length/4));return t.toString(16).padStart(r,"0")}toGray(e,t,r){let i=[];for(let o=0;o<t;o++){let s=[];for(let a=0;a<e;a++){let c=(o*e+a)*3;s.push(.299*r[c]+.587*r[c+1]+.114*r[c+2])}i.push(s)}return i}resizeGray(e,t,r){let i=e.length,o=e[0]?.length??0;if(o===t&&i===r)return e;let s=[];for(let a=0;a<r;a++){let c=(a+.5)*i/r-.5,l=Math.max(0,Math.min(i-1,Math.floor(c))),d=Math.max(0,Math.min(i-1,l+1)),g=c-l,w=[];for(let R=0;R<t;R++){let z=(R+.5)*o/t-.5,ie=Math.max(0,Math.min(o-1,Math.floor(z))),at=Math.max(0,Math.min(o-1,ie+1)),Wt=z-ie,Cn=e[l][ie],kn=e[l][at],Rn=e[d][ie],ih=e[d][at];w.push(Cn*(1-Wt)*(1-g)+kn*Wt*(1-g)+Rn*(1-Wt)*g+ih*Wt*g)}s.push(w)}return s}stabilizeDct(e){let t=e.flat(),r=Math.abs(t[0]??0),i=Math.max(.001,r*1e-8);return t.map(o=>Math.abs(o)<i?0:o)}median(e){if(e.length===0)return 0;let t=[...e].sort((i,o)=>i-o),r=Math.floor(t.length/2);return t.length%2?t[r]:.5*(t[r-1]+t[r])}dct2(e){let t=e.length,r=a=>{let c=new Array(t).fill(0);for(let l=0;l<t;l++){let d=0;for(let g=0;g<t;g++)d+=a[g]*Math.cos(Math.PI*(g+.5)*l/t);c[l]=d}return c},i=e.map(r),o=[];for(let a=0;a<t;a++)o.push(r(i.map(c=>c[a])));let s=[];for(let a=0;a<t;a++){let c=[];for(let l=0;l<t;l++)c.push(o[l][a]);s.push(c)}return s}decodePngRgb(e){let t=this.parsePngChunks(e);if(!t)return null;let r;try{r=Ex(Buffer.concat(t.idat))}catch{return null}let i=this.pngScanlinesToRgb(r,t.width,t.height,t.colorType);return{width:t.width,height:t.height,rgb:i}}parsePngChunks(e){if(e.length<8||e.subarray(0,8).toString("binary")!==`\x89PNG\r
63
71
  
64
- `)return null;let t=8,n=0,o=0,i=0,s=0,a=[];for(;t+8<=e.length;){let c=e.readUInt32BE(t),l=e.subarray(t+4,t+8).toString("ascii"),d=e.subarray(t+8,t+8+c);if(t+=12+c,l==="IHDR")n=d.readUInt32BE(0),o=d.readUInt32BE(4),i=d[8],s=d[9];else if(l==="IDAT")a.push(d);else if(l==="IEND")break}return!n||!o||i!==8||s!==2&&s!==6?null:{width:n,height:o,colorType:s,idat:a}}pngScanlinesToRgb(e,t,n,o){let i=o===6?4:3,s=t*i,a=new Uint8Array(t*n*3),c=0,l=new Uint8Array(s),d=new Uint8Array(s);for(let g=0;g<n;g++){let y=e[c++];d.set(e.subarray(c,c+s)),c+=s,this.applyPngFilter(y,d,l,i);for(let b=0;b<t;b++){let N=(g*t+b)*3,$=b*i;a[N]=d[$],a[N+1]=d[$+1],a[N+2]=d[$+2]}l.set(d)}return a}applyPngFilter(e,t,n,o){for(let i=0;i<t.length;i++){let s=i>=o?t[i-o]:0,a=n[i],c=i>=o?n[i-o]:0;e===1?t[i]=t[i]+s&255:e===2?t[i]=t[i]+a&255:e===3?t[i]=t[i]+Math.floor((s+a)/2)&255:e===4&&(t[i]=t[i]+this.paeth(s,a,c)&255)}}paeth(e,t,n){let o=e+t-n,i=Math.abs(o-e),s=Math.abs(o-t),a=Math.abs(o-n);return i<=s&&i<=a?e:s<=a?t:n}static pngChunk(e,t,n){let o=Buffer.concat([Buffer.from(e,"ascii"),t]),i=Buffer.alloc(12+t.length);return i.writeUInt32BE(t.length,0),o.copy(i,4),i.writeUInt32BE(r.pngCrc(o,n),8+t.length),i}static pngCrcTable(){let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let o=0;o<8;o++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n>>>0}return e}static pngCrc(e,t){let n=4294967295;for(let o=0;o<e.length;o++)n=t[(n^e[o])&255]^n>>>8;return(n^4294967295)>>>0}};import Ht from"fs";import vt from"path";import{randomUUID as EC}from"crypto";var yC=/^smoke-screenshot-\d+\.png$/,vC=/^smoke-crash-\d+\.log$/,wC=/^run-\d+-\d+-[0-9a-f]{4}$/;function af(r){return`smoke-screenshot-${r}.png`}function cf(r){return`smoke-crash-${r}.log`}function lf(r){return yC.test(r)||vC.test(r)}var Ho="RUNNING",Pl="ENDED",SC=1440*60*1e3,bC=1440*60*1e3;function df(r,e,t){return`run-${r}-${e}-${t}`}function uf(r){return wC.test(r)}function pf(r){try{let e=JSON.parse(r);if(typeof e.pid!="number"||typeof e.startedAt!="number"||!Number.isFinite(e.pid)||!Number.isFinite(e.startedAt))return null;let t={pid:e.pid,startedAt:e.startedAt};return typeof e.endedAt=="number"&&Number.isFinite(e.endedAt)&&(t.endedAt=e.endedAt),t}catch{}return null}function mf(r,e,t){return r===null?!0:r==="ended"?e?.endedAt===void 0?!0:t.now-e.endedAt>=SC:!e||!Number.isInteger(e.pid)||e.pid<=0||t.now-e.startedAt>=bC?!0:!t.isPidAlive(e.pid)}var CC="smoke";function PC(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}var Bo=class{constructor(e,t=PC){this.baseDir=e;this.isPidAlive=t;this.runsRoot=vt.join(e,CC)}runsRoot;static resolveBaseDir(e,t){return t??vt.join(e,".hvigor")}createRun(){let e=vt.join(this.runsRoot,df(Date.now(),process.pid,EC().slice(0,4)));Ht.mkdirSync(e,{recursive:!0});let t={pid:process.pid,startedAt:Date.now()};return Ht.writeFileSync(vt.join(e,Ho),JSON.stringify(t),"utf8"),e}prune(e,t=Date.now()){this.pruneLegacyFlatArtifacts(),this.pruneEndedRuns(e,t)}finalize(e){try{let t=this.readMarker(e,Ho),n={pid:t?.pid??process.pid,startedAt:t?.startedAt??Date.now(),endedAt:Date.now()};Ht.writeFileSync(vt.join(e,Pl),JSON.stringify(n),"utf8"),Ht.rmSync(vt.join(e,Ho),{force:!0})}catch(t){m(`Smoke: finalize run failed (${e}): ${t.message}`)}}discard(e){try{Ht.rmSync(e,{recursive:!0,force:!0})}catch(t){m(`Smoke: discard run failed (${e}): ${t.message}`)}}pruneLegacyFlatArtifacts(){let e;try{e=Ht.readdirSync(this.baseDir,{withFileTypes:!0})}catch{return}for(let t of e)!t.isFile()||!lf(t.name)||this.removeQuietly(vt.join(this.baseDir,t.name))}pruneEndedRuns(e,t){let n;try{n=Ht.readdirSync(this.runsRoot,{withFileTypes:!0})}catch{return}for(let o of n){if(!o.isDirectory()||!uf(o.name))continue;let i=vt.join(this.runsRoot,o.name);if(vt.resolve(i)===vt.resolve(e))continue;let s=this.readMarkerState(i);mf(s.kind,s.marker,{now:t,isPidAlive:this.isPidAlive})&&this.removeQuietly(i)}}readMarkerState(e){let t=this.readMarker(e,Pl);if(t!==void 0)return{kind:"ended",marker:t};let n=this.readMarker(e,Ho);return n!==void 0?{kind:"running",marker:n}:{kind:null,marker:null}}readMarker(e,t){try{return pf(Ht.readFileSync(vt.join(e,t),"utf8"))}catch(n){return n.code==="ENOENT"?void 0:null}}removeQuietly(e){try{Ht.rmSync(e,{recursive:!0,force:!0})}catch(t){m(`Smoke: prune artifact failed (${e}): ${t.message}`)}}};var ff=1e3;function IC(){let r=process.env.DEVECO_CLI_SMOKE_WAIT_MS;if(r===void 0||r==="")return ff;let e=Number(r);return Number.isFinite(e)&&e>=0?Math.floor(e):ff}var js=class{constructor(e,t,n){this.hdc=t;this.projectRoot=n;this.hilog=new lr(e),this.screenshots=new tn(e)}phash=new _s;hilog;screenshots;runDir;runStore;async collect(e){this.openRun(e);let t=IC();t>0&&await new Promise(o=>setTimeout(o,t));let n;try{n=await this.hdc.pidofBundle(e.targetDeviceId,e.bundleName)}catch(o){return console.warn(Uo(`Smoke: process check failed (${o.message}); smoke skipped.`)),{processAlive:!0,phashBlank:null,processCheckSkipped:!0}}return n?this.collectScreenshotEvidence(e):{processAlive:!1,phashBlank:null,crashLogPath:await this.writeCrashLogFile(e)}}openRun(e){let t=new Bo(Bo.resolveBaseDir(this.projectRoot,e.screenshotDir)),n=t.createRun();t.prune(n),this.runStore=t,this.runDir=n}artifactPath(e){return AC.join(this.runDir??"",e)}discardEvidence(e){for(let t of[e.screenshotPath,e.crashLogPath])if(t)try{Fs.rmSync(t,{force:!0})}catch(n){m(`Smoke: discard artifact failed (${t}): ${n.message}`)}this.runStore&&this.runDir&&this.runStore.discard(this.runDir)}finalizeRun(){this.runStore&&this.runDir&&this.runStore.finalize(this.runDir)}async collectScreenshotEvidence(e){let t=this.artifactPath(af(Date.now()));try{await this.screenshots.captureToPath(e.targetDeviceId,t)}catch(o){return this.skipBlank(`screenshot failed (${o.message})`)}if(!Fs.existsSync(t)||Fs.statSync(t).size<=32)return this.skipBlank("screenshot file missing or empty");let n=this.phash.analyzeFile(t);return n?{processAlive:!0,phashBlank:n.isBlank,phash:n.phash,phashHamming:n.hamming,screenshotPath:t}:this.skipBlank("failed to analyze screenshot",t)}skipBlank(e,t){return console.warn(Uo(`Smoke: ${e}; blank check skipped.`)),{processAlive:!0,phashBlank:null,screenshotPath:t,screenshotSkipped:!0}}async writeCrashLogFile(e){let t;try{t=await this.hilog.getLatestCrashLog(e.targetDeviceId,e.bundleName)}catch(n){console.warn(Uo(`Smoke: crash log query failed (${n.message}).`));return}if(!t?.trim()){console.warn(Uo("Smoke: no crash log found on device."));return}try{let n=this.artifactPath(cf(Date.now()));return Fs.writeFileSync(n,t,"utf8"),n}catch(n){console.warn(Uo(`Smoke: failed to save crash log (${n.message}).`));return}}};var $s=class{judge(e){if(!e.processAlive)return this.verdict("FAIL_CRASH","Application process died after launch (possible crash).",e);if(e.phashBlank===!0)return this.verdict("FAIL_BLANK",`Blank/solid screen after launch (hamming ${e.phashHamming} \u2264 ${Cl}, hash=${e.phash||"-"}).`,e);let t=e.phashBlank===null?"Process alive; screenshot unavailable, blank check skipped.":"Process alive; screenshot is not a solid blank screen.";return this.verdict("PASS",t,e)}verdict(e,t,n){return{status:e,reason:t,evidence:n,passed:e==="PASS"}}};var Hs=class{inspector;judge=new $s;formatter=new xs;constructor(e,t,n){let o=n??new Ze(e);this.inspector=new js(e,o,t)}async execute(e){let t=await this.inspector.collect(e),n=this.judge.judge(t);if(n.passed){this.inspector.discardEvidence(t),console.log(this.formatter.formatPass(n));return}throw this.inspector.finalizeRun(),this.formatter.toTraceError(n,e)}};async function Al(r){await new Hs(r.toolProvider,r.projectRoot,r.hdcAdapter).execute(r)}function Il(r){let e=r.indexOf("@"),t=e!==-1?r.substring(0,e):r,n=e!==-1?r.substring(e+1):"default";return{moduleName:t,targetName:n}}async function Us(r,e){let t=await r.listDevices();if(t.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");if(!e&&t.length>1){let o=await r.listDevicesWithName();throw new w("Multiple devices found. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+o.map(i=>` - ${i.name} (${i.serial})`).join(`
65
- `),"Multiple devices found.")}let n=await r.getDeviceInfo(t,e);if(!n)throw new Error("No active devices found.");if(!e){let o=await r.getDeviceName(n.serial);console.log(`Auto-selected device: ${o} (${n.serial})`)}return n.serial}function kl(r,e){if(e&&e.length>0)return e;let t=r.profile.modules.filter(n=>{let o=r.getModuleType(n.name);return o==="entry"||o==="feature"||o==="shared"});if(t.length===1){let n=t[0].name;return console.log(`Auto-selected module: ${n}`),[n]}throw new w(`Specify module(s) using --module <name> [<name>...].
72
+ `)return null;let t=8,r=0,i=0,o=0,s=0,a=[];for(;t+8<=e.length;){let c=e.readUInt32BE(t),l=e.subarray(t+4,t+8).toString("ascii"),d=e.subarray(t+8,t+8+c);if(t+=12+c,l==="IHDR")r=d.readUInt32BE(0),i=d.readUInt32BE(4),o=d[8],s=d[9];else if(l==="IDAT")a.push(d);else if(l==="IEND")break}return!r||!i||o!==8||s!==2&&s!==6?null:{width:r,height:i,colorType:s,idat:a}}pngScanlinesToRgb(e,t,r,i){let o=i===6?4:3,s=t*o,a=new Uint8Array(t*r*3),c=0,l=new Uint8Array(s),d=new Uint8Array(s);for(let g=0;g<r;g++){let w=e[c++];d.set(e.subarray(c,c+s)),c+=s,this.applyPngFilter(w,d,l,o);for(let R=0;R<t;R++){let z=(g*t+R)*3,ie=R*o;a[z]=d[ie],a[z+1]=d[ie+1],a[z+2]=d[ie+2]}l.set(d)}return a}applyPngFilter(e,t,r,i){for(let o=0;o<t.length;o++){let s=o>=i?t[o-i]:0,a=r[o],c=o>=i?r[o-i]:0;e===1?t[o]=t[o]+s&255:e===2?t[o]=t[o]+a&255:e===3?t[o]=t[o]+Math.floor((s+a)/2)&255:e===4&&(t[o]=t[o]+this.paeth(s,a,c)&255)}}paeth(e,t,r){let i=e+t-r,o=Math.abs(i-e),s=Math.abs(i-t),a=Math.abs(i-r);return o<=s&&o<=a?e:s<=a?t:r}static pngChunk(e,t,r){let i=Buffer.concat([Buffer.from(e,"ascii"),t]),o=Buffer.alloc(12+t.length);return o.writeUInt32BE(t.length,0),i.copy(o,4),o.writeUInt32BE(n.pngCrc(i,r),8+t.length),o}static pngCrcTable(){let e=new Uint32Array(256);for(let t=0;t<256;t++){let r=t;for(let i=0;i<8;i++)r=r&1?3988292384^r>>>1:r>>>1;e[t]=r>>>0}return e}static pngCrc(e,t){let r=4294967295;for(let i=0;i<e.length;i++)r=t[(r^e[i])&255]^r>>>8;return(r^4294967295)>>>0}};import wr from"fs";import It from"path";import{randomUUID as Tx}from"crypto";var Rx=/^smoke-screenshot-\d+\.png$/,Dx=/^smoke-crash-\d+\.log$/,xx=/^run-\d+-\d+-[0-9a-f]{4}$/;function tw(n){return`smoke-screenshot-${n}.png`}function rw(n){return`smoke-crash-${n}.log`}function nw(n){return Rx.test(n)||Dx.test(n)}var Ko="RUNNING",Yu="ENDED",Ax=1440*60*1e3,Ix=1440*60*1e3;function iw(n,e,t){return`run-${n}-${e}-${t}`}function ow(n){return xx.test(n)}function sw(n){try{let e=JSON.parse(n);if(typeof e.pid!="number"||typeof e.startedAt!="number"||!Number.isFinite(e.pid)||!Number.isFinite(e.startedAt))return null;let t={pid:e.pid,startedAt:e.startedAt};return typeof e.endedAt=="number"&&Number.isFinite(e.endedAt)&&(t.endedAt=e.endedAt),t}catch{}return null}function aw(n,e,t){return n===null?!0:n==="ended"?e?.endedAt===void 0?!0:t.now-e.endedAt>=Ax:!e||!Number.isInteger(e.pid)||e.pid<=0||t.now-e.startedAt>=Ix?!0:!t.isPidAlive(e.pid)}var Ox="smoke";function Mx(n){try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}var Xo=class{constructor(e,t=Mx){this.baseDir=e;this.isPidAlive=t;this.runsRoot=It.join(e,Ox)}runsRoot;static resolveBaseDir(e,t){return t??It.join(e,".hvigor")}createRun(){let e=It.join(this.runsRoot,iw(Date.now(),process.pid,Tx().slice(0,4)));wr.mkdirSync(e,{recursive:!0});let t={pid:process.pid,startedAt:Date.now()};return wr.writeFileSync(It.join(e,Ko),JSON.stringify(t),"utf8"),e}prune(e,t=Date.now()){this.pruneLegacyFlatArtifacts(),this.pruneEndedRuns(e,t)}finalize(e){try{let t=this.readMarker(e,Ko),r={pid:t?.pid??process.pid,startedAt:t?.startedAt??Date.now(),endedAt:Date.now()};wr.writeFileSync(It.join(e,Yu),JSON.stringify(r),"utf8"),wr.rmSync(It.join(e,Ko),{force:!0})}catch(t){m(`Smoke: finalize run failed (${e}): ${t.message}`)}}discard(e){try{wr.rmSync(e,{recursive:!0,force:!0})}catch(t){m(`Smoke: discard run failed (${e}): ${t.message}`)}}pruneLegacyFlatArtifacts(){let e;try{e=wr.readdirSync(this.baseDir,{withFileTypes:!0})}catch{return}for(let t of e)!t.isFile()||!nw(t.name)||this.removeQuietly(It.join(this.baseDir,t.name))}pruneEndedRuns(e,t){let r;try{r=wr.readdirSync(this.runsRoot,{withFileTypes:!0})}catch{return}for(let i of r){if(!i.isDirectory()||!ow(i.name))continue;let o=It.join(this.runsRoot,i.name);if(It.resolve(o)===It.resolve(e))continue;let s=this.readMarkerState(o);aw(s.kind,s.marker,{now:t,isPidAlive:this.isPidAlive})&&this.removeQuietly(o)}}readMarkerState(e){let t=this.readMarker(e,Yu);if(t!==void 0)return{kind:"ended",marker:t};let r=this.readMarker(e,Ko);return r!==void 0?{kind:"running",marker:r}:{kind:null,marker:null}}readMarker(e,t){try{return sw(wr.readFileSync(It.join(e,t),"utf8"))}catch(r){return r.code==="ENOENT"?void 0:null}}removeQuietly(e){try{wr.rmSync(e,{recursive:!0,force:!0})}catch(t){m(`Smoke: prune artifact failed (${e}): ${t.message}`)}}};var cw=3e3;function Lx(){let n=process.env.DEVECO_CLI_SMOKE_WAIT_MS;if(n===void 0||n==="")return cw;let e=Number(n);return Number.isFinite(e)&&e>=0?Math.floor(e):cw}var vc=class{constructor(e,t,r){this.hdc=t;this.projectRoot=r;this.hilog=new Br(e),this.screenshots=new $n(e)}phash=new yc;hilog;screenshots;runDir;runStore;async collect(e){this.openRun(e);let t=Lx();t>0&&await new Promise(i=>setTimeout(i,t));let r;try{r=await this.hdc.pidofBundle(e.targetDeviceId,e.bundleName)}catch(i){return console.warn(Zo(`Smoke: process check failed (${i.message}); smoke skipped.`)),{processAlive:!0,phashBlank:null,processCheckSkipped:!0}}return r?this.collectScreenshotEvidence(e):{processAlive:!1,phashBlank:null,crashLogPath:await this.writeCrashLogFile(e)}}openRun(e){let t=new Xo(Xo.resolveBaseDir(this.projectRoot,e.screenshotDir)),r=t.createRun();t.prune(r),this.runStore=t,this.runDir=r}artifactPath(e){return Nx.join(this.runDir??"",e)}discardEvidence(e){for(let t of[e.screenshotPath,e.crashLogPath])if(t)try{wc.rmSync(t,{force:!0})}catch(r){m(`Smoke: discard artifact failed (${t}): ${r.message}`)}this.runStore&&this.runDir&&this.runStore.discard(this.runDir)}finalizeRun(){this.runStore&&this.runDir&&this.runStore.finalize(this.runDir)}async collectScreenshotEvidence(e){let t=this.artifactPath(tw(Date.now()));try{await this.screenshots.captureToPath(e.targetDeviceId,t)}catch(i){return this.skipBlank(`screenshot failed (${i.message})`)}if(!wc.existsSync(t)||wc.statSync(t).size<=32)return this.skipBlank("screenshot file missing or empty");let r=this.phash.analyzeFile(t);return r?{processAlive:!0,phashBlank:r.isBlank,phash:r.phash,phashHamming:r.hamming,screenshotPath:t}:this.skipBlank("failed to analyze screenshot",t)}skipBlank(e,t){return console.warn(Zo(`Smoke: ${e}; blank check skipped.`)),{processAlive:!0,phashBlank:null,screenshotPath:t,screenshotSkipped:!0}}async writeCrashLogFile(e){let t;try{t=await this.hilog.getLatestCrashLog(e.targetDeviceId,e.bundleName)}catch(r){console.warn(Zo(`Smoke: crash log query failed (${r.message}).`));return}if(!t?.trim()){console.warn(Zo("Smoke: no crash log found on device."));return}try{let r=this.artifactPath(rw(Date.now()));return wc.writeFileSync(r,t,"utf8"),r}catch(r){console.warn(Zo(`Smoke: failed to save crash log (${r.message}).`));return}}};var bc=class{judge(e){if(!e.processAlive)return this.verdict("FAIL_CRASH","Application process died after launch (possible crash).",e);if(e.phashBlank===!0)return this.verdict("FAIL_BLANK",`Blank/solid screen after launch (hamming ${e.phashHamming} \u2264 ${Ju}, hash=${e.phash||"-"}).`,e);let t=e.phashBlank===null?"Process alive; screenshot unavailable, blank check skipped.":"Process alive; screenshot is not a solid blank screen.";return this.verdict("PASS",t,e)}verdict(e,t,r){return{status:e,reason:t,evidence:r,passed:e==="PASS"}}};var Sc=class{inspector;judge=new bc;formatter=new ec;constructor(e,t,r){let i=r??new de(e);this.inspector=new vc(e,i,t)}async execute(e){let t=await this.inspector.collect(e),r=this.judge.judge(t);if(r.passed){this.inspector.discardEvidence(t),console.log(this.formatter.formatPass(r));return}throw this.inspector.finalizeRun(),this.formatter.toTraceError(r,e)}};async function Ku(n){await new Sc(n.toolProvider,n.projectRoot,n.hdcAdapter).execute(n)}function Xu(n){let e=n.indexOf("@"),t=e!==-1?n.substring(0,e):n,r=e!==-1?n.substring(e+1):"default";return{moduleName:t,targetName:r}}async function Pc(n,e){let t=await n.listDevices();if(t.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");if(!e&&t.length>1){let i=await n.listDevicesWithName();throw new y("Multiple devices found. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+i.map(o=>` - ${o.name} (${o.serial})`).join(`
73
+ `),"Multiple devices found.")}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let i=await n.getDeviceName(r.serial);console.log(`Auto-selected device: ${i} (${r.serial})`)}return r.serial}function Zu(n,e){if(e&&e.length>0)return e;let t=n.profile.modules.filter(r=>{let i=n.getModuleType(r.name);return i==="entry"||i==="feature"||i==="shared"});if(t.length===1){let r=t[0].name;return console.log(`Auto-selected module: ${r}`),[r]}throw new y(`Specify module(s) using --module <name> [<name>...].
66
74
  Available runnable modules:
67
- `+t.map(n=>` - ${n.name}`).join(`
68
- `),"Specify module error.")}function hf(r,e,t){if(t)return t;let n=e.find(({moduleName:i})=>r.getModuleType(i)==="entry");if(n)return r.getMainAbility(n.moduleName);let o=e.find(({moduleName:i})=>r.getModuleType(i)==="feature");if(o)return r.getMainAbility(o.moduleName)}async function gf(r,e,t,n,o,i){if(i&&(console.log(`Uninstalling ${t}...`),await r.uninstallApp(e,t)||console.log(`App ${t} not installed; skipping uninstallation.`)),console.log(`
69
- Installing artifacts to device ${e}...`),await r.installApp(e,n),o){console.log(`Launching ${t}/${o}...`);let s=await r.launchApp(e,t,o);console.log(Wo(`
75
+ `+t.map(r=>` - ${r.name}`).join(`
76
+ `),"Specify module error.")}function lw(n,e,t){if(t)return t;let r=e.find(({moduleName:o})=>n.getModuleType(o)==="entry");if(r)return n.getMainAbility(r.moduleName);let i=e.find(({moduleName:o})=>n.getModuleType(o)==="feature");if(i)return n.getMainAbility(i.moduleName)}async function dw(n,e,t,r,i,o){if(o&&(console.log(`Uninstalling ${t}...`),await n.uninstallApp(e,t)||console.log(`App ${t} not installed; skipping uninstallation.`)),console.log(`
77
+ Installing artifacts to device ${e}...`),await n.installApp(e,r),i){console.log(`Launching ${t}/${i}...`);let s=await n.launchApp(e,t,i);console.log(Qo(`
70
78
  Application '${t}': ${s}`))}else console.log(`
71
- Application '${t}' installed successfully (no ability to launch).`)}function TC(r){let e={event:S.CommandExecuted,args:["run",...r.module?["--module"]:[],...r.device?["--device"]:[],...r.product?["--product"]:[],...r.buildMode?["--build-mode"]:[],...r.ability?["--ability"]:[],...r.uninstall?["--uninstall"]:[],...r.skipBuild?["--skip-build"]:[],...r.apply?["--apply"]:[],...r.hotreload?["--hotreload"]:[],...r.hotreloadApply?["--hotreload-apply"]:[]]};return r.buildMode&&(e.build_mode=r.buildMode),r.module&&(e.module_count=r.module.length),e}var RC=new kC("run").description("Build and run the project on a connected device").option("--module <modules...>","Module(s) to run (format: module or module@target)").option("--device <device>","Target device name or serial").option("--product <product>","Product name (default: default)").option("--build-mode <mode>","Build mode (options: debug, release; default: debug)").option("--ability <ability>","Ability name to launch").option("--uninstall","Uninstall existing app before installation").option("--skip-build","Skip build step and deploy existing artifacts").option("--apply <fileName>","Quick-apply changed files via quickfix (incremental hqf) and restart. <fileName> under project .hvigor/").option("--hotreload [action]",'Start hot-reload mode (build+deploy with daemon, then exit). Use "stop" to shut down the hvigor daemon.').option("--hotreload-apply <fileName>","Hot-reload changed files (.hvigor/<fileName> list) via daemon hot compile + signed hqf + quickfix, without restarting the app.").action(async r=>{let e=TC(r),t=Date.now(),n=!0,o=null;try{let i=await LC(r,e);i&&(i.ohpmMemoryMb&&(e.ohpm_install_memory=i.ohpmMemoryMb),i.syncMemoryMb&&(e.hvigor_sync_memory=i.syncMemoryMb),i.buildMemoryMb&&(e.hvigor_build_memory=i.buildMemoryMb))}catch(i){n=!1,o=q(i),console.error(DC(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:n,error_code:o};await I.track(e,i)}});async function xC(r,e,t,n,o){let i=new En(e,r.rootDir),s=new Ke(e,r.rootDir),a=new Set,c=new Set;for(let{moduleName:b,targetName:N}of t)for(let $ of r.collectNonHarDependentModuleList(b))a.add(`${$}@${N}`),c.add($);let l=[...a],d=cl(r,l),g={type:"modules",modulesToBuild:l,moduleTasks:d};for(let b of c)As.generate(r.rootDir,b,n,e);let y=await Jr(r.rootDir,()=>ll(i,s,n,o,g,r.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion..."));return console.log(`
72
- `+Wo("Build completed successfully.")),y}async function LC(r,e){let t=V.discover(process.cwd());console.warn(Bs("Ensure the project source is trusted before proceeding."));let n=await k.new();if(r.skipBuild||n.assertJava(),e.bundle_name=t.getBundleName(),r.hotreloadApply){await MC(r,t,n);return}if(r.hotreload){await OC(r,t,n);return}if(r.apply){await FC(r,t,n);return}return yf(r,t,n)}async function NC(r,e,t){r.onSocketDisconnect(()=>{console.log("Daemon disconnected (likely via --hotreload stop). Exiting watch session."),process.exit(0)});let n=new Ke(e,t.rootDir),o=setInterval(async()=>{await n.isDaemonAlive()||(clearInterval(o),console.log("Daemon stopped (via --hotreload stop). Exiting watch session."),process.exit(0))},3e3);await new Promise(()=>{})}async function OC(r,e,t){if(r.hotreload==="stop"){await Bm(t,e);return}let o=kl(e,r.module).map(Il),{moduleName:i,targetName:s}=o[0];vl(r.module,i);let a=new Ze(t),c=ue.from(t),l=await Us(c,r.device),d=l.includes("127.0.0.1")||l.includes("localhost"),g=r.product||"default";e.validateProduct(g);let y=e.getBundleName(g),b=hf(e,o,r.ability);Is.generate(e.rootDir,i,g,t);let N=new Ke(t,e.rootDir);console.log(Wo("Ensuring hvigor daemon is running (via --sync --daemon, no hap build)...")),await N.ensureDaemonRunning();let $=[`${i}@${g}`];for(let Pt of e.collectNonHarDependentModuleList(i))$.includes(`${Pt}@${g}`)||$.push(`${Pt}@${g}`);console.log(Wo("Building hap + starting watch session (socket -> CommonBuild assembleHap --hot-reload-build --watch, kept open)..."));let me=new Dn(e.rootDir,t);await me.startWatchSession({moduleSpecs:$,productName:g});let Te=Hm(e,i,s,d,g);await gf(a,l,y,Te,b,!!r.uninstall),console.log(Wo("Hot-reload watch session active (socket persistent). Edit code, write .hvigor/<file>, then `devecocli run --hotreload-apply <file>` in another terminal. Ctrl+C here to stop.")),await NC(me,t,e)}async function MC(r,e,t){let n=r.hotreloadApply;if(!n)throw new Error("hotreload-apply requires --hotreload-apply <fileName> (under .hvigor/)");if(Vo.basename(n)!==n)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n}`);let o=kl(e,r.module),{moduleName:i}=Il(o[0]);vl(r.module,i);let s=ue.from(t),a=await Us(s,r.device),c=r.product||"default";e.validateProduct(c);let l=e.getBundleName(c);$m(e,i,n);let d=[`${i}@${c}`],g=await jm({applyFileName:n,projectPath:e.rootDir,moduleName:i,productName:c,bundleName:l,toolProvider:t,targetDeviceId:a,moduleSpecs:d});if(!g.success)throw new Error(g.message)}function _C(r,e,t,n){let o=new Set;for(let{moduleName:i,targetName:s}of e)for(let a of r.collectNonHarDependentModuleList(i)){o.add(r.findArtifactPath(a,s,t,n));for(let c of r.findRemoteHspPaths(a,s,n))o.add(c)}return[...o]}async function yf(r,e,t){let o=kl(e,r.module).map(Il);for(let{moduleName:$}of o){let me=e.getModuleType($);if(me!=="entry"&&me!=="feature"&&me!=="shared")throw new w(`Module '${$}' '${me}' is not runnable. Specify an entry or feature module.`,"Module is not runnable.")}let i=new Ze(t),s=ue.from(t),a=await Us(s,r.device),c=a.includes("127.0.0.1")||a.includes("localhost"),l=r.product||"default";e.validateProduct(l);let d=r.buildMode||"debug",g;r.skipBuild||(g=await xC(e,t,o,l,d));let y=_C(e,o,c,l),b=e.getBundleName(l),N=hf(e,o,r.ability);return await gf(i,a,b,y,N,!!r.uninstall),N&&await Al({toolProvider:t,projectRoot:e.rootDir,hdcAdapter:i,targetDeviceId:a,bundleName:b}),g}async function FC(r,e,t){let n=r.apply;if(!n)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(Vo.basename(n)!==n)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n}`);let o=Vo.join(e.rootDir,".hvigor",n),i=ue.from(t),s=await Us(i,r.device),a=r.product||"default";e.validateProduct(a);let c=e.getBundleName(a),l=e.profile.modules.find(y=>e.getModuleType(y.name)==="entry")?.name,d=l?e.getMainAbility(l,r.ability):r.ability||"EntryAbility",g=new Ps(t,e.rootDir);try{await g.execute({applyFile:o,productName:a,targetDeviceId:s,bundleName:c,abilityName:d})}catch(y){console.warn(Bs(`[Apply] failed: ${y.message}`)),console.warn(Bs('[Apply] Falling back to full "devecocli run"...')),await yf(r,e,t);return}console.log(Bs('[Apply] Done. If changes did not take effect, check <module>/build/config/buildConfig.json for content, or run "devecocli run" for a full build.')),await Al({toolProvider:t,projectRoot:e.rootDir,targetDeviceId:s,bundleName:c})}var vf=RC;import{Command as ZC}from"commander";import*as If from"path";import{green as Cf,red as Pf,cyan as xl}from"colorette";import{execa as Nl}from"execa";import{spawn as BC}from"child_process";import*as Ef from"fs";import*as Ws from"path";import{yellow as UC}from"colorette";import WC from"proper-lockfile";import*as dr from"fs";import*as wf from"path";import{homedir as jC}from"os";var $C="deveco-cli",Dl,rn=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function Sf(){let r=process.env.DEVECO_CLI_DATA_DIR,t=(r===void 0||r===""?"":Kc(r))||wf.join(jC(),".local","share",$C);try{return ps(t)}catch(n){throw new rn(n instanceof Error?n.message:String(n))}}async function bf(){let r=Sf();await dr.promises.mkdir(r,{recursive:!0});let e;try{e=await dr.promises.realpath(r)}catch(n){throw new rn(`DEVECO_CLI_DATA_DIR is not usable: ${n instanceof Error?n.message:String(n)}`)}if(!(await dr.promises.stat(e)).isDirectory())throw new rn("DEVECO_CLI_DATA_DIR must be a writable directory.");return Dl=e,e}function ct(){if(Dl!==void 0)return Dl;let r=Sf();try{if(dr.existsSync(r))return dr.realpathSync(r)}catch{}return r}function Go(){return process.env.DEVECO_CLI_WRAPPER_NAME?process.env.DEVECO_CLI_WRAPPER_NAME:"@deveco-test/deveco-cli-common"}function ur(){return process.env.DEVECO_CLI_WRAPPER_VERSION?process.env.DEVECO_CLI_WRAPPER_VERSION:"0.1.7"}function Ln(){return"tmp"}function Nn(){let r=process.env.DEVECO_CLI_DISABLE_UPDATE;return r==="check"||r==="all"?r:"off"}import*as zo from"fs";import*as qo from"path";var HC={lastCheckedTimestamp:null,latestVersion:null,blockedVersions:[],checkError:null},Tl=new Map,pr=class r{static CHECK_WINDOW_HOUR=21;static ONE_DAY_MS=1440*60*1e3;cacheFilePath;lockFilePath;constructor(e){this.cacheFilePath=qo.join(e,"cache.json"),this.lockFilePath=qo.join(e,"check.lock")}async writeSuccess(e,t=[],n,o){await this.write({lastCheckedTimestamp:Date.now(),latestVersion:e,blockedVersions:t,checkError:null,checkedAgainstVersion:n,checkedAgainstTag:o})}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}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=Tl.get(this.cacheFilePath);if(e)return e;try{let t=zo.readFileSync(this.cacheFilePath,"utf-8"),n=JSON.parse(t);return Tl.set(this.cacheFilePath,n),n}catch{return{...HC}}}async write(e){m(()=>`Writing update cache: lastChecked=${e.lastCheckedTimestamp}, latest=${e.latestVersion}, blocked=[${e.blockedVersions.join(",")}], error=${e.checkError}`),await zo.promises.mkdir(qo.dirname(this.cacheFilePath),{recursive:!0}),await zo.promises.writeFile(this.cacheFilePath,JSON.stringify(e,null,2),"utf-8"),Tl.set(this.cacheFilePath,e)}};var Jo=class{constructor(e){this.actionCommand=e}cache=new pr(Ws.join(ct(),"update"));async checkAndNotify(){if(!this.shouldSkip())try{let e=ur(),t=Ln(),n=this.cache.getCheckedAgainstVersion(),o=this.cache.getCheckedAgainstTag(),i=o!=null&&o!==t,s=n!=null&&n!==e,a=i?null:this.cache.getLatestVersion();a&&Fp(a,e)>0&&(console.log(),console.log(UC(`New version ${a} available, run \`devecocli update\` to upgrade`))),(i||s||this.cache.isCheckNeeded())&&await this.spawnBackgroundCheck()}catch(e){m(`Update check failed: ${e instanceof Error?e.message:String(e)}`)}}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 VC(this.cache.getLockPath(),()=>{let e=[process.argv[1],"update","_check"];m(`Executing: ${process.execPath} ${e.join(" ")}`),BC(process.execPath,e,{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1"}}).unref()})}catch{m("Update check lock held by another process, skipping")}}};async function VC(r,e){await Ef.promises.mkdir(Ws.dirname(r),{recursive:!0});let t=await WC.lock(r,{stale:6e4,retries:0,realpath:!1});try{await e()}finally{await t()}}import*as Vs from"fs";import*as On from"path";import{execa as GC}from"execa";import{yellow as zC}from"colorette";function qC(r){return r?r.endsWith(".ts"):!0}function JC(r,e){let t=On.join(r,"package.json");try{return JSON.parse(Vs.readFileSync(t,"utf8")).name===e}catch{return!1}}function YC(r,e){let t;try{t=On.dirname(Vs.realpathSync(r))}catch{return null}for(let n=0;n<20&&t&&t!==On.dirname(t);n++){if(JC(t,e))return t;t=On.dirname(t)}return null}async function KC(){try{m("Executing: npm root -g");let{stdout:r}=await GC("npm",["root","-g"]);return r.trim()||null}catch(r){return m(`[install-check] npm root -g failed: ${r instanceof Error?r.message:String(r)}`),null}}function XC(r,e){return xo(r,e)}async function Rl(r){if(process.env.DEVECO_CLI_SKIP_INSTALL_CHECK)return;let e=process.argv[1];if(qC(e))return;let t=await KC();if(!t)return;let n=YC(e,r);if(!n){m("[install-check] running package root not found, skipping");return}XC(n,t)||(console.log(),console.log(zC(`Warning: devecocli is running from
73
- ${n}
79
+ Application '${t}' installed successfully (no ability to launch).`)}function Fx(n){let e={event:v.CommandExecuted,args:["run",...n.module?["--module"]:[],...n.device?["--device"]:[],...n.product?["--product"]:[],...n.buildMode?["--build-mode"]:[],...n.ability?["--ability"]:[],...n.uninstall?["--uninstall"]:[],...n.skipBuild?["--skip-build"]:[],...n.apply?["--apply"]:[],...n.hotreload?["--hotreload"]:[],...n.hotreloadApply?["--hotreload-apply"]:[]]};return n.buildMode&&(e.build_mode=n.buildMode),n.module&&(e.module_count=n.module.length),e}var jx=new _x("run").description("Build and run the project on a connected device").option("--module <modules...>","Module(s) to run (format: module or module@target)").option("--device <device>","Target device name or serial").option("--product <product>","Product name (default: default)").option("--build-mode <mode>","Build mode (options: debug, release; default: debug)").option("--ability <ability>","Ability name to launch").option("--uninstall","Uninstall existing app before installation").option("--skip-build","Skip build step and deploy existing artifacts").option("--apply <fileName>","Quick-apply changed files via quickfix (incremental hqf) and restart. <fileName> under project .hvigor/").option("--hotreload [action]",'Start hot-reload mode (build+deploy with daemon, then exit). Use "stop" to shut down the hvigor daemon.').option("--hotreload-apply <fileName>","Hot-reload changed files (.hvigor/<fileName> list) via daemon hot compile + signed hqf + quickfix, without restarting the app.").action(async n=>{let e=Fx(n),t=Date.now(),r=!0,i=null;try{let o=await Ux(n,e);o&&(o.ohpmMemoryMb&&(e.ohpm_install_memory=o.ohpmMemoryMb),o.syncMemoryMb&&(e.hvigor_sync_memory=o.syncMemoryMb),o.buildMemoryMb&&(e.hvigor_build_memory=o.buildMemoryMb))}catch(o){r=!1,i=X(o),console.error($x(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await D.track(e,o)}});async function Hx(n,e,t,r,i){let o=new yi(e,n.rootDir),s=new dt(e,n.rootDir),a=new Set,c=new Set;for(let{moduleName:R,targetName:z}of t)for(let ie of n.collectNonHarDependentModuleList(R))a.add(`${ie}@${z}`),c.add(ie);let l=[...a],d=wu(n,l),g={type:"modules",modulesToBuild:l,moduleTasks:d};for(let R of c)Ja.generate(n.rootDir,R,r,e);let w=await Tn(n.rootDir,()=>vu(o,s,r,i,g,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion..."));return console.log(`
80
+ `+Qo("Build completed successfully.")),w}async function Ux(n,e){let t=B.discover(process.cwd());console.warn(Ec("Ensure the project source is trusted before proceeding."));let r=await P.new();if(n.skipBuild||r.assertJava(),e.bundle_name=t.getBundleName(),n.hotreloadApply){await Vx(n,t,r);return}if(n.hotreload){await Wx(n,t,r);return}if(n.apply){await qx(n,t,r);return}return uw(n,t,r)}async function Bx(n,e,t){n.onSocketDisconnect(()=>{console.log("Daemon disconnected (likely via --hotreload stop). Exiting watch session."),process.exit(0)});let r=new dt(e,t.rootDir),i=setInterval(async()=>{await r.isDaemonAlive()||(clearInterval(i),console.log("Daemon stopped (via --hotreload stop). Exiting watch session."),process.exit(0))},3e3);await new Promise(()=>{})}async function Wx(n,e,t){if(n.hotreload==="stop"){await Jg(t,e);return}let i=Zu(e,n.module).map(Xu),{moduleName:o,targetName:s}=i[0];xu(n.module,o);let a=new de(t),c=le.from(t),l=await Pc(c,n.device),d=l.includes("127.0.0.1")||l.includes("localhost"),g=n.product||"default";e.validateProduct(g);let w=e.getBundleName(g),R=lw(e,i,n.ability);Ya.generate(e.rootDir,o,g,t);let z=new dt(t,e.rootDir);console.log(Qo("Ensuring hvigor daemon is running (via --sync --daemon, no hap build)...")),await z.ensureDaemonRunning();let ie=[`${o}@${g}`];for(let Cn of e.collectNonHarDependentModuleList(o))ie.includes(`${Cn}@${g}`)||ie.push(`${Cn}@${g}`);console.log(Qo("Building hap + starting watch session (socket -> CommonBuild assembleHap --hot-reload-build --watch, kept open)..."));let at=new ki(e.rootDir,t);await at.startWatchSession({moduleSpecs:ie,productName:g});let Wt=zg(e,o,s,d,g);await dw(a,l,w,Wt,R,!!n.uninstall),console.log(Qo("Hot-reload watch session active (socket persistent). Edit code, write .hvigor/<file>, then `devecocli run --hotreload-apply <file>` in another terminal. Ctrl+C here to stop.")),await Bx(at,t,e)}async function Vx(n,e,t){let r=n.hotreloadApply;if(!r)throw new Error("hotreload-apply requires --hotreload-apply <fileName> (under .hvigor/)");if(es.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let i=Zu(e,n.module),{moduleName:o}=Xu(i[0]);xu(n.module,o);let s=le.from(t),a=await Pc(s,n.device),c=n.product||"default";e.validateProduct(c);let l=e.getBundleName(c);qg(e,o,r);let d=[`${o}@${c}`],g=await Gg({applyFileName:r,projectPath:e.rootDir,moduleName:o,productName:c,bundleName:l,toolProvider:t,targetDeviceId:a,moduleSpecs:d});if(!g.success)throw new Error(g.message)}function Gx(n,e,t,r){let i=new Set;for(let{moduleName:o,targetName:s}of e)for(let a of n.collectNonHarDependentModuleList(o)){i.add(n.findArtifactPath(a,s,t,r));for(let c of n.findRemoteHspPaths(a,s,r))i.add(c)}return[...i]}async function uw(n,e,t){let i=Zu(e,n.module).map(Xu);for(let{moduleName:ie}of i){let at=e.getModuleType(ie);if(at!=="entry"&&at!=="feature"&&at!=="shared")throw new y(`Module '${ie}' '${at}' is not runnable. Specify an entry or feature module.`,"Module is not runnable.")}let o=new de(t),s=le.from(t),a=await Pc(s,n.device),c=a.includes("127.0.0.1")||a.includes("localhost"),l=n.product||"default";e.validateProduct(l);let d=n.buildMode||"debug",g;n.skipBuild||(g=await Hx(e,t,i,l,d));let w=Gx(e,i,c,l),R=e.getBundleName(l),z=lw(e,i,n.ability);return await dw(o,a,R,w,z,!!n.uninstall),z&&await Ku({toolProvider:t,projectRoot:e.rootDir,hdcAdapter:o,targetDeviceId:a,bundleName:R}),g}async function qx(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(es.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let i=es.join(e.rootDir,".hvigor",r),o=le.from(t),s=await Pc(o,n.device),a=n.product||"default";e.validateProduct(a);let c=e.getBundleName(a),l=e.profile.modules.find(w=>e.getModuleType(w.name)==="entry")?.name,d=l?e.getMainAbility(l,n.ability):n.ability||"EntryAbility",g=new za(t,e.rootDir);try{await g.execute({applyFile:i,productName:a,targetDeviceId:s,bundleName:c,abilityName:d})}catch(w){console.warn(Ec(`[Apply] failed: ${w.message}`)),console.warn(Ec('[Apply] Falling back to full "devecocli run"...')),await uw(n,e,t);return}console.log(Ec('[Apply] Done. If changes did not take effect, check <module>/build/config/buildConfig.json for content, or run "devecocli run" for a full build.')),await Ku({toolProvider:t,projectRoot:e.rootDir,targetDeviceId:s,bundleName:c})}var pw=jx;import{Command as yA}from"commander";import*as ip from"path";import{red as vw,cyan as Ac,yellow as rp}from"colorette";import{execa as Ic}from"execa";import{spawn as eA}from"child_process";import*as gw from"fs";import*as kc from"path";import{yellow as tA,cyan as rA}from"colorette";import nA from"proper-lockfile";function Mi(){return process.env.DEVECO_CLI_WRAPPER_NAME?process.env.DEVECO_CLI_WRAPPER_NAME:"@deveco-test/deveco-cli-common"}function Zt(){return process.env.DEVECO_CLI_WRAPPER_VERSION?process.env.DEVECO_CLI_WRAPPER_VERSION:"1.3.6-Test.1"}function Gr(){return"daily"}function Tt(){return Number.isFinite(1),1}var vr="@deveco-test/deveco-cli-knowledgebase";function Ni(){let n=process.env.DEVECO_CLI_DISABLE_UPDATE;return n==="check"||n==="all"?n:"off"}import*as ts from"fs";import*as rs from"path";var zx={lastCheckedTimestamp:null,latestVersion:null,blockedVersions:[],checkError:null,latestDocsVersion:null,latestDocsApiVersion:null,latestCompatibleDocsVersion:null,checkedAgainstDocsApi:null},Qu=new Map,qr=class n{static CHECK_WINDOW_HOUR=21;static ONE_DAY_MS=1440*60*1e3;cacheFilePath;lockFilePath;constructor(e){this.cacheFilePath=rs.join(e,"cache.json"),this.lockFilePath=rs.join(e,"check.lock")}async writeSuccess(e,t=[],r,i,o){let s=this.read();await this.write({lastCheckedTimestamp:Date.now(),latestVersion:e,blockedVersions:t,checkError:null,checkedAgainstVersion:r,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(n.CHECK_WINDOW_HOUR,0,0,0),r=t>Date.now()?t-n.ONE_DAY_MS:t;return e<r}getLockPath(){return this.lockFilePath}read(){let e=Qu.get(this.cacheFilePath);if(e)return e;try{let t=ts.readFileSync(this.cacheFilePath,"utf-8"),r=JSON.parse(t);return Qu.set(this.cacheFilePath,r),r}catch{return{...zx}}}async write(e){m(()=>`Writing update cache: lastChecked=${e.lastCheckedTimestamp}, latest=${e.latestVersion}, blocked=[${e.blockedVersions.join(",")}], error=${e.checkError}`),await ts.promises.mkdir(rs.dirname(this.cacheFilePath),{recursive:!0}),await ts.promises.writeFile(this.cacheFilePath,JSON.stringify(e,null,2),"utf-8"),Qu.set(this.cacheFilePath,e)}};import{createRequire as Jx}from"module";import{dirname as Yx,join as Li}from"path";import{pathToFileURL as Kx}from"url";import{readFile as mw,access as ep}from"fs/promises";import*as fw from"semver";var Xx=Jx(import.meta.url);async function Zx(){try{let n=Xx.resolve("@deveco-test/deveco-cli-knowledgebase/package.json"),e=JSON.parse(await mw(n,"utf8"));return{version:e.version,apiVersion:e.apiVersion??0,dir:Yx(n)}}catch{return null}}async function hw(){let n=W(),e=Li(n,"doc-data","current.json"),t;try{t=JSON.parse(await mw(e,"utf8"))}catch{return null}let r=Li(n,"doc-data",t.version);try{return await ep(Li(r,"dist","engine","index.js")),await ep(Li(r,"docs.zip")),await ep(Li(r,"index.zip")),{version:t.version,apiVersion:t.apiVersion,dir:r}}catch{return null}}async function Qx(){return[await hw(),await Zx()].filter(e=>e!==null).sort((e,t)=>fw.rcompare(e.version,t.version))}async function _i(){let n=Tt(),e=await hw();return e&&e.apiVersion<=n?e.version:null}async function Cc(){let n=Tt(),e=await Qx(),t=!1;for(let r of e){if(r.apiVersion>n){m(`docs: skip candidate v${r.version} (apiVersion ${r.apiVersion} > ${n})`);continue}t=!0;try{let i=Li(r.dir,"dist","engine","index.js");return await import(Kx(i).href)}catch(i){m(`docs: candidate v${r.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 ns=class{constructor(e){this.actionCommand=e}cache=new qr(kc.join(W(),"update"));async checkAndNotify(){if(!this.shouldSkip())try{let e=Zt(),t=Gr(),r=this.cache.getCheckedAgainstVersion(),i=this.cache.getCheckedAgainstTag(),o=i!=null&&i!==t,s=r!=null&&r!==e,a=[],c=o?null:this.cache.getLatestVersion();c&&_r(c,e)>0&&a.push(tA(`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){m(`Update check failed: ${e instanceof Error?e.message:String(e)}`)}}async buildDocsMessage(){let e=Tt(),t=this.cache.getCheckedAgainstDocsApi();if(t!=null&&t!==e)return{message:null,stale:!0};let r=this.cache.getLatestCompatibleDocsVersion();if(!r)return{message:null,stale:!1};let i=await _i();return i&&_r(r,i)<=0?{message:null,stale:!1}:{message:rA(`New docs version ${r} 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 iA(this.cache.getLockPath(),()=>{let e=[process.argv[1],"update","_check"];m(`Executing: ${process.execPath} ${e.join(" ")}`),eA(process.execPath,e,{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1"}}).unref()})}catch{m("Update check lock held by another process, skipping")}}};async function iA(n,e){await gw.promises.mkdir(kc.dirname(n),{recursive:!0});let t=await nA.lock(n,{stale:6e4,retries:0,realpath:!1});try{await e()}finally{await t()}}import{execa as oA}from"execa";function Rc(n){return Array.isArray(n)?n[0]:n}async function $i(n){let e=Gr();m(`Executing: npm view ${vr}@${e} --json`);let{stdout:t}=await oA("npm",["view",`${vr}@${e}`,"--json"]),r=Rc(JSON.parse(t)),i=typeof r.version=="string"?r.version.trim():r["dist-tags"]?.[e]?.trim();if(!i)throw new Error(`Could not resolve version for ${vr}@${e}`);let o=r.versions?.[i],s=r.dist??o?.dist;if(!s)throw new Error(`Could not resolve dist for ${vr}@${e}`);let a=r.apiVersion??o?.apiVersion??0,c={version:i,apiVersion:a,dist:s};return c.apiVersion<=n?{latest:c,compatible:c}:{latest:c,compatible:null}}import{execa as yw}from"execa";import*as Ot from"path";import*as ge from"fs/promises";import*as ww from"crypto";async function sA(n,e){let t=`${n}.tmp.${process.pid}`;await ge.writeFile(t,JSON.stringify(e,null,2),"utf-8"),await ge.rename(t,n)}function aA(n,e){let t=e.indexOf("-");if(t<0)return!1;let r=e.slice(0,t),i=e.slice(t+1);if(r!=="sha512")return!1;let o=Buffer.from(i,"base64");return ww.createHash(r).update(n).digest().equals(o)}async function cA(n,e,t){m(`Executing: npm pack ${vr}@${n}`);let{stdout:r}=await yw("npm",["pack",`${vr}@${n}`],{cwd:t}),i=r.trim().split(`
81
+ `).pop(),o=Ot.join(t,i),s=await ge.readFile(o);if(!aA(s,e))throw await ge.unlink(o).catch(()=>{}),new Error("Documentation package integrity verification failed");return o}async function lA(n,e,t){let r=Ot.join(t,e),i=Ot.join(t,`.tmp-${e}-${process.pid}`);return await ge.rm(r,{recursive:!0,force:!0}),await ge.rm(i,{recursive:!0,force:!0}),await ge.mkdir(i,{recursive:!0}),m(`Executing: tar -xzf ${Ot.basename(n)} -C ${i}`),await yw("tar",["-xzf",n,"-C",i]),await ge.rename(Ot.join(i,"package"),r),await ge.rm(i,{recursive:!0,force:!0}),await ge.unlink(n).catch(()=>{}),await ge.access(Ot.join(r,"dist","engine","index.js")),await ge.access(Ot.join(r,"docs.zip")),await ge.access(Ot.join(r,"index.zip")),r}async function Dc(n,e,t){await ge.mkdir(e,{recursive:!0});let r=await cA(n.version,n.dist.integrity,e);return await lA(r,n.version,e),await sA(Ot.join(e,"current.json"),{version:n.version,apiVersion:n.apiVersion,installedAt:Date.now(),installedBy:t}),{version:n.version,apiVersion:n.apiVersion}}import*as xc from"fs";import*as Fi from"path";import{execa as dA}from"execa";import{yellow as uA}from"colorette";function pA(n){return n?n.endsWith(".ts"):!0}function mA(n,e){let t=Fi.join(n,"package.json");try{return JSON.parse(xc.readFileSync(t,"utf8")).name===e}catch{return!1}}function fA(n,e){let t;try{t=Fi.dirname(xc.realpathSync(n))}catch{return null}for(let r=0;r<20&&t&&t!==Fi.dirname(t);r++){if(mA(t,e))return t;t=Fi.dirname(t)}return null}async function hA(){try{m("Executing: npm root -g");let{stdout:n}=await dA("npm",["root","-g"]);return n.trim()||null}catch(n){return m(`[install-check] npm root -g failed: ${n instanceof Error?n.message:String(n)}`),null}}function gA(n,e){return ou(n,e)}async function tp(n){if(process.env.DEVECO_CLI_SKIP_INSTALL_CHECK)return;let e=process.argv[1];if(pA(e))return;let t=await hA();if(!t)return;let r=fA(e,n);if(!r){m("[install-check] running package root not found, skipping");return}gA(r,t)||(console.log(),console.log(uA(`Warning: devecocli is running from
82
+ ${r}
74
83
  but \`npm\` in PATH installs global packages to
75
84
  ${t}
76
85
  The devecocli binary in PATH does not match the npm that \`devecocli update\` uses.
77
86
  The update would land in the wrong place and would not reach the binary you are running.
78
87
  Continuing with update \u2014 abort if this is unexpected.
79
- Fix: run \`which -a devecocli\` (Windows: \`where devecocli\`) to list all shims, remove the stale one, or reinstall with the matching npm: \`npm install -g ${r}@latest\`.`)))}var Ol=new ZC("update").description("Update deveco-cli to latest");Ol.command("_check",{hidden:!0}).action(async()=>{let r=Date.now(),e=new pr(If.join(ct(),"update"));try{let t=Ln(),n=Go();m(`Executing: npm view ${n}@${t} --json`);let{stdout:o}=await Nl("npm",["view",`${n}@${t}`,"--json"]),i=JSON.parse(o),s=typeof i.version=="string"?i.version.trim():null,a=Array.isArray(i.blockedVersions)?i.blockedVersions:[];await e.writeSuccess(s,a,ur(),t),await Af(r,!0,null)}catch(t){await e.writeError(t instanceof Error?t.message:String(t));let n=t,o=n.code??n.name??"UnknownError";await Af(r,!1,o)}});var QC={event:S.CommandExecuted,args:["update"]},eP={event:S.CommandExecuted,args:["update","_check"]};async function Ll(r,e,t){let n={duration_ms:Date.now()-r,success:e,error_code:t};await I.track(QC,n).catch(()=>{})}async function Af(r,e,t){let n={duration_ms:Date.now()-r,success:e,error_code:t};await I.track(eP,n).catch(()=>{})}Ol.action(async()=>{if(Nn()==="all")throw new Error("devecocli update is disabled (DEVECO_CLI_DISABLE_UPDATE=all).");await Rl(Go());let r=Date.now(),e=ur(),t=Ln();console.log(xl("Checking for updates..."));let n=Go();try{let{stdout:o}=await Nl("npm",["view",n,`dist-tags.${t}`]),i=o.trim();if(!i||i===e){console.log(Cf(`
80
- ${n} is already up to date (v${e}, tag: ${t})`)),await Ll(r,!0,null);return}console.log(xl(`
81
- New version found: ${i} (current: ${e})`)),console.log(xl(`Updating ${n}...`)),await Nl("npm",["install","-g",`${n}@${t}`],{stdio:"inherit"}),console.log(`
82
- `+Cf(`${n} updated successfully to version ${i}.`)),await Ll(r,!0,null)}catch(o){let i=o,s=i.code??i.name??"UnknownError";console.error(Pf(`Failed to update ${n}`)),i.message&&console.error(Pf(i.message)),await Ll(r,!1,s),process.exit(1)}});var kf=Ol;import{Command as TP,Option as Uf}from"commander";import{execa as Gs}from"execa";function Ae(r){return r.normalize("NFKC").replace(/\s+/g," ").trim()}function Df(r){let e=r.normalize("NFKC").match(/\((\d+)(?:\.\d+)*\)/)?.[1];return e!==void 0&&Number(e)>=26}import{spawn as tP}from"child_process";var rP=2500;function nP(r,e,t,n,o,i){r.once("exit",s=>{if(i())return;clearTimeout(e);let a=t();s===0||s===null?n():o(a||`Emulator process exited with code ${s}`)})}function oP(r,e,t,n){let o=!1,i=()=>o,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{o||(o=!0,clearTimeout(l),r.removeAllListeners(),r.stderr?.removeAllListeners(),r.stderr?.destroy(),r.unref(),t())},c=d=>{if(!o){o=!0,clearTimeout(l),r.removeAllListeners(),r.stderr?.removeAllListeners();try{r.kill()}catch{}n(new Error(d))}},l=setTimeout(a,rP);r.once("error",d=>c(d.message)),nP(r,l,s,a,c,i)}function Tf(r,e,t){m(`Spawning emulator: ${r} ${t.join(" ")}`);let n=[],o=tP(r,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});o.stderr?.on("data",a=>n.push(a));let i=o.pid!==void 0&&!At()?bn(o.pid,500,!0):void 0,s=new Promise((a,c)=>{oP(o,n,a,c)});return{pid:o.pid,started:s,tracker:i}}import*as Mn from"path";function iP(r){let e=new Set,t=[];for(let n of r){let o=JSON.stringify(n);e.has(o)||(e.add(o),t.push(n))}return t}function sP(r){let e=r.instancePath?.trim();if(e)return Mn.dirname(Mn.normalize(e)).replace(/\\/g,"/");let t=r.path?.trim();return t?Mn.dirname(Mn.normalize(t)).replace(/\\/g,"/"):""}function aP(r){let e=[];return r&&e.push(["-imageRoot",r]),e.push([]),e}function Rf(r,e){return e?[...r,"-bootmode",e]:r}function cP(r,e,t){let n=[Rf(["-start",r],t)],o=sP(e);if(o)for(let i of aP(e.imageRoot))n.push(Rf(["-hvd",r,"-path",o,...i],t));return iP(n)}async function xf(r,e,t,n){let o=new Error("No start strategy ran"),i=cP(r,e,n);for(let s of i){let a;try{return a=t(s),await a.started,{ok:!0,args:s,tracker:a.tracker}}catch(c){if(a?.tracker)try{await a.tracker.stop()}catch{}o=c}}return{ok:!1,lastError:o}}function lP(r){let e=r.normalize("NFKC").match(/^\s*chargingStatus\s*:\s*(\d+)\s*$/im);if(!e)return;let t=Number(e[1]);if(t===1||t===3)return!0;if(t===0||t===2)return!1}async function Ml(r){return(await ue.withHdcPath(r).listDevices()).map(t=>t.serial).filter(Rt)}async function _l(r){let e=await Ml(r);return e.length===0?[]:(await Promise.all(e.map(n=>Cs(r,n,"ohos.qemu.hvd.name")))).filter(n=>!!n)}async function Lf(r,e){return(await _l(r)).includes(e)}async function Nf(r,e){let t=await ue.withHdcPath(r).listDevicesWithName(),n=e.normalize("NFKC").replace(/\s+/g," ").trim(),o=t.find(a=>a.name.normalize("NFKC").replace(/\s+/g," ").trim()===n);if(!o||!Rt(o.serial))throw new Error(`Cannot resolve the running emulator serial for "${e}".`);let i=["-t",o.serial,"shell","hidumper","-s","3302","-a","-i"];m(`Executing: ${r} ${i.join(" ")}`);let s=await re(r,i);if(s.exitCode===0){let a=lP(s.stdout);if(a!==void 0)return a}throw new Error(`Cannot determine the battery charging state for emulator "${e}".`)}import*as Fn from"path";import{existsSync as dP,statSync as uP}from"fs";function _n(r,e){for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}return""}function pP(r){let e=_n(r,["instancePath","instance_path","InstancePath","instancepath","instanceDir","instance_dir","InstanceDir","deployPath","deploy_path","deployedPath","deployed_path","workPath","work_path","dataPath","data_path"]);if(e)return e;for(let[t,n]of Object.entries(r)){if(typeof n!="string"||!n.trim())continue;let o=t.toLowerCase();if(o.includes("instance")&&(o.includes("path")||o.includes("dir"))||o==="deployedpath")return n.trim()}return""}function mP(r){return _n(r,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function fP(r){let e=r.find(n=>n.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=Fn.dirname(Fn.normalize(e.instancePath));for(let n of r){if(n.instancePath?.trim())continue;let o=E.ensurePathWithinRoot(t,Fn.join(t,n.name));dP(o)&&uP(o).isDirectory()&&(n.instancePath=o.replace(/\\/g,"/"))}}function hP(r){try{let e=JSON.parse(r);return Array.isArray(e)?e.map(t=>{let n=mP(t),o=_n(t,["deviceType","DeviceType","devicetype"]),i=_n(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:pP(t),path:_n(t,["path","Path","hvdPath","hvd_path"]),imageRoot:_n(t,["imageRoot","image_root","ImageRoot"]),uuid:n||void 0,deviceType:o||void 0,osVersion:i||void 0}}).filter(t=>t.name):null}catch{return null}}function gP(r){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,n=null,o;for(;(o=t.exec(r))!==null;){let[,i,s]=o;if(i.toLowerCase()==="name")n&&e.push(n),n={name:s.trim()};else if(n){let a=i.toLowerCase();a==="isrunning"?n.isRunning=s.trim().toLowerCase()==="true":a==="instancepath"?n.instancePath=s.trim():a==="path"?n.path=s.trim():a==="imageroot"?n.imageRoot=s.trim():a==="devicetype"?n.deviceType=s.trim():a==="os.osversion"&&(n.osVersion=s.trim())}}return n&&e.push(n),e}function Of(r){let t=hP(r)??gP(r);return fP(t),t}function Fl(r,e){for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}return""}function yP(r){let e=r.downloaded??r.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function vP(r){let e=Fl(r,["osVersion","OsVersion","OSVersion"]),t=Fl(r,["SoftWareVersion","SoftwareVersion","softwareVersion"]),n=Fl(r,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:n}}function Mf(r,e=()=>!0){let t=r.trim();if(!t)return[];try{let n=JSON.parse(t);if(!Array.isArray(n))return[];let o=[];for(let i of n){if(!i||typeof i!="object")continue;let s=i;if(!e(s))continue;let a=vP(s);a&&o.push(a)}return o}catch{return[]}}function _f(r){return Mf(r)}function Ff(r){return Mf(r,yP)}var jf=/no images are available/i,wP=/Scenario simulation failed\s*[::]/i,SP="7.0.0";function Bt(r){return r.normalize("NFKC").trim().toLowerCase()}function bP(r){let e=r.message||"";return jf.test(e)}function EP(r){return r.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function Yo(r,e){return`${r} ${e.join(" ")}`.trim()}function CP(r){switch(r.type){case"gps":return`${r.type}:${r.key}=${r.value}`;case"sensor":return`${r.type}:${r.key}=${r.value}`;case"rotation":case"volume":return`${r.type}:${r.direction}`;case"folded-state":return`${r.type}:${r.state}`;case"battery":return`${r.type}:${r.level}`;case"battery-status":return`${r.type}:${r.status}`;default:return r.type}}var jn=class r{static supportedControlPaths=new Set;emulatorPath;sdkPath;hdcPath;constructor(e,t,n){this.emulatorPath=e,this.sdkPath=t,this.hdcPath=n}static from(e){return new r(e.emulatorPath,e.sdkPath,e.hdcPath)}async executeEmulator(e){return m(`Executing: ${Yo(this.emulatorPath,e)}`),Gs(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return Tf(this.emulatorPath,this.sdkPath,e)}async listEmulators(e){let t=["-list","-details"];e!==void 0&&t.push("-instancePath",e);let{stdout:n}=await this.executeEmulator(t);return Of(n)}async listEmulatorDetails(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return e}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let n of t)n.name&&n.deviceType&&e.set(Ae(n.name),n.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),n=Ae(e),o=t.find(a=>Ae(a.name)===n);if(!o)throw new w(`Emulator "${e}" not found.`,"Emulator not found.");let i=o.name;if(await this.isAlreadyRunning(i,o))return{status:"already-running"};let s=await xf(i,o,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return{status:"started",args:s.args,tracker:s.tracker};if(await this.isAlreadyRunning(i))return{status:"already-running"};throw new w(`Unable to start emulator "${e}". All methods failed.
83
- Last error: ${s.lastError.message||"unknown"}`,`Unable to start emulator. All methods failed.
84
- Last error: ${s.lastError.message||"unknown"}`)}async isAlreadyRunning(e,t){return t?.isRunning===!0||t===void 0&&(await this.listEmulators()).find(o=>o.name===e)?.isRunning===!0?!0:Lf(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),n=Ae(e),o=t.find(a=>Ae(a.name)===n);if(!o)throw new w(`Emulator "${e}" not found.`,"Emulator not found.");let i=o.name;return await this.isAlreadyRunning(i,o)?(await this.executeEmulator(["-stop",i]),"stopped"):"already-stopped"}async controlEmulator(e,t){await this.assertControlCommandSupported();let o=(await this.listEmulators()).find(s=>s.name===e);if(!o)throw new w(`Emulator "${e}" not found.`,"Emulator instance not found.");if(!await this.isAlreadyRunning(o.name,o))throw new w(`Emulator "${e}" is not running.`,"Emulator instance is not running.");if(t.type==="battery"&&!(t.assumedCharging?!0:await Nf(this.hdcPath,o.name))&&t.level===0)throw new Error("Battery level must be an integer in [1, 100] while the emulator is not charging.");let i=this.buildControlArgs(o.name,t);m(`[EmulatorManager] control ${CP(t)} -> ${Yo(this.emulatorPath,i)}`),await this.runEmulatorChecked(i,{extraReject:t.type==="folded-state"?[wP]:void 0,printOutputOnSuccess:!1})}async assertControlCommandSupported(){let e=this.emulatorPath;if(r.supportedControlPaths.has(e))return;let t=["-version"];m(`Executing: ${Yo(this.emulatorPath,t)}`);let{stdout:n,stderr:o,exitCode:i}=await Gs(this.emulatorPath,t,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:1024*1024}),s=[n,o].filter(Boolean).join(`
85
- `).trim(),a=EP(s);if(i!==0||!a)throw new Error("Emulator scene control commands require Emulator 7.0 or later. Unable to determine the current Emulator version.");if(k.compareVersion(a,SP)<0)throw new Error(`Emulator scene control commands require Emulator 7.0 or later. Current Emulator version is ${a}. Please upgrade DevEco Studio or the Emulator SDK.`);r.supportedControlPaths.add(e)}buildControlArgs(e,t){let n=["-instance",e];switch(t.type){case"shake":return[...n,"-shake"];case"power":return[...n,"-power"];case"rotation":return[...n,"-rotation",t.direction];case"volume":return[...n,"-volume",t.direction];case"folded-state":return[...n,"-foldedState",t.state];case"battery":return[...n,"-battery",String(t.level)];case"battery-status":return[...n,"-batteryStatus",String(t.status)];case"gps":return[...n,"-gps",`-${t.key}`,t.value];case"outdoor-running":return[...n,"-outdoorRunning"];case"outdoor-cycling":return[...n,"-outdoorCycling"];case"driving-navigation":return[...n,"-drivingNavigation"];case"sensor":return[...n,"-sensor",`-${t.key}`,String(t.value)];default:throw new Error(`Unknown emulator control action type: ${t.type}`)}}async executeEmulatorInherit(e){m(`Executing: ${Yo(this.emulatorPath,e)}`);let{exitCode:t}=await Gs(this.emulatorPath,e,{stdio:"inherit",env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1});if(t!==0)throw new Error(`Emulator exited with code ${t===null?"null":t}.`)}async installEmulatorImage(e){let t=["-install","-deviceType",e.deviceType,"-osVersion",e.osVersion];e.force&&t.push("-force"),await this.executeEmulatorInherit(t)}async hasAvailableEmulatorImage(e){let t=await this.listEmulatorImages({deviceType:e.deviceType}),n=Bt(e.deviceType),o=Bt(e.osVersion);return _f(t).some(i=>Bt(i.deviceType)===n&&Bt(i.osVersion)===o)}async uninstallEmulatorImage(e){let t=await this.resolveSoftwareVersionsForUninstall(e);if(t.length===0)throw new Error(`No downloaded image matches --os-version "${e.osVersion}" for --device-type "${e.deviceType}".`);let n;try{await this.runUninstallImageChecked(e.deviceType,e.osVersion)}catch(i){if(!bP(i))throw i;n=i}(n!==void 0||await this.hasMatchingDownloadedImage(e))&&await this.runSoftwareVersionFallback(e,t,n)}async listEmulatorImages(e){let t=["-imageList"];e.deviceType&&t.push("-deviceType",e.deviceType),e.downloaded!==void 0&&t.push("-downloaded",e.downloaded?"true":"false");let{stdout:n}=await this.executeEmulator(t);return n}async hasMatchingDownloadedImage(e){return(await this.findMatchingDownloadedImages(e)).length>0}async runSoftwareVersionFallback(e,t,n){try{for(let o of t)await this.runUninstallImageChecked(e.deviceType,o)}catch(o){let i=n!==void 0?`Primary uninstall failed: ${n.message}
86
- `:"";throw new Error(`${i}Fallback uninstall failed: ${o.message}`,{cause:o})}if(await this.hasMatchingDownloadedImage(e))throw new Error(`Image for --device-type "${e.deviceType}" and --os-version "${e.osVersion}" remains listed as downloaded after uninstallation.`)}async resolveSoftwareVersionsForUninstall(e){let t=await this.findMatchingDownloadedImages(e);return[...new Set(t.map(n=>n.softwareVersion).filter(Boolean))]}async findMatchingDownloadedImages(e){let t=await this.listEmulatorImages({deviceType:e.deviceType,downloaded:!0}),n=Ff(t),o=Bt(e.deviceType),i=Bt(e.osVersion);return n.filter(s=>Bt(s.deviceType)===o&&(Bt(s.osVersion)===i||Bt(s.softwareVersion)===i))}async runUninstallImageChecked(e,t){await this.runEmulatorChecked(["-uninstall","-deviceType",e,"-osVersion",t,"-force"],{printOutputOnSuccess:!0,extraReject:[jf]})}async runEmulatorChecked(e,t){m(`Executing: ${Yo(this.emulatorPath,e)}`);let{stdout:n,stderr:o,exitCode:i}=await Gs(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:20*1024*1024}),s=[n,o].filter(Boolean).join(`
87
- `).trim(),a=/Invalid command|无效命令|鏃犳晥鍛戒护/i.test(s)||/please attach the correct parameter/i.test(s),c=(t?.extraReject??[]).some(d=>d.test(s));if(i!==0||a||c)throw new Error(s||`emulator exited with code ${i===null?"null":i}`);if(t?.printOutputOnSuccess!==!1&&s){let d=(t?.transformOutput?t.transformOutput(s):s).trim();d&&console.log(d)}}async checkExistingVirtualDevice(e){let t=await this.listEmulators(e.instancePath),n=Ae(e.name),o=t.find(i=>Ae(i.name)===n);if(o)if(e.force)await this.deleteVirtualDevice(o.name,e.instancePath);else throw new w(`Emulator "${e.name}" already exists. Use \`--force\` to overwrite.`,"Emulator already exists.");return n}buildCreateVirtualDeviceArgs(e){let t=["-create",e.name,"-deviceType",e.deviceType,"-osVersion",e.osVersion];e.instancePath!==void 0&&t.push("-instancePath",e.instancePath),e.imageRoot!==void 0&&t.push("-imageRoot",e.imageRoot),e.screenProfile!==void 0&&t.push("-screenProfile",e.screenProfile),e.screen?.length&&t.push("-screen",...e.screen),e.storage!==void 0&&t.push("-storage",String(e.storage)),e.memory!==void 0&&t.push("-memory",String(e.memory));let n=e.hotBoot??(Df(e.osVersion)?!0:void 0);return n!==void 0&&t.push("-hotBoot",String(n)),t}async createVirtualDevice(e){let t=await this.checkExistingVirtualDevice(e),n=this.buildCreateVirtualDeviceArgs(e);if(await this.runEmulatorChecked(n,{extraReject:[/Device create fail/i,/already exists/i,/Invalid OS version/i,/cannot be empty/i],printOutputOnSuccess:!0,transformOutput:i=>i.split(/\r?\n/).map(s=>s.trim().startsWith("Device create success.")?"Device create success.":s).join(`
88
- `)}),!await this.waitForEmulatorPresenceByList(t,e.instancePath))throw new w(`Emulator "${e.name}" was reported as created, but it did not appear in the emulator list within the waiting period. Open the device manager list in DevEco Studio, then run this command again.`,"Emulator was reported as created, but it did not appear in the emulator list within the waiting period.")}async waitForEmulatorPresenceByList(e,t,n=1e4,o=500){let i=Date.now()+n;for(;Date.now()<i;){if((await this.listEmulators(t)).some(c=>Ae(c.name)===e))return!0;await new Promise(c=>setTimeout(c,o))}return!1}async deleteVirtualDevice(e,t){let n=await this.listEmulators(t),o=Ae(e),i=n.find(c=>Ae(c.name)===o);if(!i)throw new w(`Emulator "${e}" not found.`,"Emulator not found.");let s=i.name;if(i.isRunning===!0||await this.isAlreadyRunning(s,i))throw new w(`Failed to delete device: ${s}
89
- The device may be running.`,"Failed to delete device, The device may be running.");let a=["-delete",s];return t!==void 0&&a.push("-instancePath",t),a.push("-force"),await this.runEmulatorChecked(a,{printOutputOnSuccess:!1}),s}};import{red as RP,yellow as xP,gray as LP}from"colorette";import Wf from"ora";import{green as PP}from"colorette";var AP=[[4352,4447],[9001,9002],[11904,42191],[43360,43388],[44032,55203],[63744,64255],[65040,65049],[65072,65135],[65281,65376],[65504,65510],[127744,129535],[131072,173791],[173824,177983],[177984,178207],[178208,183983],[183984,191456]],IP=[[0,31],[127,159],[768,879],[6832,6911],[7616,7679],[8203,8207],[8400,8447],[65024,65039],[65056,65071],[8205,8205]],kP=new RegExp("\x1B\\[([0-9;]*)[a-zA-Z]","g");function $f(r,e){for(let[t,n]of e)if(r>=t&&r<=n)return!0;return!1}function jl(r){let e=r.replace(kP,""),t=0,n=0;for(;n<e.length;){let o=e.codePointAt(n);if(o===void 0)break;$f(o,IP)||($f(o,AP)?t+=2:t+=1),n+=o>65535?2:1}return t}function Hf(r,e){let t=jl(r);return r+" ".repeat(Math.max(0,e-t))}function DP(r,e){return r.map((t,n)=>{let o=jl(t);for(let i of e){let s=i.cells[n]??"";o=Math.max(o,jl(s))}return o})}function Ut(r,e){let t=DP(r,e),n=[];n.push(r.map((o,i)=>Hf(o,t[i])).join(" ")),n.push(t.map(o=>"-".repeat(o)).join(" "));for(let o of e){let i=o.cells.map((s,a)=>Hf(s??"",t[a])).join(" ").trimEnd();n.push(o.highlight?PP(i):i)}return n.join(`
90
- `)}async function Ko(r,e){let t=Date.now(),n=!0,o=null;try{await e()}catch(i){n=!1,o=q(i),console.error(RP(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:n,error_code:o};await I.track(r,i)}}function NP(r,e){if(e.size!==0)for(let t of r){if(!t.isEmulator||!t.name)continue;let n=e.get(Ae(t.name));n&&(t.deviceType=n)}}var OP=["Name","Serial","Kind","Device Type"];function MP(r){return{cells:[r.name??r.serial,r.serial,r.isEmulator?"emulator":"device",r.deviceType??"-"],highlight:!0}}function Vf(r,e){return r.isEmulator!==e.isEmulator?r.isEmulator?1:-1:(r.name??r.serial).localeCompare(e.name??e.serial)}function _P(){console.log(xP(" No active devices.")),console.log(LP(" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function FP(r){let t=[...r].sort(Vf).map(MP);console.log(Ut(OP,t))}function jP(r){return{name:r.name??r.serial,serial:r.serial,kind:r.isEmulator?"emulator":"device",deviceType:r.deviceType}}function $P(r){let e=[...r].sort(Vf);console.log(JSON.stringify(e.map(jP),null,2))}async function HP(r,e){if(!r.some(o=>o.isEmulator)||!e.emulatorPath)return;let n=await jn.from(e).getDeviceTypeByName();NP(r,n)}async function Bf(r,e,t,n="table"){try{let o=await r.getConnectedEntries();if(await HP(o,e),t?.stop(),n==="json"){$P(o);return}o.length===0?_P():FP(o)}catch(o){throw new w(`Failed to list devices: ${o.message}`,"Failed to list devices.")}finally{t?.stop()}}async function BP(r,e){let t=await r.listDevices();if(t.length<2)return;let n=["Multiple devices connected. Specify a device with:"];for(let o of t){let i=await r.getDeviceName(o.serial);n.push(` ${e} -t ${o.serial} # ${i}`)}throw new w(n.join(`
91
- `),"Multiple devices connected.")}async function UP(r,e,t="table"){e||await BP(r,"devecocli device view");let n=await r.listDevices(),o=await r.getDeviceInfo(n,e);if(!o){if(t==="json"){console.error("No connected device found."),process.exitCode=1;return}throw new w("No connected device found.")}let i=await r.getDeviceDetail(o.serial),s=await r.getDeviceName(o.serial);if(t==="json"){let a={name:s,serial:o.serial,kind:Rt(o.serial)?"emulator":"device",deviceType:i.deviceType,osVersion:i.osVersion};console.log(JSON.stringify(a,null,2));return}console.log(` Serial: ${o.serial}`),console.log(` Device Name: ${s}`),i.deviceType&&console.log(` Device Type: ${i.deviceType}`),i.osVersion&&console.log(` OS Version: ${i.osVersion}`)}async function Gf(r,e,t,n,o){let i=await yt(r,o),s=new Ze(r),a=e==="send",c=Wf({text:a?`Sending ${t} to ${n} on ${i}...`:`Receiving ${t} from ${i} to ${n}...`,color:"cyan"}).start();try{await s.transferFile(i,e,t,n),c.stop(),console.log(`${a?"Sent to device":"Received from device"} (${i}): ${t} -> ${n}`)}catch(l){c.stop();let d=a?"Send":"Recv";throw new w(`File ${d} failed: ${l.message}`,`File ${d} failed.`)}}async function WP(r,e,t,n){let o=await yt(r,n),i=new Ze(r);try{await i.runSqlite3(o,e,t)}catch(s){throw new w(`sqlite3 failed: ${s.message}`,"sqlite3 failed.")}}async function Xo(){try{let r=await k.new();return{manager:ue.from(r),toolProvider:r}}catch(r){throw new w(`Failed to initialize device manager: ${r.message}`,"Failed to initialize device manager.")}}var Zo=new TP("device").description("Manage connected devices");Zo.command("list").description("List all connected devices").addOption(new Uf("--format <format>","Output format").choices(["table","json"]).default("table")).action(async r=>{let e={event:S.CommandExecuted,args:["device","list",...r.format==="json"?["--format","json"]:[]]};await Ko(e,async()=>{let{manager:t,toolProvider:n}=await Xo();if(r.format==="json"){await Bf(t,n,void 0,"json");return}let o=Wf({text:"Querying connected devices\u2026",color:"cyan"}).start();await Bf(t,n,o,"table")})});Zo.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").addOption(new Uf("--format <format>","Output format").choices(["table","json"]).default("table")).action(async r=>{let e={event:S.CommandExecuted,args:["device","view",...r.target?["--target"]:[],...r.format==="json"?["--format","json"]:[]]};await Ko(e,async()=>{let{manager:t}=await Xo();await UP(t,r.target,r.format)})});var zf=Zo.command("file").description("Transfer files between the host and a connected device");zf.command("send").description("Send a local file to a device").option("--device <name|serial>","Target device (name or serial)").argument("<src>","Local file path to upload").argument("<dst>","Remote path on the device").action(async(r,e,t)=>{let{device:n}=t,o={event:S.CommandExecuted,args:["device","file","send",...n?["--device"]:[]]};await Ko(o,async()=>{let{toolProvider:i}=await Xo();await Gf(i,"send",r,e,n)})});zf.command("recv").description("Receive a file from a device to the host").option("--device <name|serial>","Target device (name or serial)").argument("<src>","Remote path on the device").argument("<dst>","Local file path to save").action(async(r,e,t)=>{let{device:n}=t,o={event:S.CommandExecuted,args:["device","file","recv",...n?["--device"]:[]]};await Ko(o,async()=>{let{toolProvider:i}=await Xo();await Gf(i,"recv",r,e,n)})});Zo.command("sqlite3").description("Run sqlite3 on a connected device").allowUnknownOption().option("--device <name|serial>","Target device (name or serial)").argument("<db-path>","SQLite database path on the device").argument("[args...]","Arguments forwarded to sqlite3 as-is").action(async(r,e,t)=>{let n={event:S.CommandExecuted,args:["device","sqlite3",r,...t.device?["--device"]:[]]};await Ko(n,async()=>{let{toolProvider:o}=await Xo();await WP(o,r,e,t.device)})});var qf=Zo;import{Argument as zl,Command as ql,InvalidArgumentError as iA,Option as lt}from"commander";import{green as ti,cyan as Hn,red as Jl,yellow as fr,gray as Gl}from"colorette";import sA from"ora";import VP from"readline/promises";import{execa as Yf}from"execa";import*as mr from"fs/promises";import*as Hl from"os";import*as nn from"path";var $l=`1/4:\r
88
+ Fix: run \`which -a devecocli\` (Windows: \`where devecocli\`) to list all shims, remove the stale one, or reinstall with the matching npm: \`npm install -g ${n}@latest\`.`)))}var op=new yA("update").description("Update deveco-cli to latest");op.command("_check",{hidden:!0}).action(async()=>{let n=Date.now(),e=new qr(ip.join(W(),"update"));try{let t=Gr(),r=Mi();m(`Executing: npm view ${r}@${t} --json`);let{stdout:i}=await Ic("npm",["view",`${r}@${t}`,"--json"]),{latestVersion:o,blockedVersions:s}=vA(i,t),a=await wA().catch(c=>{m(`Docs version check failed: ${c instanceof Error?c.message:String(c)}`)});await e.writeSuccess(o,s,Zt(),t,a),await bw(n,!0,null)}catch(t){await e.writeError(t instanceof Error?t.message:String(t));let r=t,i=r.code??r.name??"UnknownError";await bw(n,!1,i)}});async function wA(){let n=Tt(),{latest:e,compatible:t}=await $i(n);return{latestDocsVersion:e.version,latestDocsApiVersion:e.apiVersion,latestCompatibleDocsVersion:t?.version??null,checkedAgainstDocsApi:n}}function vA(n,e){let t=Rc(JSON.parse(n)),r=null;typeof t.version=="string"?r=t.version.trim():t["dist-tags"]?.[e]&&(r=t["dist-tags"][e].trim());let i=[];return Array.isArray(t.blockedVersions)?i=t.blockedVersions:r&&t.versions?.[r]?.blockedVersions&&(i=t.versions[r].blockedVersions),{latestVersion:r,blockedVersions:i}}var bA={event:v.CommandExecuted,args:["update"]},SA={event:v.CommandExecuted,args:["update","_check"]};async function np(n,e,t){let r={duration_ms:Date.now()-n,success:e,error_code:t};await D.track(bA,r).catch(()=>{})}async function bw(n,e,t){let r={duration_ms:Date.now()-n,success:e,error_code:t};await D.track(SA,r).catch(()=>{})}async function EA(n,e,t){let r=t,i=r.code??r.name??"UnknownError";console.error(vw(`Failed to update ${n}`)),r.message&&console.error(vw(r.message)),await np(e,!1,i),process.exit(1)}op.action(async()=>{if(Ni()==="all")throw new Error("devecocli update is disabled (DEVECO_CLI_DISABLE_UPDATE=all).");await tp(Mi());let n=Date.now(),e=Zt(),t=Gr(),r=Mi();console.log(Ac("Checking for updates..."));try{let{stdout:i}=await Ic("npm",["view",r,`dist-tags.${t}`]),o=i.trim();if(!o||o===e){console.log(rp(`
89
+ ${r} is already up to date (v${e}, tag: ${t})`)),await np(n,!0,null);return}console.log(Ac(`
90
+ New version found: ${o} (current: ${e})`)),console.log(Ac(`Updating ${r}...`)),await Ic("npm",["install","-g",`${r}@${t}`],{stdio:"inherit"}),console.log(rp(`
91
+ CLI successfully updated to ${o}`)),await PA(o).catch(s=>{m(`Docs auto-sync failed: ${s instanceof Error?s.message:String(s)}`)}),await np(n,!0,null)}catch(i){await EA(r,n,i)}});async function PA(n){let e=Mi();m(`Executing: npm view ${e}@${n} --json`);let{stdout:t}=await Ic("npm",["view",`${e}@${n}`,"--json"]),r=Rc(JSON.parse(t)),i=typeof r.supportedDocsApi=="number"?r.supportedDocsApi:Tt(),{compatible:o}=await $i(i);if(!o){m("Docs auto-sync: no compatible docs version found, skipping");return}let s=ip.join(W(),"doc-data"),a=await _i();(!a||_r(o.version,a)>0)&&await Dc({version:o.version,apiVersion:o.apiVersion,dist:o.dist},s,"cli-update"),console.log(rp(`Docs has been automatically synced to the compatible version ${o.version}`));let c=await $i(i).catch(()=>null);c?.compatible&&_r(c.compatible.version,o.version)>0&&console.log(Ac(`New docs version ${c.compatible.version} available, run \`devecocli docs update\` to upgrade`))}var Sw=op;import{Command as nO,Option as lv}from"commander";import{execa as Tc}from"execa";function Le(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}function Ew(n){let e=n.normalize("NFKC").match(/\((\d+)(?:\.\d+)*\)/)?.[1];return e!==void 0&&Number(e)>=26}import{spawn as CA}from"child_process";var kA=2500;function RA(n,e,t,r,i,o){n.once("exit",s=>{if(o())return;clearTimeout(e);let a=t();s===0||s===null?r():i(a||`Emulator process exited with code ${s}`)})}function DA(n,e,t,r){let i=!1,o=()=>i,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{i||(i=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners(),n.stderr?.destroy(),n.unref(),t())},c=d=>{if(!i){i=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners();try{n.kill()}catch{}r(new Error(d))}},l=setTimeout(a,kA);n.once("error",d=>c(d.message)),RA(n,l,s,a,c,o)}function Pw(n,e,t){m(`Spawning emulator: ${n} ${t.join(" ")}`);let r=[],i=CA(n,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});i.stderr?.on("data",a=>r.push(a));let o=i.pid!==void 0&&!Ye()?gi(i.pid,500,!0):void 0,s=new Promise((a,c)=>{DA(i,r,a,c)});return{pid:i.pid,started:s,tracker:o}}import*as ji from"path";function xA(n){let e=new Set,t=[];for(let r of n){let i=JSON.stringify(r);e.has(i)||(e.add(i),t.push(r))}return t}function AA(n){let e=n.instancePath?.trim();if(e)return ji.dirname(ji.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?ji.dirname(ji.normalize(t)).replace(/\\/g,"/"):""}function IA(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function Cw(n,e,t){let r=[...n],i=t?.bootMode??e;return i&&r.push("-bootmode",i),t?.hdcPort!==void 0&&r.push("-hdcport",String(t.hdcPort)),t?.noWindow&&r.push("-noWindow"),r}function TA(n,e,t,r){let i=[Cw(["-start",n],t,r)],o=AA(e);if(o)for(let s of IA(e.imageRoot))i.push(Cw(["-hvd",n,"-path",o,...s],t,r));return xA(i)}async function kw(n,e,t,r,i){let o=new Error("No start strategy ran"),s=TA(n,e,r,i);for(let a of s){let c;try{return c=t(a),await c.started,{ok:!0,args:a,tracker:c.tracker}}catch(l){if(c?.tracker)try{await c.tracker.stop()}catch{}o=l}}return{ok:!1,lastError:o}}function OA(n){let e=n.normalize("NFKC").match(/^\s*chargingStatus\s*:\s*(\d+)\s*$/im);if(!e)return;let t=Number(e[1]);if(t===1||t===3)return!0;if(t===0||t===2)return!1}async function sp(n){return(await le.withHdcPath(n).listDevices()).map(t=>t.serial).filter(Jt)}async function ap(n){let e=await sp(n);return e.length===0?[]:(await Promise.all(e.map(r=>qa(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function Rw(n,e){return(await ap(n)).includes(e)}async function Dw(n,e){let t=await le.withHdcPath(n).listDevicesWithName(),r=e.normalize("NFKC").replace(/\s+/g," ").trim(),i=t.find(a=>a.name.normalize("NFKC").replace(/\s+/g," ").trim()===r);if(!i||!Jt(i.serial))throw new Error(`Cannot resolve the running emulator serial for "${e}".`);let o=["-t",i.serial,"shell","hidumper","-s","3302","-a","-i"];m(`Executing: ${n} ${o.join(" ")}`);let s=await C(n,o);if(s.exitCode===0){let a=OA(s.stdout);if(a!==void 0)return a}throw new Error(`Cannot determine the battery charging state for emulator "${e}".`)}import*as Ui from"path";import{existsSync as MA,statSync as NA}from"fs";function Hi(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function LA(n){let e=Hi(n,["instancePath","instance_path","InstancePath","instancepath","instanceDir","instance_dir","InstanceDir","deployPath","deploy_path","deployedPath","deployed_path","workPath","work_path","dataPath","data_path"]);if(e)return e;for(let[t,r]of Object.entries(n)){if(typeof r!="string"||!r.trim())continue;let i=t.toLowerCase();if(i.includes("instance")&&(i.includes("path")||i.includes("dir"))||i==="deployedpath")return r.trim()}return""}function _A(n){return Hi(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function $A(n,e){for(let t of e){let r=n[t];if(!(r==null||r===""))return r===!0||String(r).toLowerCase()==="true"}}function FA(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=Ui.dirname(Ui.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let i=E.ensurePathWithinRoot(t,Ui.join(t,r.name));MA(i)&&NA(i).isDirectory()&&(r.instancePath=i.replace(/\\/g,"/"))}}function jA(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=_A(t),i=Hi(t,["deviceType","DeviceType","devicetype"]),o=Hi(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:LA(t),path:Hi(t,["path","Path","hvdPath","hvd_path"]),imageRoot:Hi(t,["imageRoot","image_root","ImageRoot"]),uuid:r||void 0,deviceType:i||void 0,osVersion:o||void 0,hotBoot:$A(t,["isHotBoot","ishotboot","hotBoot"])}}).filter(t=>t.name):null}catch{return null}}function HA(n){let e=[],t=/^(name|isrunning|ishotboot|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,r=null,i;for(;(i=t.exec(n))!==null;){let[,o,s]=i;if(o.toLowerCase()==="name")r&&e.push(r),r={name:s.trim()};else if(r){let a=o.toLowerCase();a==="isrunning"?r.isRunning=s.trim().toLowerCase()==="true":a==="ishotboot"?r.hotBoot=s.trim().toLowerCase()==="true":a==="instancepath"?r.instancePath=s.trim():a==="path"?r.path=s.trim():a==="imageroot"?r.imageRoot=s.trim():a==="devicetype"?r.deviceType=s.trim():a==="os.osversion"&&(r.osVersion=s.trim())}}return r&&e.push(r),e}function xw(n){let t=jA(n)??HA(n);return FA(t),t}function cp(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function UA(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function BA(n){let e=cp(n,["osVersion","OsVersion","OSVersion"]),t=cp(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=cp(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function Aw(n,e=()=>!0){let t=n.trim();if(!t)return[];try{let r=JSON.parse(t);if(!Array.isArray(r))return[];let i=[];for(let o of r){if(!o||typeof o!="object")continue;let s=o;if(!e(s))continue;let a=BA(s);a&&i.push(a)}return i}catch{return[]}}function Iw(n){return Aw(n)}function Tw(n){return Aw(n,UA)}var Ow=/no images are available/i,WA=/Scenario simulation failed\s*[::]/i,VA="7.0.0";function br(n){return n.normalize("NFKC").trim().toLowerCase()}function GA(n){let e=n.message||"";return Ow.test(e)}function qA(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function is(n,e){return`${n} ${e.join(" ")}`.trim()}function zA(n){switch(n.type){case"gps":return`${n.type}:${n.key}=${n.value}`;case"sensor":return`${n.type}:${n.key}=${n.value}`;case"rotation":case"volume":return`${n.type}:${n.direction}`;case"folded-state":return`${n.type}:${n.state}`;case"battery":return`${n.type}:${n.level}`;case"battery-status":return`${n.type}:${n.status}`;default:return n.type}}var Bi=class n{static supportedControlPaths=new Set;emulatorPath;sdkPath;hdcPath;constructor(e,t,r){this.emulatorPath=e,this.sdkPath=t,this.hdcPath=r}static from(e){return new n(e.emulatorPath,e.sdkPath,e.hdcPath)}async executeEmulator(e){return m(`Executing: ${is(this.emulatorPath,e)}`),Tc(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return Pw(this.emulatorPath,this.sdkPath,e)}async listEmulators(e){let t=["-list","-details"];e!==void 0&&t.push("-instancePath",e);let{stdout:r}=await this.executeEmulator(t);return xw(r)}async listEmulatorDetails(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return e}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let r of t)r.name&&r.deviceType&&e.set(Le(r.name),r.deviceType)}catch{}return e}async startEmulator(e,t){let r=await this.listEmulators(),i=Le(e),o=r.find(c=>Le(c.name)===i);if(!o)throw new y(`Emulator "${e}" not found.`,"Emulator not found.");let s=o.name;if(await this.isAlreadyRunning(s,o))return{status:"already-running"};let a=await kw(s,o,c=>this.executeEmulatorDetached(c),o.hotBoot===!1?"coldboot":"snapshot",t);if(a.ok)return{status:"started",args:a.args,tracker:a.tracker};if(await this.isAlreadyRunning(s))return{status:"already-running"};throw new y(`Unable to start emulator "${e}". All methods failed.
92
+ Last error: ${a.lastError.message||"unknown"}`,`Unable to start emulator. All methods failed.
93
+ Last error: ${a.lastError.message||"unknown"}`)}async isAlreadyRunning(e,t){return t?.isRunning===!0||t===void 0&&(await this.listEmulators()).find(i=>i.name===e)?.isRunning===!0?!0:Rw(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=Le(e),i=t.find(a=>Le(a.name)===r);if(!i)throw new y(`Emulator "${e}" not found.`,"Emulator not found.");let o=i.name;return await this.isAlreadyRunning(o,i)?(await this.executeEmulator(["-stop",o]),"stopped"):"already-stopped"}async controlEmulator(e,t){await this.assertControlCommandSupported();let i=(await this.listEmulators()).find(s=>s.name===e);if(!i)throw new y(`Emulator "${e}" not found.`,"Emulator instance not found.");if(!await this.isAlreadyRunning(i.name,i))throw new y(`Emulator "${e}" is not running.`,"Emulator instance is not running.");if(t.type==="battery"&&!(t.assumedCharging?!0:await Dw(this.hdcPath,i.name))&&t.level===0)throw new Error("Battery level must be an integer in [1, 100] while the emulator is not charging.");let o=this.buildControlArgs(i.name,t);m(`[EmulatorManager] control ${zA(t)} -> ${is(this.emulatorPath,o)}`),await this.runEmulatorChecked(o,{extraReject:t.type==="folded-state"?[WA]:void 0,printOutputOnSuccess:!1})}async assertControlCommandSupported(){let e=this.emulatorPath;if(n.supportedControlPaths.has(e))return;let t=["-version"];m(`Executing: ${is(this.emulatorPath,t)}`);let{stdout:r,stderr:i,exitCode:o}=await Tc(this.emulatorPath,t,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:1024*1024}),s=[r,i].filter(Boolean).join(`
94
+ `).trim(),a=qA(s);if(o!==0||!a)throw new Error("Emulator scene control commands require Emulator 7.0 or later. Unable to determine the current Emulator version.");if(P.compareVersion(a,VA)<0)throw new Error(`Emulator scene control commands require Emulator 7.0 or later. Current Emulator version is ${a}. Please upgrade DevEco Studio or the Emulator SDK.`);n.supportedControlPaths.add(e)}buildControlArgs(e,t){let r=["-instance",e];switch(t.type){case"shake":return[...r,"-shake"];case"power":return[...r,"-power"];case"rotation":return[...r,"-rotation",t.direction];case"volume":return[...r,"-volume",t.direction];case"folded-state":return[...r,"-foldedState",t.state];case"battery":return[...r,"-battery",String(t.level)];case"battery-status":return[...r,"-batteryStatus",String(t.status)];case"gps":return[...r,"-gps",`-${t.key}`,t.value];case"outdoor-running":return[...r,"-outdoorRunning"];case"outdoor-cycling":return[...r,"-outdoorCycling"];case"driving-navigation":return[...r,"-drivingNavigation"];case"sensor":return[...r,"-sensor",`-${t.key}`,String(t.value)];default:throw new Error(`Unknown emulator control action type: ${t.type}`)}}async executeEmulatorInherit(e){m(`Executing: ${is(this.emulatorPath,e)}`);let{exitCode:t}=await Tc(this.emulatorPath,e,{stdio:"inherit",env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1});if(t!==0)throw new Error(`Emulator exited with code ${t===null?"null":t}.`)}async installEmulatorImage(e){let t=["-install","-deviceType",e.deviceType,"-osVersion",e.osVersion];e.force&&t.push("-force"),await this.executeEmulatorInherit(t)}async hasAvailableEmulatorImage(e){let t=await this.listEmulatorImages({deviceType:e.deviceType}),r=br(e.deviceType),i=br(e.osVersion);return Iw(t).some(o=>br(o.deviceType)===r&&br(o.osVersion)===i)}async uninstallEmulatorImage(e){let t=await this.resolveSoftwareVersionsForUninstall(e);if(t.length===0)throw new Error(`No downloaded image matches --os-version "${e.osVersion}" for --device-type "${e.deviceType}".`);let r;try{await this.runUninstallImageChecked(e.deviceType,e.osVersion)}catch(o){if(!GA(o))throw o;r=o}(r!==void 0||await this.hasMatchingDownloadedImage(e))&&await this.runSoftwareVersionFallback(e,t,r)}async listEmulatorImages(e){let t=["-imageList"];e.deviceType&&t.push("-deviceType",e.deviceType),e.downloaded!==void 0&&t.push("-downloaded",e.downloaded?"true":"false");let{stdout:r}=await this.executeEmulator(t);return r}async hasMatchingDownloadedImage(e){return(await this.findMatchingDownloadedImages(e)).length>0}async runSoftwareVersionFallback(e,t,r){try{for(let i of t)await this.runUninstallImageChecked(e.deviceType,i)}catch(i){let o=r!==void 0?`Primary uninstall failed: ${r.message}
95
+ `:"";throw new Error(`${o}Fallback uninstall failed: ${i.message}`,{cause:i})}if(await this.hasMatchingDownloadedImage(e))throw new Error(`Image for --device-type "${e.deviceType}" and --os-version "${e.osVersion}" remains listed as downloaded after uninstallation.`)}async resolveSoftwareVersionsForUninstall(e){let t=await this.findMatchingDownloadedImages(e);return[...new Set(t.map(r=>r.softwareVersion).filter(Boolean))]}async findMatchingDownloadedImages(e){let t=await this.listEmulatorImages({deviceType:e.deviceType,downloaded:!0}),r=Tw(t),i=br(e.deviceType),o=br(e.osVersion);return r.filter(s=>br(s.deviceType)===i&&(br(s.osVersion)===o||br(s.softwareVersion)===o))}async runUninstallImageChecked(e,t){await this.runEmulatorChecked(["-uninstall","-deviceType",e,"-osVersion",t,"-force"],{printOutputOnSuccess:!0,extraReject:[Ow]})}async runEmulatorChecked(e,t){m(`Executing: ${is(this.emulatorPath,e)}`);let{stdout:r,stderr:i,exitCode:o}=await Tc(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:20*1024*1024}),s=[r,i].filter(Boolean).join(`
96
+ `).trim(),a=/Invalid command|无效命令|鏃犳晥鍛戒护/i.test(s)||/please attach the correct parameter/i.test(s),c=(t?.extraReject??[]).some(d=>d.test(s));if(o!==0||a||c)throw new Error(s||`emulator exited with code ${o===null?"null":o}`);if(t?.printOutputOnSuccess!==!1&&s){let d=(t?.transformOutput?t.transformOutput(s):s).trim();d&&console.log(d)}}async checkExistingVirtualDevice(e){let t=await this.listEmulators(e.instancePath),r=Le(e.name),i=t.find(o=>Le(o.name)===r);if(i)if(e.force)await this.deleteVirtualDevice(i.name,e.instancePath);else throw new y(`Emulator "${e.name}" already exists. Use \`--force\` to overwrite.`,"Emulator already exists.");return r}buildCreateVirtualDeviceArgs(e){let t=["-create",e.name,"-deviceType",e.deviceType,"-osVersion",e.osVersion];e.instancePath!==void 0&&t.push("-instancePath",e.instancePath),e.imageRoot!==void 0&&t.push("-imageRoot",e.imageRoot),e.screenProfile!==void 0&&t.push("-screenProfile",e.screenProfile),e.screen?.length&&t.push("-screen",...e.screen),e.storage!==void 0&&t.push("-storage",String(e.storage)),e.memory!==void 0&&t.push("-memory",String(e.memory));let r=e.hotBoot??(Ew(e.osVersion)?!0:void 0);return r!==void 0&&t.push("-hotBoot",String(r)),t}async createVirtualDevice(e){let t=await this.checkExistingVirtualDevice(e),r=this.buildCreateVirtualDeviceArgs(e);if(await this.runEmulatorChecked(r,{extraReject:[/Device create fail/i,/already exists/i,/Invalid OS version/i,/cannot be empty/i],printOutputOnSuccess:!0,transformOutput:o=>o.split(/\r?\n/).map(s=>s.trim().startsWith("Device create success.")?"Device create success.":s).join(`
97
+ `)}),!await this.waitForEmulatorPresenceByList(t,e.instancePath))throw new y(`Emulator "${e.name}" was reported as created, but it did not appear in the emulator list within the waiting period. Open the device manager list in DevEco Studio, then run this command again.`,"Emulator was reported as created, but it did not appear in the emulator list within the waiting period.")}async waitForEmulatorPresenceByList(e,t,r=1e4,i=500){let o=Date.now()+r;for(;Date.now()<o;){if((await this.listEmulators(t)).some(c=>Le(c.name)===e))return!0;await new Promise(c=>setTimeout(c,i))}return!1}async deleteVirtualDevice(e,t){let r=await this.listEmulators(t),i=Le(e),o=r.find(c=>Le(c.name)===i);if(!o)throw new y(`Emulator "${e}" not found.`,"Emulator not found.");let s=o.name;if(o.isRunning===!0||await this.isAlreadyRunning(s,o))throw new y(`Failed to delete device: ${s}
98
+ The device may be running.`,"Failed to delete device, The device may be running.");let a=["-delete",s];return t!==void 0&&a.push("-instancePath",t),a.push("-force"),await this.runEmulatorChecked(a,{printOutputOnSuccess:!1}),s}};import{yellow as iO,gray as oO}from"colorette";import sO from"ora";import{green as JA}from"colorette";var YA=[[4352,4447],[9001,9002],[11904,42191],[43360,43388],[44032,55203],[63744,64255],[65040,65049],[65072,65135],[65281,65376],[65504,65510],[127744,129535],[131072,173791],[173824,177983],[177984,178207],[178208,183983],[183984,191456]],KA=[[0,31],[127,159],[768,879],[6832,6911],[7616,7679],[8203,8207],[8400,8447],[65024,65039],[65056,65071],[8205,8205]],XA=new RegExp("\x1B\\[([0-9;]*)[a-zA-Z]","g");function Mw(n,e){for(let[t,r]of e)if(n>=t&&n<=r)return!0;return!1}function lp(n){let e=n.replace(XA,""),t=0,r=0;for(;r<e.length;){let i=e.codePointAt(r);if(i===void 0)break;Mw(i,KA)||(Mw(i,YA)?t+=2:t+=1),r+=i>65535?2:1}return t}function Nw(n,e){let t=lp(n);return n+" ".repeat(Math.max(0,e-t))}function ZA(n,e){return n.map((t,r)=>{let i=lp(t);for(let o of e){let s=o.cells[r]??"";i=Math.max(i,lp(s))}return i})}function Sr(n,e){let t=ZA(n,e),r=[];r.push(n.map((i,o)=>Nw(i,t[o])).join(" ")),r.push(t.map(i=>"-".repeat(i)).join(" "));for(let i of e){let o=i.cells.map((s,a)=>Nw(s??"",t[a])).join(" ").trimEnd();r.push(i.highlight?JA(o):o)}return r.join(`
99
+ `)}import{red as QA}from"colorette";async function O(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=X(o),console.error(QA(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await D.track(n,o)}}async function M(){try{let n=await P.new();return{manager:le.from(n),toolProvider:n}}catch(n){throw new y(`Failed to initialize device manager: ${n.message}`,"Failed to initialize device manager.")}}import{Command as eI,Option as hp}from"commander";import{yellow as gp}from"colorette";import{existsSync as _w}from"fs";import Er from"ora";function Lw(n,e){let t=n.match(e);return t?t[1]:void 0}function dp(n){let e=[],t=n.split(/(?=AbilityRecord ID #)/);for(let r of t){let i=r.match(/^\s*state #(\w+)/m);i&&i[1].toUpperCase()==="FOREGROUND"&&e.push({bundleName:Lw(r,/app name \[([^\]]+)\]/),abilityName:Lw(r,/main name \[([^\]]+)\]/)})}return e}function up(n){let e=[],t=o=>{typeof o.bundleName=="string"&&e.push({bundleName:o.bundleName,label:typeof o.label=="string"?o.label:void 0})},r;try{r=JSON.parse(n)}catch{r=null}if(Array.isArray(r)){for(let o of r)t(o);if(e.length>0)return e}let i=n.match(/\{[^{}]+\}/g)??[];for(let o of i)try{t(JSON.parse(o))}catch{}return e}function pp(n){let e=n.indexOf("{");if(e===-1)return null;try{return JSON.parse(n.slice(e))}catch{return null}}function mp(n){let e=n.trim();return{success:!/error:\s*failed to start|error code:\s*\d+|the specified ability does not exist/i.test(e),message:e}}function fp(n){let e=n.hapModuleInfos,t=Array.isArray(e)&&e[0]?e[0]:void 0;return{bundleName:n.name,entryModuleName:n.entryModuleName,mainAbility:t?.mainAbility,versionCode:n.versionCode,versionName:n.versionName}}var Qt=class{constructor(e){this.hdcPath=e}async listInstalledApps(e){let t=["-t",e,"shell","bm","dump","-a","-l"];m(`Executing: ${this.hdcPath} ${t.join(" ")}`);let r=await C(this.hdcPath,t);if(r.exitCode!==0)throw new Error(`bm dump -a -l failed: ${(r.stderr||r.stdout).trim()}`);return r.stdout}async getAppInfo(e,t){let r=["-t",e,"shell","bm","dump","-n",t];m(`Executing: ${this.hdcPath} ${r.join(" ")}`);let i=await C(this.hdcPath,r);if(i.exitCode!==0)throw new Error(`bm dump -n ${t} failed: ${(i.stderr||i.stdout).trim()}`);return i.stdout}async getForegroundApp(e){let t=["-t",e,"shell","aa","dump","-l"];m(`Executing: ${this.hdcPath} ${t.join(" ")}`);let r=await C(this.hdcPath,t);if(r.exitCode!==0)throw new Error(`aa dump -l failed: ${(r.stderr||r.stdout).trim()}`);return r.stdout}async startApp(e,t,r,i,o){let s=["-t",e,"shell","aa","start"];t&&s.push("-b",t),r&&s.push("-a",r),i&&s.push("-A",i),o&&s.push("-U",o),m(`Executing: ${this.hdcPath} ${s.join(" ")}`);let a=await C(this.hdcPath,s);if(a.exitCode!==0)throw new Error(`aa start failed: ${(a.stderr||a.stdout).trim()}`);return a.stdout}async clearAppData(e,t){let r=["-t",e,"shell","bm","clean","-d","-n",t];m(`Executing: ${this.hdcPath} ${r.join(" ")}`);let i=await C(this.hdcPath,r);if(i.exitCode!==0)throw new Error(`bm clean -d -n ${t} failed: ${(i.stderr||i.stdout).trim()}`);return i.stdout}async clearAppCache(e,t){let r=["-t",e,"shell","bm","clean","-c","-n",t];m(`Executing: ${this.hdcPath} ${r.join(" ")}`);let i=await C(this.hdcPath,r);if(i.exitCode!==0)throw new Error(`bm clean -c -n ${t} failed: ${(i.stderr||i.stdout).trim()}`);return i.stdout}};function tI(n,e){if(e==="json")console.log(JSON.stringify(n,null,2));else if(n.length>0)for(let t of n){let r=t.label||"";console.log(`${t.bundleName} ${r}`)}else console.log(gp("No installed apps found."))}async function rI(n,e,t="default"){let r=await T(n,e),i=new Qt(n.hdcPath),o=Er({text:"Listing installed apps...",color:"cyan"}).start();try{let s=await i.listInstalledApps(r);o.stop();let a=up(s);tI(a,t)}catch(s){throw o.stop(),new y(`Failed to list apps: ${s.message}`,"Failed to list apps.")}}function nI(n,e){if(n.length>0)if(e==="json")console.log(JSON.stringify(n,null,2));else for(let t of n)console.log(`${t.bundleName??""}#${t.abilityName??""}`);else console.log(e==="json"?"[]":gp("No foreground app."))}async function iI(n,e,t="default"){let r=await T(n,e),i=new Qt(n.hdcPath),o=Er({text:"Querying foreground app...",color:"cyan"}).start();try{let s=await i.getForegroundApp(r);o.stop();let a=dp(s);nI(a,t)}catch(s){throw o.stop(),new y(`Failed to get foreground app: ${s.message}`,"Failed to get foreground app.")}}async function oI(n,e,t,r="default"){let i=await T(n,t),o=new Qt(n.hdcPath),s=Er({text:`Querying app info for ${e}...`,color:"cyan"}).start();try{let a=await o.getAppInfo(i,e);s.stop();let c=pp(a);if(!c)throw new y(`No app info found for ${e}. The app may not be installed.`,"No app info found. The app may not be installed.");if(r==="json")console.log(JSON.stringify(c,null,2));else{let l=fp(c);console.log(` bundleName: ${l.bundleName??"-"}`),console.log(` entryModuleName: ${l.entryModuleName??"-"}`),console.log(` mainAbility: ${l.mainAbility??"-"}`),console.log(` versionCode: ${l.versionCode??"-"}`),console.log(` versionName: ${l.versionName??"-"}`)}}catch(a){throw s.stop(),new y(`Failed to get app info: ${a.message}`,"Failed to get app info.")}}async function sI(n,e){if(!e.bundle&&!e.action&&!e.uri)throw new y("At least one of --bundle, --action, or --uri must be provided.","At least one of --bundle, --action, or --uri must be provided.");if(e.bundle&&!e.ability)throw new y("--ability is required when --bundle is specified.","--ability is required when --bundle is specified.");let t=await T(n,e.device),r=new Qt(n.hdcPath),i=e.bundle??"(no bundle)",o=Er({text:`Starting app ${i}...`,color:"cyan"}).start();try{let s=await r.startApp(t,e.bundle,e.ability,e.action,e.uri);o.stop();let{success:a,message:c}=mp(s);if(!a)throw new y(`Failed to start app: ${c}`,"Failed to start app. The app or ability may not be installed.");console.log(`App ${i}: ${c}`)}catch(s){throw o.stop(),new y(`Failed to start app: ${s.message}`,"Failed to start app.")}}async function aI(n,e){let t=await T(n,e.device),r=new de(n),i=Er({text:`Stopping app ${e.bundle}...`,color:"cyan"}).start();try{let o=await r.forceStopApp(t,e.bundle);i.stop();let s=o.trim();if(s&&/error|failed|not found|not installed/i.test(s))throw new y(s,"Failed to stop app.");console.log(`Stopped app ${e.bundle}.`)}catch(o){throw i.stop(),new y(o.message,"Failed to stop app.")}}function cI(n,e){if(n.length===0&&!e.shared?.length)throw new y("At least one package file or --shared must be provided.","At least one package file or --shared must be provided.");for(let t of n)if(!_w(t))throw new y(`HAP file not found: ${t}`,"HAP file not found.");if(e.shared){for(let t of e.shared)if(!_w(t))throw new y(`Shared HSP file not found: ${t}`,"Shared HSP file not found.")}}function lI(n,e){let t=[];return n.length>0&&t.push(n.length===1?n[0]:`${n.length} packages`),e.shared?.length&&t.push(`${e.shared.length} shared HSP(s)`),t.join(" + ")}async function dI(n,e,t){let r=await T(n,t.device);cI(e,t);let i={replace:t.replace,shared:t.shared,wait:t.wait,user:t.user},o=new de(n),s=lI(e,t),a=Er({text:`Installing ${s}...`,color:"cyan"}).start();try{await o.installApp(r,e,i),a.stop(),console.log(`Installed ${s}.`)}catch(c){throw a.stop(),new y(c.message,"Failed to install app.")}}async function uI(n,e){let t=await T(n,e.device),r=new de(n),i=Er({text:`Uninstalling ${e.bundle}...`,color:"cyan"}).start();try{let o=await r.uninstallApp(t,e.bundle);i.stop(),console.log(o?`Uninstalled ${e.bundle}.`:gp(`${e.bundle} was not installed.`))}catch(o){throw i.stop(),new y(`Failed to uninstall app: ${o.message}`,"Failed to uninstall app.")}}async function pI(n,e){E.assertBundleNameStrict(e.bundle);let t=await T(n,e.device),r=new Qt(n.hdcPath),i=Er({text:`Clearing cache for ${e.bundle}...`,color:"cyan"}).start();try{let o=await r.clearAppCache(t,e.bundle);i.stop();let s=o.trim();if(s&&/error|failed|not found|not installed/i.test(s))throw new y(s,"Failed to clear app cache.");console.log(`Cleared cache for ${e.bundle}.`)}catch(o){throw i.stop(),new y(o.message,"Failed to clear app cache.")}}async function mI(n,e){E.assertBundleNameStrict(e.bundle);let t=await T(n,e.device),r=new Qt(n.hdcPath),i=Er({text:`Clearing data for ${e.bundle}...`,color:"cyan"}).start();try{let o=await r.clearAppData(t,e.bundle);i.stop();let s=o.trim();if(s&&/error|failed|not found|not installed/i.test(s))throw new y(s,"Failed to clear app data.");console.log(`Cleared data for ${e.bundle}.`)}catch(o){throw i.stop(),new y(o.message,"Failed to clear app data.")}}var Mt=new eI("app").description("Manage apps on a connected device");Mt.command("list").description("List installed apps").option("--device <name|serial>","Target device (name or serial)").addOption(new hp("--format <format>","Output format").choices(["default","json"]).default("default")).action(async n=>{let{device:e,format:t}=n,r={event:v.CommandExecuted,args:["device","app","list",...t==="json"?["--format","json"]:[],...e?["--device"]:[]]};await O(r,async()=>{let{toolProvider:i}=await M();await rI(i,e,t)})});Mt.command("foreground").description("Show current foreground app info").option("--device <name|serial>","Target device (name or serial)").addOption(new hp("--format <format>","Output format").choices(["default","json"]).default("default")).action(async n=>{let{device:e,format:t}=n,r={event:v.CommandExecuted,args:["device","app","foreground",...t==="json"?["--format","json"]:[],...e?["--device"]:[]]};await O(r,async()=>{let{toolProvider:i}=await M();await iI(i,e,t)})});Mt.command("info").description("Show app info").option("--device <name|serial>","Target device (name or serial)").addOption(new hp("--format <format>","Output format").choices(["default","json"]).default("default")).argument("<bundleName>","Bundle name to query").action(async(n,e)=>{let{device:t,format:r}=e,i={event:v.CommandExecuted,args:["device","app","info","<bundleName>",...r==="json"?["--format","json"]:[],...t?["--device"]:[]]};await O(i,async()=>{let{toolProvider:o}=await M();await oI(o,n,t,r)})});Mt.command("start").description("Start an app on the device").option("--device <name|serial>","Target device (name or serial)").option("--bundle <name>","Bundle name (e.g. com.example.app)").option("--ability <name>","Ability to start (-a)").option("--action <action>","Action to send (-A)").option("--uri <uri>","URI to start with (-U)").action(async n=>{let e={event:v.CommandExecuted,args:["device","app","start",...n.bundle?["--bundle"]:[],...n.ability?["--ability"]:[],...n.action?["--action"]:[],...n.uri?["--uri"]:[],...n.device?["--device"]:[]]};await O(e,async()=>{let{toolProvider:t}=await M();await sI(t,n)})});Mt.command("install").description("Install package(s) on the device").option("--device <name|serial>","Target device (name or serial)").option("--replace","Override install").option("--shared <path>","Inter-app shared HSP path (repeatable)",(n,e)=>[...e,n],[]).option("--wait <seconds>","Install wait time in seconds",n=>parseInt(n,10)).option("--user <userId>","Target user ID").argument("[files...]","Local package path(s) to install (hap/hsp)").action(async(n,e)=>{let t={event:v.CommandExecuted,args:["device","app","install",...n.map(()=>"<file>"),...e.replace?["--replace"]:[],...e.shared?.length?["--shared"]:[],...e.wait!==void 0?["--wait"]:[],...e.user?["--user"]:[],...e.device?["--device"]:[]]};await O(t,async()=>{let{toolProvider:r}=await M();await dI(r,n,e)})});Mt.command("uninstall").description("Uninstall an app from the device").option("--device <name|serial>","Target device (name or serial)").requiredOption("--bundle <name>","Bundle name").action(async n=>{let e={event:v.CommandExecuted,args:["device","app","uninstall","--bundle",...n.device?["--device"]:[]]};await O(e,async()=>{let{toolProvider:t}=await M();await uI(t,n)})});Mt.command("stop").description("Stop an app on the device").option("--device <name|serial>","Target device (name or serial)").requiredOption("--bundle <name>","Bundle name").action(async n=>{let e={event:v.CommandExecuted,args:["device","app","stop","--bundle",...n.device?["--device"]:[]]};await O(e,async()=>{let{toolProvider:t}=await M();await aI(t,n)})});Mt.command("clearcache").description("Clear app cache on the device").option("--device <name|serial>","Target device (name or serial)").requiredOption("--bundle <name>","Bundle name").action(async n=>{let e={event:v.CommandExecuted,args:["device","app","clearcache","--bundle",...n.device?["--device"]:[]]};await O(e,async()=>{let{toolProvider:t}=await M();await pI(t,n)})});Mt.command("cleardata").description("Clear app data on the device").option("--device <name|serial>","Target device (name or serial)").requiredOption("--bundle <name>","Bundle name").action(async n=>{let e={event:v.CommandExecuted,args:["device","app","cleardata","--bundle",...n.device?["--device"]:[]]};await O(e,async()=>{let{toolProvider:t}=await M();await mI(t,n)})});import{Command as zr}from"commander";import{red as $w,yellow as fI}from"colorette";import Jr from"ora";function Ue(n){let e=`${n.stdout}
100
+ ${n.stderr}`;if(/testhelper.*(?:not found|inaccessible)/i.test(e))throw new Error("testhelper is not available on this device. Please upgrade the device system version to support this command.")}var pt=class{constructor(e){this.toolProvider=e}async getDeviceType(e){return(await C(this.toolProvider.hdcPath,["-t",e,"shell","param","get","const.product.devicetype"])).stdout}async wakeScreen(e){return(await C(this.toolProvider.hdcPath,["-t",e,"shell","power-shell","wakeup"])).stdout}async suspendScreen(e){return(await C(this.toolProvider.hdcPath,["-t",e,"shell","power-shell","suspend"])).stdout}async getScreenStatus(e){return(await C(this.toolProvider.hdcPath,["-t",e,"shell","hidumper","-s","PowerManagerService","-a","-s"])).stdout}async getDisplayInfo(e){return(await C(this.toolProvider.hdcPath,["-t",e,"shell","hidumper","-s","DisplayManagerService","-a","-a"])).stdout}async swipeScreen(e,t,r,i,o,s=6e3){let a=await C(this.toolProvider.hdcPath,["-t",e,"shell","uitest","uiInput","swipe",String(t),String(r),String(i),String(o),String(s)]);if(a.exitCode!==0)throw new Error(a.stderr||a.stdout||"swipe failed");return a.stdout}async getTime(e){let t=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","get-time"]);return Ue(t),t.stdout}async setTime(e,t){let r=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","set-time",t]);return Ue(r),r.stdout}async getTimezone(e){let t=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","get-timezone"]);return Ue(t),t.stdout}async setTimezone(e,t){let r=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","set-timezone",t]);return Ue(r),r.stdout}};function Un(n){let e=n.match(/\[DISPLAY INFO\][\s\S]*?Width:\s*(\d+)[\s\S]*?Height:\s*(\d+)/);return e?{width:Number(e[1]),height:Number(e[2])}:null}function yp(n){let e=n.match(/Current State:\s*(\w+)/);return e?e[1]:null}var Wi=class{constructor(e){this.toolProvider=e}async getDisplayInfo(e){return(await C(this.toolProvider.hdcPath,["-t",e,"shell","hidumper","-s","DisplayManagerService","-a","-a"])).stdout}async setScreenTimeout(e,t){return await C(this.toolProvider.hdcPath,["-t",e,"shell","hidumper","-s","PowerManagerService","-a","-f"]),(await C(this.toolProvider.hdcPath,["-t",e,"shell","power-shell","timeout","-o",String(t)])).stdout}async setScreenNeverSleep(e){return await C(this.toolProvider.hdcPath,["-t",e,"shell","power-shell","timeout","-r"]),(await C(this.toolProvider.hdcPath,["-t",e,"shell","hidumper","-s","PowerManagerService","-a","-t"])).stdout}};var hI=["phone","tablet"];async function wp(n,e){let i=(await new pt(n).getDeviceType(e)).trim().toLowerCase();if(!hI.includes(i))throw new y(`This command is only supported on phone and tablet devices (current: ${i||"unknown"}).`,"Unsupported device type.")}async function gI(n,e){let t=await T(n,e),r=new pt(n),i=Jr({text:"Waking screen...",color:"cyan"}).start();try{let o=await r.wakeScreen(t);i.stop();let s=o.trim();console.log(s||"Screen woken.")}catch(o){throw i.stop(),new y(`Failed to wake screen: ${o.message}`,"Failed to wake screen.")}}async function yI(n,e){let t=await T(n,e),r=new pt(n),i=Jr({text:"Suspending screen...",color:"cyan"}).start();try{let o=await r.suspendScreen(t);i.stop();let s=o.trim();console.log(s||"Screen suspended.")}catch(o){throw i.stop(),new y(`Failed to suspend screen: ${o.message}`,"Failed to suspend screen.")}}async function wI(n,e){let t=await T(n,e),r=new pt(n),i=Jr({text:"Querying screen status...",color:"cyan"}).start();try{let o=await r.getScreenStatus(t);i.stop();let s=yp(o);console.log(s?` Screen State: ${s}`:fI("No screen state found in output."))}catch(o){throw i.stop(),new y(`Failed to get screen status: ${o.message}`,"Failed to get screen status.")}}async function vI(n,e){let t=await T(n,e);await wp(n,t);let r=new pt(n),i=Jr({text:"Unlocking screen...",color:"cyan"}).start();try{await r.wakeScreen(t);let o=await r.getDisplayInfo(t),s=Un(o);if(!s)throw new Error("Failed to parse screen resolution from display info");let a=Math.round(s.width/2),c=Math.round(s.height*.98),l=c-Math.round(s.height/2);await r.swipeScreen(t,a,c,a,l),i.stop(),console.log(`Screen unlocked: swipe (${a}, ${c}) -> (${a}, ${l})`)}catch(o){throw i.stop(),new y(`Failed to unlock screen: ${o.message}`,"Failed to unlock screen.")}}async function bI(n,e){let t=await T(n,e);await wp(n,t);let r=new pt(n),i=Jr({text:"Opening control center...",color:"cyan"}).start();try{let o=await r.getDisplayInfo(t),s=Un(o);if(!s)throw new Error("Failed to parse screen resolution from display info");let a=Math.round(s.width*4/5),c=Math.round(s.height*.02),l=c+Math.round(s.height/3);await r.swipeScreen(t,a,c,a,l),i.stop(),console.log(`Control center opened: swipe (${a}, ${c}) -> (${a}, ${l})`)}catch(o){throw i.stop(),new y(`Failed to open control center: ${o.message}`,"Failed to open control center.")}}async function SI(n,e){let t=await T(n,e);await wp(n,t);let r=new pt(n),i=Jr({text:"Opening notification center...",color:"cyan"}).start();try{let o=await r.getDisplayInfo(t),s=Un(o);if(!s)throw new Error("Failed to parse screen resolution from display info");let a=Math.round(s.width/5),c=Math.round(s.height*.02),l=c+Math.round(s.height/3);await r.swipeScreen(t,a,c,a,l),i.stop(),console.log(`Notification center opened: swipe (${a}, ${c}) -> (${a}, ${l})`)}catch(o){throw i.stop(),new y(`Failed to open notification center: ${o.message}`,"Failed to open notification center.")}}var EI=/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;async function PI(n,e,t){let r=await T(n,t),i=new pt(n),o=e!==void 0;if(o&&!EI.test(e))throw new y(`Invalid time format. Time must be in 'YYYY-MM-DD HH:MM:SS' format (e.g. "2026-10-13 17:18:07").`,"Invalid time format.");let s=Jr({text:o?`Setting time to ${e}...`:"Getting time...",color:"cyan"}).start();try{let a=o?await i.setTime(r,e):await i.getTime(r);s.stop();let c=a.trim();/^error/i.test(c)?(console.error($w(c)),process.exitCode=1):console.log(c)}catch(a){throw s.stop(),new y(`Time ${o?"set":"get"} failed: ${a.message}`,`Time ${o?"set":"get"} failed.`)}}async function CI(n,e,t){let r=await T(n,t),i=new pt(n),o=e!==void 0,s=Jr({text:o?`Setting timezone to ${e}...`:"Getting timezone...",color:"cyan"}).start();try{let a=o?await i.setTimezone(r,e):await i.getTimezone(r);s.stop();let c=a.trim();/^error/i.test(c)?(console.error($w(c)),process.exitCode=1):console.log(c)}catch(a){throw s.stop(),new y(`Timezone ${o?"set":"get"} failed: ${a.message}`,`Timezone ${o?"set":"get"} failed.`)}}var Fw=[new zr("wake").description("Wake up the device screen").option("--device <name|serial>","Target device (name or serial)").action(async n=>{let{device:e}=n,t={event:v.CommandExecuted,args:["device","wake",...e?["--device"]:[]]};await O(t,async()=>{let{toolProvider:r}=await M();await gI(r,e)})}),new zr("sleep").description("Turn off the device screen").option("--device <name|serial>","Target device (name or serial)").action(async n=>{let{device:e}=n,t={event:v.CommandExecuted,args:["device","sleep",...e?["--device"]:[]]};await O(t,async()=>{let{toolProvider:r}=await M();await yI(r,e)})}),new zr("status").description("Query screen power state").option("--device <name|serial>","Target device (name or serial)").action(async n=>{let{device:e}=n,t={event:v.CommandExecuted,args:["device","status",...e?["--device"]:[]]};await O(t,async()=>{let{toolProvider:r}=await M();await wI(r,e)})}),new zr("unlock").description("Unlock the screen").option("--device <name|serial>","Target device (name or serial)").action(async n=>{let{device:e}=n,t={event:v.CommandExecuted,args:["device","unlock",...e?["--device"]:[]]};await O(t,async()=>{let{toolProvider:r}=await M();await vI(r,e)})}),new zr("open-control-center").description("Open the control center").option("--device <name|serial>","Target device (name or serial)").action(async n=>{let{device:e}=n,t={event:v.CommandExecuted,args:["device","open-control-center",...e?["--device"]:[]]};await O(t,async()=>{let{toolProvider:r}=await M();await bI(r,e)})}),new zr("open-notification-center").description("Open the notification center").option("--device <name|serial>","Target device (name or serial)").action(async n=>{let{device:e}=n,t={event:v.CommandExecuted,args:["device","open-notification-center",...e?["--device"]:[]]};await O(t,async()=>{let{toolProvider:r}=await M();await SI(r,e)})}),new zr("time").description("Get or set the device time").option("--device <name|serial>","Target device (name or serial)").argument("[datetime]","Datetime to set; omit to get current time").action(async(n,e)=>{let{device:t}=e,r={event:v.CommandExecuted,args:["device","time",...n?["<datetime>"]:[],...t?["--device"]:[]]};await O(r,async()=>{let{toolProvider:i}=await M();await PI(i,n,t)})}),new zr("timezone").description("Get or set the device timezone").option("--device <name|serial>","Target device (name or serial)").argument("[timezone]","Timezone to set; omit to get current timezone").action(async(n,e)=>{let{device:t}=e,r={event:v.CommandExecuted,args:["device","timezone",...n?["<timezone>"]:[],...t?["--device"]:[]]};await O(r,async()=>{let{toolProvider:i}=await M();await CI(i,n,t)})})];import{Command as OT,Option as MT}from"commander";import{yellow as NT}from"colorette";import bs from"ora";import{appendFileSync as B5}from"fs";var Nt={TRACE:10,DEBUG:20,INFO:30,WARN:40,ERROR:50,SILENT:100},Hw={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",100:"SILENT"};function vp(n){if(typeof n=="number")return n;let e=String(n||"").toUpperCase();return e in Nt?Nt[e]:Nt.INFO}function kI(n){return{write:n}}function RI({useStderr:n}={}){return kI((e,t)=>{let r=`${DI[Hw[e.level]]||""}${t}`;n||e.level>=Nt.ERROR?process.stderr.write(r+`
101
+ `):process.stdout.write(r+`
102
+ `)})}var DI={TRACE:"",DEBUG:"",INFO:"",WARN:"",ERROR:""};function xI(n){let e=new Date(n),t=(r,i=2)=>String(r).padStart(i,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}.${t(e.getMilliseconds(),3)}`}var os=class n{name;level;transports;fields;timestamp;constructor(e={}){this.name=e.name||"hm",this.level=vp(e.level??"info"),this.transports=e.transports||[RI()],this.fields={...e.fields||{}},this.timestamp=e.timestamp!==!1}child(e,t){return new n({name:e?`${this.name}:${e}`:this.name,level:this.level,transports:this.transports,fields:{...this.fields,...t||{}},timestamp:this.timestamp})}withFields(e){return this.child("",e)}setLevel(e){return this.level=vp(e),this}addTransport(e){return this.transports.push(e),this}isLevelEnabled(e){return vp(e)>=this.level}trace(e,...t){this._log(Nt.TRACE,e,t)}debug(e,...t){this._log(Nt.DEBUG,e,t)}info(e,...t){this._log(Nt.INFO,e,t)}warn(e,...t){this._log(Nt.WARN,e,t)}error(e,...t){this._log(Nt.ERROR,e,t)}timeStart(e,t=Nt.DEBUG){let r=Date.now();return i=>{let o=Date.now()-r;return this._log(t,`${e} cost ${o}ms${i?" "+i:""}`,[]),o}}_log(e,t,r){if(e<this.level)return;let i;try{i=typeof t=="string"?t:jw(t),r&&r.length&&(i+=" "+r.map(l=>l instanceof Error?`${l.name}: ${l.message}`:typeof l=="string"?l:jw(l)).join(" "))}catch{i=String(t)}let o=AI(this.fields),a=`${this.timestamp?`[${xI(Date.now())}] `:""}[${Hw[e]}] [${this.name}]${o} ${i}`,c={level:e,name:this.name,message:i,fields:{...this.fields},ts:Date.now()};for(let l of this.transports)try{l.write(c,a)}catch{}}};function AI(n){let e=Object.keys(n||{});return e.length?" "+e.map(t=>`${t}=${n[t]}`).join(" "):""}function jw(n){try{return JSON.stringify(n)}catch{return String(n)}}var bp=new os({name:"hm",level:"info"});function Sp(n={}){return bp=new os({name:"hm",...n}),bp}function ss(n){return bp.child(n,{})}import{spawn as II}from"child_process";var Vi=class extends Error{code;details;constructor(e,t={}){super(e,t.cause?{cause:t.cause}:void 0),this.name=new.target.name,this.code=t.code||new.target.code||"HM_ERROR",this.details=t.details,Error.captureStackTrace&&Error.captureStackTrace(this,new.target)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}},Bn=class extends Vi{static code="HDC_ERROR";args;stderr;constructor(e,t={}){super(e,{...t,code:t.code||"HDC_ERROR"}),this.args=t.details?.args||[],this.stderr=t.details?.stderr||""}},Yr=class extends Bn{static code="HDC_TIMEOUT";constructor(e,t={}){super(e,{...t,code:"HDC_TIMEOUT"})}},as=class extends Bn{static code="HDC_COMMAND_FAILED";constructor(e,t={}){super(e,{...t,code:"HDC_COMMAND_FAILED"})}},bt=class extends Vi{static code="DEVICE_ERROR";constructor(e,t={}){super(e,{...t,code:t.code||"DEVICE_ERROR"})}},Kr=class extends bt{static code="DEVICE_NOT_FOUND";constructor(e,t={}){super(e,{...t,code:"DEVICE_NOT_FOUND"})}},Xr=class extends bt{static code="DEVICE_FILE_ERROR";constructor(e,t={}){super(e,{...t,code:"DEVICE_FILE_ERROR"})}},er=class extends Vi{static code="RPC_ERROR";endpoint;constructor(e,t={}){super(e,{...t,code:t.code||"RPC_ERROR"}),this.endpoint=t.details?.endpoint||""}},tr=class extends er{static code="RPC_LIFECYCLE_ERROR";constructor(e,t={}){super(e,{...t,code:"RPC_LIFECYCLE_ERROR"})}},Pr=class extends tr{static code="RPC_DISPOSED";constructor(e,t={}){super(e,{...t,code:"RPC_DISPOSED"})}},_e=class extends er{static code="RPC_TRANSPORT_ERROR";constructor(e,t={}){super(e,{...t,code:"RPC_TRANSPORT_ERROR"})}},Zr=class extends er{static code="RPC_TIMEOUT";constructor(e,t={}){super(e,{...t,code:"RPC_TIMEOUT"})}},Lt=class extends er{static code="RPC_PROTOCOL_ERROR";constructor(e,t={}){super(e,{...t,code:"RPC_PROTOCOL_ERROR"})}},cs=class extends er{static code="RPC_REMOTE_ERROR";remote;constructor(e,t={}){super(e,{...t,code:"RPC_REMOTE_ERROR"}),this.remote=t.details?.remote}};function Uw(n){return n instanceof _e||n instanceof Zr||n instanceof Lt}function Ep(n){return n instanceof Pr?!1:Uw(n)||n instanceof tr}var ls=class{args;code;stdout;stderr;durationMs;constructor({args:e,code:t=0,stdout:r="",stderr:i="",durationMs:o=0}){this.args=e,this.code=t,this.stdout=r,this.stderr=i,this.durationMs=o}get ok(){return this.code===0}get command(){return this.args.join(" ")}assertOk(e="hdc command"){if(this.ok)return this;throw new as(`${e} failed: ${this.stderr||this.stdout||`exit ${this.code}`}`,{details:{args:this.args,stderr:this.stderr,stdout:this.stdout,code:this.code}})}toString(){return this.command}},ds=class{bin;host;port;execTimeoutMs;logger;dfx;constructor(e={}){this.bin=e.bin||"hdc",this.host=e.host||"127.0.0.1",this.port=e.port??8710,this.execTimeoutMs=e.execTimeoutMs??1e4,this.logger=e.logger??null,this.dfx=e.dfx??null}async exec(e,t){throw new Bn("HdcExecutor.exec() must be implemented by subclass")}get serverAddress(){return`${this.host||"127.0.0.1"}:${this.port??8710}`}serverPrefixArgs(){return(!this.host||this.host==="127.0.0.1"||this.host==="localhost")&&(this.port??8710)===8710?[]:["-s",this.serverAddress]}async listTargets(e){let t=await this.exec(["list","targets"],e);return Bw(t.stdout)}};function Bw(n){let e=String(n||"").trim();return!e||/\[Empty\]/i.test(e)||/^Empty$/i.test(e)?[]:e.split(/\r?\n/).map(t=>t.trim()).filter(t=>t&&!/\[Empty\]/i.test(t)&&!/^Empty$/i.test(t))}function Pp(n){let e=[];for(let t of String(n||"").split(/\r?\n/)){let r=t.trim();if(!r||/\[Empty\]/i.test(r)||/^Empty$/i.test(r))continue;let i=/tcp:(\d+)\s+(\S+)/.exec(r);if(!i)continue;let o=Number(i[1]);Number.isInteger(o)&&e.push({hostPort:o,deviceEndpoint:i[2],taskString:`tcp:${o} ${i[2]}`})}return e}function Cp(n){let e=[];for(let t of String(n||"").split(/\r?\n/)){let r=t.trim();if(!r)continue;let i=/^(\S+)\s+(\d+)\s+(\d+)\s+(.*)$/.exec(r);i&&e.push({user:i[1],pid:Number(i[2]),cmd:i[4]})}return e}var Wn=class extends ds{env;onStderr;windowsHide;constructor(e={}){super(e),this.env=e.env||process.env,this.onStderr=e.onStderr??null,this.windowsHide=e.windowsHide!==!1}_childEnv(){let e={...this.env};return this.host&&this.host!=="127.0.0.1"&&(e.HDC_SERVER_IP||(e.HDC_SERVER_IP=this.host),e.HDC_SERVER_PORT||(e.HDC_SERVER_PORT=String(this.port))),e}exec(e,t={}){let r=t.timeoutMs??this.execTimeoutMs,i=Date.now(),o=this.dfx?this.dfx.timer("hdc.exec",{cmd:e[0]}):null,s=[...this.serverPrefixArgs(),...e],a=this._childEnv();return new Promise((c,l)=>{let d=this.spawnHdcChild(s,a,o,l);d&&this.attachChildHandlers(d,e,r,i,o,c,l)})}spawnHdcChild(e,t,r,i){try{return m(`Executing: ${this.bin} ${e.join(" ")}`),II(this.bin,e,{env:t,stdio:["ignore","pipe","pipe"],windowsHide:this.windowsHide})}catch(o){return r&&r({ok:0}),i(new Yr(`spawn ${this.bin} failed: ${o.message}`,{cause:o})),null}}attachChildHandlers(e,t,r,i,o,s,a){let c={outChunks:[],errChunks:[],settled:!1,timedOut:!1,timer:null};c.timer=setTimeout(()=>{c.timedOut=!0;try{e.kill("SIGKILL")}catch{}},r),e.stdout?.on("data",l=>{c.outChunks.length<4096&&c.outChunks.push(l)}),e.stderr?.on("data",l=>{c.errChunks.push(l),this.onStderr&&this.onStderr(l.toString())}),e.on("close",l=>{this.finalizeResult(l,t,r,i,o,c,s,a)}),e.on("error",l=>{this.handleChildError(l,t,o,c,a)})}finalizeResult(e,t,r,i,o,s,a,c){if(s.settled)return;s.settled=!0,s.timer&&clearTimeout(s.timer);let l=Buffer.concat(s.outChunks).toString("utf8").trim(),d=Buffer.concat(s.errChunks).toString("utf8").trim(),g=Date.now()-i;if(o&&o({ok:e===0?1:0}),this.dfx&&this.dfx.counter(e===0?"hdc.exec.ok":"hdc.exec.error",1,{cmd:t[0]}),this.logger&&this.logger.debug(`hdc ${t.join(" ")} -> code=${e} (${g}ms)`),s.timedOut){c(new Yr(`hdc ${t.join(" ")} timeout after ${r}ms`,{details:{args:t,stdout:l,stderr:d}}));return}a(new ls({args:t,code:e??-1,stdout:l,stderr:d,durationMs:g}))}handleChildError(e,t,r,i,o){i.settled||(i.settled=!0,i.timer&&clearTimeout(i.timer),r&&r({ok:0}),o(new Yr(`hdc ${t.join(" ")} spawn error: ${e.message}`,{cause:e})))}};var Ww=Object.freeze({hdc:{bin:"hdc",host:"127.0.0.1",port:8710,execTimeoutMs:1e4,maxOutputBytes:4194304},device:{autoSelectFirst:!0,queryVersion:!0,newUiTestMinVersion:"6.0.2.2",autoPushResources:!0,resourcesDir:"",fastModeDir:""},rpc:{mode:"fast",framing:"auto",connectTimeoutMs:5e3,requestTimeoutMs:3e4,socketIdleTimeoutMs:3e4,portRange:{start:1e4,end:19999},concurrency:"auto",maxInFlight:16,strictPairing:!1,timeoutKillsConnection:!1,recovery:{enabled:!0,maxAttempts:1,delayMs:200},fast:{connectTimeoutMs:1500,probeOnReuse:!0,keepOnRelease:!0,forceRestartOnProbeFailure:!0},operate:{fastHostPort:19801,startWaitMs:500,processWaitTimeoutMs:15e3,processCheckIntervalMs:200,checkListening:!0,resources:[]}},log:{level:"info",timestamp:!0,transports:["console"],file:""},dfx:{enabled:!0,sinks:["memory"],slowThresholdMs:1e3}}),TI={HM_HDC_BIN:"hdc.bin",HM_HDC_HOST:"hdc.host",HM_HDC_PORT:"hdc.port",HM_LOG_LEVEL:"log.level",HM_RPC_MODE:"rpc.mode",HM_RPC_REQUEST_TIMEOUT:"rpc.requestTimeoutMs"};function Mc(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function kp(n){if(typeof structuredClone=="function")try{return structuredClone(n)}catch{}return JSON.parse(JSON.stringify(n))}function Oc(n,e){let t=kp(n);for(let[r,i]of Object.entries(e||{}))i!==void 0&&(Mc(i)&&Mc(t[r])?t[r]=Oc(t[r],i):t[r]=kp(i));return t}function OI(n,e){return e.split(".").reduce((t,r)=>{if(!(t==null||typeof t!="object"))return t[r]},n)}function Vw(n,e,t){let r=e.split("."),i=r.pop(),o=n;for(let s of r)Mc(o[s])||(o[s]={}),o=o[s];return o[i]=t,n}var Nc=class{_data;constructor(e={}){this._data=Oc(Ww,MI()),e&&Object.keys(e).length&&(this._data=Oc(this._data,e))}slice(e){let t=this.get(e);return Mc(t)?t:{}}get(e,t){let r=OI(this._data,e);return r===void 0?t:r}set(e,t){return Vw(this._data,e,t),this}merge(e){return this._data=Oc(this._data,e),this}snapshot(){return kp(this._data)}toJSON(){return this.snapshot()}};function MI(){let n={};for(let[e,t]of Object.entries(TI)){let r=process.env[e];if(r===void 0||r==="")continue;let i=r;if(t==="hdc.port"||t==="rpc.requestTimeoutMs"){let o=Number(r);if(Number.isNaN(o))continue;i=o}Vw(n,t,i)}return n}function us(n){return new Nc(n)}var Lc=class{records;constructor(){this.records=[]}write(e){this.records.push(e)}select(e){return this.records.filter(t=>typeof e=="function"?e(t.name):t.name===e||t.name.startsWith(e+"."))}sum(e){return this.select(e).reduce((t,r)=>t+(r.value||0),0)}count(e){return this.select(e).length}snapshot(){return{counters:Gw(this.records,"counter"),timers:Gw(this.records,"timer"),events:this.records.filter(e=>e.type==="event").map(e=>({name:e.name,fields:e.fields,ts:e.ts}))}}reset(){this.records.length=0}};function Gw(n,e){let t={};for(let r of n){if(r.type!==e)continue;t[r.name]||(t[r.name]={count:0,sum:0,min:1/0,max:0,avg:0});let i=e==="counter"?r.value||0:r.durationMs||0;t[r.name].count+=1,t[r.name].sum+=i,t[r.name].min=Math.min(t[r.name].min,i),t[r.name].max=Math.max(t[r.name].max,i)}for(let r of Object.keys(t))t[r].avg=t[r].sum/t[r].count,t[r].min===1/0&&(t[r].min=0);return t}var _c=class n{enabled;tags;sinks;slowThresholdMs;logger;constructor(e={}){this.enabled=e.enabled!==!1,this.tags={...e.tags||{}},this.sinks=e.sinks||[new Lc],this.slowThresholdMs=e.slowThresholdMs??1e3,this.logger=e.logger??null}child(e){return new n({enabled:this.enabled,sinks:this.sinks,tags:{...this.tags,...e||{}},slowThresholdMs:this.slowThresholdMs,logger:this.logger})}counter(e,t=1,r={}){this._emit({type:"counter",name:e,value:t,fields:r})}event(e,t={}){this._emit({type:"event",name:e,fields:t})}timer(e,t={}){let r=Date.now();return(i={})=>{let o=Date.now()-r;return this._emit({type:"timer",name:e,fields:{...t,...i},durationMs:o}),this.slowThresholdMs>0&&o>this.slowThresholdMs&&this._emit({type:"event",name:"slow",fields:{...t,...i,metric:e,durationMs:o}}),o}}async span(e,t,r={}){let i=this.timer(e,r);try{let o=await t();return i({ok:1}),this.counter(`${e}.ok`,1,r),o}catch(o){throw i({ok:0}),this.counter(`${e}.error`,1,{...r,code:o?.code||o?.name}),o}}_emit(e){if(!this.enabled)return;let t={type:e.type,name:e.name,value:e.value,durationMs:e.durationMs,fields:{...this.tags,...e.fields||{}},ts:Date.now()};for(let r of this.sinks)try{r.write(t)}catch{}}snapshot(){let e=this.sinks.find(t=>t instanceof Lc);return e?e.snapshot():null}reset(){for(let e of this.sinks)typeof e.reset=="function"&&e.reset()}};function ps(n={}){return new _c(n)}function Gi(n){return new Promise(e=>setTimeout(e,n))}async function $c(n,{timeoutMs:e,intervalMs:t=200,firstDelayMs:r=0,description:i="condition"}){let o=Date.now()+e;r>0&&await Gi(r);let s;for(;;){if(s=await n(),s)return s;if(Date.now()>=o){let a=new Error(`wait for ${i} timeout after ${e}ms`);throw a.name="TimeoutError",a}await Gi(t)}}var qi=class{_tail;locked;constructor(){this._tail=Promise.resolve(),this.locked=!1}async runExclusive(e){let t,r=new Promise(o=>{t=o}),i=this._tail;this._tail=i.then(()=>r),await i.catch(()=>{}),this.locked=!0;try{return await e()}finally{this.locked=!1,t()}}},zi=class{limit;used;_waiters;_idleWaiters;constructor(e=1){this.limit=Math.max(1,e|0),this.used=0,this._waiters=[],this._idleWaiters=[]}get available(){return Math.max(0,this.limit-this.used)}get waiting(){return this._waiters.length}get isIdle(){return this.used===0}acquire(){return new Promise((e,t)=>{this._waiters.push({resolve:e,reject:t}),this._dispatch()})}resize(e){let t=Math.max(1,e|0);t!==this.limit&&(this.limit=t,this._dispatch())}abortAll(e){let t=this._waiters.splice(0);for(let r of t)try{r.reject(e)}catch{}}drain(){return this.used===0?Promise.resolve():new Promise(e=>{this._idleWaiters.push({resolve:e})})}_dispatch(){for(;this._waiters.length>0&&this.used<this.limit;){let e=this._waiters.shift();this.used+=1;let t=!1;e.resolve(()=>{t||(t=!0,this.used-=1,this._dispatch(),this.used===0&&this._idleWaiters.length&&this._resolveIdleWaiters())})}}_resolveIdleWaiters(){let e=this._idleWaiters.splice(0);for(let t of e)t.resolve()}},Vn=class{_map;constructor(){this._map=new Map}run(e,t){let r=this._map.get(e);if(r)return r;let o=(async()=>t())().finally(()=>{this._map.get(e)===o&&this._map.delete(e)});return this._map.set(e,o),o}pending(e){return this._map.get(e)||null}has(e){return this._map.has(e)}keys(){return[...this._map.keys()]}};var NI=64*1024*1024,Rp={name:"length-prefixed",frameDelimited:!0,encode(n){let e=Buffer.from(typeof n=="string"?n:JSON.stringify(n),"utf8"),t=Buffer.alloc(4);return t.writeUInt32BE(e.length,0),Buffer.concat([t,e])},decode(n){if(n.length<4)return null;let e=n.readUInt32BE(0);if(e>NI||e<0)throw new Lt(`invalid frame length ${e}`);if(n.length<4+e)return null;let t=n.subarray(4,4+e).toString("utf8"),r;try{r=JSON.parse(t)}catch{throw new Lt(`response is not valid JSON: ${t.slice(0,200)}`)}return{value:r,rest:n.subarray(4+e)}}},Fc={name:"raw",frameDelimited:!1,encode(n){return Buffer.from(typeof n=="string"?n:JSON.stringify(n),"utf8")},decode(n){let e=n.toString("utf8").trim();if(!e)return null;let t;try{t=JSON.parse(e)}catch{return null}return{value:t,rest:Buffer.alloc(0)}}};function LI(n){if(!n||n.length===0)return null;let e=n[0];return e===123||e===91?"raw":"length-prefixed"}function Dp(n="auto"){return n==="raw"?Fc:n==="length-prefixed"?Rp:_I()}function _I(){let n=null;return{name:"auto",frameDelimited:!1,get detected(){return n},encode(e){return Fc.encode(e)},decode(e){return n||(n=LI(e)),n==="length-prefixed"?Rp.decode(e):Fc.decode(e)}}}var xp=0;function rr(n="hm"){xp=(xp+1)%1e6;let e=new Date().toISOString().replace(/[-:T]/g,"").replace(/\..+/,""),t=Math.random().toString(36).slice(2,8);return`${n}-${e}-${xp.toString(36)}-${t}`}import Ap from"net";function Ip(n,e,t=500){return new Promise(r=>{let i=new Ap.Socket,o=!1,s=a=>{o||(o=!0,i.destroy(),r(a))};i.setTimeout(t),i.once("connect",()=>s(!0)),i.once("timeout",()=>s(!1)),i.once("error",()=>s(!1));try{i.connect(e,n)}catch{s(!1)}})}async function Tp({host:n="127.0.0.1",start:e=1e4,end:t=19999,exclude:r}={}){let i=new Set(r||[]);for(let o=e;o<=t;o++){if(i.has(o))continue;if(await FI(n,o))return o}throw new Error(`no free port in range ${e}-${t}`)}var $I=Tp;function FI(n,e){return new Promise(t=>{let r=Ap.createServer();r.once("error",()=>t(!1)),r.once("listening",()=>{r.close(()=>t(!0))}),r.listen(e,n)})}async function jI({host:n="127.0.0.1",start:e=1e4,end:t=19999,exclude:r,timeoutMs:i=500,stepDelayMs:o=0}={}){if(!n)throw new Error("getFreeRemotePort requires host");let s=new Set(r||[]);for(let a=e;a<=t;a++){if(s.has(a))continue;if(!await Ip(n,a,i))return a;o>0&&await new Promise(l=>setTimeout(l,o))}throw new Error(`no free port on remote ${n} in range ${e}-${t}`)}async function qw({hdcHost:n="127.0.0.1",start:e,end:t,exclude:r}={}){return!n||n==="127.0.0.1"||n==="localhost"?{port:await $I({host:n||"127.0.0.1",start:e,end:t,exclude:r}),scope:"local"}:{port:await jI({host:n,start:e,end:t,exclude:r,stepDelayMs:50}),scope:"remote"}}function jc({host:n,port:e,timeoutMs:t=5e3,keepAliveMs:r}){return new Promise((i,o)=>{let s=new Ap.Socket,a=!1,c=l=>{a||(a=!0,s.destroy(),o(l))};s.setTimeout(t),s.once("timeout",()=>{let l=new Error(`connect to ${n}:${e} timeout after ${t}ms`);l.code="ETIMEDOUT",c(l)}),s.once("error",c),s.connect(e,n,()=>{a||(a=!0,s.removeListener("error",c),s.removeListener("timeout",c),r&&r>0&&s.setKeepAlive(!0,r),s.setNoDelay(!0),i(s))})})}function _t(n,e){let t=zw(n),r=zw(e),i=Math.max(t.length,r.length);for(let o=0;o<i;o++){let s=t[o]??0,a=r[o]??0;if(s>a)return 1;if(s<a)return-1}return 0}function zw(n){return String(n||"").trim().split(/[.\-+_]/).filter(Boolean).map(e=>{let t=parseInt(e,10);return Number.isNaN(t)?0:t})}function Ji(n){let e=/(\d+(?:\.\d+)+)/.exec(String(n||""));return e?e[1]:null}var HI=/^[A-Za-z0-9_@%+=:,./-]+$/,UI=/'/g,BI="'\\''";function Gn(n){let e=n==null?"":String(n);return e===""?"''":HI.test(e)?e:`'${e.replace(UI,BI)}'`}function St(n){if(!Array.isArray(n))throw new TypeError("shellJoin expects an array of arguments");return n.filter(e=>e!=null&&e!=="").map(e=>Gn(e)).join(" ")}function Op(n){let e=String(n??"");if(/[\r\n\0]/.test(e))throw new nr("shell command must not contain newline or NUL characters");return e}function ir(n){let e=String(n??"").trim();if(!e)throw new nr("remote path is empty");if(!e.startsWith("/"))throw new nr(`remote path must be absolute: ${JSON.stringify(n)}`);if(/[\r\n\0]/.test(e))throw new nr("remote path must not contain newline or NUL characters");return e}function Mp(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new nr(`invalid pid: ${JSON.stringify(n)}`);return e}function Hc(n){let e=String(n??"").trim();if(!/^(localabstract|localfilesystem|tcp|jdwp):[A-Za-z0-9_.-]+$/.test(e))throw new nr(`invalid device endpoint: ${JSON.stringify(n)}`);return e}function Uc(n){let e=Number(n);if(!Number.isInteger(e)||e<1||e>65535)throw new nr(`invalid host port: ${JSON.stringify(n)}`);return e}var nr=class extends Error{constructor(e){super(e),this.name="ShellSafetyError"}};import{stat as PT}from"fs/promises";var zI="6.0.2.2";async function Jw(n,e={}){let t=e.minVersion||zI,r=(await n.shellArgs(["file","/system/bin/uitest"])).trim(),i=/x86[ _-]64/.test(r)?"x86_64":"arm64",o=(await n.shellArgs(["/system/bin/uitest","--version"])).trim(),s=JI(o)||o,a=_t(s,t)>=0;return{version:s,arch:i,isNewUiTest:a,endpointStyle:a&&i!=="x86_64"?"unix":"tcp",fileOutput:r}}function JI(n){let e=/(\d+(?:\.\d+)+)/.exec(String(n||""));return e?e[1]:null}import{fileURLToPath as eT}from"url";import{dirname as tT,join as Xw}from"path";import{readdirSync as YI}from"fs";import{join as KI,basename as $8}from"path";var XI=/^uitest_agent_v(\d+\.\d+\.\d+)(\.x86_64)?\.so$/,ZI="/data/local/tmp/agent.so",Np="UITEST_AGENT_LIBRARY";function QI(n){let e;try{e=YI(n)}catch{return[]}return e.filter(t=>t.endsWith(".so"))}function Yw({dir:n,arch:e,isNewUiTest:t}){let r=e==="x86_64",i=[];for(let s of QI(n)){let a=XI.exec(s);if(!a)continue;let c=!!a[2];if(r!==c)continue;if(r){i.push({fileName:s,version:a[1],x86_64:c});continue}let l=_t(a[1],"1.2.2")>=0;t===l&&i.push({fileName:s,version:a[1],x86_64:c})}if(!i.length)return null;i.sort((s,a)=>_t(a.version,s.version));let o=i[0];return{fileName:o.fileName,localPath:KI(n,o.fileName),version:o.version,x86_64:o.x86_64,remotePath:ZI,versionProbe:Np}}function Kw(n){let e=String(n||""),t=e.indexOf("#"),r=t>=0?e.slice(t+1):e;return Ji(r)}var rT=Xw(tT(eT(import.meta.url)),"..",".."),nT=Xw(rT,"resources"),Bc=class{device;config;logger;dfx;_agentState;constructor({device:e,config:t,logger:r,dfx:i}){this.device=e,this.config=t,this.logger=r?r.child("ResourceMgr"):null,this.dfx=i??null,this._agentState=null}get resourcesDir(){return this.config.get("device.resourcesDir")||nT}async getInfo(e=!1){return this.device.getUitestInfo(e)}async ensureAgent(e={}){if(this._agentState&&!e.force)return this._agentState;let t=await this.getInfo(),r=Yw({dir:this.resourcesDir,arch:t.arch,isNewUiTest:t.isNewUiTest});if(!r)throw new bt(`no uitest agent found for arch=${t.arch} isNewUiTest=${t.isNewUiTest} in ${this.resourcesDir}`,{details:{resourcesDir:this.resourcesDir}});let i=await this.device.fileExists(r.remotePath),o=null,s=!i;return i&&(o=await this._probeAgentVersion(r.remotePath),(!o||_t(r.version,o)>0)&&(s=!0)),s?(this.logger&&this.logger.info(`update agent.so: local=v${r.version} remote=${o||"none"} (arch=${r.x86_64?"x86_64":"arm64"})`),await this.stopUitestDaemons(),await this.device.rm(r.remotePath),await this._push(r.localPath,r.remotePath,"agent.so"),this.dfx&&this.dfx.counter("resource.agent.update",1,{arch:t.arch})):this.logger&&this.logger.debug(`agent.so up-to-date: v${o}`),this._agentState={candidate:r,updated:s,remoteVersion:o},this._agentState}async repushAgent(){let e=this._agentState?.candidate;e||(e=(await this.ensureAgent()).candidate),this.logger&&this.logger.info(`repush agent.so unconditionally (suspect corruption): ${e.fileName}`),await this.stopUitestDaemons(),await this.device.rm(e.remotePath),await this._push(e.localPath,e.remotePath,"agent.so"),this.dfx&&this.dfx.counter("resource.agent.repush",1,{file:e.fileName}),this._agentState={candidate:e,updated:!0,remoteVersion:e.version}}async _probeAgentVersion(e){try{let t=await this.device.shell(`cat ${Gn(e)} | ${St(["grep","-a",Np])}`);return Kw(t)}catch{return null}}async _push(e,t,r){let i=this.dfx?this.dfx.timer("resource.push",{file:r}):null;await this.device.fileSend(e,t),i&&i({ok:1})}async stopUitestDaemons(){let t=(await this.device.findProcesses()).filter(r=>r.cmd.includes("uitest")&&r.cmd.includes("start-daemon")).map(r=>r.pid);for(let r of t)try{await this.device.killProcess(r)}catch(i){this.logger&&this.logger.debug(`kill daemon pid=${r} failed: ${i.message}`)}return t.length&&this.logger&&this.logger.info(`stopped uitest daemons before agent update: [${t.join(", ")}]`),t.length}};import{join as Lp}from"path";import{mkdir as iT,readFile as Zw,writeFile as Qw,unlink as oT,readdir as sT}from"fs/promises";function aT(n){return String(n||"unknown").replace(/[^A-Za-z0-9._-]/g,"_")}var cT=Lp(W(),"fast-mode"),Wc=class{config;logger;_explicitDir;constructor({config:e,dir:t,logger:r}={}){this.config=e,this.logger=r?r.child("FastModeStore"):null,this._explicitDir=t}get dir(){if(this._explicitDir)return this._explicitDir;if(this.config){let e=this.config.get("device.fastModeDir");if(e)return e}return cT}pathFor(e){return Lp(this.dir,`${aT(e)}.json`)}async _ensureDir(){await iT(this.dir,{recursive:!0,mode:448})}async save(e,t){await this._ensureDir();let r=await this.read(e)||{serial:e,createdAt:new Date(0).toISOString(),updatedAt:new Date(0).toISOString(),endpoints:{}};r.serial=e,r.updatedAt=new Date().toISOString(),(!r.createdAt||r.createdAt===new Date(0).toISOString())&&(r.createdAt=r.updatedAt),r.hdcServer=t.hdcServer||r.hdcServer||"",r.endpoints[t.endpoint]={hostPort:t.hostPort,deviceEndpoint:t.deviceEndpoint,style:t.style,agentVersion:t.agentVersion||null,uitestVersion:t.uitestVersion||null,savedAt:r.updatedAt};let i=this.pathFor(e);return await Qw(i,JSON.stringify(r,null,2),{mode:384}),this.logger&&this.logger.debug(`saved fast-mode state for ${e}: ${t.endpoint} -> tcp:${t.hostPort}`),r}async read(e){try{let t=await Zw(this.pathFor(e),"utf8"),r=JSON.parse(t);return!r||typeof r!="object"||!r.endpoints?null:r}catch{return null}}async get(e,t){let r=await this.read(e);return r&&r.endpoints&&r.endpoints[t]||null}async forget(e){try{return await oT(this.pathFor(e)),this.logger&&this.logger.debug(`removed fast-mode state for ${e}`),!0}catch{return!1}}async forgetEndpoint(e,t){let r=await this.read(e);return!r||!r.endpoints[t]?!1:(r.endpoints=Object.fromEntries(Object.entries(r.endpoints).filter(([i])=>i!==t)),Object.keys(r.endpoints).length?(await this._ensureDir(),await Qw(this.pathFor(e),JSON.stringify(r,null,2),{mode:384}),!0):this.forget(e))}async list(){let e;try{e=await sT(this.dir)}catch{return[]}let t=[];for(let r of e)if(r.endsWith(".json"))try{t.push(JSON.parse(await Zw(Lp(this.dir,r),"utf8")))}catch{}return t}};var or={AUTO:"auto",PIPELINED:"pipelined",SERIAL:"serial"},ms=class{host;port;name;codec;frameDelimited;concurrency;maxInFlight;strictPairing;timeoutKillsConnection;connectTimeoutMs;requestTimeoutMs;socketIdleTimeoutMs;logger;dfx;socket;buffer;pending;_sem;generation;_closed;_failure;onClose;_serverEchoesRequestId;_seq;stats;constructor(e){this.host=e.host||"127.0.0.1",this.port=e.port,this.name=e.name||"rpc",this.codec=Dp(e.framing||"auto"),this.frameDelimited=this.codec.frameDelimited===!0,this.concurrency=e.concurrency||or.AUTO,this.maxInFlight=Math.max(1,e.maxInFlight??16),this.strictPairing=e.strictPairing===!0,this.timeoutKillsConnection=e.timeoutKillsConnection===!0,this.connectTimeoutMs=e.connectTimeoutMs??5e3,this.requestTimeoutMs=e.requestTimeoutMs??3e4,this.socketIdleTimeoutMs=e.socketIdleTimeoutMs??3e4,this.logger=e.logger??null,this.dfx=e.dfx??null,this.socket=null,this.buffer=Buffer.alloc(0),this.pending=new Map,this._sem=new zi(this._initialLimit()),this.generation=0,this._closed=!0,this._failure=null,this.onClose=null,this._serverEchoesRequestId=null,this._seq=0,this.stats={connectCount:0,requestCount:0,bytesIn:0,bytesOut:0,maxInFlight:0,timeouts:0,unmatchedResponses:0,queued:0}}get isConnected(){return!!this.socket&&!this.socket.destroyed&&!this._closed}get inFlight(){return this.pending.size}get concurrencyMode(){return this.concurrency===or.SERIAL?"serial":this.frameDelimited?this.concurrency===or.PIPELINED?"pipelined":this._serverEchoesRequestId===!0?"pipelined(auto)":"serial(auto)":"serial(raw)"}async connect(e={}){await this.destroy();let t=e.port??this.port,r=e.timeoutMs??this.connectTimeoutMs,i=this.dfx?this.dfx.timer("rpc.connect",{endpoint:this.name}):null;try{this.socket=await jc({host:this.host,port:t,timeoutMs:r})}catch(a){let c=a;throw i&&i({ok:0}),this.dfx&&this.dfx.counter("rpc.connect.error",1,{endpoint:this.name}),new _e(`connect ${this.host}:${t} failed: ${c.message}`,{cause:c,details:{endpoint:this.name,host:this.host,port:t}})}let o=++this.generation;this._postConnectSetup(),i&&i({ok:1}),this.dfx&&this.dfx.counter("rpc.connect.ok",1,{endpoint:this.name});let s=this.socket;s.setTimeout(this.socketIdleTimeoutMs),this._attachSocketHandlers(s,o),this.logger&&this.logger.info(`connected to ${this.host}:${t} (${this.name}, gen=${o})`)}_postConnectSetup(){this._closed=!1,this._failure=null,this.buffer=Buffer.alloc(0),this.pending.clear(),this._serverEchoesRequestId=null,this._sem.resize(this._computeLimit()),this.stats.connectCount+=1}_attachSocketHandlers(e,t){e.on("data",r=>{t===this.generation&&this._onData(r)}),e.on("error",r=>{t===this.generation&&this._fail(new _e(`socket error: ${r.message}`,{cause:r}))}),e.on("timeout",()=>{t===this.generation&&this._fail(new Zr(`socket idle timeout after ${this.socketIdleTimeoutMs}ms`))}),e.on("close",()=>{t===this.generation&&this._fail(new _e("connection closed by peer"))})}_onData(e){this.stats.bytesIn+=e.length,this.buffer=Buffer.concat([this.buffer,e]);try{for(;;){let t=this.codec.decode(this.buffer);if(!t)break;this.buffer=t.rest,this._dispatch(t.value)}}catch(t){let r=t;this._fail(r instanceof Lt?r:new Lt(`decode failed: ${r.message}`))}}_dispatch(e){let t=e,r=t&&typeof t=="object"?t.request_id:void 0,i=null;if(r!=null&&this.pending.has(r)?i=r:r==null&&(this.pending.size===1&&(i=[...this.pending.keys()][0]),this._noteNoRequestId()),i==null){this.stats.unmatchedResponses+=1,this.dfx&&this.dfx.counter("rpc.response.unmatched",1,{endpoint:this.name,hasId:String(r!=null)}),this.logger&&this.logger.warn(`drop unmatched response (request_id=${r}, pending=${this.pending.size})`),this.strictPairing&&this._fail(new Lt(`unmatched response, request_id=${r}, pending=${this.pending.size}`));return}let o=this.pending.get(i);this.pending.delete(i),o.timer&&clearTimeout(o.timer),r!=null&&this._serverEchoesRequestId!==!0&&(this._serverEchoesRequestId=!0,this._applyLimit()),o.resolve(e)}_noteNoRequestId(){this._serverEchoesRequestId!==!1&&(this._serverEchoesRequestId=!1,this._applyLimit(),this.logger&&this.logger.warn("server does not echo request_id, degrade to serial mode for this connection"),this.dfx&&this.dfx.counter("rpc.concurrency.degrade",1,{endpoint:this.name}))}_computeLimit(){return this.concurrency===or.SERIAL||!this.frameDelimited?1:this.concurrency===or.PIPELINED?this.maxInFlight:this._serverEchoesRequestId===!0?this.maxInFlight:1}_initialLimit(){return this.concurrency===or.SERIAL||!this.frameDelimited?1:this.concurrency===or.PIPELINED?this.maxInFlight:1}_applyLimit(){this._sem.resize(this._computeLimit())}_nextRequestId(e){if(e!=null&&!this.pending.has(String(e)))return String(e);let t=rr();for(;this.pending.has(t);)t=rr();return t}async send(e,t={}){this._assertUsable();let r=await this._acquireSendSlot();try{this._assertUsable();let i=this.generation,o=t.timeoutMs??this.requestTimeoutMs,s=this._nextRequestId(e&&e.request_id),a={...e,request_id:s},c=++this._seq,l=this.dfx?this.dfx.timer("rpc.request",{endpoint:this.name}):null,d=await this._awaitResponse(s,a,i,c,o,l);return l&&l({ok:1}),this.dfx&&this.dfx.counter("rpc.request.ok",1,{endpoint:this.name}),d}finally{r&&r()}}async _acquireSendSlot(){let e=null;try{(this._sem.available<=0||this._sem.waiting>0)&&(this.stats.queued+=1),e=await this._sem.acquire()}catch(t){let r=t;throw new _e(`request rejected while queued: ${r.message}`,{cause:r,details:{endpoint:this.name}})}return e}_awaitResponse(e,t,r,i,o,s){return new Promise((a,c)=>{let l={resolve:a,reject:c,timer:null,t0:Date.now(),gen:r,seq:i},d=this._createSettleFn(e,l);l.timer=setTimeout(()=>this._onRequestTimeout(e,o,s,d,c),o),this._registerPending(e,l),this._writeFrame(t,i,d,c)})}_createSettleFn(e,t){return(r,i)=>{this.pending.get(e)===t&&(this.pending.delete(e),t.timer&&clearTimeout(t.timer),r(i))}}_onRequestTimeout(e,t,r,i,o){this.stats.timeouts+=1;let s=new Zr(`rpc request ${e} timeout after ${t}ms`,{details:{endpoint:this.name,requestId:e}});r&&r({ok:0,reason:"timeout"}),this.dfx&&this.dfx.counter("rpc.request.error",1,{endpoint:this.name,reason:"timeout"}),i(o,s),this.timeoutKillsConnection&&this._fail(s)}_registerPending(e,t){this.pending.set(e,t),this.stats.requestCount+=1,this.stats.maxInFlight=Math.max(this.stats.maxInFlight,this.pending.size)}_writeFrame(e,t,r,i){let o=!1;try{let s=this.codec.encode(e);this.stats.bytesOut+=s.length,this.logger&&this.logger.debug(`-> ${this.name} #${t} ${JSON.stringify(e).slice(0,300)}`);let a=this.socket;if(!a)throw new _e("socket is null");o=a.write(s,c=>{c&&r(i,new _e(`write failed: ${c.message}`,{cause:c}))})}catch(s){let a=s;r(i,new _e(`write failed: ${a.message}`,{cause:a}));return}!o&&this.logger&&this.logger.debug(`socket backpressure on #${t}`)}_assertUsable(){if(!this.isConnected)throw new _e(this._failure?`connection broken: ${this._failure.message}`:"transport is not connected",{cause:this._failure||void 0,details:{endpoint:this.name}})}_fail(e){if(!(this._closed&&this.pending.size===0&&this._sem.waiting===0)&&(this._failure=e,this._rejectAll(e),this._closeSocket(),this.onClose))try{this.onClose(e)}catch{}}_rejectAll(e){let t=[...this.pending.values()];this.pending.clear();for(let r of t){r.timer&&clearTimeout(r.timer);try{r.reject(e)}catch{}}this._sem.abortAll(e)}_closeSocket(){this._closed=!0,this.generation+=1;let e=this.socket;if(this.socket=null,e){e.removeAllListeners();try{e.destroy()}catch{}}}async close(e="closed by client"){let t=new _e(`transport closed: ${e}`);this._failure=null,this._rejectAll(t),this._closeSocket(),this.logger&&this.logger.debug(`transport closed: ${e}`)}async destroy(){await this.close("destroy")}getSnapshot(){return{name:this.name,host:this.host,port:this.port,connected:this.isConnected,generation:this.generation,concurrency:this.concurrency,concurrencyMode:this.concurrencyMode,maxInFlight:this._sem.limit,inFlight:this.pending.size,queued:this._sem.waiting,serverEchoesRequestId:this._serverEchoesRequestId,stats:{...this.stats}}}};var Vc="com.ohos.devicetest.hypiumApiHelper",_p="callHypiumApi";function Gc({module:n,method:e,params:t={},requestId:r}){return{module:n,method:e,params:t,request_id:r||rr()}}function qc(n){if(!n||typeof n!="object")return!1;let e=n.exception;return e!=null&&e!==""}function zc(n){return n?n.result:void 0}var Ce={IDLE:"IDLE",BOOTING:"BOOTING",RESOURCES_READY:"RESOURCES_READY",PROCESS_RUNNING:"PROCESS_RUNNING",FORWARDED:"FORWARDED",CONNECTING:"CONNECTING",CONNECTED:"CONNECTED",READY:"READY",WARM:"WARM",RESETTING:"RESETTING",ERROR:"ERROR",DISPOSED:"DISPOSED"},fs=class{device;endpoint;config;name;displayName;logger;dfx;mode;state;transport;_mutex;_epoch;_readyFlight;_resetFlight;_disposed;ctx;constructor({device:e,endpoint:t,config:r,logger:i,dfx:o,mode:s}){this.device=e,this.endpoint=t,this.config=r,this.name=t.name,this.displayName=t.displayName||t.name,this.logger=i?i.child(`Rpc:${this.displayName}`):null,this.dfx=o?o.child({endpoint:this.name}):null,this.mode=s||r.get("rpc.mode","stable"),this.state=Ce.IDLE,this.transport=null,this._mutex=new qi,this._epoch=0,this._readyFlight=new Vn,this._resetFlight=new Vn,this._disposed=!1,this.ctx=this._freshContext()}_bumpEpoch(){return this._epoch+=1,this._epoch}_freshContext(){return{hostPort:null,deviceEndpoint:null,pids:[],owned:!1,resourcesPushed:!1,style:null,startedAt:0,startCount:0,resetCount:0}}get endpointConfig(){return this.config.get(`rpc.${this.name}`,{})}get resources(){return this.endpointConfig.resources||[]}get isReady(){return this.state===Ce.READY&&!!this.transport&&this.transport.isConnected}async ensureReady(){if(this._disposed)throw new Pr(`${this.name} rpc is disposed`,{details:{endpoint:this.name}});if(this.isReady)return this.ctx;let e=this._resetFlight.pending("reset");if(e){if(await e.catch(()=>{}),this._disposed)throw new Pr(`${this.name} rpc is disposed`,{details:{endpoint:this.name}});if(this.isReady)return this.ctx}return this._readyFlight.run("ready",()=>this._ensureReadyOnce())}async _ensureReadyOnce(){if(this._disposed)throw new Pr(`${this.name} rpc is disposed`,{details:{endpoint:this.name}});return this.isReady?this.ctx:this.mode==="fast"&&await this._tryFastConnect()?this.ctx:(await this._stableFlow(),this.ctx)}async _stableFlow(){let e=this.dfx?this.dfx.timer("rpc.lifecycle.prepare",{mode:"stable"}):null;try{let t=await this.device.getEndpointStyle(),r=this.endpoint.buildDeviceEndpoint(t);this.ctx.style=t,this.ctx.deviceEndpoint=r,await this._ensureResources(),this.state=Ce.RESOURCES_READY,await this._ensureProcess(t),this.state=Ce.PROCESS_RUNNING;let i=await this._selectStableHostPort(t);return await this._tryForward(i,r)||(i=await this.device.getFreeHostPort({exclude:[i]}),await this._ensureForward(i,r)),this.ctx.hostPort=i,this.state=Ce.FORWARDED,await this._connectAndProbe(i,{probe:!0}),this.state=Ce.READY,await this._onStableReady(i,r,t,e),this.ctx}catch(t){return this._onStableFlowError(t,e)}}async _onStableReady(e,t,r,i){this.mode==="fast"&&await this._persistFastState({hostPort:e,deviceEndpoint:t,style:r}),i&&i({ok:1}),this.dfx&&this.dfx.counter("rpc.lifecycle.ready",1,{mode:this.mode}),this.logger&&this.logger.info(`ready: tcp:${e} -> ${t} (mode=${this.mode}, owned=${this.ctx.owned})`)}_onStableFlowError(e,t){this.state=Ce.ERROR,t&&t({ok:0}),this.dfx&&this.dfx.counter("rpc.lifecycle.error",1,{code:e?.code||e?.name});let r=e instanceof er?e:new tr(`${this.name} rpc prepare failed: ${e.message}`,{cause:e,details:{endpoint:this.name}});throw this.logger&&this.logger.error(`prepare failed: ${r.message}`),r}async _tryFastConnect(){let e=await this._readFastStateUnchecked(),t=e?.style||await this.device.getEndpointStyle(),r=this.endpoint.buildDeviceEndpoint(t),i=this.config.get("rpc.fast",{}),o=i.connectTimeoutMs??1500,s=i.probeOnReuse!==!1,a=await this._fastPortCandidates(t);for(let c of a)try{return await this._connectAndProbe(c,{probe:s,timeoutMs:o}),await this._onFastConnectSuccess(c,r,t)}catch(l){await this._onFastConnectMiss(l,c)}return await this._cleanupStaleFports(a,e,r),await this._clearFastState(),i.forceRestartOnProbeFailure!==!1&&await this._killEndpointProcesses(),!1}async _onFastConnectSuccess(e,t,r){return this.ctx.hostPort=e,this.ctx.deviceEndpoint=t,this.ctx.style=r,this.ctx.owned=!1,this.state=Ce.READY,await this._persistFastState({hostPort:e,deviceEndpoint:t,style:r}),this.dfx&&this.dfx.counter("rpc.fast.hit",1,{hostPort:e}),this.logger&&this.logger.info(`fast mode hit: reused tcp:${e}`),!0}async _onFastConnectMiss(e,t){this.dfx&&this.dfx.counter("rpc.fast.miss",1,{reason:e?.code||e.name,hostPort:t}),this.logger&&this.logger.info(`fast mode miss on tcp:${t} (${e.message}), try next/fallback`),await this._safeCloseTransport("fast miss")}async _cleanupStaleFports(e,t,r){let i=new Set(e);t&&Number.isInteger(t.hostPort)&&i.add(t.hostPort);for(let o of i)await this._removeStaleFport(o,t,r)}async _removeStaleFport(e,t,r){try{let i=t?.deviceEndpoint||r,o=await this.device.fportRemove(e,i);this._logFportRemoval(e,i,o)}catch(i){this.logger&&this.logger.debug(`fast mode fallback: remove stale fport tcp:${e} failed: ${i.message}`)}}_logFportRemoval(e,t,r){this.logger&&(r?this.logger.info(`fast mode fallback: removed stale fport tcp:${e} -> ${t}`):this.logger.debug(`fast mode fallback: fport rm tcp:${e} -> ${t} returned false (may not exist or different endpoint)`))}async _fastPortCandidates(e){let t=[],r=await this._readFastState(e);r&&Number.isInteger(r.hostPort)&&t.push(r.hostPort);let i=this.endpointConfig.fastHostPort;return Number.isInteger(i)&&t.push(i),[...new Set(t)]}async _readFastStateUnchecked(){try{let e=this.device.fastStore;if(!e)return null;let t=await e.get(this.device.serial,this.name);return t||null}catch{return null}}async _readFastState(e){try{let t=this.device.fastStore;if(!t)return null;let r=await t.get(this.device.serial,this.name);if(!r)return null;let i=r;return i.style&&i.style!==e?null:i}catch{return null}}async _persistFastState({hostPort:e,deviceEndpoint:t,style:r}){try{let i=this.device.fastStore;if(!i)return;let o=this.device._uitestInfo||null,s=this.ctx.agentVersion||null;if(!s){let a=await i.get(this.device.serial,this.name).catch(()=>null);a&&a.agentVersion&&(s=a.agentVersion)}await i.save(this.device.serial,{endpoint:this.name,hostPort:e,deviceEndpoint:t,style:r,agentVersion:s,uitestVersion:o?o.version:null,hdcServer:this.device.hdcServer})}catch(i){this.logger&&this.logger.debug(`persist fast state failed: ${i.message}`)}}async _clearFastState(){try{let e=this.device.fastStore;e&&await e.forgetEndpoint(this.device.serial,this.name)}catch{}}async _ensureResources(){await this._ensureManagedResources();let e=this.resources;for(let t of e){if(!await this.device.fileExists(t.remotePath)){await this._pushResource(t,"missing");continue}if(!t.version||!t.versionProbe)continue;let i=await this._probeRemoteVersion(t);(!i||_t(t.version,i)>0)&&(await this._killEndpointProcesses(),await this.device.rm(t.remotePath),await this._pushResource(t,"version"))}this.ctx.resourcesPushed=!0}async _ensureManagedResources(){}async _pushResource(e,t){let r=this.dfx?this.dfx.timer("rpc.lifecycle.push",{reason:t}):null;await this.device.fileSend(e.localPath,e.remotePath),r&&r({ok:1}),this.dfx&&this.dfx.counter("rpc.lifecycle.push",1,{reason:t}),this.logger&&this.logger.info(`push resource ${e.name||e.remotePath} (${t})`)}async _probeRemoteVersion(e){try{let t=await this.device.shell(`cat ${Gn(e.remotePath)} | ${St(["grep","-a",e.versionProbe])}`);if(!t)return null;let r=t.split("#"),i=r.length>1?r[r.length-1]:t;return Ji(i)}catch{return null}}async _detectProcesses(e){let r=(await this.device.findProcesses()).filter(i=>this.endpoint.matchProcess(i));return r.length?this.endpointConfig.checkListening&&!await this.endpoint.isListening(this.device,e)?[]:r:[]}async _ensureProcess(e){let t=await this._detectProcesses(e);if(t.length){this.ctx.pids=t.map(i=>i.pid),this.ctx.owned=!1;return}await this._killStaleProcesses();let r;try{r=await this._launchAndWaitReady(e)}catch(i){let o=i;this.logger&&this.logger.warn(`${this.name} launch failed, try re-push managed resources: ${o.message}`);try{await this._onLaunchFailure()}catch(s){this.logger&&this.logger.warn(`${this.name} onLaunchFailure hook error: ${s.message}`)}await this._killStaleProcesses(),r=await this._launchAndWaitReady(e)}this.ctx.pids=r.map(i=>i.pid),this.ctx.owned=!0,this.ctx.startedAt=Date.now()}async _killStaleProcesses(){let e=(await this.device.findProcesses()).filter(t=>this.endpoint.matchProcess(t));for(let t of e)await this.device.killProcess(t.pid)}async _onLaunchFailure(){}async _launchAndWaitReady(e){let t=this.endpoint.buildStartCommand({style:e});this.logger&&this.logger.info(`start device process: ${t}`),await this.device.shell(t),this.ctx.startCount+=1,this.dfx&&this.dfx.counter("rpc.lifecycle.start",1);let r=this.endpointConfig;try{return await $c(async()=>{let i=await this._detectProcesses(e);return i.length?i:null},{timeoutMs:r.processWaitTimeoutMs??15e3,intervalMs:r.processCheckIntervalMs??200,firstDelayMs:r.startWaitMs??500,description:`${this.name} process ready`})}catch(i){throw new tr(`${this.name} process did not become ready: ${i.message}`,{cause:i,details:{endpoint:this.name,startCmd:t}})}}async _ensureForward(e,t){if(!await this._tryForward(e,t))throw new tr(`create fport failed: tcp:${e} -> ${t}`,{details:{endpoint:this.name,hostPort:e,deviceEndpoint:t}})}async _tryForward(e,t){return await this.device.fportAdd(e,t)?!0:!!(await this.device.fportListAll()).find(s=>s.hostPort===e&&s.deviceEndpoint===t)}async _selectStableHostPort(e){if(this.mode==="fast"){let t=await this._readFastState(e),r=this.endpointConfig.fastHostPort,i=t&&Number.isInteger(t.hostPort)&&t.hostPort||r;if(i!=null&&Number.isInteger(i)&&!this.device.fportList.some(s=>s.hostPort===i))return i}return this.device.getFreeHostPort()}async _connectAndProbe(e,{probe:t=!0,timeoutMs:r}={}){let i=new ms({host:this.device.hdcHost,port:e,name:this.name,framing:this.config.get("rpc.framing","auto"),concurrency:this.config.get("rpc.concurrency",or.AUTO),maxInFlight:this.config.get("rpc.maxInFlight",16),strictPairing:this.config.get("rpc.strictPairing",!1),timeoutKillsConnection:this.config.get("rpc.timeoutKillsConnection",!1),connectTimeoutMs:r??this.config.get("rpc.connectTimeoutMs",5e3),requestTimeoutMs:this.config.get("rpc.requestTimeoutMs",3e4),socketIdleTimeoutMs:this.config.get("rpc.socketIdleTimeoutMs",3e4),logger:this.logger,dfx:this.dfx});await this._safeCloseTransport("reconnect"),await i.connect(),this._bumpEpoch(),i.onClose=o=>{this._onTransportClose(i,o)},this.transport=i,this.state=Ce.CONNECTED,t&&await this._probe()}_onTransportClose(e,t){this.transport===e&&(this._bumpEpoch(),(this.state===Ce.READY||this.state===Ce.CONNECTED)&&(this.state=this.mode==="fast"?Ce.WARM:Ce.IDLE,this.logger&&this.logger.warn(`connection lost: ${t?t.message:"closed"}`),this.dfx&&this.dfx.counter("rpc.connection.lost",1,{reason:t?.code||"close"})))}async _probe(){let e=this.config.get("rpc.connectTimeoutMs",5e3),t=this.buildProbePayload(),r=await this.transport.send(t,{timeoutMs:e});if(qc(r)&&this.logger){let i=r.exception;this.logger.debug(`probe got business exception (link is healthy): ${typeof i=="string"?i:JSON.stringify(i)}`)}return zc(r)}async request(e,t={}){let{timeoutMs:r}=t,i=this.config.get("rpc.recovery",{}),o=i.enabled!==!1,s=Math.max(0,i.maxAttempts??1),a=null,c=0,l=0;for(let d=0;d<=s+1;d++){if(this._disposed)throw new Pr(`${this.name} rpc is disposed, request rejected`,{details:{endpoint:this.name}});let g=this._epoch;try{await this.ensureReady(),g=this._epoch;let w=await this._sendOnce(e,{timeoutMs:r});return this._logRecovered(c+l),w}catch(w){a=w;let R=await this._handleRequestError(w,o,s,g,c,l,i.delayMs);c=R.ownRecoveries,l=R.borrowedRecoveries}}throw a||new tr(`${this.name} rpc request failed`)}_logRecovered(e){e>0&&this.dfx&&this.dfx.counter("rpc.request.recovered",1,{endpoint:this.name})}async _handleRequestError(e,t,r,i,o,s,a){if(this._disposed||!t||!Ep(e))throw e;return this._epoch===i?o=await this._attemptOwnRecovery(e,r,o):s=this._attemptBorrowedRecovery(e,r,s),a&&await Gi(a),{ownRecoveries:o,borrowedRecoveries:s}}async _attemptOwnRecovery(e,t,r){if(r>=t)throw e;let i=r+1;return this.dfx&&this.dfx.counter("rpc.request.retry",1,{code:e.code,attempt:i}),this.logger&&this.logger.warn(`recover from ${e.code||e.name}: ${e.message} (retry ${i}/${t})`),await this.reset({reason:e.message,code:e.code}),i}_attemptBorrowedRecovery(e,t,r){let i=r+1;if(i>t)throw e;return this.dfx&&this.dfx.counter("rpc.request.retry.borrowed",1,{code:e.code}),this.logger&&this.logger.debug(`retry after another caller reset (${e.code||e.name})`),i}async _sendOnce(e,{timeoutMs:t}={}){if(!this.transport||!this.transport.isConnected)throw new _e("rpc transport is not connected",{details:{endpoint:this.name}});let r=await this.transport.send(e,{timeoutMs:t??this.config.get("rpc.requestTimeoutMs",3e4)});return this.interpret(r)}interpret(e){if(qc(e)){let t=e.exception,r;if(t instanceof Error)r=t.message;else if(typeof t=="string")r=t;else if(t&&typeof t=="object")try{r=JSON.stringify(t)}catch{r=String(t)}else r=String(t);let i=new cs(`remote exception: ${r}`,{details:{endpoint:this.name,remote:t}});throw this.dfx&&this.dfx.counter("rpc.request.remoteError",1,{endpoint:this.name}),i}return zc(e)}reset({reason:e="manual",code:t="MANUAL"}={}){return this._resetFlight.run("reset",()=>this._resetOnce({reason:e,code:t}))}async _resetOnce({reason:e="manual",code:t="MANUAL"}={}){if(this._disposed)return;let r=this._readyFlight.pending("ready");if(r&&await r.catch(()=>{}),this._disposed)return;this._bumpEpoch(),this.dfx&&this.dfx.counter("rpc.lifecycle.reset",1,{reason:t}),this.logger&&this.logger.warn(`reset: ${e}`);try{await this._killEndpointProcesses()}catch(s){this.logger&&this.logger.warn(`kill process failed during reset: ${s.message}`)}await this._safeCloseTransport("reset");try{this.ctx.hostPort&&this.ctx.deviceEndpoint&&await this.device.fportRemove(this.ctx.hostPort,this.ctx.deviceEndpoint)}catch(s){this.logger&&this.logger.warn(`remove fport failed during reset: ${s.message}`)}let i=this.ctx.resetCount+1,o=this.ctx.startCount;this.ctx=this._freshContext(),this.ctx.resetCount=i,this.ctx.startCount=o,this.state=Ce.IDLE}async release(){if(await this._safeCloseTransport("release"),this.mode==="fast"&&this.config.get("rpc.fast.keepOnRelease",!0)){this.state=Ce.WARM,this.dfx&&this.dfx.counter("rpc.release",1,{keep:1}),this.logger&&this.logger.info(`released (keep process & fport on tcp:${this.ctx.hostPort})`);return}await this._removeForward(),await this._killEndpointProcesses(),this.dfx&&this.dfx.counter("rpc.release",1,{keep:0}),this.logger&&this.logger.info("released (process & fport cleaned)"),this.ctx=this._freshContext(),this.state=Ce.IDLE}async dispose(){this._disposed=!0,this._bumpEpoch();let e=this._readyFlight.pending("ready");e&&await e.catch(()=>{});let t=this._resetFlight.pending("reset");t&&await t.catch(()=>{}),await this._safeCloseTransport("dispose"),await this._removeForward(),await this._killEndpointProcesses(),this.ctx=this._freshContext(),this.state=Ce.DISPOSED}async _removeForward(){let e=new Set;this.ctx.hostPort&&e.add(this.ctx.hostPort),this.mode==="fast"&&this.endpointConfig.fastHostPort&&e.add(this.endpointConfig.fastHostPort);let t=this.ctx.deviceEndpoint||void 0;for(let r of e)try{let i=await this.device.fportRemove(r,t);this.logger&&!i&&this.logger.warn(`remove fport tcp:${r} -> ${t} returned false`)}catch(i){this.logger&&this.logger.debug(`remove fport tcp:${r} failed: ${i.message}`)}}async _killEndpointProcesses(){let t=(await this.device.findProcesses()).filter(r=>this.endpoint.matchProcess(r));for(let r of t)await this.device.killProcess(r.pid);return t.length&&this.logger&&this.logger.info(`killed ${this.name} processes: [${t.map(r=>r.pid).join(", ")}]`),t.length}async _safeCloseTransport(e){if(this.transport){try{await this.transport.close(e)}catch{}this.transport=null}}buildProbePayload(){return{module:"debug",method:"ping",params:{},request_id:void 0}}getSnapshot(){return{name:this.name,mode:this.mode,state:this.state,epoch:this._epoch,disposed:this._disposed,ctx:{...this.ctx},transport:this.transport?this.transport.getSnapshot():null}}};var $p={name:"operate",displayName:"uitest",socketName:"uitest_socket",devicePort:8012,buildDeviceEndpoint(n){return n==="unix"?`localabstract:${this.socketName}`:`tcp:${this.devicePort}`},buildStartCommand(){return"/system/bin/uitest start-daemon singleness &"},buildStopCommands(n){return n.map(e=>St(["kill","-9",e]))},matchProcess(n){return n.cmd.includes("uitest start-daemon singleness")&&!n.cmd.includes("--extension-name")},async isListening(n,e){return e==="unix"?(await n.shell(`cat /proc/net/unix | ${St(["grep",this.socketName])}`)).includes(this.socketName):(await n.shell(`netstat -anp | ${St(["grep",String(this.devicePort)])}`)).includes("LISTEN")}};var hs=class extends fs{constructor(e){super({...e,endpoint:$p})}async _ensureManagedResources(){if(this.config.get("device.autoPushResources",!0)===!1||!this.device.resources||typeof this.device.resources.ensureAgent!="function")return;let e=await this.device.resources.ensureAgent();this.ctx.agentVersion=e.candidate.version}async _onLaunchFailure(){this.config.get("device.autoPushResources",!0)!==!1&&(!this.device.resources||typeof this.device.resources.repushAgent!="function"||await this.device.resources.repushAgent())}buildProbePayload(){return Gc({module:Vc,method:"ping",params:{},requestId:rr()})}async call(e,t="",r=[],i={}){let o=Gc({module:Vc,method:_p,params:{api:e,this:t,args:r,message_type:"hypium"},requestId:rr()});return this.dfx&&this.dfx.counter("rpc.call",1,{api:e}),this.request(o,i)}async ping(e={}){return this.request(this.buildProbePayload(),e)}};function lT(n){if(n!==void 0)return Array.isArray(n)?{value:String(n[0]),pattern:n[1]}:{value:String(n)}}function Fp(n){return ev(n)}function ev(n){let e={};return n.text!==void 0&&(e.text=lT(n.text)),n.key!==void 0&&(e.key=String(n.key)),n.id!==void 0&&(e.id=String(n.id)),n.type!==void 0&&(e.type=String(n.type)),n.clickable!==void 0&&(e.clickable=!!n.clickable),n.scrollable!==void 0&&(e.scrollable=!!n.scrollable),n.enabled!==void 0&&(e.enabled=!!n.enabled),n.focused!==void 0&&(e.focused=!!n.focused),n.selected!==void 0&&(e.selected=!!n.selected),e}function tv(n){let e=ev(n);return n.isBefore&&(e.isBefore=Fp(n.isBefore)),n.isAfter&&(e.isAfter=Fp(n.isAfter)),n.within&&(e.within=Fp(n.within)),e}function dT(n){let e=[];return n.text&&e.push(["On.text",[n.text.value,n.text.pattern??0]]),n.key!==void 0&&e.push(["On.key",[n.key]]),n.id!==void 0&&e.push(["On.id",[n.id]]),n.type!==void 0&&e.push(["On.type",[n.type]]),n.clickable!==void 0&&e.push(["On.clickable",[n.clickable]]),n.scrollable!==void 0&&e.push(["On.scrollable",[n.scrollable]]),n.enabled!==void 0&&e.push(["On.enabled",[n.enabled]]),n.focused!==void 0&&e.push(["On.focused",[n.focused]]),n.selected!==void 0&&e.push(["On.selected",[n.selected]]),e}var Be=class n{spec;constructor(e={}){this.spec=e}static from(e){return new n(tv(e))}text(e,t){return this.spec.text={value:e,pattern:t},this}key(e){return this.spec.key=e,this}id(e){return this.spec.id=e,this}type(e){return this.spec.type=e,this}clickable(e=!0){return this.spec.clickable=e,this}scrollable(e=!0){return this.spec.scrollable=e,this}enabled(e=!0){return this.spec.enabled=e,this}focused(e=!0){return this.spec.focused=e,this}selected(e=!0){return this.spec.selected=e,this}isBefore(e){return this.spec.isBefore=e.spec,this}isAfter(e){return this.spec.isAfter=e.spec,this}within(e){return this.spec.within=e.spec,this}async buildOn(e){let t=this.spec,r=dT(t);if(r.length===0)throw new Error("Empty selector: at least one lookup condition required");let i=await e.create(r[0][0],r[0][1]);for(let o=1;o<r.length;o++)await e.call(r[o][0],i,r[o][1]);if(t.isBefore){let o=await new n(t.isBefore).buildOn(e);await e.call("On.isBefore",i,[o])}if(t.isAfter){let o=await new n(t.isAfter).buildOn(e);await e.call("On.isAfter",i,[o])}if(t.within){let o=await new n(t.within).buildOn(e);await e.call("On.within",i,[o])}return i}};var gs=class n{constructor(e,t,r=0){this.host=e;this.selector=t;this.index=r}use(e){return this.host.withComponentRef(this.selector,this.index,t=>e(t))}async click(){await this.use(e=>this.host.rpc.call("Component.click",e,[]))}async doubleClick(){await this.use(e=>this.host.rpc.call("Component.doubleClick",e,[]))}async longClick(){await this.use(e=>this.host.rpc.call("Component.longClick",e,[]))}async inputText(e){await this.use(t=>this.host.rpc.call("Component.inputText",t,[e]))}async clearText(){await this.use(e=>this.host.rpc.call("Component.clearText",e,[]))}async getId(){return String(await this.use(e=>this.host.rpc.call("Component.getId",e,[])))}async getText(){return String(await this.use(e=>this.host.rpc.call("Component.getText",e,[])))}async getType(){return String(await this.use(e=>this.host.rpc.call("Component.getType",e,[])))}async getHint(){return String(await this.use(e=>this.host.rpc.call("Component.getHint",e,[])))}async isClickable(){return!!await this.use(e=>this.host.rpc.call("Component.isClickable",e,[]))}async isScrollable(){return!!await this.use(e=>this.host.rpc.call("Component.isScrollable",e,[]))}async isEnabled(){return!!await this.use(e=>this.host.rpc.call("Component.isEnabled",e,[]))}async isFocused(){return!!await this.use(e=>this.host.rpc.call("Component.isFocused",e,[]))}async isSelected(){return!!await this.use(e=>this.host.rpc.call("Component.isSelected",e,[]))}async getBounds(){return await this.use(t=>this.host.rpc.call("Component.getBounds",t,[]))}async getBoundsCenter(){return await this.use(t=>this.host.rpc.call("Component.getBoundsCenter",t,[]))}async scrollSearch(e){let t=e instanceof Be?e:Be.from(e);return await this.host.withComponentRef(this.selector,this.index,async(i,o)=>{let s=await t.buildOn(o),a=await o.call("Component.scrollSearch",i,[s]);return a?(o.track(String(a)),!0):!1})?new n(this.host,t):null}async dragTo(e){let t=e instanceof n?e.selector:e instanceof Be?e:Be.from(e);await this.host.withComponentRef(this.selector,this.index,async(r,i,o)=>{let s=await t.buildOn(i),c=(await i.call("Driver.findComponents",o,[s])??[]).map(String);if(i.trackAll(c),c.length===0)throw new Error("dragTo target component not found (0 returned)");await i.call("Component.dragTo",r,[c[0]])})}async pinchOut(e){await this.use(t=>this.host.rpc.call("Component.pinchOut",t,[e]))}async pinchIn(e){await this.use(t=>this.host.rpc.call("Component.pinchIn",t,[e]))}async scrollToTop(e=600){await this.use(t=>this.host.rpc.call("Component.scrollToTop",t,[e]))}async scrollToBottom(e=600){await this.use(t=>this.host.rpc.call("Component.scrollToBottom",t,[e]))}};var uT=600,jp=1,Jc=16;function pT(n,e){return Math.hypot(e.x-n.x,e.y-n.y)}function rv(n,e,t,r){if(r!==void 0&&r>0)return Math.max(jp,Math.round(r/Jc));let i=pT(n,e);if(i<=0||t<=0)return jp;let o=i/t*1e3;return Math.max(jp,Math.round(o/Jc))}function Yc(n,e,t){return Math.round(n+(e-n)*t)}function nv(n,e,t,r){if(e===null)throw new Error("wait/pressHold before first down, missing start coordinate");for(let i=0;i<r;i++)n.push({pressed:t,x:e.x,y:e.y})}function mT(n,e,t){if(t.pressed)throw new Error("Duplicate down: finger already pressed");let r={x:e.x,y:e.y};t.cur=r,t.pressed=!0,n.push({pressed:t.pressed,x:r.x,y:r.y})}function fT(n,e,t,r){if(r.cur===null)throw new Error("moveTo before down");let i=r.cur,o={x:e.x,y:e.y},s=rv(i,o,t,e.durationMs);for(let a=1;a<=s;a++){let c=a/s;n.push({pressed:r.pressed,x:Yc(i.x,o.x,c),y:Yc(i.y,o.y,c)})}r.cur=o}function hT(n,e,t,r){if(r.cur===null)throw new Error("move before down");let i=r.cur,o={x:i.x+e.dx,y:i.y+e.dy},s=rv(i,o,t,e.durationMs);for(let a=1;a<=s;a++){let c=a/s;n.push({pressed:r.pressed,x:Yc(i.x,o.x,c),y:Yc(i.y,o.y,c)})}r.cur=o}function gT(n,e,t){nv(n,t.cur,t.pressed,Math.max(1,Math.round(e.durationMs/Jc)))}function yT(n,e,t){if(!t.pressed)throw new Error("pressHold before down");nv(n,t.cur,t.pressed,Math.max(1,Math.round(e.durationMs/Jc)))}function wT(n,e){if(!e.pressed)throw new Error("up before down");e.pressed=!1;let t=e.cur;t!==null&&n.push({pressed:e.pressed,x:t.x,y:t.y})}function vT(n,e){let t=[],r={cur:null,pressed:!1};for(let i of n.actions)switch(i.type){case"down":{mT(t,i,r);break}case"moveTo":{fT(t,i,e,r);break}case"move":{hT(t,i,e,r);break}case"wait":{gT(t,i,r);break}case"pressHold":{yT(t,i,r);break}case"up":{wT(t,r);break}default:{let o=i;throw new Error(`Unknown gesture action: ${JSON.stringify(o)}`)}}return t}function Hp(n){if(!n.fingers.length)throw new Error("Gesture requires at least one finger");let e=n.speed??uT,t=n.fingers.map(o=>vT(o,e)),r=Math.max(...t.map(o=>o.length));return{fingers:t.map(o=>{if(o.length===0)return[];let s=o[o.length-1],a=[...o];for(;a.length<r;)a.push({...s});return a}),speed:e}}var bT="PointerMatrix#seed";async function Up(n,e){let{fingers:t,speed:r}=Hp(e);if(t.length===0)throw new Error("Empty gesture");let i=t[0].length,o=await n.create("PointerMatrix.create",[t.length,i],bT);for(let s=0;s<t.length;s++)for(let a=0;a<i;a++){let c=t[s][a];await n.call("PointerMatrix.setPoint",o,[s,a,{x:c.x,y:c.y}])}return{ref:o,speed:r}}var iv="Driver.create",ST="BackendObjectsCleaner";var Bp="On#seed";async function Kc(n,e){let t=e.filter(r=>r&&r!==Bp);if(t.length!==0)try{for(let r=0;r<t.length;r+=10)await n.call(ST,"",[t.slice(r,r+10)])}catch{}}var Qr=class{constructor(e){this.rpc=e}refs=[];async create(e,t=[],r=Bp){let i=String(await this.rpc.call(e,r,t));return this.refs.push(i),i}async call(e,t,r=[]){return this.rpc.call(e,t,r)}track(e){return e&&e!==Bp&&this.refs.push(e),e}trackAll(e){for(let t of e)this.track(t);return e}async dispose(){await Kc(this.rpc,this.refs),this.refs.length=0}async run(e){try{return await e(this)}finally{await this.dispose()}}};var ys=class{constructor(e,t,r=0){this.host=e;this.filter=t;this.index=r}use(e){return this.host.withWindowRef(this.filter,this.index,t=>e(t))}async getBundleName(){return String(await this.use(e=>this.host.rpc.call("UiWindow.getBundleName",e,[])))}async isActive(){return!!await this.use(e=>this.host.rpc.call("UiWindow.isActive",e,[]))}async isFocused(){return!!await this.use(e=>this.host.rpc.call("UiWindow.isFocused",e,[]))}async getBounds(){return await this.use(t=>this.host.rpc.call("UiWindow.getBounds",t,[]))}};var ws=class{constructor(e,t){this.shell=t;this.rpc=e}driverRef=null;rpc;async ensureDriver(){return this.driverRef?this.driverRef:(this.driverRef=String(await this.rpc.call(iv,"",[])),this.driverRef)}selector(e){return e?Be.from(e):new Be}findComponent(e,t=0){let r=e instanceof Be?e:Be.from(e);return new gs(this,r,t)}async withComponentRef(e,t,r){let i=await this.ensureDriver();return new Qr(this.rpc).run(async s=>{let a=await e.buildOn(s),c=[];for(let l=0;l<8&&(c=(await s.call("Driver.findComponents",i,[a])??[]).map(String),!(c.length>0));l++)await new Promise(g=>setTimeout(g,1e3));if(s.trackAll(c),t>=c.length)throw new Error(`findComponents: no component matched (returned ${c.length}), index ${t} out of range`);return r(c[t],s,i)})}findWindow(e,t=0){return new ys(this,e,t)}async withWindowRef(e,t,r){let i=await this.ensureDriver();return new Qr(this.rpc).run(async s=>{let a;if(t===0){let c=await s.call("Driver.findWindow",i,[ET(e)]);if(!c||c==="null")throw new Error("findWindow: no window matched");a=s.track(String(c))}else throw new Error(`findWindow: only returns a single window, index=${t} not supported`);return r(a,s)})}async gesture(e){await this.swipe(e)}async swipe(e){let t=await this.ensureDriver();await this.withPointerRef(e,async(r,i)=>{await this.rpc.call("Driver.injectMultiPointerAction",t,[r,i])})}async withPointerRef(e,t){return new Qr(this.rpc).run(async i=>{let{ref:o,speed:s}=await Up(i,e);return t(o,s,i)})}async screenCapture(e){if(!this.shell)throw new Error("screenCapture requires shell capability (provided via device.uitest)");let t=e.toLowerCase().endsWith(".png")?".png":".jpeg",r=`/data/local/tmp/hypium${t}`;if(await this.shell.shell(`rm -f ${r}`),t===".png"?await this.shell.shell(`uitest screenCap -p ${r}`):await this.shell.shell(`snapshot_display -f ${r}`),!await this.shell.fileRecv(r,e))throw new Error(`screenCapture pull failed: ${r} -> ${e}`)}async setDisplayRotation(e){let t={0:0,90:1,180:2,270:3};if(!(e in t))throw new Error(`rotation must be 0, 90, 180, or 270, got ${e}`);let r=await this.ensureDriver();await this.rpc.call("Driver.setDisplayRotation",r,[t[e]])}async getDisplayRotation(){let e=await this.ensureDriver(),t=await this.rpc.call("Driver.getDisplayRotation",e,[]),r={0:0,1:90,2:180,3:270},i=typeof t=="number"?t:Number(t);return r[i]??i}async setDisplayRotationEnabled(e){let t=await this.ensureDriver();await this.rpc.call("Driver.setDisplayRotationEnabled",t,[e])}async delay(e){await new Promise(t=>setTimeout(t,e))}async pressBack(){let e=await this.ensureDriver();await this.rpc.call("Driver.pressBack",e,[])}async pressHome(){let e=await this.ensureDriver();await this.rpc.call("Driver.pressHome",e,[])}async clickXY(e,t){let r=await this.ensureDriver();await this.rpc.call("Driver.click",r,[e,t])}async doubleClick(e,t){let r=await this.ensureDriver();await this.rpc.call("Driver.doubleClick",r,[e,t])}async inputText(e,t){let r=await this.ensureDriver();await this.rpc.call("Driver.inputText",r,[e,t])}async getDisplaySize(){let e=await this.ensureDriver(),r=await this.rpc.call("Driver.getDisplaySize",e,[]);return{width:r.width??r.x??0,height:r.height??r.y??0}}async assertComponentExist(e,t=!0){let r=e instanceof Be?e:Be.from(e),i=await this.ensureDriver();return new Qr(this.rpc).run(async s=>{let a=await r.buildOn(s),l=(await s.call("Driver.findComponents",i,[a])??[]).length>0;return t?l:!l})}async release(){this.driverRef&&(await Kc(this.rpc,[this.driverRef]),this.driverRef=null)}};function ET(n){let e={};return n.title!==void 0&&(e.title=typeof n.title=="string"?n.title:n.title.value),n.bundleName!==void 0&&(e.bundleName=n.bundleName),n.active!==void 0&&(e.active=n.active),e}function ov({config:n,logger:e,dfx:t,executor:r}){if(r)return r;let i={bin:n.get("hdc.bin","hdc"),host:n.get("hdc.host","127.0.0.1"),port:n.get("hdc.port",8710),execTimeoutMs:n.get("hdc.execTimeoutMs",1e4),logger:e,dfx:t};return new Wn(i)}var vs=class n{executor;config;logger;dfx;rpcMode;devices;_rpcFactories;constructor({executor:e,config:t,logger:r,dfx:i,rpcMode:o}){this.executor=e,this.config=t,this.logger=r??null,this.dfx=i??null,this.rpcMode=o||t.get("rpc.mode","stable"),this.devices=new Map,this._rpcFactories=new Map}static async create(e={}){let t=e.config&&typeof e.config.get=="function"?e.config:us(e.config||{});e.mode&&t.set("rpc.mode",e.mode);let r=e.logger||ss("HMDeviceManager"),i=e.dfx||ps({logger:r,tags:{mode:t.get("rpc.mode")}}),o=ov({config:t,logger:r,dfx:i,executor:e.executor});return new n({executor:o,config:t,logger:r,dfx:i,rpcMode:t.get("rpc.mode","stable")})}static _default=null;static async getDefault(e={}){return n._default||(n._default=await n.create(e)),n._default}static resetDefault(){n._default=null}async listTargets(){let e=this.dfx?this.dfx.timer("device.listTargets"):null,t=await this.executor.listTargets();return e&&e({count:t.length}),this.logger&&this.logger.info(`list targets -> [${t.join(", ")}]`),t}async listDevices({detail:e=!1}={}){let r=(await this.listTargets()).map(i=>({serial:i,cached:this.devices.has(i)}));if(!e)return r;for(let i of r)try{let s=await(await this.getDevice(i.serial)).getInfo();Object.assign(i,{model:s.model,abi:s.abi,uitestVersion:s.version,endpointStyle:s.endpointStyle})}catch(o){i.error=o.message}return r}async getDevice(e,t={}){let r=this.dfx?this.dfx.timer("device.create"):null,i=await this.listTargets();if(!i.length)throw new Kr("no device connected");let o=e;if(o){if(!i.includes(o))throw new Kr(`device ${o} is not found, connected: [${i.join(", ")}]`)}else if(this.config.get("device.autoSelectFirst",!0))o=i[0];else throw new Kr("serial is required when autoSelectFirst is disabled");let s=this.devices.get(o);if(s)return r&&r({sn:o,reused:1}),s;let a=new qn({serial:o,executor:this.executor,config:this.config,logger:this.logger,dfx:this.dfx,rpcMode:t.rpcMode||this.rpcMode});for(let[l,d]of this._rpcFactories)a.attachRpc(l,d);return(t.queryVersion??this.config.get("device.queryVersion",!0))&&await a.getUitestInfo(),this.devices.set(o,a),r&&r({sn:o,ok:1}),this.dfx&&this.dfx.counter("device.create",1,{sn:o}),this.logger&&this.logger.info(`device created: ${o}`),a}async createDevice(e,t={}){return this.getDevice(e,t)}async connect(e,t={}){return this.getDevice(e,t)}attachRpc(e,t){if(typeof t!="function")throw new Kr(`attachRpc(${e}) expects a factory function`);this._rpcFactories.set(e,t);for(let r of this.devices.values())r.attachRpc(e,t);return this}async removeDevice(e){let t=this.devices.get(e);return t?(await t.release(),this.devices.delete(e),!0):!1}async release({disposeRpc:e=!1}={}){for(let t of this.devices.values())e?await t.dispose():await t.release();this.devices.clear()}async dispose(){for(let e of this.devices.values())await e.dispose();this.devices.clear()}};var CT="6.0.2.2",kT={uitest:n=>new hs({device:n,config:n.config,logger:n.logger,dfx:n.dfx,mode:n.rpcMode})},qn=class{serial;executor;config;logger;dfx;hdcHost;hdcPort;execTimeoutMs;rpcMode;_uitestInfo;fportList;resources;fastStore;_rpcs;_rpcFactories;_uitestDriver=null;file;fport;proc;constructor({serial:e,executor:t,config:r,logger:i,dfx:o,rpcMode:s}){this.serial=e,this.executor=t,this.config=r,this.logger=i??null,this.dfx=o?o.child({sn:e}):null,this.hdcHost=r.get("hdc.host","127.0.0.1"),this.hdcPort=r.get("hdc.port",8710),this.execTimeoutMs=r.get("hdc.execTimeoutMs",1e4),this.rpcMode=s||r.get("rpc.mode","stable"),this._uitestInfo=null,this.fportList=[],this.resources=new Bc({device:this,config:r,logger:this.logger,dfx:this.dfx}),this.fastStore=new Wc({config:r,logger:this.logger}),this._rpcs=new Map,this._rpcFactories=new Map(Object.entries(kT)),this.file=new Wp(this),this.fport=new Vp(this),this.proc=new Gp(this)}get isRemoteHdcServer(){return!!this.hdcHost&&this.hdcHost!=="127.0.0.1"&&this.hdcHost!=="localhost"}get hdcServer(){return`${this.hdcHost||"127.0.0.1"}:${this.hdcPort??8710}`}async exec(e,t={}){let r=["-t",this.serial,...e],i=await this.executor.exec(r,{timeoutMs:t.timeoutMs??this.execTimeoutMs});return this.logger&&this.logger.debug(`hdc ${r.join(" ")} -> ${i.code}`),i}async shell(e,t={}){return Op(e),(await this.exec(["shell",e],t)).stdout}async shellArgs(e,t={}){return this.shell(St(e),t)}async fileSend(e,t,r={}){ir(t),await RT(e);let i=await this.exec(["file","send",e,t],r);if(!(i.ok&&i.stdout.includes("FileTransfer finish")))throw new Xr(`push ${e} -> ${t} failed: ${i.stderr||i.stdout}`,{details:{localPath:e,remotePath:t}});return this.dfx&&this.dfx.counter("device.file.send",1),!0}async fileRecv(e,t,r={}){if(ir(e),!await this.fileExists(e))throw new Xr(`remote file does not exist: ${e}`);let i=await this.exec(["file","recv",e,t],r);if(!(i.ok&&i.stdout.includes("FileTransfer finish")))throw new Xr(`pull ${e} -> ${t} failed: ${i.stderr||i.stdout}`,{details:{localPath:t,remotePath:e}});return this.dfx&&this.dfx.counter("device.file.recv",1),!0}async fileExists(e){ir(e);let t=await this.shellArgs(["ls","-ld",e]);return!!t&&!t.includes("No such file or directory")}async isDirectory(e){ir(e);let t=await this.shellArgs(["ls","-ld",e]);return!!t&&t.startsWith("d")&&!t.includes("No such file or directory")}async rm(e,{force:t=!0}={}){return ir(e),await this.shellArgs(t?["rm","-f",e]:["rm",e]),!0}async mkdir(e){return ir(e),await this.shellArgs(["mkdir","-p",e]),!0}async readRemoteText(e){ir(e);let t=await this.shellArgs(["cat",e]);if(t.includes("No such file or directory"))throw new Xr(`remote file does not exist: ${e}`);return t}async listDir(e="/data/local/tmp"){ir(e);let t=await this.shellArgs(["ls",e]);return t.includes("No such file or directory")?[]:t.split(/\r?\n/).map(r=>r.trim()).filter(Boolean)}async fportAdd(e,t){Uc(e),Hc(t);let r=await this.exec(["fport",`tcp:${e}`,t]),i=r.ok&&(r.stdout.includes("result:OK")||r.stdout.toLowerCase().includes("success"));if(i){let o={hostPort:e,deviceEndpoint:t,taskString:`tcp:${e} ${t}`};this.fportList.some(s=>s.hostPort===e)||this.fportList.push(o),this.dfx&&this.dfx.counter("device.fport.add",1)}return i}async fportRemove(e,t){Uc(e),t&&Hc(t);let r=await this.exec(t?["fport","rm",`tcp:${e}`,t]:["fport","rm",`tcp:${e}`]),i=r.ok&&(r.stdout.includes("result:OK")||r.stdout.toLowerCase().includes("success"));return i&&(this.fportList=this.fportList.filter(o=>o.hostPort!==e),this.dfx&&this.dfx.counter("device.fport.remove",1)),i}async fportListAll(){let e=await this.exec(["fport","ls"]);return Pp(e.stdout)}async getFreeHostPort(e={}){let t=this.config.get("rpc.portRange",{start:1e4,end:19999}),r=new Set([...this.fportList.map(o=>o.hostPort),...e.exclude||[]]),{port:i}=await qw({hdcHost:this.hdcHost,start:e.start??t.start,end:e.end??t.end,exclude:r});return i}async getFreeDevicePort({start:e=4e4,end:t=49999,exclude:r}={}){let i=await this.shell("cat /proc/net/tcp /proc/net/tcp6 2>/dev/null"),o=new Set(r||[]);for(let s of String(i).split(/\r?\n/)){let c=s.trim().split(/\s+/)[1];if(!c||!c.includes(":"))continue;let l=c.split(":")[1],d=parseInt(l,16);Number.isInteger(d)&&o.add(d)}for(let s=e;s<=t;s++)if(!o.has(s))return s;throw new bt(`no free device port in range ${e}-${t}`)}async findProcesses(){let e=await this.shellArgs(["ps","-ef"]);return Cp(e)}async killProcess(e){let t=Mp(e);return await this.shellArgs(["kill","-9",t]),this.dfx&&this.dfx.counter("device.process.kill",1),!0}async getUitestInfo(e=!1){if(this._uitestInfo&&!e)return this._uitestInfo;let t=await Jw(this,{minVersion:this.config.get("device.newUiTestMinVersion",CT)});return this._uitestInfo={version:t.version,arch:t.arch,isNewUiTest:t.isNewUiTest,endpointStyle:t.endpointStyle},this.logger&&this.logger.info(`uitest info: version=${t.version} arch=${t.arch} endpointStyle=${t.endpointStyle}`),this._uitestInfo}async getEndpointStyle(){return this._uitestInfo||await this.getUitestInfo(),this._uitestInfo.endpointStyle}async getSystemProp(e){let t=e.map(r=>({bin:"getprop",key:r}));for(let r of e){let i=r.startsWith("ro.")?`const.${r.slice(3)}`:r;t.push({bin:"param",key:i})}for(let{bin:r,key:i}of t)try{let o=(await this.shellArgs([r,"get",i])).trim();if(!o||/fail|inaccessible|not found|Get parameter/i.test(o))continue;return o}catch{}return""}async getInfo(){let[e,t,r]=await Promise.all([this.getSystemProp(["ro.product.model","const.product.model"]),this.getSystemProp(["ro.product.cpu.abi","const.product.cpu.abilist"]),this.getUitestInfo()]);return{serial:this.serial,model:e,abi:t,...r}}attachRpc(e,t){if(typeof t!="function")throw new bt(`attachRpc(${e}) expects a factory function`);return this._rpcFactories.set(e,t),this._rpcs.delete(e),this}rpc(e){let t=this._rpcs.get(e);if(t)return t;let r=this._rpcFactories.get(e);if(!r)throw new bt(`rpc module "${e}" is not attached, available: [${[...this._rpcFactories.keys()].join(", ")}]`);let i=r(this);return this._rpcs.set(e,i),this.logger&&this.logger.debug(`rpc attached: ${e} -> ${i.name}`),i}get uitestRpc(){return this.rpc("uitest")}get uitest(){return this._uitestDriver||(this._uitestDriver=new ws(this.uitestRpc,{shell:e=>this.shell(e),fileRecv:(e,t)=>this.fileRecv(e,t)})),this._uitestDriver}static async create(e={}){let t=await vs.getDefault({config:e.config,mode:e.mode});return e.mode&&t.config.set("rpc.mode",e.mode),t.getDevice(e.serial,{queryVersion:e.queryVersion,rpcMode:e.mode})}get operate(){return this.uitestRpc}async call(e,t="",r=[],i={}){return this.uitestRpc.call(e,t,r,i)}getSnapshot(){return{serial:this.serial,mode:this.rpcMode,rpcs:this.listRpcs(),uitest:this.listRpcs().includes("uitest")?this.uitestRpc.getSnapshot():null}}listRpcs(){return[...this._rpcs.keys()]}async releaseRpc(e){let t=e?[e]:[...this._rpcs.keys()];for(let r of t){let i=this._rpcs.get(r);i&&(await i.release(),this._rpcs.delete(r))}!e&&this._uitestDriver&&(await this._uitestDriver.release(),this._uitestDriver=null)}async disposeRpc(e){let t=e?[e]:[...this._rpcFactories.keys()];for(let r of t){let i=this._rpcs.get(r)||this.rpc(r);i&&await i.dispose(),this._rpcs.delete(r)}!e&&this._uitestDriver&&(await this._uitestDriver.release(),this._uitestDriver=null)}async release(){await this.releaseRpc()}async dispose(){await this.disposeRpc(),await this._clearFports()}async _clearFports(){for(let e of[...this.fportList])try{await this.fportRemove(e.hostPort,e.deviceEndpoint)}catch{}this.fportList=[]}toString(){return`HMDevice(${this.serial})`}},Wp=class{device;constructor(e){this.device=e}push(e,t,r){return this.device.fileSend(e,t,r)}pull(e,t,r){return this.device.fileRecv(e,t,r)}exists(e){return this.device.fileExists(e)}isDir(e){return this.device.isDirectory(e)}remove(e,t){return this.device.rm(e,t)}mkdir(e){return this.device.mkdir(e)}readText(e){return this.device.readRemoteText(e)}list(e){return this.device.listDir(e)}},Vp=class{device;constructor(e){this.device=e}add(e,t){return this.device.fportAdd(e,t)}remove(e,t){return this.device.fportRemove(e,t)}list(){return this.device.fportListAll()}freeHostPort(){return this.device.getFreeHostPort()}},Gp=class{device;constructor(e){this.device=e}list(){return this.device.findProcesses()}kill(e){return this.device.killProcess(e)}async find(e){return(await this.device.findProcesses()).filter(r=>r.cmd.includes(e))}};async function RT(n){try{if(!(await PT(n)).isFile())throw new Error("not a file")}catch(e){throw new bt(`local file does not exist: ${n}`,{cause:e})}}import{fileURLToPath as xT}from"url";import{dirname as AT,join as qp}from"path";import{existsSync as IT}from"fs";var DT={write:(n,e)=>m(e)};Sp({name:"uitest",level:"trace",transports:[DT]});function TT(){let n=AT(xT(import.meta.url)),e=[qp(n,"../../resources/uitest"),qp(n,"../src/resources/uitest")];return e.find(t=>IT(qp(t,"uitest_agent_v1.1.9.so")))||e[1]}async function Xc(n,e){let t=ss("HMDevice"),r=ps({logger:t,tags:{mode:"fast"}}),i=new Wn({bin:n,logger:t,dfx:r}),o=us({device:{resourcesDir:TT()}}),s=new qn({serial:e,executor:i,config:o,logger:t,dfx:r,rpcMode:o.get("rpc.mode","fast")});return await s.getUitestInfo(),{driver:s.uitest,async dispose(){await s.uitest.release(),await s.release()}}}async function LT(n,e,t="default"){let r=await T(n,e),i=new Wi(n),o=bs({text:"Querying screen size...",color:"cyan"}).start();try{let s=await i.getDisplayInfo(r);o.stop();let a=Un(s);console.log(a?t==="json"?JSON.stringify({width:a.width,height:a.height},null,2):`${a.width}x${a.height}`:NT("No display info found in output."))}catch(s){throw o.stop(),new y(`Failed to get screen size: ${s.message}`,"Failed to get screen size.")}}async function _T(n,e,t){let r=await T(n,t),i=new Wi(n),o=e===-1;if(!o&&(e<5e3||e>36e5))throw new y(`Invalid timeout ${e}ms. Use -1 for never sleep, or a value between 5000 and 3600000ms.`,"Invalid screen-off timeout value.");let s=bs({text:o?"Disabling screen-off...":`Setting screen-off timeout to ${e}ms...`,color:"cyan"}).start();try{o?await i.setScreenNeverSleep(r):await i.setScreenTimeout(r,e),s.stop(),console.log(o?"Screen-off disabled (always on).":`Screen-off timeout set to ${e}ms.`)}catch(a){throw s.stop(),new y(`Failed to set screen-off timeout: ${a.message}`,"Failed to set screen-off timeout.")}}async function $T(n,e,t){let r=await T(n,t),i=bs({text:`Setting screen rotation to ROTATION_${e}...`,color:"cyan"}).start();try{let{driver:o,dispose:s}=await Xc(n.hdcPath,r);try{await o.setDisplayRotation(e)}finally{await s()}i.stop(),console.log(`Screen rotation set to ROTATION_${e}.`)}catch(o){throw i.stop(),new y(`Failed to set screen rotation: ${o.message}`,"Failed to set screen rotation.")}}async function FT(n,e){let t=await T(n,e),r=bs({text:"Querying screen rotation...",color:"cyan"}).start();try{let{driver:i,dispose:o}=await Xc(n.hdcPath,t);try{let s=await i.getDisplayRotation();r.stop(),console.log(`Screen rotation: ROTATION_${s}`)}finally{await o()}}catch(i){throw r.stop(),new y(`Failed to get screen rotation: ${i.message}`,"Failed to get screen rotation.")}}async function jT(n,e,t){let r=await T(n,t),i=bs({text:`${e?"Locking":"Unlocking"} screen rotation...`,color:"cyan"}).start();try{let{driver:o,dispose:s}=await Xc(n.hdcPath,r);try{await o.setDisplayRotationEnabled(!e)}finally{await s()}i.stop(),console.log(e?"Screen rotation locked (auto-rotation disabled).":"Screen rotation unlocked (auto-rotation enabled).")}catch(o){throw i.stop(),new y(`Failed to set rotation lock: ${o.message}`,"Failed to set rotation lock.")}}var zn=new OT("screen").description("Query and manage screen properties");zn.command("size").description("Query screen resolution").option("--device <name|serial>","Target device (name or serial)").addOption(new MT("--format <format>","Output format").choices(["default","json"]).default("default")).action(async n=>{let{device:e,format:t}=n,r={event:v.CommandExecuted,args:["device","screen","size",...t==="json"?["--format","json"]:[],...e?["--device"]:[]]};await O(r,async()=>{let{toolProvider:i}=await M();await LT(i,e,t)})});zn.command("rotation").description("Query current screen rotation").option("--device <name|serial>","Target device (name or serial)").action(async n=>{let{device:e}=n,t={event:v.CommandExecuted,args:["device","screen","rotation",...e?["--device"]:[]]};await O(t,async()=>{let{toolProvider:r}=await M();await FT(r,e)})});zn.command("sleeptime").description("Set screen-off timeout in milliseconds; use -1 for never").allowUnknownOption().option("--device <name|serial>","Target device (name or serial)").argument("<ms>","Screen-off timeout in milliseconds; -1 for never").action(async(n,e)=>{let{device:t}=e,r={event:v.CommandExecuted,args:["device","screen","sleeptime","<ms>",...t?["--device"]:[]]};await O(r,async()=>{let{toolProvider:i}=await M();await _T(i,Number(n),t)})});zn.command("rotate").description("Set screen rotation (clockwise)").argument("<rotation>","Rotation angle: 0, 90, 180, or 270").option("--device <name|serial>","Target device (name or serial)").action(async(n,e)=>{let{device:t}=e,r=Number(n);if(![0,90,180,270].includes(r))throw new y(`Invalid rotation "${n}". Valid values: 0, 90, 180, 270`,"Invalid rotation value.");let o={event:v.CommandExecuted,args:["device","screen","rotate","<rotation>",...t?["--device"]:[]]};await O(o,async()=>{let{toolProvider:s}=await M();await $T(s,r,t)})});zn.command("rotation-lock").description("Lock or unlock screen rotation (on=lock/disable auto-rotation, off=unlock/enable auto-rotation)").argument("<state>","on or off").option("--device <name|serial>","Target device (name or serial)").action(async(n,e)=>{let{device:t}=e;if(n!=="on"&&n!=="off")throw new y(`Invalid state "${n}". Valid values: on, off`,"Invalid rotation-lock state.");let r={event:v.CommandExecuted,args:["device","screen","rotation-lock","<state>",...t?["--device"]:[]]};await O(r,async()=>{let{toolProvider:i}=await M();await jT(i,n==="on",t)})});import{Command as HT}from"commander";import{gray as UT}from"colorette";import BT from"ora";var Ss=class{constructor(e){this.toolProvider=e}async readClipboard(e){let t=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","get-pastedata"]);if(Ue(t),t.exitCode!==0)throw new Error(t.stderr||t.stdout||"read clipboard failed");return t.stdout}async writeClipboard(e,t){let r=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","set-pastedata",t]);if(Ue(r),r.exitCode!==0)throw new Error(r.stderr||r.stdout||"write clipboard failed");return r.stdout}async clearClipboard(e){let t=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","clear-pastedata"]);if(Ue(t),t.exitCode!==0)throw new Error(t.stderr||t.stdout||"clear clipboard failed");return t.stdout}};async function zp(n,e,t,r){let i=await T(n,r),o=new Ss(n),s=BT({text:`Clipboard ${e}...`,color:"cyan"}).start();try{let a;if(e==="read"?a=await o.readClipboard(i):e==="write"?a=await o.writeClipboard(i,t??""):a=await o.clearClipboard(i),s.stop(),e==="read"){let c=a.trim().replace(/^Pasteboard text:\s*/,"");console.log(c||UT("(clipboard is empty)"))}else console.log(`Clipboard ${e==="write"?"written":"cleared"}.`)}catch(a){throw s.stop(),new y(`Clipboard ${e} failed: ${a.message}`,`Clipboard ${e} failed.`)}}var Es=new HT("clipboard").description("Read, write, or clear the device clipboard");Es.command("read").description("Read current clipboard text from the device").option("--device <name|serial>","Target device (name or serial)").action(async n=>{let{device:e}=n,t={event:v.CommandExecuted,args:["device","clipboard","read",...e?["--device"]:[]]};await O(t,async()=>{let{toolProvider:r}=await M();await zp(r,"read",void 0,e)})});Es.command("write").description("Write text to the device clipboard").option("--device <name|serial>","Target device (name or serial)").argument("<text>","Text to write to the clipboard").action(async(n,e)=>{let{device:t}=e,r={event:v.CommandExecuted,args:["device","clipboard","write",...t?["--device"]:[]]};await O(r,async()=>{let{toolProvider:i}=await M();await zp(i,"write",n,t)})});Es.command("clear").description("Clear the device clipboard").option("--device <name|serial>","Target device (name or serial)").action(async n=>{let{device:e}=n,t={event:v.CommandExecuted,args:["device","clipboard","clear",...e?["--device"]:[]]};await O(t,async()=>{let{toolProvider:r}=await M();await zp(r,"clear",void 0,e)})});import{Command as WT}from"commander";import{yellow as VT}from"colorette";import{existsSync as GT}from"fs";import Jp from"ora";import{execa as Zc}from"execa";var Yi=class{constructor(e){this.toolProvider=e}async fileExists(e,t){let r=this.toolProvider.hdcPath,i=["-t",e,"shell","ls","-l",t];m(`Executing: ${r} ${i.join(" ")}`);let o;try{let{stdout:s,stderr:a}=await Zc(r,i,{env:{...process.env}});o=`${s}
103
+ ${a}`}catch(s){let a=s;if(o=`${a.stdout??""}
104
+ ${a.stderr??""}
105
+ ${a.message??""}`,/no such file or directory/i.test(o))return!1;throw s}return!/no such file or directory/i.test(o)}async deleteFile(e,t){let r=this.toolProvider.hdcPath,i=["-t",e,"shell","rm","-f",t];m(`Executing: ${r} ${i.join(" ")}`);try{let{stdout:o}=await Zc(r,i,{env:{...process.env}});return o}catch(o){return o.stdout??""}}async sendFile(e,t,r){let i=this.toolProvider.hdcPath,o=["-t",e,"file","send",t,r];m(`Executing: ${i} ${o.join(" ")}`);let{stdout:s}=await Zc(i,o,{env:{...process.env}});if(!s.includes("FileTransfer finish"))throw new Error(`File send failed: ${s.trim()||"hdc returned no output"}`);return s.trim()}async recvFile(e,t,r){let i=this.toolProvider.hdcPath,o=["-t",e,"file","recv",t,r];m(`Executing: ${i} ${o.join(" ")}`);let{stdout:s}=await Zc(i,o,{env:{...process.env}});if(!s.includes("FileTransfer finish"))throw new Error(`File recv failed: ${s.trim()||"hdc returned no output"}`);return s.trim()}};async function sv(n,e,t,r,i){let o=await T(n,i),s=e==="send";if(s&&!GT(t))throw new y(`File not found: ${t}`,"File not found.");let a=new de(n),c=Jp({text:s?`Sending ${t} to ${r}...`:`Receiving ${t} to ${r}...`,color:"cyan"}).start();try{await a.transferFile(o,e,t,r),c.stop(),console.log(`${s?"Sent to device":"Received from device"}: ${t} -> ${r}`)}catch(l){c.stop();let d=s?"Send":"Recv";throw new y(l.message,`File ${d} failed.`)}}async function qT(n,e,t){let r=await T(n,t),i=new Yi(n),o=Jp({text:`Checking ${e}...`,color:"cyan"}).start();try{let s=await i.fileExists(r,e);o.stop(),s?console.log(`exists: ${e}`):(console.log(VT(`not found: ${e}`)),process.exitCode=1)}catch(s){throw o.stop(),new y(`Existence check failed: ${s.message}`,"Existence check failed.")}}async function zT(n,e,t){let r=await T(n,t),i=new Yi(n),o=Jp({text:`Deleting ${e}...`,color:"cyan"}).start();try{if(!await i.fileExists(r,e))throw o.stop(),new y(`File not found: ${e}`,"File not found.");let a=await i.deleteFile(r,e);o.stop();let c=a.trim();if(c&&/error|no such file/i.test(c))throw new Error(c);console.log(`Deleted ${e}.`)}catch(s){throw o.stop(),new y(`Delete failed: ${s.message}`,"Delete failed.")}}var Ki=new WT("file").description("Transfer files between the host and a connected device");Ki.command("send").description("Send a local file to a device").option("--device <name|serial>","Target device (name or serial)").argument("<src>","Local file path to upload").argument("<dst>","Remote path on the device").action(async(n,e,t)=>{let{device:r}=t,i={event:v.CommandExecuted,args:["device","file","send",...r?["--device"]:[]]};await O(i,async()=>{let{toolProvider:o}=await M();await sv(o,"send",n,e,r)})});Ki.command("recv").description("Receive a file from a device to the host").option("--device <name|serial>","Target device (name or serial)").argument("<src>","Remote path on the device").argument("<dst>","Local file path to save").action(async(n,e,t)=>{let{device:r}=t,i={event:v.CommandExecuted,args:["device","file","recv",...r?["--device"]:[]]};await O(i,async()=>{let{toolProvider:o}=await M();await sv(o,"recv",n,e,r)})});Ki.command("exist").description("Check if a file exists on the device").option("--device <name|serial>","Target device (name or serial)").argument("<path>","Remote path on the device to check").action(async(n,e)=>{let{device:t}=e,r={event:v.CommandExecuted,args:["device","file","exist",...t?["--device"]:[]]};await O(r,async()=>{let{toolProvider:i}=await M();await qT(i,n,t)})});Ki.command("delete").description("Delete a file on the device").option("--device <name|serial>","Target device (name or serial)").argument("<path>","Remote path on the device to delete").action(async(n,e)=>{let{device:t}=e,r={event:v.CommandExecuted,args:["device","file","delete",...t?["--device"]:[]]};await O(r,async()=>{let{toolProvider:i}=await M();await zT(i,n,t)})});import{Command as YT}from"commander";import{red as KT}from"colorette";import{existsSync as XT}from"fs";import ZT from"ora";import{basename as JT}from"path";var Ps=class{constructor(e){this.toolProvider=e;this.hdc=new de(e)}hdc;async pushFontToDevice(e,t){let r=`/data/local/tmp/${JT(t)}`;return await this.hdc.transferFile(e,"send",t,r),r}async installFont(e,t){let r=await this.pushFontToDevice(e,t),i=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","install-font",r]);return Ue(i),i.stdout}async getFontInfo(e,t){let r=await this.pushFontToDevice(e,t),i=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","get-fontname",r]);return Ue(i),i.stdout}async uninstallFont(e,t){let r=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","uninstall-font",t]);return Ue(r),r.stdout}};async function Yp(n,e,t,r){let i=await T(n,r);if(e!=="uninstall"&&!XT(t))throw new y(`Font file not found: ${t}`,"Font file not found.");let o=new Ps(n),s=ZT({text:`Font ${e} ${t}...`,color:"cyan"}).start();try{let a;e==="install"?a=await o.installFont(i,t):e==="info"?a=await o.getFontInfo(i,t):a=await o.uninstallFont(i,t),s.stop();let c=a.trim();/^error/i.test(c)?(console.error(KT(c)),process.exitCode=1):console.log(c)}catch(a){throw s.stop(),new y(a.message,`Font ${e} failed.`)}}var Cs=new YT("font").description("Manage device fonts");Cs.command("install").description("Install a font on the device").option("--device <name|serial>","Target device (name or serial)").argument("<fontpath>","Local font file path to install").action(async(n,e)=>{let{device:t}=e,r={event:v.CommandExecuted,args:["device","font","install","<fontpath>",...t?["--device"]:[]]};await O(r,async()=>{let{toolProvider:i}=await M();await Yp(i,"install",n,t)})});Cs.command("info").description("Get font name from a font file").option("--device <name|serial>","Target device (name or serial)").argument("<fontpath>","Local font file path to query").action(async(n,e)=>{let{device:t}=e,r={event:v.CommandExecuted,args:["device","font","info","<fontpath>",...t?["--device"]:[]]};await O(r,async()=>{let{toolProvider:i}=await M();await Yp(i,"info",n,t)})});Cs.command("uninstall").description("Uninstall a font from the device").option("--device <name|serial>","Target device (name or serial)").argument("<name>","Font name to uninstall").action(async(n,e)=>{let{device:t}=e,r={event:v.CommandExecuted,args:["device","font","uninstall","<name>",...t?["--device"]:[]]};await O(r,async()=>{let{toolProvider:i}=await M();await Yp(i,"uninstall",n,t)})});import{Command as QT}from"commander";import{red as eO}from"colorette";import tO from"ora";var ks=class{constructor(e){this.toolProvider=e}async getViewmode(e){return(await C(this.toolProvider.hdcPath,["-t",e,"shell","param","get","persist.ace.darkmode"])).stdout}async setViewmode(e,t){let r=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","set-viewmode",t]);return Ue(r),/already set to/i.test(r.stdout)?r.stdout.replace(/^Error:\s*/i,"").trim():r.stdout}};async function rO(n,e,t){let r=await T(n,t),i=new ks(n),o=e!==void 0;if(o&&e!=="dark"&&e!=="light")throw new y(`Invalid viewmode "${e}". Valid values: dark, light`,"Invalid viewmode value.");let s=tO({text:o?`Setting viewmode to ${e}...`:"Getting viewmode...",color:"cyan"}).start();try{let a=o?await i.setViewmode(r,e):await i.getViewmode(r);s.stop();let c=a.trim();/fail/i.test(c)?(console.error(eO(c)),process.exitCode=1):console.log(c)}catch(a){throw s.stop(),new y(`Viewmode ${o?"set":"get"} failed: ${a.message}`,`Viewmode ${o?"set":"get"} failed.`)}}var av=new QT("viewmode").description("Get or set the device view mode").option("--device <name|serial>","Target device (name or serial)").argument("[mode]","View mode to set (dark|light); omit to get current").action(async(n,e)=>{let{device:t}=e,r={event:v.CommandExecuted,args:["device","viewmode",...n?[n]:[],...t?["--device"]:[]]};await O(r,async()=>{let{toolProvider:i}=await M();await rO(i,n,t)})});function aO(n,e){if(e.size!==0)for(let t of n){if(!t.isEmulator||!t.name)continue;let r=e.get(Le(t.name));r&&(t.deviceType=r)}}var cO=["Name","Serial","Kind","Device Type"];function lO(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function dv(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function dO(){console.log(iO(" No active devices.")),console.log(oO(" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function uO(n){let t=[...n].sort(dv).map(lO);console.log(Sr(cO,t))}function pO(n){return{name:n.name??n.serial,serial:n.serial,kind:n.isEmulator?"emulator":"device",deviceType:n.deviceType}}function mO(n){let e=[...n].sort(dv);console.log(JSON.stringify(e.map(pO),null,2))}async function fO(n,e){if(!n.some(i=>i.isEmulator)||!e.emulatorPath)return;let r=await Bi.from(e).getDeviceTypeByName();aO(n,r)}async function cv(n,e,t,r="table"){try{let i=await n.getConnectedEntries();if(await fO(i,e),t?.stop(),r==="json"){mO(i);return}i.length===0?dO():uO(i)}catch(i){throw new y(`Failed to list devices: ${i.message}`,"Failed to list devices.")}finally{t?.stop()}}async function hO(n,e){let t=await n.listDevices();if(t.length<2)return;let r=["Multiple devices connected. Specify a device with:"];for(let i of t){let o=await n.getDeviceName(i.serial);r.push(` ${e} -t ${i.serial} # ${o}`)}throw new y(r.join(`
106
+ `),"Multiple devices connected.")}async function gO(n,e,t="table"){e||await hO(n,"devecocli device view");let r=await n.listDevices(),i=await n.getDeviceInfo(r,e);if(!i){if(t==="json"){console.error("No connected device found."),process.exitCode=1;return}throw new y("No connected device found.")}let o=await n.getDeviceDetail(i.serial),s=await n.getDeviceName(i.serial);if(t==="json"){let a={name:s,serial:i.serial,kind:Jt(i.serial)?"emulator":"device",deviceType:o.deviceType,osVersion:o.osVersion};console.log(JSON.stringify(a,null,2));return}console.log(` Serial: ${i.serial}`),console.log(` Device Name: ${s}`),o.deviceType&&console.log(` Device Type: ${o.deviceType}`),o.osVersion&&console.log(` OS Version: ${o.osVersion}`)}async function yO(n,e,t,r){let i=await T(n,r),o=new de(n);try{await o.runSqlite3(i,e,t)}catch(s){throw new y(`sqlite3 failed: ${s.message}`,"sqlite3 failed.")}}var $t=new nO("device").description("Manage connected devices");$t.command("list").description("List all connected devices").addOption(new lv("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:v.CommandExecuted,args:["device","list",...n.format==="json"?["--format","json"]:[]]};await O(e,async()=>{let{manager:t,toolProvider:r}=await M();if(n.format==="json"){await cv(t,r,void 0,"json");return}let i=sO({text:"Querying connected devices\u2026",color:"cyan"}).start();await cv(t,r,i,"table")})});$t.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").addOption(new lv("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:v.CommandExecuted,args:["device","view",...n.target?["--target"]:[],...n.format==="json"?["--format","json"]:[]]};await O(e,async()=>{let{manager:t}=await M();await gO(t,n.target,n.format)})});$t.addCommand(Mt);$t.addCommand(Ki);$t.addCommand(Es);$t.addCommand(zn);$t.addCommand(Cs);$t.addCommand(av);for(let n of Fw)$t.addCommand(n);$t.command("sqlite3").description("Run sqlite3 on a connected device").allowUnknownOption().option("--device <name|serial>","Target device (name or serial)").argument("<db-path>","SQLite database path on the device").argument("[args...]","Arguments forwarded to sqlite3 as-is").action(async(n,e,t)=>{let r={event:v.CommandExecuted,args:["device","sqlite3",n,...t.device?["--device"]:[]]};await O(r,async()=>{let{toolProvider:i}=await M();await yO(i,n,e,t.device)})});var uv=$t;import{Argument as im,Command as om,InvalidArgumentError as rm,Option as We}from"commander";import{green as xs,cyan as Zi,red as sm,yellow as tn,gray as nm}from"colorette";import MO from"ora";import wO from"readline/promises";import{execa as mv}from"execa";import*as en from"fs/promises";import*as Xp from"os";import*as Jn from"path";var Kp=`1/4:\r
92
107
  ---------------------------------------\r
93
108
  Statement About HarmonyOS and Privacy\r
94
109
  \r
@@ -1258,13 +1273,13 @@ Part I: Chinese mainland.\r
1258
1273
  Part II: Aland Islands, Albania, Andorra, Australia, Austria, Belgium, Bonaire, Bosnia and Herzegovina, Bulgaria, Canada, Croatia, Curacao, Cyprus, Czech Republic, Denmark, Dutch Caribbean, Estonia, Faroe Islands, Finland, France, Germany, Gibraltar, Greece, Greenland, Guernsey, Hungary, Iceland, Israel, Italy, Jersey, Latvia, Liechtenstein, Lithuania, Luxembourg, Malta, Moldova, Monaco, Montenegro, Netherlands, New Zealand, North Macedonia, Norway, Poland, Portugal, Ireland, Romania, Saba, Saint Vincent and the Grenadines, San Marino, Serbia, Sint Eustatius, Sint Maarten, Slovakia, Slovenia, Spain, St. Martin, St. Pierre and Miquelon (France), Sweden, Switzerland, Turkey, Ukraine, United Kingdom, United States, Vatican City.\r
1259
1274
  \r
1260
1275
  Part III: Other countries and regions.\r
1261
- ---------------------------------------\r`;var GP=new Set,zs=new Map,Bl="HarmonyOS_Software_Service_Agreement",Kf=["Emulator license agreements are not accepted yet.","","Accept the agreements interactively (shows full text + y/N prompt):"," devecocli emulator license","","Or accept non-interactively (no prompt, for CI/scripts):"," devecocli emulator license accept","","To review the agreement text (read-only):"," devecocli emulator license view"].join(`
1262
- `),Xf=Kf,Ul="HarmonyOS_SDK_Agreement";function Zf(r,e){return`${r}\0${e}`}function Qf(){GP.clear(),zs.clear()}var zP=Kf,Wt=class extends Error{constructor(e=zP){super(e),this.name="EmulatorLicenseBlockedError"}};function eh(r,e){return[r??"",e??""].join(`
1263
- `)}function th(r){let e=r.normalize("NFKC"),t=e.match(/(\d+)\.(\d+)\.\d+/);if(t)return`${t[1]}.${t[2]}`;let n=e.match(/(\d+)\.(\d+)\b/);return n?`${n[1]}.${n[2]}`:null}function qP(r){return`Emulator${r.trim()}`}function rh(r){let e=qP(r);if(process.platform==="win32"){let n=process.env.LOCALAPPDATA;if(!n)throw new Error("LOCALAPPDATA is not set; cannot resolve .emu_config path.");return nn.join(n,"Huawei",e,".emu_config")}if(process.platform==="darwin")return nn.join(Hl.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||nn.join(Hl.homedir(),".cache");return nn.join(t,"Huawei",e,".emu_config")}async function JP(r,e,t){let n=Zf(r,e),o=zs.get(n);if(o!==void 0)return o;let i=await Yf(r,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=eh(i.stdout,i.stderr).trim();if(i.exitCode!==0||!s)throw new Wt(t);return zs.set(n,s),s}function YP(r){let e=r[0],t=r[r.length-1];return(e==='"'||e==="'")&&e===t?r.slice(1,-1):r}function KP(r){try{let e=JSON.parse(r);if(e&&typeof e=="object"&&!Array.isArray(e)){let t={};for(let[n,o]of Object.entries(e))t[n]={value:typeof o=="string"?o:String(o),delimiter:"json"};return t}}catch{return}}function XP(r){let e=r.trim();if(!(!e||e.startsWith("#")))for(let t of["=",":"]){let n=e.indexOf(t);if(n<=0)continue;let o=e.slice(0,n).trim();if(!o||t===":"&&o.includes("//"))continue;let i=YP(e.slice(n+1).trim());return{key:o,entry:{value:i,delimiter:t}}}}function ZP(r){let e={};for(let t of r.split(/\r?\n/)){let n=XP(t);n&&(e[n.key]=n.entry)}return e}function QP(r){let e=r.trim();if(!e)return{};let t=KP(e);return t||ZP(r)}function eA(r){return typeof r!="string"?!1:r.normalize("NFKC").trim().toLowerCase()==="agree"}async function nh(r,e,t,n){let o=await JP(r,e,n),i=th(o);if(!i)throw new Wt(n);let s=rh(i),a;try{a=await mr.readFile(s,"utf8")}catch(d){throw d.code==="ENOENT"?new Wt(n):d}let l=QP(a)[t];if(!l)throw new Wt(n);if(l.delimiter==="=")throw new Wt(n);if(!eA(l.value))throw new Wt(n)}async function Wl(r,e){await nh(r,e,Bl,Xf)}async function Vl(r,e){await nh(r,e,Ul,Xf)}async function tA(r,e){let t=await Yf(r,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),n=eh(t.stdout,t.stderr).trim();if(t.exitCode!==0||!n)throw new Error(`Emulator -version failed (exit ${String(t.exitCode)}); cannot resolve .emu_config path.`);let o=Zf(r,e);return zs.set(o,n),n}async function oh(r,e){let t=await tA(r,e),n=th(t);if(!n)throw new Error(`Cannot parse Emulator major.minor from:
1264
- ${t}.`);return rh(n)}function Jf(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function rA(r,e,t){if(!t.startsWith("{"))return!1;try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n[Bl]="agree",n[Ul]="agree",await mr.writeFile(r,`${JSON.stringify(n,null,2)}
1265
- `,"utf8"),!0}catch{}return!1}async function nA(r,e){let t=Bl,n=Ul,o=[{k:t,re:new RegExp(`^\\s*${Jf(t)}\\s*[:=]`)},{k:n,re:new RegExp(`^\\s*${Jf(n)}\\s*[:=]`)}],i=e.length===0?[]:e.split(/\r?\n/),s=[],a=new Set;for(let c of i){let l=!1;for(let{k:d,re:g}of o)if(g.test(c)){s.push(`${d}:agree`),a.add(d),l=!0;break}l||s.push(c)}a.has(t)||s.push(`${t}:agree`),a.has(n)||s.push(`${n}:agree`),await mr.writeFile(r,s.join(`
1276
+ ---------------------------------------\r`;var vO=new Set,Qc=new Map,Zp="HarmonyOS_Software_Service_Agreement",fv=["Emulator license agreements are not accepted yet.","","Accept the agreements interactively (shows full text + y/N prompt):"," devecocli emulator license","","Or accept non-interactively (no prompt, for CI/scripts):"," devecocli emulator license accept","","To review the agreement text (read-only):"," devecocli emulator license view"].join(`
1277
+ `),hv=fv,Qp="HarmonyOS_SDK_Agreement";function gv(n,e){return`${n}\0${e}`}function yv(){vO.clear(),Qc.clear()}var bO=fv,Cr=class extends Error{constructor(e=bO){super(e),this.name="EmulatorLicenseBlockedError"}};function wv(n,e){return[n??"",e??""].join(`
1278
+ `)}function vv(n){let e=n.normalize("NFKC"),t=e.match(/(\d+)\.(\d+)\.\d+/);if(t)return`${t[1]}.${t[2]}`;let r=e.match(/(\d+)\.(\d+)\b/);return r?`${r[1]}.${r[2]}`:null}function SO(n){return`Emulator${n.trim()}`}function bv(n){let e=SO(n);if(process.platform==="win32"){let r=process.env.LOCALAPPDATA;if(!r)throw new Error("LOCALAPPDATA is not set; cannot resolve .emu_config path.");return Jn.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return Jn.join(Xp.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||Jn.join(Xp.homedir(),".cache");return Jn.join(t,"Huawei",e,".emu_config")}async function EO(n,e,t){let r=gv(n,e),i=Qc.get(r);if(i!==void 0)return i;let o=await mv(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=wv(o.stdout,o.stderr).trim();if(o.exitCode!==0||!s)throw new Cr(t);return Qc.set(r,s),s}function PO(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function CO(n){try{let e=JSON.parse(n);if(e&&typeof e=="object"&&!Array.isArray(e)){let t={};for(let[r,i]of Object.entries(e))t[r]={value:typeof i=="string"?i:String(i),delimiter:"json"};return t}}catch{return}}function kO(n){let e=n.trim();if(!(!e||e.startsWith("#")))for(let t of["=",":"]){let r=e.indexOf(t);if(r<=0)continue;let i=e.slice(0,r).trim();if(!i||t===":"&&i.includes("//"))continue;let o=PO(e.slice(r+1).trim());return{key:i,entry:{value:o,delimiter:t}}}}function RO(n){let e={};for(let t of n.split(/\r?\n/)){let r=kO(t);r&&(e[r.key]=r.entry)}return e}function DO(n){let e=n.trim();if(!e)return{};let t=CO(e);return t||RO(n)}function xO(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function Sv(n,e,t,r){let i=await EO(n,e,r),o=vv(i);if(!o)throw new Cr(r);let s=bv(o),a;try{a=await en.readFile(s,"utf8")}catch(d){throw d.code==="ENOENT"?new Cr(r):d}let l=DO(a)[t];if(!l)throw new Cr(r);if(l.delimiter==="=")throw new Cr(r);if(!xO(l.value))throw new Cr(r)}async function em(n,e){await Sv(n,e,Zp,hv)}async function tm(n,e){await Sv(n,e,Qp,hv)}async function AO(n,e){let t=await mv(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),r=wv(t.stdout,t.stderr).trim();if(t.exitCode!==0||!r)throw new Error(`Emulator -version failed (exit ${String(t.exitCode)}); cannot resolve .emu_config path.`);let i=gv(n,e);return Qc.set(i,r),r}async function Ev(n,e){let t=await AO(n,e),r=vv(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
1279
+ ${t}.`);return bv(r)}function pv(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function IO(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[Zp]="agree",r[Qp]="agree",await en.writeFile(n,`${JSON.stringify(r,null,2)}
1280
+ `,"utf8"),!0}catch{}return!1}async function TO(n,e){let t=Zp,r=Qp,i=[{k:t,re:new RegExp(`^\\s*${pv(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${pv(r)}\\s*[:=]`)}],o=e.length===0?[]:e.split(/\r?\n/),s=[],a=new Set;for(let c of o){let l=!1;for(let{k:d,re:g}of i)if(g.test(c)){s.push(`${d}:agree`),a.add(d),l=!0;break}l||s.push(c)}a.has(t)||s.push(`${t}:agree`),a.has(r)||s.push(`${r}:agree`),await en.writeFile(n,s.join(`
1266
1281
  `)+(s.length>0?`
1267
- `:""),"utf8")}async function ih(r){await mr.mkdir(nn.dirname(r),{recursive:!0});let e="";try{e=await mr.readFile(r,"utf8")}catch(n){if(n.code!=="ENOENT")throw n}let t=e.trim();await rA(r,e,t)||await nA(r,e)}async function sh(r,e){return console.log($l),0}var oA="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function ah(r,e){try{return await Wl(r,e),await Vl(r,e),!0}catch(t){if(t instanceof Wt)return!1;throw t}}async function ch(r,e){if(await ah(r,e))return console.log("Emulator license agreements are already accepted."),0;if(console.log($l),!process.stdin.isTTY||!process.stdout.isTTY)return console.error("`devecocli emulator license` requires an interactive terminal.\nFor non-interactive environments, use: devecocli emulator license accept"),1;let n=VP.createInterface({input:process.stdin,output:process.stdout}),o;try{o=await n.question(oA)}finally{n.close()}let i=o.trim().toLowerCase();if(i!=="y"&&i!=="yes")return console.error("Agreements not accepted. Emulator features will remain blocked until accepted."),1;try{let s=await oh(r,e);await ih(s),Qf()}catch(s){return console.error(s.message),1}return console.log("Emulator license agreements accepted."),0}async function lh(r,e){if(await ah(r,e))return console.log("Emulator license agreements are already accepted."),0;try{let t=await oh(r,e);await ih(t),Qf()}catch(t){return console.error(t.message),1}return console.log("Emulator license agreements accepted."),0}async function dt(r,e){let t=Date.now(),n=!0,o=null;try{await e()}catch(i){n=!1,o=q(i),console.error(Jl(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:n,error_code:o};await I.track(r,i)}}var aA=["ohos.qemu.hvd.name","const.product.name","const.product.model"],dh=["open","half-open","close","vertical-open","single","double","triple","left-folded-right-half-folded","left-half-folded-right-expanded","left-expanded-right-folded","left-half-folded-right-folded","left-expanded-right-half-folded","left-half-folded-right-half-folded"],cA=`
1282
+ `:""),"utf8")}async function Pv(n){await en.mkdir(Jn.dirname(n),{recursive:!0});let e="";try{e=await en.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await IO(n,e,t)||await TO(n,e)}async function Cv(n,e){return console.log(Kp),0}var OO="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function kv(n,e){try{return await em(n,e),await tm(n,e),!0}catch(t){if(t instanceof Cr)return!1;throw t}}async function Rv(n,e){if(await kv(n,e))return console.log("Emulator license agreements are already accepted."),0;if(console.log(Kp),!process.stdin.isTTY||!process.stdout.isTTY)return console.error("`devecocli emulator license` requires an interactive terminal.\nFor non-interactive environments, use: devecocli emulator license accept"),1;let r=wO.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await r.question(OO)}finally{r.close()}let o=i.trim().toLowerCase();if(o!=="y"&&o!=="yes")return console.error("Agreements not accepted. Emulator features will remain blocked until accepted."),1;try{let s=await Ev(n,e);await Pv(s),yv()}catch(s){return console.error(s.message),1}return console.log("Emulator license agreements accepted."),0}async function Dv(n,e){if(await kv(n,e))return console.log("Emulator license agreements are already accepted."),0;try{let t=await Ev(n,e);await Pv(t),yv()}catch(t){return console.error(t.message),1}return console.log("Emulator license agreements accepted."),0}async function Et(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=X(o),console.error(sm(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await D.track(n,o)}}var NO=["ohos.qemu.hvd.name","const.product.name","const.product.model"],xv=["open","half-open","close","vertical-open","single","double","triple","left-folded-right-half-folded","left-half-folded-right-expanded","left-expanded-right-folded","left-half-folded-right-folded","left-expanded-right-half-folded","left-half-folded-right-half-folded"],LO=`
1268
1283
  Folded state scene mappings:
1269
1284
  foldableFold (3):
1270
1285
  open Fully expanded state
@@ -1287,135 +1302,120 @@ Folded state scene mappings:
1287
1302
  left-half-folded-right-folded
1288
1303
  left-expanded-right-half-folded
1289
1304
  left-half-folded-right-half-folded
1290
- `,lA="6.1.0";function dA(r){let e=r.trim();if(!e)throw new Error("--target must not be empty.");return e}function uA(r){let e=r.trim();if(!dh.includes(e))throw new Error(`Invalid fold state "${r}". Available values: ${dh.join(", ")}`);return e}function ph(r,e,t,n){let o=e.trim();if(!/^-?\d+$/.test(o))throw new Error(`${r} must be an integer in [${t}, ${n}].`);let i=Number(o);if(i<t||i>n)throw new Error(`${r} must be in [${t}, ${n}].`);return i}function mh(r,e,t,n,o){let i=e.trim(),s=Number(i);if(!i||Number.isNaN(s))throw new Error(`${r} must be a number in [${t}, ${n}].`);if(o!==void 0&&!pA(i,o))throw new Error(`${r} supports at most ${o} decimal place(s).`);if(s<t||s>n)throw new Error(`${r} must be in [${t}, ${n}].`);return i}function pA(r,e){let t=r.split(".")[1];return t===void 0||t.length<=e}function on(r,e,t,n,o){return Number(mh(r,e,t,n,o))}var mA=["Name","Status","Serial","Device Type","OS Version"];function fA(r){return{cells:[r.name,r.status,r.serial??"-",r.deviceType??"-",r.osVersion??"-"],highlight:r.status==="running"}}async function hA(r,e){let t=await Promise.all(e.map(async n=>{let o=await An(r,n,aA);return[n,o]}));return new Map(t)}async function gA(r){let e=await Ml(r),t=await hA(r,e);return{serials:e,params:t}}function yA(r,e,t,n,o){if(e)for(let i of["const.product.name","const.product.model"]){let s=e.get(i);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),o.set(s,r);let c=n.indexOf(r);c!==-1&&n.splice(c,1);return}}function vA(r,e,t){let n=new Map,o=new Map,i=[...r],s=[...t];for(let a of r){let c=e.get(a),l=c?.get("ohos.qemu.hvd.name");l&&o.set(l,a),t.length>0&&yA(a,c,s,i,n)}for(let a=0;a<s.length&&a<i.length;a++)n.set(s[a],i[a]);return{productSerialMap:n,hvdSerialMap:o}}function wA(r,e,t){let n=r.map(o=>({emu:o,serial:e.get(o.name)??t.get(o.name),effectiveRunning:o.isRunning===!0||t.has(o.name)}));return n.sort((o,i)=>o.effectiveRunning!==i.effectiveRunning?o.effectiveRunning?-1:1:o.emu.name.localeCompare(i.emu.name)),n.map(({emu:o,serial:i,effectiveRunning:s})=>({name:o.name,status:s?"running":"stopped",serial:i??null,deviceType:o.deviceType??null,osVersion:o.osVersion??null}))}async function SA(r,e,t,n){try{let[o,i]=await Promise.all([r.listEmulators(),gA(e)]);if(o.length===0){n?.stop(),console.log(t==="json"?"[]":fr(" No emulator instances found."));return}let s=o.filter(g=>g.isRunning).map(g=>g.name),{productSerialMap:a,hvdSerialMap:c}=vA(i.serials,i.params,s);n?.stop();let l=wA(o,a,c);if(t==="json"){console.log(JSON.stringify(l,null,2));return}let d=l.map(fA);console.log(Ut(mA,d))}catch(o){throw n?.stop(),new Error(`Failed to list emulators: ${o.message}`,{cause:o})}}function fh(r,e,t){let n=!1;for(let o=0;o<r.length;o++){let i=r[o];if(i.status!=="rejected")continue;n=!0;let s=i.reason;console.error(Jl(`Failed to ${t} emulator "${e[o]}": ${s.message}`)),s.stdout&&console.error(Gl(s.stdout)),s.stderr&&console.error(Gl(s.stderr))}return n}var bA=2e3,EA=6e4;async function CA(r,e){let t=Ae(e);return(await _l(r)).some(o=>Ae(o)===t)}async function hh(r,e,t,n=EA,o=bA){let i=Date.now()+n;for(;Date.now()<i;){if(await CA(r,e)===t)return!0;await new Promise(a=>setTimeout(a,o))}return!1}function PA(r){if(!r)return null;let e=r.indexOf("-bootmode");return e>=0&&e+1<r.length&&r[e+1]==="snapshot"}async function AA(r,e,t){let n=await r.startEmulator(t);if(n.status==="already-running")return console.log(fr(`Emulator "${t}" is already running.`)),{started:!1,memoryBytes:0,hotBoot:null};console.log(Hn(`Starting emulator "${t}"...`));let o=n.tracker,i=0,s=PA(n.args);try{let a=await hh(e,t,!0);console.log(a?ti(`Emulator "${t}" started successfully.`):fr(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}finally{if(o)try{i=await o.stop()}catch{}}return{started:!0,memoryBytes:i,hotBoot:s}}async function IA(r,e,t){let n=await Promise.allSettled(t.map(s=>AA(r,e,s)));if(fh(n,t,"start"))throw new w("One or more emulators failed to start.");let o=n.filter(s=>s.status==="fulfilled").map(s=>s.value).filter(s=>s.started);return{emulatorMemory:o.length===0||o.some(s=>s.memoryBytes===0)?"unknown":te(o.reduce((s,a)=>s+a.memoryBytes,0)),hotBoot:o.length===0?null:o.every(s=>s.hotBoot===!0)}}async function gh(r,e){let t=e.trim();if(!Rt(t))return t;let n=await ue.withHdcPath(r).getDeviceName(t);if(n===t)throw new Error(`Cannot resolve a running emulator with serial "${t}". Use \`devecocli emulator list\` or pass the emulator name instead.`);return n}async function kA(r,e,t){let n=await gh(e,t);if(console.log(Hn(`Stopping emulator "${n}"...`)),await r.stopEmulator(n)==="already-stopped"){console.log(fr(`Emulator "${n}" is already stopped.`));return}let i=await hh(e,n,!1);console.log(i?ti(`Emulator "${n}" stopped successfully.`):fr(`Emulator "${n}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function DA(r,e,t){let n=await Promise.allSettled(t.map(o=>kA(r,e,o)));fh(n,t,"stop")}async function ut(){let r=await k.new();return{manager:jn.from(r),toolProvider:r}}async function Vt(r,e,t){let n={event:S.CommandExecuted,args:["emulator",t,"--target"]};await dt(n,async()=>{let o=dA(r.target),i=e(),s=Array.isArray(i)?i:[i],{manager:a,toolProvider:c}=await ut(),l=await gh(c.hdcPath,o);for(let d of s)await a.controlEmulator(l,d);console.log(ti(`Emulator "${o}" operation completed.`))})}function TA(r){let e=[];if(qs(e,"longitude",r.longitude,-180,180,8),qs(e,"latitude",r.latitude,-90,90,8),qs(e,"altitude",r.altitude,-1e4,1e4,2),qs(e,"bearing",r.direction,0,359.99,2,"--direction"),e.length===0)throw new Error("Specify at least one geolocation option.");return(r.longitude===void 0||r.latitude===void 0)&&console.warn(fr("Warning: --longitude and --latitude should be specified together to form a valid location.")),e}function RA(r){let e=[];if(Qo(e,"light",r.lightIntensity,0,1e5,!1,"--light-intensity"),Qo(e,"humidity",r.humidity,0,100,!1),Qo(e,"temperature",r.temperature,-273.1,100,!1),Qo(e,"steps",r.steps,0,1e4,!0),Qo(e,"heartrate",r.heartrate,0,255,!0),e.length===0)throw new Error("Specify at least one sensor option.");return e}function qs(r,e,t,n,o,i,s=`--${e}`){t!==void 0&&r.push({type:"gps",key:e,value:mh(s,t,n,o,i)})}function Qo(r,e,t,n,o,i,s=`--${e}`){if(t===void 0)return;let a=i?ph(s,t,n,o):on(s,t,n,o,1);r.push({type:"sensor",key:e,value:a})}function xA(r){let e=[];if(r.status!==void 0){let o=r.status==="charging"?1:0;e.push({type:"battery-status",status:o})}if(r.level!==void 0&&e.push({type:"battery",level:ph("--level",r.level,0,100),assumedCharging:r.status==="charging"}),e.length===0)throw new Error("Specify --level or --status.");let t=e.some(o=>o.type==="battery"&&o.level===0),n=e.some(o=>o.type==="battery-status"&&o.status===0);if(t&&n)throw new Error("Battery level 0 is only allowed while charging; --level 0 cannot be combined with --status discharging.");return e}var fe=new ql("emulator").description("Manage emulator instances");fe.configureOutput({outputError:(r,e)=>{e(r),/too many arguments/i.test(r)&&e(`
1291
- ${fr("Tip: ")}${Gl("An option value containing spaces/parentheses must be quoted. Use:")}
1292
- ${Hn('devecocli emulator <subcommand> --<option> "value with spaces"')}
1293
- ${Hn('devecocli emulator <subcommand> --<option>="value with spaces"')}
1294
- `)}});fe.hook("preAction",async()=>{(await k.new()).require({studio:lA})});var LA=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Yl(r){let e=new lt("--device-type <type>","Emulator device type").choices([...LA]);return r?e.makeOptionMandatory():e}function NA(){return new lt("--device-type <type>","Emulator device type (case-insensitive)").argParser(r=>{if(!r.trim())throw new iA("--device-type must not be empty.");return r}).makeOptionMandatory()}function OA(r){if(r!==void 0){if(r.length>=4&&r.length%4===0&&r.every(e=>/^\d+(?:\.\d+)?$/.test(e)))throw new Error('--screen value must be quoted: --screen "1316 2832 560 6.9".');if(r.length>2)throw new Error("--screen accepts one or two configurations.");for(let[e,t]of r.entries()){let n=t.trim().split(/\s+/),o=r.length===1?"--screen":`--screen configuration ${e+1}`;if(n.length!==4||n.some(i=>i.length===0))throw new Error(`${o} must contain four values: width(px), height(px), DPI, and screen diagonal length(inch).`);on(`${o} width`,n[0],720,3500),on(`${o} height`,n[1],720,3500),on(`${o} DPI`,n[2],240,640),on(`${o} screen diagonal length`,n[3],3.5,9)}return r}}function MA(r){return["--device-type","--os-version",...r.instancePath!==void 0?["--instance-path"]:[],...r.imageRoot!==void 0?["--image-root"]:[],...r.screenProfile!==void 0?["--screen-profile"]:[],...r.screen!==void 0?["--screen"]:[],...r.storage!==void 0?["--storage"]:[],...r.memory!==void 0?["--memory"]:[],...r.hotBoot!==void 0?["--hot-boot"]:[],...r.force?["--force"]:[]]}function $n(r,e){for(let t of e)if(t in r)return r[t]}function ei(r){return r==null?"":typeof r=="string"?r.trim():String(r).trim()}function uh(r){let e=ei(r).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var _A=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],FA="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";async function jA(r,e,t){if(!await r.hasAvailableEmulatorImage({deviceType:e,osVersion:t}))throw new Error(`Invalid --os-version value "${t}".
1295
- Run \`devecocli emulator image list --all\` and use an exact OS Version value.`)}function yh(r){try{let e=JSON.parse(r);return Array.isArray(e)?e:null}catch{return null}}function vh(r,e){let t=[];for(let n of r){if(!n||typeof n!="object")continue;let o=n,i=ei($n(o,["osVersion","OsVersion","OSVersion","os_version"])),s=ei($n(o,["deviceType","DeviceType","device_type"])),a=uh($n(o,["downloaded","Downloaded","isDownloaded"])),c=ei($n(o,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=ei($n(o,["releaseType","ReleaseType","release_type"])),d=uh($n(o,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[i,s,c,l,d,a],highlight:e&&a==="true"})}return t}function $A(r){let e=r.trim();if(!e)return!0;let t=yh(e);return t===null?!1:t.length===0?!0:vh(t,!0).length===0}function HA(r,e){let t=r.trim();if(!t)return"";let n=yh(t);if(!n)return r.trimEnd();let o=vh(n,e);return Ut(_A,o)}var Js=new ql("image").description("HarmonyOS emulator system images (download, list, remove)");Js.command("download").description("Download system image").addOption(Yl(!1)).option("--os-version <version>","Example: HarmonyOS 5.1.1(19) or HarmonyOS 6.0.1(21) (required)").option("--force","Overwrite an existing image").action(async r=>{let e={event:S.CommandExecuted,args:["emulator","image","download",...r.deviceType?["--device-type"]:[],...r.osVersion?["--os-version"]:[],...r.force?["--force"]:[]]};await dt(e,async()=>{let{manager:t,toolProvider:n}=await ut();await Vl(n.emulatorPath,n.sdkPath);let o=r.deviceType?.trim(),i=r.osVersion?.trim();if(!o)throw new w("Error: missing required option '--device-type <type>'","Missing required device type.");if(!i)throw new w("Error: misssing required option '--os-version <version>'","Missing required OS version.");await jA(t,o,i),await t.installEmulatorImage({deviceType:o,osVersion:i,force:r.force===!0})})});Js.command("remove").description("Remove a downloaded system image").addOption(Yl(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async r=>{let e={event:S.CommandExecuted,args:["emulator","image","remove","--device-type","--os-version"]};await dt(e,async()=>{let{manager:t}=await ut();await t.uninstallEmulatorImage({deviceType:r.deviceType,osVersion:r.osVersion})})});Js.command("list").description("List system images").addOption(Yl(!1)).option("--all","List all images (local and remote)").addOption(new lt("--format <format>","Output format").choices(["table","json"]).default("table")).action(async r=>{let e={event:S.CommandExecuted,args:["emulator","image","list",...r.deviceType?["--device-type"]:[],...r.all?["--all"]:[],...r.format!=="table"?["--format"]:[]]};await dt(e,async()=>{let{manager:t}=await ut(),n;r.all?n=void 0:n=!0;let o=await t.listEmulatorImages({deviceType:r.deviceType,downloaded:n});if($A(o)){console.log(fr(FA));return}if(r.format==="json"){console.log(o.trimEnd());return}let i=HA(o,r.all===!0);console.log(i)})});fe.addCommand(Js);var Ys=new ql("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");Ys.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let r={event:S.CommandExecuted,args:["emulator","license","view"]};await dt(r,async()=>{let{toolProvider:e}=await ut(),t=await sh(e.emulatorPath,e.sdkPath);process.exitCode=t})});Ys.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let r={event:S.CommandExecuted,args:["emulator","license","accept"]};await dt(r,async()=>{let{toolProvider:e}=await ut(),t=await lh(e.emulatorPath,e.sdkPath);process.exitCode=t})});Ys.action(async()=>{let r={event:S.CommandExecuted,args:["emulator","license"]};await dt(r,async()=>{let{toolProvider:e}=await ut(),t=await ch(e.emulatorPath,e.sdkPath);process.exitCode=t})});fe.addCommand(Ys);fe.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(r=>Vt(r,()=>({type:"shake"}),"shake"));fe.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(r=>Vt(r,()=>({type:"power"}),"power"));fe.command("rotate").description("Rotate emulator").addOption(new lt("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new zl("<direction>").choices(["left","right"])).action((r,e)=>Vt(e,()=>({type:"rotation",direction:r}),"rotate"));fe.command("volume").description("Change volume").addOption(new lt("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new zl("<direction>").choices(["up","down"])).action((r,e)=>Vt(e,()=>({type:"volume",direction:r}),"volume"));fe.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",cA).action((r,e)=>Vt(e,()=>({type:"folded-state",state:uA(r)}),"fold"));fe.command("battery").description("Set battery level and/or charging status").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--level <0-100>","Battery level, SOC (charging: 0-100; not charging: 1-100)").addOption(new lt("--status <status>","Charging status").choices(["charging","discharging"])).action(r=>Vt(r,()=>xA(r),"battery"));fe.command("geolocation").description("Inject geographic coordinates and direction").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--longitude <value>","Longitude (-180.0 to 180.0)").option("--latitude <value>","Latitude (-90.0 to 90.0)").option("--altitude <value>","Altitude (-10000.0 to 10000.0)").option("--direction <value>","Heading direction in degrees (0.00 to 359.99)").action(r=>Vt(r,()=>TA(r),"geolocation"));fe.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new zl("<type>","Motion simulation scene").choices(["outdoorRunning","outdoorCycling","drivingNavigation"])).action((r,e)=>{let t={outdoorRunning:{type:"outdoor-running"},outdoorCycling:{type:"outdoor-cycling"},drivingNavigation:{type:"driving-navigation"}};return Vt(e,()=>t[r],"scene")});fe.command("sensor").description("Inject sensor data").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--light-intensity <value>","Light sensor (0 to 100000)").option("--humidity <value>","Humidity sensor (0 to 100)").option("--temperature <value>","Temperature sensor (-273.1 to 100)").option("--steps <value>","Steps sensor (integer 0 to 10000)").option("--heartrate <value>","Heart rate sensor (integer 0 to 255)").action(r=>Vt(r,()=>RA(r),"sensor"));fe.command("list").description("List all emulator instances").addOption(new lt("--details","Output the raw JSON of `Emulator -list -details` without transformation").conflicts("format")).addOption(new lt("--format <format>","Output format").choices(["table","json"]).default("table")).action(async r=>{let e={event:S.CommandExecuted,args:["emulator","list",...r.details?["--details"]:[],...r.format!=="table"?["--format"]:[]]};await dt(e,async()=>{let{manager:t,toolProvider:n}=await ut();if(r.details){let i=await t.listEmulatorDetails();console.log(i.trimEnd());return}let o=r.format==="table"?sA({text:"Listing emulators\u2026",color:"cyan"}).start():void 0;await SA(t,n.hdcPath,r.format,o)})});fe.command("start [names...]").description("Start one or more emulator instances").action(async r=>{let e={event:S.CommandExecuted,args:["emulator","start"],emulatorMemory:"unknown",hotBoot:null};await dt(e,async()=>{let{manager:t,toolProvider:n}=await ut();if(await Wl(n.emulatorPath,n.sdkPath),!r?.length)throw new w("Error: missing required argument 'names'","Missing required emulator name.");let o=await IA(t,n.hdcPath,r);e.emulatorMemory=o.emulatorMemory,e.hotBoot=o.hotBoot})});fe.command("stop <names...>").description("Stop one or more emulator instances (by name or serial,e.g.,127.0.0.1:<port>)").action(async r=>{let e={event:S.CommandExecuted,args:["emulator","stop"]};await dt(e,async()=>{let{manager:t,toolProvider:n}=await ut();if(!r?.length){console.error(Jl("Error: missing required argument 'names'")),process.exitCode=1;return}await DA(t,n.hdcPath,r)})});var BA=fe.command("create <name>").description("Create a local emulator instance.").addOption(NA()).requiredOption("--os-version <version>",'Downloaded image label. which will be quoted in PowerShell (e.g. "HarmonyOS 6.0.1(21)") or be used in the format --os-version="\u2026";For details, run`devecocli emulator image list`').addOption(new lt("--path, --instance-path <path>","Emulator instance path")).option("--image-root <path>","Emulator image path").option("--screen-profile <model>","Emulator screen profile").addOption(new lt("--screen <config...>",'Screen: "width(px) height(px) DPI screen-diagonal-length(inch)" (720-3500, 720-3500, 240-640, 3.5-9); pass two values for a foldable device')).option("--storage <size>","Storage size in GB (2-1023)").option("--memory <size>","Memory size in GB (2-32)").addOption(new lt("--hot-boot <boolean>","Enable or disable hot boot").choices(["true","false"])).option("--force","Overwrite an existing emulator instance");BA.action(async(r,e)=>{let t={event:S.CommandExecuted,args:["emulator","create",...MA(e)]};await dt(t,async()=>{if(!e.osVersion.trim())throw new Error("--os-version must not be empty.");let n={name:r,deviceType:e.deviceType,osVersion:e.osVersion,instancePath:e.instancePath,imageRoot:e.imageRoot,screenProfile:e.screenProfile,screen:OA(e.screen),storage:e.storage===void 0?void 0:on("--storage",e.storage,2,1023),memory:e.memory===void 0?void 0:on("--memory",e.memory,2,32),hotBoot:e.hotBoot===void 0?void 0:e.hotBoot==="true",force:e.force===!0},{manager:o}=await ut();console.log(Hn(`Creating emulator "${r}"...`)),await o.createVirtualDevice(n),console.log(ti(`Emulator "${r}" created successfully.`))})});fe.command("delete <name>").description("Delete a local emulator instance").addOption(new lt("--path, --instance-path <path>","Emulator instance path")).action(async(r,e)=>{let t={event:S.CommandExecuted,args:["emulator","delete",...e.instancePath!==void 0?["--instance-path"]:[]]};await dt(t,async()=>{let{manager:n}=await ut();console.log(Hn(`Deleting emulator "${r}"...`));let o=await n.deleteVirtualDevice(r,e.instancePath);console.log(ti(`Emulator "${o}" deleted successfully.`))})});var wh=fe;import{Command as lI}from"commander";import{red as td,cyan as Nt}from"colorette";import*as Bh from"readline";import*as $h from"crypto";import*as Sh from"http";import*as bh from"crypto";import{URL as UA}from"url";var Ks=class{server=null;port=0;clientSecret;callbackPath="/callback";resolveCallback=null;rejectCallback=null;timeoutId=null;baseUrl;successRedirectUrl;failedRedirectUrl;constructor(e,t,n,o){this.clientSecret=e,this.baseUrl=t,this.successRedirectUrl=n,this.failedRedirectUrl=o}async start(){return new Promise((e,t)=>{let n=Sh.createServer((o,i)=>{this.handleRequest(o,i)});n.keepAliveTimeout=1,n.on("error",o=>{t(new Error("Failed to start local auth server",{cause:o}))}),n.listen(0,"127.0.0.1",()=>{this.server=n;let o=n.address();this.port=o.port,e()})})}async waitForCallback(e=3e4){return new Promise((t,n)=>{this.resolveCallback=o=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),t(o)},this.rejectCallback=o=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),n(o)},this.timeoutId=setTimeout(()=>{this.timeoutId=null,this.rejectCallback?.(new Error("Callback timeout"))},e)})}async stop(){return this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.server?new Promise(e=>{let t=this.server;this.server=null,typeof t.closeAllConnections=="function"&&t.closeAllConnections();let n=setTimeout(()=>{e()},100);t.close(()=>{clearTimeout(n),e()})}):Promise.resolve()}handleRequest(e,t){let n=e.headers.host||"";if(![`127.0.0.1:${this.port}`,`localhost:${this.port}`].includes(n.toLowerCase())){t.writeHead(400),t.end("Bad Host");return}let i=new UA(e.url??"",`http://${n}`);if(i.pathname!==this.callbackPath){t.writeHead(404),t.end("Not Found");return}try{let s=i.searchParams;e.method==="POST"?this.readBody(e,t,s):this.handleCallbackRequest(e,t,s,"")}catch(s){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(s)}}readBody(e,t,n){let o="",i=0,s=65536;e.on("data",a=>{if(i+=a.length,i>s){e.destroy(new Error("Request body too large"));return}o+=a.toString()}),e.on("end",()=>{this.handleCallbackRequest(e,t,n,o)})}handleCallbackRequest(e,t,n,o){try{let i=this.parseParams(n,o),s=i.get("code"),a=i.get("tempToken"),c=i.get("siteId"),l=i.get("quit");if(!this.validateCode(s)){t.writeHead(400),t.end("Bad Request");return}if(this.isQuitRequest(l)){this.handleQuitRequest(t);return}if(!a||!c){t.writeHead(400),t.end("Bad Request");return}let d={tempToken:a,siteId:c,quit:l??void 0};this.resolveCallback?.(d),this.sendSuccessResponse(t)}catch(i){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(i)}}parseParams(e,t){return t&&t.trim()?new URLSearchParams(t):e}validateCode(e){let t=Buffer.from(e||"","utf8"),n=Buffer.from(this.clientSecret,"utf8");return t.length===n.length&&bh.timingSafeEqual(t,n)}isQuitRequest(e){return e==="true"||e==="access_denied"||e==="quit"}handleQuitRequest(e){this.rejectCallback?.(new Error("User quit the login process")),e.writeHead(302,{Location:`${this.baseUrl}/${this.failedRedirectUrl}`}),e.end()}sendSuccessResponse(e){e.writeHead(302,{Location:`${this.baseUrl}/${this.successRedirectUrl}`}),e.end()}getPort(){return this.port}};import*as Ue from"fs";import*as hr from"path";import{homedir as YA}from"os";var Gt={};vS(Gt,{LocalCrypto:()=>Gt,decryptForLocalStorage:()=>zA,decryptForLocalStorageFromDirectory:()=>qA,encryptForLocalStorage:()=>GA,isEncryptedBlob:()=>JA});import*as oe from"fs";import*as Oe from"path";import*as Be from"crypto";import*as Ch from"os";import{homedir as Ph}from"os";var Ne=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var ri=Ur.ALGORITHM,Ah=Ur.IV_LENGTH,ni=Ur.KEY_LENGTH,oi=Ur.KEY_LENGTH,sn=Ur.KEK_VERSIONS,Xs=process.env.DEVECO_CLI_DATA_DIR||Oe.join(Ph(),Ee.CONFIG_DIR_NAME,Ee.APP_NAME),Zs=Oe.join(Ph(),".local","share",Ee.APP_NAME,"keys"),Bn=Oe.join(Xs,Ee.KEY_FILE_NAME);function Eh(r){return Ch.platform()==="win32"?`Permission denied. Please run as administrator or grant write permission to ${r}.`:`Permission denied. You can try: sudo chown -R $(whoami) ${r}`}function Kl(r){return Oe.join(Zs,`${r}.bin`)}function Ih(){if(!oe.existsSync(Xs))try{oe.mkdirSync(Xs,{recursive:!0,mode:448})}catch(r){throw r.code==="EACCES"?new Ne(Eh(Xs)):r}if(!oe.existsSync(Zs))try{oe.mkdirSync(Zs,{recursive:!0,mode:448})}catch(r){throw r.code==="EACCES"?new Ne(Eh(Oe.dirname(Zs))):r}}function kh(){Ih();for(let r of sn){let e=Kl(r);oe.existsSync(e)||oe.writeFileSync(e,Be.randomBytes(ni),{mode:384})}}function Dh(r){if(!sn.includes(r))throw new Error(`Invalid kekId: ${r}`);kh();let e=Kl(r),t=oe.readFileSync(e);if(t.length===ni)return t;let n=Be.randomBytes(ni);return oe.writeFileSync(e,n,{mode:384}),n}function Xl(r,e){let t=Be.randomBytes(Ah),n=Dh(e),o=Be.createCipheriv(ri,n,t),i=Buffer.concat([o.update(r),o.final()]),s=o.getAuthTag();return{version:1,algorithm:ri,kekId:e,encryptedDek:i.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function Th(r,e){return Rh(Buffer.from(r.encryptedDek,"base64"),e,r.iv,r.authTag)}function Rh(r,e,t,n){let o=Be.createDecipheriv(ri,e,Buffer.from(t,"base64"));return o.setAuthTag(Buffer.from(n,"base64")),Buffer.concat([o.update(r),o.final()])}function xh(r,e){return Rh(Buffer.from(r.ciphertext,"base64"),e,r.iv,r.authTag).toString("utf8")}function WA(){if(kh(),oe.existsSync(Bn))return;let r=Be.randomBytes(oi),e=Xl(r,sn[0]);oe.writeFileSync(Bn,JSON.stringify(e,null,2),{mode:384})}function Lh(){WA();let r=JSON.parse(oe.readFileSync(Bn,"utf8")),e=Th(r,Dh(r.kekId));if(e.length===oi)return e;let t=Be.randomBytes(oi),n=Xl(t,sn[0]);return oe.writeFileSync(Bn,JSON.stringify(n,null,2),{mode:384}),t}function VA(){Ih();for(let t of sn){let n=Kl(t);oe.existsSync(n)||oe.writeFileSync(n,Be.randomBytes(ni),{mode:384})}if(oe.existsSync(Bn))return;let r=Be.randomBytes(oi),e=Xl(r,sn[0]);oe.writeFileSync(Bn,JSON.stringify(e,null,2),{mode:384})}function GA(r){let e=Lh(),t=Be.randomBytes(Ah),n=Be.createCipheriv(ri,e,t),o=Buffer.concat([n.update(r,"utf8"),n.final()]),i=n.getAuthTag();return{version:1,algorithm:ri,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:i.toString("base64"),timeStamp:Date.now()}}function zA(r){try{return xh(r,Lh())}catch{throw VA(),new Error("Failed to decrypt local ciphertext")}}function qA(r,e){let t=Oe.join(e,Ee.KEY_FILE_NAME),n=JSON.parse(oe.readFileSync(t,"utf8"));if(!sn.includes(n.kekId))throw new Error(`Invalid kekId: ${n.kekId}`);let o=Oe.join(e,"keys",`${n.kekId}.bin`),i=Oe.resolve(o),s=Oe.resolve(Oe.join(e,"keys"));if(!i.startsWith(s+Oe.sep)&&i!==s)throw new Error("kekId resolves outside the keys directory");let a=oe.readFileSync(i);if(a.length!==ni)throw new Error("Invalid external root key");let c=Th(n,a);if(c.length!==oi)throw new Error("Invalid external data encryption key");return xh(r,c)}function JA(r){if(!r||typeof r!="object")return!1;let e=r;return e.algorithm==="aes-256-gcm"&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}function We(){return process.env.DEVECO_CLI_AUTH_SOURCE===Ee.AUTH_SOURCE_DEVECO_CODE}var Qs=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR||hr.join(YA(),Ee.CONFIG_DIR_NAME,Ee.APP_NAME);return hr.join(e,Ee.TOKEN_FILE_NAME)}ensureConfigDir(){let e=hr.dirname(this.getLocalTokenFilePath());Ue.existsSync(e)||Ue.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=Gt.encryptForLocalStorage(e);this.ensureConfigDir();let n=this.getLocalTokenFilePath();Ue.writeFileSync(n,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return We()?this.loadDevecoCodeToken():this.loadLocalJwtToken()}loadDevecoCodeToken(){if(!We())return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;let t=hr.resolve(e);try{let n=hr.join(t,Ee.TOKEN_FILE_NAME);if(!Ue.existsSync(n))return null;let o=JSON.parse(Ue.readFileSync(n,"utf8"));return Gt.isEncryptedBlob(o)?Gt.decryptForLocalStorageFromDirectory(o,e):null}catch{return null}}async loadLocalJwtToken(){let e=this.getLocalTokenFilePath();try{if(!Ue.existsSync(e))return null;let t=JSON.parse(Ue.readFileSync(e,"utf8"));return Gt.isEncryptedBlob(t)?Gt.decryptForLocalStorage(t):null}catch(t){let n=t.code;return n==="EACCES"||n==="EPERM"||n==="ENOENT"||await this.clearToken(),null}}async clearToken(){if(We()){m("clearToken: skipped, session managed by DevEco Code");return}let e=this.getLocalTokenFilePath();try{Ue.existsSync(e)&&Ue.unlinkSync(e)}catch(t){throw new Error("Failed to clear token",{cause:t})}}},zt=new Qs;import{spawn as KA}from"child_process";function XA(r){try{let e=new URL(r);return!(!["http:","https:"].includes(e.protocol)||e.hostname===""||r.includes('"'))}catch{return!1}}function ZA(r){return r.replace(/[&|<>()^%!]/g,e=>`^${e}`)}async function Nh(r){if(!XA(r))throw new Error(`Invalid URL: ${JSON.stringify(r)}`);let e,t;switch(process.platform){case"win32":e="cmd",t=["/c","start",'""',ZA(r)];break;case"darwin":e="open",t=[r];break;default:e="xdg-open",t=[r];break}let n=KA(e,t,{stdio:"ignore",shell:!1,windowsHide:!0});return new Promise((o,i)=>{n.on("error",s=>{i(new Error("Failed to open browser",{cause:s}))}),n.on("close",s=>{s===0?o():i(new Error(`Browser process exited with code ${s}`))})})}import QA from"axios";import{getProxyForUrl as eI}from"proxy-from-env";function tI(r){let e=new URL(r);return{protocol:e.protocol,host:e.hostname,port:e.port?Number.parseInt(e.port,10):e.protocol==="https:"?443:80,auth:{username:decodeURIComponent(e.username),password:decodeURIComponent(e.password)}}}var Zl=class{client;constructor(){let e={timeout:Eo.HTTP_TIMEOUT_MS,headers:{"User-Agent":Yi.USER_AGENT,"accept-language":Yi.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=QA.create(e),this.client.interceptors.request.use(t=>{let n=eI(t.url??"");return t.proxy=n?tI(n):!1,t}),this.client.interceptors.response.use(t=>t,t=>{let n=`Network connection failed (${t.code}). Please check your proxy configuration or network settings`;throw new Error(`${t.message}
1296
- ${n}`)})}async get(e,t){let n=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(n)}async post(e,t){let n=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(n)}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,statusText:e.statusText??"",headers:e.headers}}parseJson(e){try{return JSON.parse(e.data)}catch(t){throw new Error(`Failed to parse JSON response: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}async getBinary(e,t){let n=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout});if(n.status!==200)throw new Error(`HTTP ${n.status}`);return Buffer.from(n.data)}async postAllowFailure(e,t){let n=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(n)}async deleteAllowFailure(e,t){let n=await this.client.request({method:"DELETE",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(n)}async getBinaryAllowFailure(e,t){let n=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0}),o=Buffer.from(n.data),i=o.toString("utf8");return{statusCode:n.status,statusText:n.statusText??"",buffer:o,body:i}}},L=new Zl;function Oh(r){let e=r.split(".");return e.length===3&&e.every(t=>t.length>0)}var qt={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},an={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},ea={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},rI={[qt.CHINA]:an.CHINA,[qt.RUSSIA]:an.RUSSIA,[qt.EUROPE]:an.EUROPE,[qt.SINGAPORE]:an.CHINA},nI={[ea.CHINA]:qt.CHINA,[ea.SINGAPORE]:qt.SINGAPORE,[ea.EUROPE]:qt.EUROPE,[ea.RUSSIA]:qt.RUSSIA};function Mh(r){return rI[r]??an.CHINA}function _h(r){return nI[r]??qt.CHINA}var Ql=class{async getJwtToken(e,t,n,o,i){let s=e.split("&")[0],a=_h(t),c={tempToken:s,site:a,version:Ee.API_VERSION,appid:i},l=`${n}/${o}`,d=await L.get(l,{params:c});if(d.statusCode!==200)throw new Error(`Failed to get jwtToken: status=${d.statusCode}`);let g=d.data.trim();if(!Oh(g))throw new Error("Invalid jwtToken format");return g}},Fh=new Ql;var ed=class{async checkJwtToken(e,t,n=!1){let o={refresh:String(n),jwtToken:e},i=`${t}/${X.JWT_TOKEN_CHECK_PATH}`,s=await L.get(i,{headers:o});if(s.statusCode!==200)throw new Error(`Failed to check jwtToken: ${s.statusCode}`);return L.parseJson(s)}async refreshToken(e){let t=await zt.loadJwtToken();return t?this.refreshTokenWithToken(t,e):null}async refreshTokenWithToken(e,t){try{let n={refresh:"true",jwtToken:e},o=`${t}/${X.JWT_TOKEN_CHECK_PATH}`,i=await L.get(o,{headers:n});if(i.statusCode!==200)return null;let s=L.parseJson(i);return!s.status||!s.userInfo?null:{accessToken:s.userInfo.accessToken,refreshToken:s.userInfo.refreshToken??""}}catch(n){let o=n;return console.error(`Failed to refresh token: ${o.code??""} ${o.message??""}`),null}}async getUserInfoFromJwt(e,t,n=!1){let o=await this.checkJwtToken(e,t,n);return!o.status||!o.userInfo||!o.userInfo.accessToken?(m("jwtToken invalid."),await zt.clearToken(),null):{userId:o.userInfo.userId??"",userName:o.userInfo.name??"",accessToken:o.userInfo.accessToken,refreshToken:o.userInfo.refreshToken??"",jwtToken:e,countryCode:o.userInfo.nationalCode,language:Mh(o.userInfo.nationalCode),isRealName:String(o.userInfo.realName)==="true"}}async fetchUserInfo(e,t){let n=await zt.loadJwtToken();return n?this.getUserInfoFromJwt(n,e,t):null}},Un=new ed;import oI from"querystring";import{spawn as iI}from"child_process";function jh(r){try{let e=JSON.stringify({signInfo:[{agrType:Co.PRIVACY_ID,country:"CN",language:"zh_CN",isAgree:!0}]}),t=oI.stringify({nsp_svc:"as.user.sign",access_token:r,request:e}),n=iI("curl",["-s","-X","POST",Co.TMS_URL,"-H","Content-Type: application/x-www-form-urlencoded","-d",t,"--max-time","5","-o","/dev/null","-w","%{http_code}"],{detached:!0,stdio:["ignore","pipe","ignore"]});n.unref(),n.stdout?.on("data",o=>{let i=o.toString().trim();i==="200"?m("Agreement sign reported successfully"):m(`Agreement sign failed: HTTP ${i}`)}).on("error",()=>{})}catch(e){m(`Agreement sign error: ${e.message}`)}}var ta=class{config;server=null;constructor(e){this.config={...Po,...e}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}async login(){try{m(`Login started, isDevecoCodeAuth: ${We()}`);let e=this.generateClientSecret();this.server=new Ks(e,X.CN_LOGIN_URL,this.config.successRedirectUrl,this.config.failedRedirectUrl),await this.server.start(),m(`Local auth server started on port ${this.server.getPort()}`),await this.openLoginPage(this.server.getPort(),e),m("Browser opened for authentication");let t=await this.server.waitForCallback(this.config.timeout);if(m(`Callback received: siteId=${t.siteId}`),t.siteId!=="1")throw new Ne("Non-China accounts are not supported.");let n=await Fh.getJwtToken(t.tempToken,t.siteId,X.CN_LOGIN_URL,this.config.tempTokenCheckUrl,this.config.appId);m("JWT token received");let o=await Un.getUserInfoFromJwt(n,X.CN_LOGIN_URL);if(!o)throw new Ne("Login failed: failed to get user info");return m(`User info received: ${o.userName}`),await zt.saveJwtToken(n),m("JWT token saved"),jh(o.accessToken),o}finally{this.server&&(await this.server.stop(),this.server=null)}}async isLoggedIn(){return await this.getUserInfo(!0)!==null}async logout(){let e=await zt.loadJwtToken();if(!e)return!1;let n=`${X.CN_LOGIN_URL}/${this.config.logoutUrl}?jwtToken=${e}`;try{await L.post(n,{timeout:5e3})}catch{m("Logout: server notification failed, local token cleared")}finally{await zt.clearToken()}return!0}async getUserInfo(e=!0){return Un.fetchUserInfo(X.CN_LOGIN_URL,e)}generateClientSecret(){return $h.randomUUID().replace(/-/g,"")}async openLoginPage(e,t){let o=`${X.CN_LOGIN_URL}/${this.config.authUrl}?port=${e}&appid=${this.config.appId}&code=${t}`;await Nh(o)}async refreshToken(){return Un.refreshToken(X.CN_LOGIN_URL)}},Me=new ta;function aI(){return We()?"Not logged in. Please login via DevEco Code first.":"Please run `devecocli auth login` first."}function cI(r){if(r==null||typeof r!="object")return[];let e=r;if(e.ret&&e.ret.code!==0)throw new Error(`team list request failed: code=${e.ret.code}${e.ret.msg?`, msg=${e.ret.msg}`:""}`);return Array.isArray(e.teams)?e.teams.filter(t=>typeof t=="object"&&t!==null).map(t=>({id:String(t.id??""),upSiteId:Number(t.upSiteId??0),name:String(t.name??""),countryCode:String(t.countryCode??""),siteId:Number(t.siteId??0),userType:Number(t.userType??0),lastLoginTime:String(t.lastLoginTime??""),isMirror:t.isMirror===!0})).filter(t=>t.id.length>0):[]}var ra=class{config;constructor(e){this.config={...Po,...e}}updateConfig(e){this.config={...this.config,...e}}async listTeams(){let e=await Un.fetchUserInfo(X.CN_LOGIN_URL,!0);if(!e)throw new Ne(aI());let t=await this.fetchTeamList(e.accessToken,e.userId),n=cI(t);return{userId:e.userId,teamList:n}}async fetchTeamList(e,t){let n=this.config.agcTeamListUrl,o;try{o=await L.get(n,{headers:{oauth2Token:e,uid:t,source:"cli",lang:an.CHINA},timeout:15e3})}catch(i){let s=i.message;throw s.includes("401")?new Ne("Token expired. Run `devecocli auth login` again."):new Error(`Network error while listing teams: ${s}`,{cause:i})}if(o.statusCode!==200)throw new Error(`Failed to list teams: HTTP ${o.statusCode}`);return typeof o.data=="string"?JSON.parse(o.data):o.data}},Hh=new ra;async function gr(){return Hh.listTeams()}async function na(r,e,t){let n=Date.now(),o=!0,i=null;try{await e()}catch(s){o=!1,i=q(s);let a=t?.(s);if(a)throw a}finally{let s={duration_ms:Date.now()-n,success:o,error_code:i};await I.track(r,s)}}function dI(r){if(r.length===0)return Nt("No teams found for the current user.");let e=["Id","Name"],t=r.map(s=>[s.id,s.name]),n=e.map((s,a)=>Math.max(s.length,...t.map(c=>c[a].length))),o=s=>s.map((a,c)=>a.padEnd(n[c])).join(" "),i=n.map(s=>"-".repeat(s)).join(" ");return[o(e),i,...t.map(o)].join(`
1297
- `)}function uI(){return new Promise(r=>{let e=Bh.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),r()})})}var ii=new lI("auth").description("Authentication commands (login, logout, status, team)");ii.command("login").description("Log in to your Huawei Developer account").action(async()=>{if(We()){console.log(td("Login is managed by DevEco Code. Login from DevEco Code instead."));return}let r={event:S.CommandExecuted,args:["auth","login"]};await na(r,async()=>{let e=await Me.getUserInfo();if(e){console.log(Nt(`Already logged in, User Name:${e.userName}`));return}console.log(Nt("Starting login process...")),console.log(Nt("Press Enter to open browser for login...")),await uI();let t=await Me.login();console.log(Nt(`Login successful. Logged in as ${t.userName}.`))},e=>{throw e instanceof Ne||(e instanceof Error?e.message:String(e)).includes("Network connection failed")?e:new Error("Login failed",{cause:e})})});ii.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(We()){console.log(td("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}let r={event:S.CommandExecuted,args:["auth","logout"]};await na(r,async()=>{let e=await Me.logout();console.log(e?Nt("Logout successful"):Nt("Already logged out."))},e=>new Error("Logout failed",{cause:e}))});ii.command("status").description("Show the currently logged-in user").action(async()=>{let r={event:S.CommandExecuted,args:["auth","status"]};await na(r,async()=>{let e=await Me.getUserInfo();if(!e){console.log(Nt("Not logged in"));return}console.log(Nt(`Current user: ${e.userName}`))},()=>{console.log(Nt("Not logged in"))})});var pI=ii.command("team").description("Team-related commands");pI.command("list").description("List team accounts the current user has joined").action(async()=>{let r={event:S.CommandExecuted,args:["auth","team","list"]};await na(r,async()=>{let e=await gr();console.log(dI(e.teamList))},e=>{if(e instanceof Ne){console.log(td(e.message));return}throw new Error("Failed to list teams",{cause:e})})});var Uh=ii;import{Command as kI}from"commander";import{green as DI,red as di,cyan as dg,yellow as ug,dim as pg}from"colorette";import TI from"p-limit";import mI from"ora";var Qe=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=mI(e),this.spinner.start(),this.isRunning=!0}stop(){this.spinner&&this.isRunning&&(this.spinner.stop(),this.isRunning=!1)}succeed(e){this.spinner&&(this.spinner.succeed(e),this.isRunning=!1)}fail(e){this.spinner&&(this.spinner.fail(e),this.isRunning=!1)}};import*as Vh from"fs";import*as rd from"path";import{homedir as Wh}from"os";function yr(r){if(!/^[A-Za-z0-9._-]+$/.test(r)||r==="."||r==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(r)}`)}var Gh=["DevEco"];async function oa(){let r=await L.get(nt.TAGS_API_URL),t=ia(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 fI(r){let e=[],t=nt.DEFAULT_PAGE_SIZE,n=nt.DEFAULT_MAX_PAGES,o=1;for(;o<=n;){let i=await L.post(nt.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:o,pageSize:t,tagIds:[r]}}),s=ia(i,"Skills API");if(e.push(...s.data.list),s.data.list.length<t)break;o++}return e}async function nd(r){let e=new Map,t=r.map(o=>fI(o)),n=await Promise.all(t);for(let o of n)for(let i of o)e.has(i.id)||e.set(i.id,i);return Array.from(e.values()).filter(o=>o.tags?.every(i=>!Gh.includes(i.name)))}async function hI(r,e){let t=await L.post(nt.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:nt.DEFAULT_PAGE_SIZE,keyword:r,tagIds:[e]}});return ia(t,"Skills API").data.list}async function od(r,e){let t=new Map,n=e.map(i=>hI(r,i)),o=await Promise.all(n);for(let i of o)for(let s of i)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(i=>i.tags?.every(s=>!Gh.includes(s.name)))}function zh(r){yr(r);let e=[];for(let[,t]of Object.entries(ht)){let n=E.ensurePathWithinRoot(rd.join(Wh(),t.path),rd.join(Wh(),t.path,r));Vh.existsSync(n)&&e.push(t.displayName)}return e.sort()}function ia(r,e){if(r.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${r.statusCode}`);let t=L.parseJson(r);if(t.code!==nt.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function qh(r){yr(r);let e=`${nt.SKILL_API_BASE}/${r}/checksum`,t=await L.get(e);return ia(t,"Checksum API").data}import gI from"adm-zip";import yI from"crypto";import{timingSafeEqual as vI}from"crypto";import Yh from"fs";import ce from"path";import{fileURLToPath as wI}from"url";import{homedir as Kh}from"os";import{red as SI}from"colorette";var Jt=Yh.promises;function Jh(r,e){let t=ce.resolve(e),n=ce.resolve(r),o=ce.relative(n,t);if(o.startsWith("..")||ce.isAbsolute(o))throw new Error(`Path traversal detected: ${e}.`)}function id(r){return ce.isAbsolute(r)?r:ce.resolve(process.cwd(),r)}function bI(r){return yI.createHash("sha256").update(r).digest("hex")}async function EI(r,e){if(r.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let n=bI(r),o=e.sha256.toLowerCase(),i=Buffer.from(n,"hex"),s=Buffer.from(o,"hex");if(i.length!==s.length||!vI(i,s))throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function Xh(r){yr(r);let e=`${nt.SKILL_API_BASE}/${r}/install?format=zip`,t=await L.getBinary(e),n=await qh(r);return await EI(t,n),t}async function CI(r,e,t){yr(t);let n=new gI(r),o=n.getEntries();try{await Jt.stat(e)}catch{await Jt.mkdir(e,{recursive:!0})}let i=ce.join(e,t);Jh(e,i);for(let s of o){let a=ce.join(i,s.entryName);Jh(i,a)}n.extractAllTo(i,!0)}async function sd(r){let e=ht[r];if(!e)throw new Error(`Invalid agent: ${r}, Valid options are: ${Object.keys(ht).join(", ")}`);let t=ce.join(Kh(),e.path.replace("/skills",""));try{return await Jt.access(t),!0}catch{return!1}}function ad(r){let e=ht[r];return ce.join(Kh(),e.path)}function PI(r){let e=ht[r];if(!e)throw new Error(`Invalid agent: ${r}, Valid options are: ${Object.keys(ht).join(", ")}`);return e}function cd(r,e){let t=PI(e),n="projectPath"in t?t.projectPath:ce.join("."+e,"skills");return ce.join(r,n)}async function AI(r,e,t){yr(e);let n=ce.join(r,e);try{if(await Jt.access(n),t)await Jt.rm(n,{recursive:!0,force:!0});else return console.log(`Skill ${e} exists in ${r}.`),{skillDir:n,shouldSkip:!0}}catch{}return{skillDir:n,shouldSkip:!1}}async function ld(r,e,t){await CI(r,e,t),console.log(`Skill ${t} installed to ${ce.join(e,t)}.`)}async function dd(r,e,t){let n=ce.join(e,t);await Jt.mkdir(n,{recursive:!0});let o=ce.join(n,ce.basename(r));await Jt.copyFile(r,o),console.log(`Skill ${t} installed to ${n}.`)}function Zh(r,e,t=""){let n=e instanceof Error?e.message:t;return console.log(SI(`Faild to exute operation for skill "${r}": ${n}`)),{success:!1,error:n}}async function Wn(r,e,t,n){try{let o=await e(),{shouldSkip:i}=await AI(o,r,n);return i?{success:!0,skipped:!0}:(await t(o),{success:!0})}catch(o){return Zh(r,o,"Installation failed")}}async function ud(r,e){try{yr(r);let t=await e(),n=ce.join(t,r);try{await Jt.access(n)}catch{return console.log(`Skill ${r} not found in ${t}`),{success:!0,skipped:!0}}return await Jt.rm(n,{recursive:!0,force:!0}),console.log(`Skill ${r} removed from ${n}.`),{success:!0}}catch(t){return Zh(r,t,"Removal failed")}}async function Qh(r,e,t,n=!1){return Wn(r,()=>ad(e),o=>ld(t,o,r),n)}async function eg(r,e,t,n=!1){return Wn(r,()=>t,o=>ld(e,o,r),n)}async function tg(r,e,t,n,o=!1){return Wn(r,()=>cd(t,n),i=>ld(e,i,r),o)}async function rg(r,e,t,n=!1){return Wn(r,()=>ad(t),o=>dd(e,o,r),n)}async function ng(r,e,t,n,o=!1){return Wn(r,()=>cd(t,n),i=>dd(e,i,r),o)}async function og(r,e,t,n=!1){return Wn(r,()=>t,o=>dd(e,o,r),n)}async function pd(r,e){return ud(r,()=>ad(e))}async function ig(r,e){return ud(r,()=>e)}async function sg(r,e,t){return ud(r,()=>cd(e,t))}function ag(){let e=ce.dirname(wI(import.meta.url));for(;;){let t=ce.join(e,"SKILL.md");if(Yh.existsSync(t))return t;let n=ce.dirname(e);if(n===e)break;e=n}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import cg from"fs";import{cyan as II}from"colorette";async function si(r){if(!r)return[];let e=[],t=r.split(",").map(n=>n.trim());for(let n of t){if(!await sd(n))throw new Error(`Agent ${n} not found`);e.push(n)}return e}async function ai(){let r=[];for(let e of Object.keys(ht))await sd(e)&&r.push(e);return r}function ci(r){let e=r.filter(o=>o.success&&!o.skipped).length,t=r.filter(o=>o.skipped).length,n=r.filter(o=>!o.success).length;console.log(),console.log(II("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`),n>0&&(process.exitCode=1)}function vr(r,e,t){if(!cg.existsSync(r)){if(t)return;throw new Error(`${e} "${r}" not found`)}if(!cg.statSync(r).isDirectory())throw new Error(`"${r}" is not a directory`)}function li(r,e,t){if(r&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:r?id(r):void 0,resolvedProject:e?id(e):void 0}}async function sa(r,e,t){let n=[],o=[],i;if(e?i=e:t&&r.agent?o=(await si(r.agent)).map(a=>({project:t,agent:a})):t?o=(await ai()).map(a=>({project:t,agent:a})):r.agent?n=await si(r.agent):n=await ai(),!i&&n.length===0&&o.length===0)throw new Error("No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location.");return{agents:n,projectAgents:o,customPath:i}}var mg="deveco";async function RI(r){let e=await oa();if(r.all)return(await nd(e)).map(n=>n.enName);{let n=(await od(r.skill,e)).find(o=>o.enName===r.skill);if(!n)throw new cn("errorCode",`Skill "${r.skill}" not found`);return[n.enName]}}async function xI(r,e,t,n){let o=[];if(t.customPath){let i=await eg(r,e,t.customPath,n);return o.push(i),o}for(let i of t.agents){let s=await Qh(r,i,e,n);o.push(s)}for(let{project:i,agent:s}of t.projectAgents){let a=await tg(r,e,i,s,n);o.push(a)}return o}function LI(r){if(r.all&&r.skill)throw new cn("errorCode","`--all` and `--skill` cannot be specified together.");if(!r.all&&!r.skill)throw new cn("errorCode","Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=li(r.path,r.project,r.agent);return t&&vr(t,"Project directory",r.force),e&&vr(e,"Directory",r.force),{resolvedPath:e,resolvedProject:t}}function NI(r,e,t){return!!(e||t||r.path||r.project||r.agent)}function OI(){return{agents:[mg],projectAgents:[],customPath:void 0}}async function MI(r,e,t){let n=We()&&!NI(r,e,t)?OI():await sa(r,e,t);return{skillNames:await RI(r),targets:n}}async function _I(r,e,t,n){let o=[],i=0,s=r.length,a=TI(5),c=r.map(l=>a(()=>FI(l)));for(let l=0;l<r.length;l++){let d=r[l],g=s>1?` (${l+1}/${s})`:"";n.start(`Installing ${d}${g}...`);let y=await c[l];if(!y.success){n.fail(),console.log(di(`${d}: Download failed - ${y.error}`)),o.push({success:!1});continue}i+=y.buffer.length,n.stop();let b=await xI(d,y.buffer,e,t);o.push(...b)}return{results:o,diskBytes:i}}async function FI(r){try{let e=await Xh(r);return{name:r,buffer:e,success:!0}}catch(e){let t=e instanceof Error?e.message:"unknown error";return{name:r,error:t,success:!1}}}async function jI(r){let e=new Qe;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:n}=LI(r),{skillNames:o,targets:i}=await MI(r,t,n),{results:s,diskBytes:a}=await _I(o,i,r.force||!1,e);return e.stop(),ci(s),{diskBytes:a,results:s}}catch(t){throw e.stop(),t}}function fg(r){let e=r.length,t=r.filter(s=>s.success&&!s.skipped).length,n=r.filter(s=>s.skipped).length,o=r.filter(s=>!s.success).length,i=[...new Set(r.filter(s=>!s.success&&typeof s.error=="string").map(s=>$I(s.error)))];return{opTotal:e,opSuccess:t,opFailed:o,opSkipped:n,...i.length>0?{failedErrors:i}:{}}}function $I(r){let e=/^([A-Za-z_][A-Za-z0-9_-]*)/.exec(r.trim());return e?e[1].slice(0,32):"error"}var cn=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function HI(r){let e=r;return r instanceof cn?r.code:e.code??e.name??"UnknownError"}function ca(r,e={}){return["skills",r,...e.all?["--all"]:[],...e.long?["--long"]:[],...e.skill?["--skill"]:[],...e.force?["--force"]:[],...e.agent?["--agent",e.agent]:[],...e.project?["--project"]:[],...e.path?["--path"]:[]]}async function la(r,e,t){let n=Date.now(),o=!0,i=null,s={};try{s=await e()}catch(a){throw o=!1,i=HI(a),a}finally{let a={event:S.SkillOperation,subAction:r,args:t,...s};await I.track(a,{duration_ms:Date.now()-n,success:o,error_code:i})}}function BI(r){return la("add",async()=>{let{diskBytes:e,results:t}=await jI(r);return{diskUsage:te(e),...r.skill?{skillName:r.skill}:{},...fg(t)}},ca("add",r))}function UI(r){let{resolvedPath:e,resolvedProject:t}=li(r.path,r.project,r.agent);return t&&vr(t,"Project directory"),e&&vr(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function WI(r,e){let t=new Qe;try{t.start("Removing skill...");let{resolvedPath:n,resolvedProject:o}=UI(e);t.stop();let i=await VI(e,r,n,o);return t.stop(),ci(i),i}catch(n){throw t.stop(),n}}function lg(r,e=""){if(r.length===0)throw new cn("errorCode",`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function aa(r,e){let t=[];for(let n of e){let o=n.type==="agent"?await pd(r,n.agent):await sg(r,n.project,n.agent);t.push(o)}return t}async function VI(r,e,t,n){if(t)return[await ig(e,t)];if(n&&r.agent){let a=(await si(r.agent)).map(c=>({type:"projectAgent",agent:c,project:n}));return aa(e,a)}if(n){let s=await ai();lg(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:n}));return aa(e,a)}if(r.agent){let a=(await si(r.agent)).map(c=>({type:"agent",agent:c}));return aa(e,a)}if(We())return[await pd(e,mg)];let o=await ai();lg(o,"or use --path for a custom location.");let i=o.map(s=>({type:"agent",agent:s}));return aa(e,i)}var ui=new kI("skills").description("Manage HarmonyOS skills");ui.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async r=>{try{await la("list",async()=>{let e=new Qe;try{e.start("Fetching skills...");let t=await oa(),n=await nd(t);if(n.length===0)return e.stop(),console.log(ug("No skills available.")),{resultTotal:0};e.succeed(`Fetched ${n.length} skills`);for(let o of n)if(r.long){console.log(dg(o.enName)),console.log(pg(o.description));let i=zh(o.enName);i.length>0&&console.log(DI(`Installed for: ${i.join(", ")}`)),console.log()}else console.log(o.enName);return{resultTotal:n.length}}finally{e.stop()}},ca("list",r))}catch(e){console.error(di(e.message)),process.exit(1)}});ui.command("find <keyword>").description("Search skills by keyword").action(async r=>{try{await la("find",async()=>{let e=new Qe;try{e.start("Searching skills...");let t=await oa(),n=await od(r,t);if(n.length===0)return console.log(ug(`No skills found matching '${r}'.`)),e.stop(),{resultTotal:0,queryLen:r.length,keyword:r};e.succeed(`Found ${n.length} skills.`);for(let o of n)console.log(dg(o.enName)),console.log(pg(o.description)),console.log();return{resultTotal:n.length,queryLen:r.length,keyword:r}}finally{e.stop()}},ca("find"))}catch(e){console.error(di(e.message)),process.exit(1)}});ui.command("add").description("Install skills to AI agents").option("--all","Install all available skills").option("--agent <agents>","Target agents, comma-separated; Omit to install to all available agents").option("--skill <skill-name>","Name of the skill to install").option("-f, --force","Overwrite an existing skill installation").option("--project <path>","Project root directory for skill installation").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").action(async r=>{try{await BI(r)}catch(e){console.error(di(e.message)),process.exit(1)}});ui.command("remove").description("Remove an installed skill from AI agents").requiredOption("--skill <skill-name>","Name of the skill to remove").option("--agent <agents>","Target agents, comma-separated.Omit to remove from all available agents").option("--project <path>","Project root directory for skill removal").option("--path <path>","Path for skill removal").action(async r=>{try{await la("remove",async()=>{let e=await WI(r.skill,r);return{skillName:r.skill,...fg(e)}},ca("remove",r))}catch(e){console.error(di(e.message)),process.exit(1)}});var hg=ui;import{Command as GI,InvalidArgumentError as da}from"commander";import{cyan as md,red as yg}from"colorette";import zI from"ora";function qI(r){return["log",...r.device?["--device"]:[],...r.crash?["--crash"]:[],...r.level?["--level"]:[],...r.bundleName?["--bundle-name"]:[],...r.keyword?["--keyword"]:[],...r.tail!==void 0?["--tail"]:[],...r.from!==void 0?["--from"]:[],...r.to!==void 0?["--to"]:[],...r.follow?["--follow"]:[]]}function JI(r){return{event:S.CommandExecuted,args:qI(r),logType:r.crash?"crash":"common",level:r.level??"ALL",bundleName:r.bundleName??"ALL"}}function YI(r){return r instanceof w?r.traceMessage:r instanceof Error?r.code??r.name:"UnknownError"}async function KI(r,e){let t=Date.now(),n=!0,o=null;try{await e()}catch(i){n=!1,o=YI(i),console.error(yg(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:n,error_code:o};await I.track(r,i).catch(()=>{})}}function XI(r){try{return E.parsePositiveInteger(r,"tail")}catch{throw new da("`tail` must be a positive integer.")}}function gg(r,e){try{return E.parseDurationToSeconds(r,e)}catch{throw new da(`${e} must be a valid duration string (e.g.,30s, 5m or 2.5m).Supported units: s and m.when specified in seconds(with \`s\` or as a raw number), the value must be an integer.`)}}function ZI(r){try{return E.assertHilogLevel(r),r}catch{throw new da("`level` must be one of: D, I, W, E, F.")}}function QI(r){try{return E.assertBundleNameStrict(r),r}catch(e){throw new da(e.message)}}function ek(r){if(r.to&&r.follow)throw new Error("`--to` cannot be used with `--follow`.")}async function tk(r,e,t,n,o){return t.crash?await r.getCrashLog(e,t.bundleName):await r.getHilog(e,{level:t.level,bundleName:t.bundleName,keyword:t.keyword,isFollow:!!t.follow,tail:t.tail,fromSeconds:n,toSeconds:o})}function rk(r,e,t,n){let o=E.filterLogsByRelativeWindow(r,t,n);return e.tail?E.getLastLines(o,e.tail):o}var nk=new GI("log").description("Obtain device application logs").configureOutput({outputError:(r,e)=>e(yg(r))}).option("--device <device>","Target device (name or serial)").option("--crash","Only obtain crash logs").option("--level <level>","Log level filter: D, I, W, E, F",ZI).option("--bundle-name <bundle-name>","Filter by application bundle name",QI).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",XI).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",r=>gg(r,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",r=>gg(r,"to")).option("--follow","Follow the log stream in real-time.").action(async r=>{await KI(JI(r),()=>ok(r))});async function ok(r){let e=zI({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};e.start();try{ek(r);let n=r.from,o=r.to,i=await k.new(),s=new lr(i),a=await s.selectDevice(r.device);if(!a)throw new w("No active devices found.","No active devices found.");m(md(`deviceId: ${a}`)),m(md(`type: ${r.crash?"Crash logs":"Common logs"}`)),m(md("Obtaining logs ...")),e.text="Fetching logs\u2026",r.follow&&t();let c=await tk(s,a,r,n,o);t(),r.crash&&c&&(c=rk(c,r,n,o)),c&&console.log(c)}finally{t()}}var vg=nk;import mi from"path";import Yt from"fs";import gd from"process";import kg from"os";import{Command as yk}from"commander";import{green as Cg,red as fd,cyan as vk,yellow as Pg}from"colorette";import he from"fs-extra";import U from"path";import*as Sg from"os";import{fileURLToPath as ik}from"url";var wg={17:{sdkVersion:"5.0.5(17)",modelVersion:"5.0.5"},18:{sdkVersion:"5.1.0(18)",modelVersion:"5.1.0"},19:{sdkVersion:"5.1.1(19)",modelVersion:"5.1.1"},20:{sdkVersion:"6.0.0(20)",modelVersion:"6.0.0"},21:{sdkVersion:"6.0.1(21)",modelVersion:"6.0.1"},22:{sdkVersion:"6.0.2(22)",modelVersion:"6.0.2"},23:{sdkVersion:"6.1.0(23)",modelVersion:"6.1.0"},24:{sdkVersion:"6.1.1(24)",modelVersion:"6.1.1"}},sk=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function ak(){let r=import.meta.url,e=ik(r);if(e.includes("dist")){let i=U.dirname(e),s=U.dirname(i);return U.join(s,"templates","application")}let t=U.dirname(e),n=U.dirname(t),o=U.dirname(n);return U.join(o,"templates","application")}function bg(r,e){he.mkdirSync(e,{recursive:!0});for(let t of he.readdirSync(r,{withFileTypes:!0})){let n=U.join(r,t.name),o=U.join(e,t.name);if(t.isDirectory()){bg(n,o);continue}he.existsSync(o)||(he.mkdirSync(U.dirname(o),{recursive:!0}),he.copyFileSync(n,o))}}function pi(r,e){let t=he.readFileSync(r,"utf-8"),n=t;for(let[o,i]of e)n=n.replaceAll(o,i);n!==t&&he.writeFileSync(r,n,"utf-8")}function ck(r){if(wg[r])return wg[r];if(r>=26){let e=`${r}.0.0`;return{sdkVersion:e,modelVersion:e}}}function lk(r,e){if(e===22)return;let t=ck(e);t&&(pi(U.join(r,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),pi(U.join(r,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),pi(U.join(r,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function dk(r){return sk.filter(t=>!he.existsSync(U.join(r,t))).length===0}function uk(){return Buffer.from([137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,1,0,0,0,1,8,2,0,0,0,144,119,83,222,0,0,0,12,73,68,65,84,8,215,99,248,255,255,255,0,5,254,2,254,0,0,0,0,73,69,78,68,174,66,96,130])}function pk(r){return Sg.platform()==="darwin"?U.join(r,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):U.join(r,"plugins","codegenie-plugin","previewProjectTemplate")}function mk(r,e){let t=pk(e);if(!he.existsSync(t))return!1;let n=[["AppScope/resources/base/media/background.png","AppScope/resources/base/media/background.png"],["AppScope/resources/base/media/foreground.png","AppScope/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/background.png"],["entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/startIcon.png","entry/src/main/resources/base/media/startIcon.png"]];for(let[o,i]of n){let s=U.join(t,o),a=U.join(r,i);he.existsSync(s)&&(he.mkdirSync(U.dirname(a),{recursive:!0}),he.copyFileSync(s,a))}return!0}function fk(r){let e=uk(),t=["AppScope/resources/base/media/background.png","AppScope/resources/base/media/foreground.png","entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/startIcon.png"];for(let n of t){let o=U.join(r,n);he.mkdirSync(U.dirname(o),{recursive:!0}),he.writeFileSync(o,e)}}function hk(r,e){e&&mk(r,e)||fk(r)}function gk(r){let e=[U.join(r,"gitignore.txt"),U.join(r,"entry","gitignore.txt")];for(let t of e)if(he.existsSync(t)){let n=U.dirname(t);he.renameSync(t,U.join(n,".gitignore"))}}function Eg(r,e,t,n,o){let i=ak();if(!he.existsSync(i))throw new Error(`Template directory not found: ${i}`);he.mkdirSync(r,{recursive:!0}),bg(i,r),gk(r),hk(r,o),pi(U.join(r,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),pi(U.join(r,"AppScope","app.json5"),[["com.example.myapplication",t]]),lk(r,n);let s=dk(r);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:r,appName:e,bundleName:t,apiLevel:n,verified:s}}function wk(r){if(r.length<1||r.length>200)throw new ge("errorCode",`App name length must be 1-200 characters. Current: ${r.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(r))throw new ge("errorCode","Application name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function Dg(r){if(kg.platform()==="win32"){let t=r.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return r.replace(/\/+/g,"/")}function Ag(r){if(r.length===0)throw new ge("errorCode","Project path cannot be empty.");if(r.length>120)throw new ge("errorCode",`Project path cannot exceed 120 characters (current: ${r.length}).`);let e=kg.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(r)){let i=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new ge("errorCode",`Project path can only contain ${i}.`)}let n=Dg(r);if(/[\u4e00-\u9fff]/.test(n))throw new ge("errorCode","Project path cannot contain Chinese characters.");if(n.endsWith("."))throw new ge("errorCode","Project path cannot end with a dot (.)")}function Sk(r){let e=r,t=mi.parse(r).root;for(;e!==t;){if(Yt.existsSync(e))return e;e=mi.dirname(e)}return Yt.existsSync(t)?t:null}function Ig(r){let e=Sk(r);if(!e)throw new ge("errorCode",`No existing parent directory found for '${r}'. Cannot create project directory.`);try{Yt.accessSync(e,Yt.constants.W_OK)}catch{throw new ge("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}let t=mi.join(e,`.deveco_write_test_${Date.now()}`);try{Yt.writeFileSync(t,"test"),Yt.unlinkSync(t)}catch{throw new ge("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}}function bk(r){return`com.example.${r.toLowerCase()}`}function Ek(r,e){if(e){let o=Dg(e),i=mi.resolve(o);if(Yt.existsSync(i)){if(Yt.readdirSync(i).length>0)throw new ge("errorCode",`Directory '${i}' is not empty. Cannot create project here.`)}else Ig(i);return i}let t=gd.cwd(),n=mi.join(t,r);if(Yt.existsSync(n))throw new ge("errorCode",`Directory '${n}' already exists. Cannot create project here.`);return Ig(n),n}function Ck(r,e){let t=e?.getMaxApiLevel(),n=23;if(r.apiLevel){let o=Number(r.apiLevel);if(!Number.isInteger(o)||o<17)throw new ge("errorCode",`Invalid API version ${r.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(o>t)throw new ge("errorCode",`Invalid API version ${r.apiLevel}. Your SDK supports API version 17-${t}`)}else if(o>n)throw new ge("errorCode",`Invalid API version ${r.apiLevel}. Without DevEco Studio, supported range is API version 17-${n}`);return o}return t!==void 0?t:23}async function Pk(){try{return await k.new()}catch(r){console.error(Pg(`DevEco Studio not found: ${r.message}`)),console.log(Pg("Use placeholder API level instead."));return}}var ge=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};async function hd(r,e,t,n){let o={event:S.CommandExecuted,args:["create"],apiLevel:n?.apiLevel??null},i={duration_ms:Date.now()-r,success:e,error_code:t};await I.track(o,i).catch(()=>{})}function Ak(r){console.log(`
1298
- `+Cg("Project created successfully.")),console.log(`Project root: ${r.projectRoot}`),console.log(`App name: ${r.appName}`),console.log(`Bundle name: ${r.bundleName}`),console.log(`API level: ${r.apiLevel}`),console.log(Cg("Template integrity check passed."))}var Ik=new yk("create").description("Scaffold a new HarmonyOS application project").option("--project-path <path>","Project directory path (default: ./<app-name>)").option("--app-name <name>","Application name").option("--bundle-name <bundle>","Bundle name (auto-derived as com.example.<app-name> if omitted)").option("--api-level <level>","API level (auto-detected from SDK if omitted; minimum: 17)").action(async r=>{let e=Date.now();try{r.appName||(console.error(fd("Error: --app-name is required")),await hd(e,!1,"errorCode",r),gd.exit(1));let t=r.appName;wk(t);let n=r.bundleName||bk(t);E.assertBundleNameStrict(n),r.projectPath&&Ag(r.projectPath);let o=Ek(t,r.projectPath);Ag(o),console.log(vk("Initializing project...")),console.log(`Project path: ${o}`),console.log(`App name: ${t}`),console.log(`Bundle name: ${n}`);let i=await Pk(),s=Ck(r,i);console.log(`API level: ${s}`);let a=i?.devecoStudioPath,c=Eg(o,t,n,s,a);Ak(c),await hd(e,!0,null,r)}catch(t){let n=t,i=t instanceof ge?t.code:n.code??n.name??"UnknownError";console.error(fd(`
1299
- Failed to create project.`)),console.error(fd(n.message)),await hd(e,!1,i,r),gd.exit(1)}}),Tg=Ik;import{Command as Nk}from"commander";import{red as Ok,cyan as Fg}from"colorette";import kk from"fs";import ua from"path";import{cyan as Dk}from"colorette";import*as pa from"smol-toml";var Vn=kk.promises;async function Tk(r){try{let e=await Vn.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 Rk(r){try{let e=await Vn.readFile(r,"utf8");return e.trim()===""?{}:pa.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 xk(r,e){let t=ua.dirname(r);await Vn.mkdir(t,{recursive:!0});let n=JSON.stringify(e,null,2);await Vn.writeFile(r,n,"utf8")}async function Lk(r,e){let t=ua.dirname(r);await Vn.mkdir(t,{recursive:!0});let n=pa.stringify(e);await Vn.writeFile(r,n,"utf8")}function Rg(r,e,t){let n=r[e];return!n||typeof n!="object"?!1:t in n}function xg(r,e,t,n,o){(!r[e]||typeof r[e]!="object")&&(r[e]={});let i=r[e];return t in i&&!o?!1:(i[t]=n,!0)}async function Lg(r,e){return r.format==="codex"?Rk(e):Tk(e)}async function Ng(r,e,t){return r.format==="codex"?Lk(e,t):xk(e,t)}async function Og(r,e,t=!1){let n=or[r];if(!n)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(or).join(", ")}`};if(!n.supportsGlobal)return{success:!1,error:`${n.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let o=await Lg(n,n.globalConfigPath);if(Rg(o,n.mcpServersKey,Tt)&&!t)return console.log(`MCP server ${Tt} already configured in ${n.globalConfigPath}.`),{success:!0,skipped:!0,configPath:n.globalConfigPath,agentName:r,installType:"global"};let i=ms(n,void 0);return xg(o,n.mcpServersKey,Tt,i,t),await Ng(n,n.globalConfigPath,o),console.log(`MCP server ${Tt} configured in ${n.globalConfigPath}.`),{success:!0,configPath:n.globalConfigPath,agentName:r,installType:"global"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${n.displayName}: ${o.message}`}}}async function yd(r,e,t=!1){let n=or[r];if(!n)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(or).join(", ")}`};let o=ua.isAbsolute(n.projectConfigPath)?n.projectConfigPath:ua.join(e,n.projectConfigPath);try{let i=await Lg(n,o);if(Rg(i,n.mcpServersKey,Tt)&&!t)return console.log(`MCP server ${Tt} already configured in ${o}.`),{success:!0,skipped:!0,configPath:o,agentName:r,installType:"project"};let s=ms(n,e);return xg(i,n.mcpServersKey,Tt,s,t),await Ng(n,o,i),console.log(`MCP server ${Tt} configured in ${o}.`),{success:!0,configPath:o,agentName:r,installType:"project"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${n.displayName}: ${i.message}`}}}function Mg(r){let e=r.filter(o=>o.success&&!o.skipped).length,t=r.filter(o=>o.skipped).length,n=r.filter(o=>!o.success).length;console.log(),console.log(Dk("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`);for(let o of r)!o.success&&o.error&&console.error(` - ${o.agentName??"unknown"}: ${o.error}`);n>0&&(process.exitCode=1)}var vd="deveco-cli";async function Mk(r,e,t){if(r.customPath)return[await og(vd,e,r.customPath,t.force)];let n=[...r.projectAgents.map(({project:s,agent:a})=>()=>ng(vd,e,s,a,t.force)),...r.agents.map(s=>()=>rg(vd,e,s,t.force))],o=5,i=[];for(let s=0;s<n.length;s+=o){let a=n.slice(s,s+o);i.push(...await Promise.all(a.map(c=>c())))}return i}function _k(r){return[...new Set([...r.agents,...r.projectAgents.map(({agent:e})=>e)])]}async function _g(r,e,t,n){await I.track(r,{duration_ms:Date.now()-e,success:t,error_code:n}).catch(()=>{})}async function Fk(r,e,t,n,o){let i={event:S.SkillConfigOperation,subAction:"install",targetType:n?"path":o?"project":"global",agents:_k(r)},s=Date.now();try{let a=await Mk(r,e,t),c=a.every(l=>l.success||l.skipped);return await _g(i,s,c,c?null:"SKILL_INSTALL_FAILED"),a}catch(a){let c=a instanceof Error?a.code??a.name:"UnknownError";throw await _g(i,s,!1,c),a}}async function jk(r,e,t){let n=[];for(let{project:o,agent:i}of r.projectAgents){let s=await yd(i,o,t);n.push(s)}for(let o of r.agents){let i=await yd(o,e,t);n.push(i)}return n}async function $k(r,e){let t=[];for(let n of r){if(!or[n])continue;let i=await Og(n,process.cwd(),e);t.push(i)}return t}async function Hk(r,e,t){let n=["qoder","dsh"];if(t.agent){let l=t.agent.split(",").map(d=>d.trim());for(let d of n)if(l.includes(d))throw new Error(`${d} does not support MCP configuration via DevEco CLI. Use --skill instead, or use other supported agents for MCP.`)}let o=t.force??!1,i=r.projectAgents.filter(l=>!n.includes(l.agent)),s=r.agents.filter(l=>!n.includes(l)),a={...r,projectAgents:i,agents:s},c=e?await jk(a,e,o):await $k(a.agents,o);c.length>0&&(console.log(Fg("MCP Configuration:")),Mg(c))}async function Bk(r,e,t){let n={event:S.Init,subAction:"install",targetType:e?"project":"global",agentName:t.agent},o=Date.now(),i=!0,s=null;try{await Hk(r,e,t)}catch(a){throw i=!1,s=a instanceof Error?a.code??a.name:"UnknownError",a}finally{let a={duration_ms:Date.now()-o,success:i,error_code:s};await I.track(n,a)}}async function Uk(r){if(r.skill&&r.mcp)throw new Error("Cannot use `--skill` and `--mcp` together. Use `--skill` for skill installation only, or `--mcp` for MCP configuration only.");let{resolvedPath:e,resolvedProject:t}=li(r.path,r.project,r.agent);t&&vr(t,"Project directory",r.force),e&&vr(e,"Directory",r.force);let n=await sa(r,e,t);if(r.mcp){await Bk(n,t,r);return}let o=ag(),i=await Fk(n,o,r,e,t);console.log(),i.length>0&&(console.log(Fg("Skill Installation:")),ci(i))}var Wk=new Nk("init").description("Install the deveco-cli skill or configure the deveco-mcp server into AI agents").option("--agent <agents>","Target agents, comma-separated; installs to all available agents if omitted").option("--project <path>","Project root directory for skill or MCP configuration").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").option("--skill","Install the deveco-cli skill only (same as default behavior; explicit for symmetry with --mcp)").option("--mcp","Configure the deveco-mcp server (syntax checking for .ets and C/C++) only; no skill installation").option("-f, --force","Overwrite existing skill/MCP configuration").action(async r=>{try{await Uk(r)}catch(e){console.error(Ok(e instanceof Error?e.message:String(e))),process.exit(1)}}),jg=Wk;import{Command as qD}from"commander";import{McpServer as xD}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as LD}from"@modelcontextprotocol/sdk/server/stdio.js";import*as Si from"fs";import*as so from"path";import{z as ye}from"zod";import ma from"path";function Bg(r,e,t,n,o){if(e.isError)return{};let i=e.content?.[0]?.text??"";if(!i)return{};let s;switch(r){case"check":s=Vk(i);break;case"hover":s={hit:Gn(i)!=null};break;case"definition":case"declaration":s=$g(i,t,n,o,!0);break;case"references":s=zk(i);break;case"implementation":s=$g(i,t,n,o,!1);break;case"documentSymbol":s=qk(i);break;case"callHierarchy":s=Jk(i,t,n,o);break;case"workspaceSymbol":s=Yk(i,t);break;default:s={}}return s}function Ug(r){let e=Array.isArray(r.files)?r.files[0]:r.file;return typeof e!="string"||!e?void 0:ma.extname(e).toLowerCase().replace(/^\./,"")||void 0}function Gn(r){let e=r.indexOf(": ");if(e<0)return;let t=r.slice(e+2).trim();if(!(!t||t==="no result"))try{return JSON.parse(t)}catch{return}}function Vk(r){let e={total:0,error:0,warn:0,info:0},t=new Set,n=" => Diagnostic: ";for(let i of r.split(`
1300
- `)){let s=i.indexOf(n);if(s<0)continue;let a;try{a=JSON.parse(i.slice(s+n.length))}catch{continue}if(Array.isArray(a))for(let c of a)c&&typeof c=="object"&&Gk(c,e,t)}let o={diagTotal:e.total,diagError:e.error,diagWarn:e.warn,diagInfo:e.info};return t.size>0&&(o.rules=[...t]),o}function Gk(r,e,t){e.total++;let n=r.severity;n===1?e.error++:n===2?e.warn++:(n===3||n===4)&&e.info++,typeof r.source=="string"&&t.add(r.source)}function zk(r){let e=Gn(r),t=Array.isArray(e)?e:[],n=new Set;for(let o of t){let i=o?.uri;typeof i=="string"&&n.add(i)}return{refTotal:t.length,fileCount:n.size}}function $g(r,e,t,n,o){let i=Gn(r);if(i==null)return{found:!1};let s=Array.isArray(i)?i:[i],a=s[0]?.uri;return o?{found:!0,sameFile:Kk(a,e),sourceType:Vg(a,t,n)}:{implTotal:s.length,found:!0}}function qk(r){let e=Gn(r),t=Array.isArray(e)?e:[],n=0,o=new Map,i=s=>{for(let a of s){if(!a||typeof a!="object")continue;n++;let c=a.kind;typeof c=="number"&&o.set(c,(o.get(c)??0)+1);let l=a.children;Array.isArray(l)&&i(l)}};return i(t),{symbolTotal:n,kindDist:wd(o)}}function Jk(r,e,t,n){let i=Gn(r)?.calls,s=Array.isArray(i)?i:[],a=e.direction,c=new Map;for(let l of s){if(!l||typeof l!="object")continue;let g=(a==="incoming"?l.from:l.to)?.uri,y=Vg(g,t,n);c.set(y,(c.get(y)??0)+1)}return{callsTotal:s.length,calleeSrcDist:wd(c)}}function Yk(r,e){let t=Gn(r),n=Array.isArray(t)?t:[],o=new Map,i=0;for(let c of n){if(!c||typeof c!="object")continue;let l=c.kind;typeof l=="number"&&o.set(l,(o.get(l)??0)+1);let d=c.tags;(Array.isArray(d)&&d.includes(1)||c.deprecated===!0)&&i++}let s={resultTotal:n.length,kindDist:wd(o),deprecatedHit:i},a=e.query;return typeof a=="string"&&(s.queryLen=a.length),s}function Wg(r){if(typeof r!="string"||!r)return null;let e=r;return e.startsWith("file://")&&(e=e.slice(7),process.platform==="win32"&&e.startsWith("/")&&(e=e.slice(1))),e}function Vg(r,e,t){let n=Wg(r);return n?e&&Hg(n,e)?"user_project":t&&Hg(n,t)?"sdk":"system":"unknown"}function Kk(r,e){let t=Wg(r),n=e.file;return!t||typeof n!="string"?!1:fa(t)===fa(n)}function fa(r){try{return ma.resolve(r).replace(/\\/g,"/").toLowerCase()}catch{return r.replace(/\\/g,"/").toLowerCase()}}function Hg(r,e){let t=ma.relative(fa(e),fa(r));return t!==""&&!t.startsWith("..")&&!ma.isAbsolute(t)}function wd(r){let e={};for(let[t,n]of r)e[String(t)]=n;return e}var ha=class{constructor(e,t,n,o){this.telemetry=e;this.getAceServerPid=t;this.getProjectPath=n;this.getSdkPath=o}tools=new Map;add(e,t){return this.tools.set(e.name,{definition:e,handler:t}),this}getAll(){return Array.from(this.tools.values())}registerToServer(e){for(let{definition:t,handler:n}of this.getAll())e.registerTool(t.name,{description:t.description,inputSchema:t.inputSchema},(async o=>this.invokeTool(t.name,o,n)))}async invokeTool(e,t,n){if(h.info(`[telemetry] mcp tool call: ${e}`),!this.telemetry)return n(t);let o=te(process.memoryUsage().rss),i=await this.resolveLspMemory(),s=Date.now(),a=!0,c=null,l;try{l=await n(t)}catch(d){throw a=!1,c=d instanceof Error?d.code??d.name:"UnknownError",d}finally{await this.trackToolCall(e,t,l,s,o,i,a,c)}return l}async trackToolCall(e,t,n,o,i,s,a,c){if(!this.telemetry)return;let l=n?.isError===!0,d=n&&!l?Bg(e,n,t,this.getProjectPath?.()??"",this.getSdkPath?.()??""):{},g=l?!1:a,y=l&&n?Xk(n):c,b={event:S.McpToolCall,subAction:e,mcpMemory:i,lspMemory:s,fileExt:Ug(t),...d};typeof t.direction=="string"&&(b.direction=t.direction),await this.telemetry.track(b,{duration_ms:Date.now()-o,success:g,error_code:y})}async resolveLspMemory(){let e=this.getAceServerPid?.()??null;if(e===null)return"unknown";let t=await $e(e);return t===null?"unknown":te(Number(t)*1024)}};function Xk(r){let e=r.content.map(t=>t.text).join(`
1301
- `);return/not ready|not initialized|initializing|please retry|retry \d+s|syncing|C\+\+ project initialization failed/i.test(e)?"NotReady":/No project detected|PROJECT_PATH|no project path/i.test(e)?"NoProject":/Missing.*parameter|invalid parameters|Unknown feature|must be|Must specify|cannot be used together|invalid/i.test(e)?"BadRequest":/Too many files|Maximum allowed/i.test(e)?"TooManyFiles":/does not exist|not exist|not found|No valid|not a .ets|not a supported|Unsupported/i.test(e)?"InvalidFile":"ToolError"}function Sd(r,e,t,n){return new ha(r,e,t,n)}import*as pt from"fs";import*as Ie from"path";function Gg(r){return"method"in r&&!("id"in r)}import{spawn as Zk}from"child_process";import{EventEmitter as Qk}from"events";import*as zn from"fs";import*as zg from"path";var eD=50*1024*1024,wr=class extends Qk{constructor(t){super();this.config=t}process=null;buffer=Buffer.alloc(0);isClosing=!1;get pid(){return this.process?.pid??null}ensureDirectories(){let t=zg.join(this.config.logPath,"lspLog");return zn.existsSync(t)||zn.mkdirSync(t,{recursive:!0}),zn.existsSync(this.config.indexingDataLocation)||zn.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let n=this.ensureDirectories();f.info(`[LspClient] serverMaxSize=${t}MB`);let o=J(n),i=["--expose-gc",`--max-old-space-size=${t}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${o}`,this.config.serverPath,"--stdio",`--logger-path=${o}`,"--logger-level=TRACE"];f.info(`[LspClient] Starting process: node ${i.join(" ")}`);let s=process.execPath??"node";f.info(`[LspClient] nodePath: ${s}`),this.process=Zk(s,i,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0}),this.bindProcessEvents(),await new Promise(a=>setTimeout(a,500)),f.info("[LspClient] start lsp process success")}attachProcess(t,n){if(this.process)throw new Error("[LspClient] process already attached");this.process=t,this.bindProcessEvents(n?.stderrAsError??!0),f.info("[LspClient] attached to external process")}bindProcessEvents(t=!0){this.process&&(this.process.stdout?.on("data",n=>{this.handleData(n)}),this.process.stderr?.on("data",n=>{let o=n.toString("utf8").trim();f.error(`[LspClient] stderr: ${o}`),!this.isClosing&&t&&this.emit("error",new Error(`[LspClient] stderr: ${o}`))}),this.process.on("exit",n=>{f.info(`[LSP EXIT] code=${n}`),this.isClosing||this.emit("error",new Error(`LSP process exited with code ${n}`))}))}sendRaw(t,n){if(!this.process?.stdin?.writable){f.warn("[LspClient] Cannot send message, stdin not writable");return}f.info(`[LspClient] send message: ${n}`);let o=this.buildLspMessage(t);this.process.stdin.write(o,"utf8")}send(t,n,o){let i={jsonrpc:"2.0",method:t,params:n};o!==void 0&&(i.id=o),this.sendRaw(JSON.stringify(i),t)}sendNotification(t,n){this.sendRaw(JSON.stringify({jsonrpc:"2.0",method:t,params:n}),t)}sendRequest(t,n,o){this.sendRaw(JSON.stringify({jsonrpc:"2.0",id:o,method:t,params:n}),t)}buildLspMessage(t){return`Content-Length: ${Buffer.from(t,"utf8").length}\r
1302
- \r
1303
- ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let n=this.buffer.indexOf(`\r
1304
- \r
1305
- `);if(n===-1)break;let i=this.buffer.slice(0,n).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!i){f.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(n+4);continue}let s=parseInt(i[1],10);if(!Number.isFinite(s)||s<0||s>eD){f.warn(`[LspClient] Invalid Content-Length: ${i[1]}, drop until next packet`),this.buffer=this.buffer.slice(n+4);continue}let a=n+4,c=a+s;if(this.buffer.length<c)break;let l=this.buffer.slice(a,c).toString("utf8"),d=this.recoverFramedJson(l);if(d&&d.rest.length>0){f.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${l.length}, restLen=${d.rest.length}`),this.emit("message",d.json),this.buffer=Buffer.concat([Buffer.from(d.rest,"utf8"),this.buffer.slice(c)]);continue}this.emit("message",l),this.buffer=this.buffer.slice(c)}}waitForExitOrTimeout(t){let n=this.process;return!n||n.exitCode!==null||n.signalCode!==null?Promise.resolve():new Promise(o=>{let i=!1,s=()=>{i||(i=!0,clearTimeout(c),n.off("exit",a),o())},a=()=>s();n.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let n=t.search(/\S/);if(n<0||t[n]!=="{"&&t[n]!=="[")return null;let o=0,i=!1,s=!1;for(let a=n;a<t.length;a++){let c=t[a];if(i){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(i=!1);continue}if(c==='"'){i=!0;continue}if(c==="{"||c==="["){o++;continue}if((c==="}"||c==="]")&&(o--,o===0)){let l=t.slice(n,a+1),d=t.slice(a+1);return{json:l,rest:d}}}return null}stop(){this.isClosing=!0;let t=this.process;if(!t)return;if(this.process=null,t.exitCode===null&&t.signalCode===null)try{t.kill()}catch{}}};var Sr=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,n){return new Promise((o,i)=>{let s;n>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),i(new Error(`LSP request '${t}' (id=${e}) timeout after ${n}ms`))},n),this.timeouts.set(e,s)),this.pending.set(e,{resolve:o,reject:i,method:t,timer:s})})}resolvePending(e,t){this.clearTimeout(e);let n=this.pending.get(e);return n?(n.resolve(t),this.pending.delete(e),!0):!1}rejectPending(e,t){this.clearTimeout(e);let n=this.pending.get(e);return n?(n.reject(t),this.pending.delete(e),!0):!1}register(e,t){this.callbacks.set(e,t)}emit(e,t,n){f.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let o=this.callbacks.get(e);if(o)try{o(t,n)}finally{this.callbacks.delete(e)}else{let i=[...this.callbacks.keys()].map(s=>String(s));f.info(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${i.join(",")}]`)}}registerTimeout(e,t,n,o){let i=this.timeouts.get(e);i&&clearTimeout(i);let s=setTimeout(()=>{f.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`);try{o()}finally{this.timeouts.delete(e)}},n);this.timeouts.set(e,s)}clearTimeout(e){let t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e))}deleteCallback(e){this.callbacks.delete(e)}hasCallback(e){return this.callbacks.has(e)||this.pending.has(e)}clear(e){this.clearTimeout(e);let t=this.pending.get(e);t&&(t.reject(new Error(`Request '${t.method}' (id=${e}) cancelled`)),this.pending.delete(e)),this.callbacks.delete(e)}rejectAll(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear();for(let[,t]of this.timeouts)clearTimeout(t);this.timeouts.clear(),this.callbacks.clear()}};var ga=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var qn=class{map=new Map;register(e,t){let n=this.map.get(e);n||(n=new Set,this.map.set(e,n)),n.add(t)}unregister(e,t){let n=this.map.get(e);n&&(t!==void 0?n.delete(t):n.clear(),n.size===0&&this.map.delete(e))}invoke(e,...t){let n=this.map.get(e);if(n)for(let o of n)try{o(...t)}catch(i){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,i)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function T(r){return typeof r=="object"&&r!==null}var qg=20*1e3,tD=30*1e3,Jg=300,rD=300;function nD(){let r=process.env.DEVECO_CLI_LSP_STANDARD_EXIT_TIMEOUT_MS;if(r===void 0||r==="")return Jg;let e=parseInt(r,10);return Number.isFinite(e)?Math.max(rD,e):Jg}var ya=class{client;nextRequestId=1;stopOnce=null;callbacks=new qn;requestCallbacks=new Sr;diagnosticMap=new Map;initProgressReset=null;get lspPid(){return this.client.pid}constructor(e){this.client=new wr(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{f.info("[ClientMessageHandle] Sending shutdown request"),this.client.sendRequest(v.SHUTDOWN,null,this.nextRequestId++),f.info("[ClientMessageHandle] Sending exit notification"),this.client.sendNotification(v.EXIT,null),f.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(nD()),f.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(v.BROADCAST),this.callbacks.register(v.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(v.BROADCAST,e)}async sendInitialize(e){let t=this.nextRequestId++,n=this.requestCallbacks.registerPending(t,v.INITIALIZE,ot);return this.client.sendRequest(v.INITIALIZE,e,t),n}sendInitializeResettable(e,t){let n=this.nextRequestId++,o=this.requestCallbacks.registerPending(n,v.INITIALIZE,0);return this.client.sendRequest(v.INITIALIZE,e,n),new Promise((i,s)=>{let a,c=()=>{a=setTimeout(()=>{this.initProgressReset=null,s(new Error(`LSP initialization timeout after ${t}ms`))},t)},l=()=>{clearTimeout(a),c()};this.initProgressReset=l,c(),o.then(()=>{clearTimeout(a),this.initProgressReset=null,i()},d=>{clearTimeout(a),this.initProgressReset=null,s(d)})})}sendInitialized(){this.client.sendNotification(v.INITIALIZED,{})}sendDidOpen(e){let t=e.textDocument.uri;this.diagnosticMap.has(t)||(this.diagnosticMap.set(t,new ga(t)),this.registerDiagnosticTimeout(t)),this.client.sendNotification(v.DID_OPEN,e)}sendDidChange(e){let t=e.textDocument.uri,n=this.diagnosticMap.get(t);n&&(n.clear(),this.registerDiagnosticTimeout(t)),this.client.sendNotification(v.DID_CHANGE,e)}closeFile(e){this.cleanupDiagnosticState(e.textDocument.uri),this.client.sendNotification(v.DID_CLOSE,e)}sendLspRequest(e,t,n=tD){let o=this.nextRequestId++,i=this.requestCallbacks.registerPending(o,e,n);return this.client.sendRequest(e,t,o),i}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}onDidChangeWatchedFiles(e){e.length!==0&&this.client.sendNotification(v.WORKSPACE_DID_CHANGE_WATCHED_FILES,{changes:e})}sendDidChangeConfiguration(e){this.client.sendNotification(v.WORKSPACE_DID_CHANGE_CONFIGURATION,{settings:e})}sendNotification(e,t){this.client.sendNotification(e,t)}getDiagnosticMessages(e){let t=this.diagnosticMap.get(e);return t?t.get():[]}clearDiagnostic(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(n){let o=n instanceof Error?n.message:String(n);f.error(`[LSP] JSON parse error: ${o}, raw: ${e}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotificationOrRequest(t):f.warn(`[LSP] Unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t===void 0)return;let n=t;if(e.error){let o=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(n,o)}else this.requestCallbacks.resolvePending(n,e.result)}handleNotificationOrRequest(e){let t=e.method;if(t)switch(this.initProgressReset?.(),t){case v.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case v.PROGRESS:this.handleProgress(e.params);break;case v.WINDOW_SHOW_MESSAGE:f.info(`[LSP] window/showMessage: ${JSON.stringify(e.params)}`);break;case v.WINDOW_LOG_MESSAGE:f.info(`[LSP] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.broadcastToClients(e)}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=e.uri,n=this.diagnosticMap.get(t);if(!n)return;let o=e.diagnostics||[];this.normalizeDiagnostics(o),n.set(o),this.finalizeDiagnostic(t,o)}normalizeDiagnostics(e){for(let t of e)if(t.severity!==void 0){let n={1:"Error",2:"Warning",3:"Information",4:"Hint"};t.severityStr=n[t.severity]||"Unknown"}}handleProgress(e){T(e)&&this.broadcastToClients({jsonrpc:R,method:v.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,v.PUBLISH_DIAGNOSTICS,qg,()=>{let t=this.diagnosticMap.get(e),n=t?t.get():[];this.finalizeDiagnostic(e,n,n.length>0?void 0:`received no diagnostics within ${qg}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,n){let o={uri:e,diagnostics:t,...n?{errorMessage:n}:{}};this.requestCallbacks.emit(e,v.PUBLISH_DIAGNOSTICS,o),this.diagnosticMap.get(e)?.clear()}handleError(e){let t=Array.from(this.diagnosticMap.keys()).filter(n=>this.requestCallbacks.hasCallback(n));if(t.length>0){let n={range:{start:{line:0,character:0},end:{line:0,character:0}},severity:1,message:e.message};for(let o of t)this.finalizeDiagnostic(o,[n]);return}this.broadcastToClients({jsonrpc:R,method:v.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var va=class{uri;messages=[];receivedTypes=new Set;uniqueMessages=new Set;isFromEditor=!1;constructor(e){this.uri=e}setReceivedType(e){this.receivedTypes.add(e)}addMessage(e,t){this.receivedTypes.add(e);let n=`${e}:${t}`;if(this.uniqueMessages.has(n)){f.info(`[LegacyDiagnostic] addMessage: duplicate message=${n}`);return}this.uniqueMessages.add(n),this.messages.push(new bd(e,t))}clearMessages(){this.messages=[]}clear(){this.receivedTypes.clear(),this.uniqueMessages.clear(),this.messages=[]}hasReceivedAllTypes(e){for(let t of e)if(!this.receivedTypes.has(t))return!1;return!0}getMessages(){return this.messages.map(e=>e.diagnostics)}},bd=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var oD={EXIT:"exit",INITIALIZED:"initialized",ON_DID_CHANGE_PACKAGE_DEPENDENCIES:"aceProject/onDidChangePackageDependencies",ON_ASYNC_DID_OPEN:"aceProject/onAsyncDidOpen",ON_ASYNC_DID_CHANGE:"aceProject/onAsyncDidChange",DID_CLOSE:"textDocument/didClose",ON_ASYNC_HOVER:"aceProject/onAsyncHover",ON_ASYNC_DEFINITION:"aceProject/onAsyncDefinition",ON_ASYNC_FIND_USAGES:"aceProject/onAsyncFindUsages"},iD={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing"},x={...oD,...iD},br={EXIT:"exit",INITIALIZED:"initialized",EMPTY:"empty",ON_DID_CHANGE_PACKAGE_DEPENDENCIES:"onDidChangePackageDependencies",ON_ASYNC_DID_OPEN:"onAsyncDidOpen",ON_ASYNC_DID_CHANGE:"onAsyncDidChange",DID_CLOSE:"didClose",ON_ASYNC_HOVER:"onAsyncHover",ON_ASYNC_DEFINITION:"onAsyncDefinition",ON_ASYNC_FIND_USAGES:"onAsyncFindUsages"},Yg=new Set([1e3,2e3,3e3,3001]);function sD(r){if(!T(r))return!1;let e=r.textDocument;return T(e)&&typeof e.uri=="string"}function aD(r){return T(r)?typeof r.uri=="string"&&typeof r.type=="number":!1}function cD(r){return T(r)&&typeof r.moduleName=="string"&&typeof r.current=="number"&&typeof r.total=="number"?`indexing module '${r.moduleName}', ${r.current} of total ${r.total} modules`:`params=${JSON.stringify(r??null)}`}var wa=class r{client;isInitialized=!1;stopOnce=null;callbacks=new qn;requestCallbacks=new Sr;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;get lspPid(){return this.client.pid}constructor(e){this.client=new wr(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{f.info("[LegacyClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:x.EXIT,params:{}}),br.EXIT),f.info("[LegacyClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),f.info("[LegacyClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(x.BROADCAST),this.callbacks.register(x.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(x.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(x.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(x.INDEXING_PROGRESS_UPDATE,e)}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}sendInitialize(e,t){this.client.send("initialize",e,t)}sendInitialized(e){this.client.sendRaw(JSON.stringify({jsonrpc:R,method:x.INITIALIZED,params:{editors:e}}),br.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:R,id:0,result:{}}),br.EMPTY)}sendAsyncRequest(e,t,n,o){if(!T(t)){f.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!sD(t)){f.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof n!="number"){f.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(n)}`);return}let i=t.textDocument.uri,s=gt(i);t.textDocument.uri=s,delete t.requestId;let a=o??e;f.info(`[LSP] sendAsyncRequest ${a}, filePath: ${i}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:e,params:{params:t,requestId:n}}),a)}onDidChangeWatchedFiles(e){if(f.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let n of e){if(!aD(n)){f.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(n)}`);continue}t.push(n)}this.client.sendRaw(JSON.stringify({jsonrpc:R,method:x.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),x.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!T(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){f.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;f.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:x.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),br.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,n=t.split(".").pop()||"";if(n!=="ets"&&n!=="ts")return;let o=gt(t);e.textDocument.uri=o,f.info(`[LSP] onAsyncOpenFile, uri: ${o}`);let i=this.diagnosticMap.get(o);i||(i=new va(o),this.diagnosticMap.set(o,i),this.registerDiagnosticTimeout(o,x.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(i.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:x.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),br.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=gt(e.uri),n=this.diagnosticMap.get(t);n&&(n.clear(),this.registerDiagnosticTimeout(t,x.PUBLISH_DIAGNOSTICS)),f.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:x.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),br.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let n=gt(e);f.info(`[LSP] didClose, uri: ${n}`);let o=this.diagnosticMap.get(n);if(!t&&(!o||o.isFromEditor)){f.info(`[LSP] closeFile skip, !diagnostic: ${!o}, isFromEditor: ${o?.isFromEditor}`);return}this.cleanupDiagnosticState(n),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:x.DID_CLOSE,params:{textDocument:{uri:n}}}),br.DID_CLOSE)}getDiagnosticMessage(e){let t=gt(e),n=this.diagnosticMap.get(t);return n?n.getMessages():[]}clear(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){try{let t=JSON.parse(e);this.handleLspMessage(t)}catch(t){let n=t instanceof Error?t.message:String(t);f.error(`[LSP] JSON parse error: ${n}, raw: ${e}`)}}handleError(e){let t=this.getPendingDiagnosticUris();if(t.length>0){let n=JSON.stringify({message:e.message,severity:"Error",severityStr:"Error"});for(let o of t)this.finalizeDiagnostic(o,x.PUBLISH_DIAGNOSTICS,[n]);return}this.broadcastToClients({jsonrpc:R,method:x.ARKTS_ERROR,params:{message:e.message}})}handleLspMessage(e){let t=e.method;t!==void 0&&(!this.isInitialized&&this.handlePreInitMessage(t,e)||this.handlePostInitMessage(t,e))}handlePreInitMessage(e,t){switch(e){case x.MODULE_INIT_FINISH:return f.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(x.MODULE_INIT_FINISH),this.callbacks.unregister(x.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case x.INDEXING_PROGRESS_UPDATE:return f.info(`[LSP] onIndexingProgressUpdate: ${cD(t.params)}`),this.callbacks.invoke(x.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case x.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case x.ON_PACKAGE_CHANGE_FINISH:f.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case x.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case x.ON_ASYNC_HOVER:this.handleAsyncResponse(t,x.HOVER);return;case x.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,x.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case x.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,x.REFERENCES);return;default:f.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){f.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;T(t)&&T(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){f.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,n={jsonrpc:R,method:x.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){f.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(n);return}if(!(t.length>0&&t[0]===!0)){f.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(n);return}f.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){f.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let n=e.params;if(!T(n)){f.warn("[LSP] aceProject/onAsyncHover message invalid");return}let o=n.requestId;if(typeof o!="number"){f.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(o,t,n)}handleForceOpenFile(e){if(!e){f.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,x.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){f.info("[LSP] publishDiagnostics uri is null");return}let n=e.version??-1;if(n===-1)return;let o=this.diagnosticMap.get(t);if(!o){f.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let i=e.diagnostics||[];i.length!==0?i.forEach(s=>{this.normalizeDiagnostic(s),o.addMessage(n,JSON.stringify(s))}):o.setReceivedType(n),o.hasReceivedAllTypes(Yg)&&this.finalizeDiagnostic(t,x.PUBLISH_DIAGNOSTICS,o.getMessages())}normalizeDiagnostic(e){let t=e;if(delete t.source,t.severity!==void 0){let n=typeof t.severity=="number"?t.severity:parseInt(t.severity),i={1:"Error",2:"Warning",3:"Information",4:"Hint"}[n]||"Unknown";t.severityStr=i,t.severity=i}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let n=e[t];n&&typeof n.line=="number"&&(n.line=n.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,r.DIAGNOSTIC_TIMEOUT_MS,()=>{let n=this.diagnosticMap.get(e),o=n?n.getMessages():[];this.finalizeDiagnostic(e,t,o,o.length>0?void 0:`received no diagnostics within ${r.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,n,o){let i={uri:e,diagnostics:n,...o?{errorMessage:o}:{}};this.requestCallbacks.emit(e,t,i),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import Ed from"path";import*as Ia from"path";var Sa=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var ba=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var Ea=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var Ca=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Pa=class{typeSetting=new Ea;parameterNames=new Ca};var Aa=class{constructor(e,t,n,o){this.rootUri=e;this.lspServerWorkspacePath=J(Ia.dirname(t)),this.indexingDataLocation=J(o),this.loggerPath=J(Ia.join(n,"lspLog"))}modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new Sa;gutterIconsSetting=new ba;inlayHintsSetting=new Pa;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Kg from"path";var fi=class{productName="default";buildModeName="debug";targetName="default";arkTSVersion="1.1";resourceDirectories=[];targetESVersion="ES2021";maxFlowDepth=2e3;caseSensitiveCheck=!0;tsImportSendable=!1;compatibleSdkVersionStage="";useNormalizedOHMUrl=!0;reExportCheckMode="noCheck";skipOhModulesLint=!1;byteCodeHar=!0;obfuscationRuleOptionsEnable=!1;enableStrictCheckOHModules=!1;sourceRoots=[];constructor(e){e&&this.resourceDirectories.push(J(Kg.join(e,"src","main","resources")))}};var lD="OS",Jn=class{deviceType=[5];aceLoaderPath;modulePath;jsComponentType="declarative";sdkJsPath;compatibleSdkVersion;compatibleSdkLevel;compileSdkLevel;compileSdkVersion="6.0.1.112";compileSdkType="Release";syscap={NDeviceSysCaps:[],addedSysCaps:[]};apiType="stageMode";hosSdkPath;runtimeOs=`Harmony${lD}`;moduleName;moduleType;compileMode="jsbundle";crossPlatform=!1;ignoreCrossPlatform=!1;packageManagerType="ohpm";permissions=[];testPermissions=[];buildProfileParam;appParam={bundleType:"app"};packageName;projectType="OHOS";projectName;moduleDependencies;moduleJsonParam=null;globalDeclarationFiles=[];constructor(e){e?(this.modulePath=e,this.buildProfileParam=new fi(e)):this.buildProfileParam=new fi}toString(){return JSON.stringify(this)}};var Yn=class{constructor(e=[]){this.pages=e}pagesFileName="main_pages.json";metaDataList=[]};import*as _e from"path";import*as Zn from"fs";var ka=class{modulePath;dependencies={};dynamicDependencies={}};var ln=class{registryType;resolved;name;version;type;constructor(e){let t=typeof e=="object"&&e!==null?e:{};this.name=typeof t.name=="string"?t.name:"",this.version=typeof t.version=="string"?t.version:"",typeof t.registryType=="string"?this.registryType=t.registryType:this.registryType=typeof t.path=="string"?"local":"ohpm",typeof t.resolved=="string"?this.resolved=t.resolved:typeof t.storePath=="string"?this.resolved=t.storePath:this.resolved="",this.type=typeof t.type=="string"?t.type:void 0}};var Kn=class{constructor(e,t,n){this.projectPath=e;this.moduleName=t;this.modulePath=n}dependencies=[];devDependencies=[];dynamicDependencies=[];finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[]};import*as Kt from"path";import*as Da from"fs";var Xn=class{name="";version="";storePath="";dependencyPath="";path=""};var F={HVIGOR_CACHE:".hvigor",DEPENDENCY:"dependencyMap",JSON5:".json5",KEY_DEPENDENCY:"dependencies",KEY_DYNAMIC_DEPENDENCY:"dynamicDependencies",KEY_DEV_DEPENDENCY:"devDependencies",OH_MODULES_PATH:"oh_modules",OHPM_PATH:".ohpm",LOCK_JSON5_FILE:"lock.json5",OH_PACKAGE_JSON5:Re.OH_PACKAGE_JSON5},hi=`${F.HVIGOR_CACHE}/${F.DEPENDENCY}`,dn=`${F.DEPENDENCY}${F.JSON5}`,Nq=Re.SYNC_OUTPUT_PATH;var gi=class r{dependencyPath;modulePath;projectPath;static FILE_DEPENDENCY_PREFIX="file:";static PARAMETER_PREFIX="@param:";fileSpecPattern;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;static PACKAGE_JSON_PARSER_MAP=new Map;dependencies=[];devDependencies=[];dynamicDependencies=[];static getInstance(e,t,n){let o=this.PACKAGE_JSON_PARSER_MAP.get(e);return o||(o=new r(e,t,n),this.PACKAGE_JSON_PARSER_MAP.set(e,o)),o}constructor(e,t,n){this.dependencyPath=e,this.modulePath=t,this.projectPath=n,this.fileSpecPattern=r.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=Kt.join(this.dependencyPath,F.OH_PACKAGE_JSON5),n=Xe(t);n&&(this.dependencies=this.getDependencyList(n,F.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(n,F.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(n,F.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let n=[];if(!T(e))return n;let o=e[t];if(!T(o))return n;for(let[i,s]of Object.entries(o)){if(typeof s!="string"){f.error(`${i} package dependency value is not String ${t}`);continue}let a=new Xn;a.name=i;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(r.PARAMETER_PREFIX)||this.parseDependencyPath(i,c,a,!1),n.push(a)}return n}parseDependencyPath(e,t,n,o){if(!(!e||!t))try{let i=Kt.normalize(Kt.join(this.modulePath,F.OH_MODULES_PATH,e));if(!(t.startsWith(r.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){n.dependencyPath=i;return}if(n.path=t,this.fileNameForOhpm.test(t)){n.dependencyPath=i;return}let s=t;if(t.startsWith(r.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(r.FILE_DEPENDENCY_PREFIX.length)),Kt.isAbsolute(s)){n.dependencyPath=i;return}o||(i=Kt.resolve(this.modulePath,s)),Da.existsSync(i)&&Da.statSync(i).isDirectory()&&(n.dependencyPath=i)}catch(i){f.error("parser dependency path is invalid",i)}}};import*as un from"fs";import*as Er from"path";import dD from"json5";var Ta=class r{projectPath;static FILE_DEPENDENCY_PREFIX="file:";static MAX_LOCK_FILE_SIZE=20*1024*1024;static MAX_KEYS_PER_OBJECT=5e4;static MAX_JSON_DEPTH=50;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[];storePathMap=new Map;lockFileCache=null;lockFileParsed=!1;constructor(e=""){this.projectPath=e}parseDependencies(e){if(!this.ensureLockFileParsed())return!1;let t=this.lockFileCache;return this.extractDependencies(t.modules,t.storePathMap,e),!0}ensureLockFileParsed(){if(this.lockFileParsed)return this.lockFileCache!==null;this.lockFileParsed=!0;let e=this.getLockFilePath(),t=this.readLockFile(e);if(!t)return!1;let n=this.validateLockFile(t);return n.valid?(this.lockFileCache={modules:n.modules,storePathMap:this.parseStorePathMap(n.packages)},!0):!1}getLockFilePath(){return Er.join(this.projectPath,F.OH_MODULES_PATH,F.OHPM_PATH,F.LOCK_JSON5_FILE)}static checkObjectDepth(e,t,n=0){if(n>t)return!1;if(typeof e!="object"||e===null)return!0;if(Array.isArray(e)){for(let o of e)if(!r.checkObjectDepth(o,t,n+1))return!1;return!0}for(let o in e)if(Object.prototype.hasOwnProperty.call(e,o)&&!r.checkObjectDepth(e[o],t,n+1))return!1;return!0}readLockFile(e){if(!un.existsSync(e))return f.error("lock file does not exist"),this.clearDependencies(),null;try{let t=un.statSync(e);if(t.size>r.MAX_LOCK_FILE_SIZE)return f.error(`lock file is too large (${t.size} bytes), read aborted`),this.clearDependencies(),null}catch(t){return f.error(`Failed to stat lock file: ${t instanceof Error?t.message:String(t)}`),this.clearDependencies(),null}try{let t=un.readFileSync(e,"utf8"),n=dD.parse(t);return n?r.checkObjectDepth(n,r.MAX_JSON_DEPTH)?n:(f.error("lock.json5 nesting depth exceeds limit"),this.clearDependencies(),null):(f.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return f.error(`Error parsing lock.json5: ${t instanceof Error?t.message:String(t)}`),this.clearDependencies(),null}}validateLockFile(e){if(!T(e))return f.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return f.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let n=e.packages;return n?{valid:!0,modules:t,packages:n}:(f.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,n){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,F.KEY_DEPENDENCY,n),this.finalDevDependencies=this.getDependencyList(e,F.KEY_DEV_DEPENDENCY,n),this.finalDynamicDependencies=this.getDependencyList(e,F.KEY_DYNAMIC_DEPENDENCY,n)}parseStorePathMap(e){let t=new Map;if(!T(e))return t;let n=0;for(let o in e){if(!Object.prototype.hasOwnProperty.call(e,o))continue;let i=e[o];if(!T(i)){f.error(`${o} value is not json object`);continue}if(++n>r.MAX_KEYS_PER_OBJECT){f.warn("lock.json5 packages object exceeds key limit, truncating");break}typeof i.storePath=="string"&&t.set(o,i.storePath)}return t}getDependencyList(e,t,n){if(!T(e))return[];let o=0;for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;if(++o>r.MAX_KEYS_PER_OBJECT){f.warn("lock.json5 modules object exceeds key limit, truncating");break}let s=e[i];if(T(s)){let a=typeof s.name=="string"?s.name:"";if(n==="."&&a===""||a===n)return this.getFinalDependencyList(e,t,i)}}return[]}getFinalDependencyList(e,t,n){let o=e[n];if(!T(o))return f.error("moduleJsonObject is null"),[];let i=[],s=o[t];if(!T(s))return[];let a=0;for(let c in s){if(!Object.prototype.hasOwnProperty.call(s,c))continue;if(++a>r.MAX_KEYS_PER_OBJECT){f.warn("lock.json5 dependencies object exceeds key limit, truncating");break}let l=s[c];if(!T(l))continue;let d=typeof l.specifier=="string"?l.specifier:"",g=typeof l.version=="string"?l.version:"",y=new Xn;y.name=c,y.version=g.startsWith(r.FILE_DEPENDENCY_PREFIX)?g.substring(r.FILE_DEPENDENCY_PREFIX.length):g,this.parseDependencyPath(y,n,c,d,g);let b=`${c}@${g}`;this.storePathMap.has(b)&&(y.storePath=this.storePathMap.get(b)||""),i.push(y)}return i}parseDependencyPath(e,t,n,o,i){let s=Er.resolve(this.projectPath,Er.join(t,F.OH_MODULES_PATH,n));try{let a=i.startsWith(r.FILE_DEPENDENCY_PREFIX)?i.substring(r.FILE_DEPENDENCY_PREFIX.length):i,c=Er.isAbsolute(a)?a:Er.resolve(this.projectPath,a);un.existsSync(c)?(e.path=o,e.dependencyPath=this.fileNameForOhpm.test(i)?s:c):e.dependencyPath=s}catch(a){f.error("Invalid dependency path in lock.json5, msg:",a instanceof Error?a.message:String(a))}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function Xg(r){return T(r)?typeof r.name=="string"&&typeof r.srcPath=="string":!1}var pn=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new Ft(this.projectPath)}moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,n=_e.join(t,hi),o=_e.join(n,dn);if(!Zn.existsSync(n)||!Zn.existsSync(o)){let c="Dependency map or JSON not found";return f.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let i=new Kn(this.projectPath,".",this.projectPath);this.parseProjectDependencies(n,i),this.parseLockJson(i);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return f.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:c}}let a=Date.now();for(let c=0;c<s.length;c++){let l=s[c];if(Xg(l)){try{E.assertModuleName(l.name)}catch{f.warn(`[Parser] Skipping module with invalid name: ${l.name}`);continue}this.parseSingleModule(l,n,i,e),(c+1)%100===0&&f.info(`[Parser] getAllDependencyMap progress: ${c+1}/${s.length} (${Date.now()-a}ms)`)}}return f.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-a}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],n=this.projectPath,o=_e.join(n,hi),i=_e.join(o,dn);if(!Zn.existsSync(o)||!Zn.existsSync(i))return f.warn("[Parser] Dependency map or JSON not found."),t;let s=e&&e.length>0?new Set(e.map(l=>l.trim()).filter(Boolean)):null,a=new Kn(this.projectPath,".",this.projectPath);this.parseProjectDependencies(o,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return f.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let l of c){if(!Xg(l))continue;let d=l.name;try{E.assertModuleName(d)}catch{f.warn(`[Parser] Skipping module with invalid name: ${d}`);continue}if(s&&!s.has(d))continue;let g=_e.resolve(this.projectPath,l.srcPath),y=_e.join(o,d),b=J(g),N=this.buildModuleDependencies(d,b,y,a);N.moduleName=d,t.push(N)}return t}parseSingleModule(e,t,n,o){let i=e.name,s=_e.resolve(this.projectPath,e.srcPath),a=_e.join(t,i),c=J(s),l=new Jn(c),d=this.buildModuleDependencies(i,c,a,n);this.parseModuleJson5(c,l);let g=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=i,l.moduleType=i,l.packageName=i,l.moduleDependencies=d,l.moduleJsonParam=new Yn(g),o.push(l)}buildModuleDependencies(e,t,n,o){let i=new Kn(this.projectPath,e,t);gi.getInstance(n,t,this.projectPath).parseDependency(i),this.parseLockJson(i),i.finalDependencies.push(...o.finalDependencies),i.finalDevDependencies.push(...o.finalDevDependencies),i.finalDynamicDependencies.push(...o.finalDynamicDependencies),i.finalDependencies.push(...i.finalDevDependencies);let a=new ka;return a.modulePath=t,this.toModuleDependencies(i,a),a}toModuleDependencies(e,t){let n={},o={};for(let i of e.finalDependencies)n[i.name]=new ln(i);for(let i of e.finalDynamicDependencies)o[i.name]=new ln(i);t.dependencies=n,t.dynamicDependencies=o}parseProjectDependencies(e,t){let n=_e.join(e,F.OH_PACKAGE_JSON5);if(!Zn.existsSync(n))return;gi.getInstance(e,this.projectPath,this.projectPath).parseDependency(t)}parseLockJson(e){let t=this.getLockJson5Parser();t.parseDependencies(e.moduleName)?(e.finalDependencies=t.finalDependencies,e.finalDevDependencies=t.finalDevDependencies,e.finalDynamicDependencies=t.finalDynamicDependencies):(e.finalDependencies=e.dependencies,e.finalDevDependencies=e.devDependencies,e.finalDynamicDependencies=e.dynamicDependencies)}getLockJson5Parser(){return this.lockJson5Parser||(this.lockJson5Parser=new Ta(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let n=_e.join(e,"src","main","module.json5"),o=Xe(n);if(!T(o)||!T(o.module))return;let i=o.module;t.permissions=this.parseRequestPermissions(i),t.deviceType=this.parseDeviceTypes(i)}parseRequestPermissions(e){let t=[];if(T(e)&&Array.isArray(e.requestPermissions))for(let n of e.requestPermissions)T(n)&&typeof n.name=="string"&&t.push(n.name);return t}parseMainPages(e){let t=_e.join(e,"src","main","resources","base","profile","main_pages.json"),n=Xe(t);return!T(n)||!Array.isArray(n.src)?[]:n.src.filter(o=>typeof o=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!T(t)||!T(t.data))){if(typeof t.data.apiVersion=="string"){let n=parseInt(t.data.apiVersion,10);!Number.isNaN(n)&&n>=26&&typeof t.data.platformVersion=="string"?e.compileSdkLevel=t.data.platformVersion:e.compileSdkLevel=t.data.apiVersion}typeof t.data.releaseType=="string"&&(e.compileSdkType=t.data.releaseType),typeof t.data.version=="string"&&(e.compileSdkVersion=t.data.version)}}getSdkPkg(){if(this.sdkPkgCache===void 0){let e=_e.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=Xe(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!T(t)||!T(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let n=t.app.products[0];if(!T(n)||typeof n.compatibleSdkVersion!="string")return;let[o,i]=this.parseBySplit(n.compatibleSdkVersion);e.compatibleSdkVersion=o,e.compatibleSdkLevel=i}getBuildProfile(){if(this.buildProfileCache===void 0){let e=_e.join(this.projectPath,"build-profile.json5");this.buildProfileCache=Xe(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,e];let n=e.substring(0,t),o=e.substring(t+1,e.length-1);return[n,o]}parseDeviceTypes(e){return!T(e)||!Array.isArray(e.deviceTypes)?[]:e.deviceTypes.filter(t=>typeof t=="string").map(t=>this.getDeviceType(t))}getDeviceType(e){return{liteWearable:1,wearable:2,tv:3,car:4,phone:5,default:5,smartVision:6,tablet:7,router:8,pc:9,"2in1":10}[e]||0}};var Ra=class{constructor(e=[]){this.valueSet=e}};var Qn=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Zg=(A=>(A[A.File=1]="File",A[A.Module=2]="Module",A[A.Namespace=3]="Namespace",A[A.Package=4]="Package",A[A.Class=5]="Class",A[A.Method=6]="Method",A[A.Property=7]="Property",A[A.Field=8]="Field",A[A.Constructor=9]="Constructor",A[A.Enum=10]="Enum",A[A.Interface=11]="Interface",A[A.Function=12]="Function",A[A.Variable=13]="Variable",A[A.Constant=14]="Constant",A[A.String=15]="String",A[A.Number=16]="Number",A[A.Boolean=17]="Boolean",A[A.Array=18]="Array",A[A.Object=19]="Object",A[A.Key=20]="Key",A[A.Null=21]="Null",A[A.EnumMember=22]="EnumMember",A[A.Struct=23]="Struct",A[A.Event=24]="Event",A[A.Operator=25]="Operator",A[A.TypeParameter=26]="TypeParameter",A))(Zg||{}),Qg=()=>Object.values(Zg).filter(r=>typeof r=="number");var xa=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var La=class{applyEdit=!0;workspaceEdit=new xa;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Ra(Qg());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Qn;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Na=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Oa=class{constructor(e=[]){this.valueSet=e}};var Ma=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var ey=(D=>(D[D.Text=1]="Text",D[D.Method=2]="Method",D[D.Function=3]="Function",D[D.Constructor=4]="Constructor",D[D.Field=5]="Field",D[D.Variable=6]="Variable",D[D.Class=7]="Class",D[D.Interface=8]="Interface",D[D.Module=9]="Module",D[D.Property=10]="Property",D[D.Unit=11]="Unit",D[D.Value=12]="Value",D[D.Enum=13]="Enum",D[D.Keyword=14]="Keyword",D[D.Snippet=15]="Snippet",D[D.Color=16]="Color",D[D.File=17]="File",D[D.Reference=18]="Reference",D[D.Folder=19]="Folder",D[D.EnumMember=20]="EnumMember",D[D.Constant=21]="Constant",D[D.Struct=22]="Struct",D[D.Event=23]="Event",D[D.Operator=24]="Operator",D[D.TypeParameter=25]="TypeParameter",D))(ey||{}),ty=()=>Object.values(ey).filter(r=>typeof r=="number");var _a=class{completionItemKind=new Oa(ty());completionItem=new Ma;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Fa=class{synchronization=new Na;completion=new _a;hover={contentFormat:{},dynamicRegistration:{}};signatureHelp={signatureInformation:{},contextSupport:{},dynamicRegistration:{}};references={dynamicRegistration:{}};documentHighlight={dynamicRegistration:!0};documentSymbol=null;formatting={dynamicRegistration:{}};rangeFormatting={dynamicRegistration:{}};onTypeFormatting={dynamicRegistration:{}};declaration={};definition={linkSupport:{},dynamicRegistration:{}};codeLens=null;documentLink={tooltipSupport:{},dynamicRegistration:{}};colorProvider=null;rename={prepareSupport:!0,prepareSupportDefaultBehavior:null,honorsChangeAnnotations:null,dynamicRegistrationSupport:null};publishDiagnostics=null;foldingRage=null;typeHierarchy=null;callHierarchy={dynamicRegistration:{}};selectionRange=null;semanticTokens=new Qn;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var ja=class{workspace=new La;textDocument=new Fa;notebookDocument=null;window=null;general=null;experimental=null};var $a=class{constructor(e,t,n){this.rootUri=e;this.initializationOptions=t;this.capabilities=n}};var Ha=class{constructor(e,t,n,o,i,s=!0){this.sdkPath=e;this.rootUri=n;this.nodeMaxOldSpaceSize=i;this.useStandardProtocol=s;this.serverPath=Io(t,this.useStandardProtocol),this.logPath=tm(),this.indexLogPath=o||this.logPath;let a={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath};this.messageHandle=this.useStandardProtocol?new ya(a):new wa(a),this.messageHandle.setBroadcastToClients(c=>this.onLspMessage(c))}messageHandle;get stdHandle(){return this.messageHandle}get legacyHandle(){return this.messageHandle}get lspPid(){return this.messageHandle.lspPid}onAsyncOpenFile(e){this.legacyHandle.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.legacyHandle.closeFile(e,t)}serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}async start(e,t){let n=!1;try{f.info(`serverPath: ${this.serverPath}`),f.info(`rootUri: ${this.rootUri}`),f.info(`sdkPath: ${this.sdkPath}`),f.info(`logPath: ${this.logPath}`);let o=gt(this.rootUri),i=new Aa(o,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new pn(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),i.modules=s;let l=Ss(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new $a(o,i,new ja),this.useStandardProtocol){let d=this.messageHandle;await d.sendInitializeResettable(this.currentParams,ot),f.info("[LSP] initialize response received"),d.broadcastToClients({jsonrpc:R,method:v.ARKTS_INDEXING_PROGRESS,params:{}}),d.sendInitialized()}else await this.startLegacy(this.currentParams,e);n=!0}catch(o){this.lastStartErrorMessage=o instanceof Error?o.message:String(o),f.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(n)}async startLegacy(e,t){let n=this.messageHandle;n.sendInitialize(e,1),n.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:R,method:v.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((o,i)=>{n.onIndexingProgressUpdate(i),n.onInitializationCompleted(o)},"LSP initialization",ot),n.sendInitialized(t)}withResettableTimeout(e,t,n){return new Promise((o,i)=>{let s,a=()=>{s=setTimeout(()=>{i(new Error(`${t} timeout after ${n}ms`))},n)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),o()},c)})}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){f.info(`[LSP] registerDiagnosticCallback uri='${e}', useStandardProtocol=${this.useStandardProtocol}`),this.messageHandle.registerRequestCallback(e,(t,n)=>{let o=T(n)?n:{};f.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let i={jsonrpc:R,method:t,params:{uri:typeof o.uri=="string"?o.uri:e,diagnostics:Array.isArray(o.diagnostics)?o.diagnostics:[],...typeof o.errorMessage=="string"?{errorMessage:o.errorMessage}:{}}};this.onLspMessage(i)})}async hover(e){let t=e.textDocument.uri;return this.registerDiagnosticCallback(t),this.stdHandle.sendLspRequest(v.HOVER,e)}async definition(e){return this.stdHandle.sendLspRequest(v.DEFINITION,e)}async references(e){return this.stdHandle.sendLspRequest(v.REFERENCES,e)}async completion(e){return this.stdHandle.sendLspRequest(v.COMPLETION,e)}async documentSymbol(e){return this.stdHandle.sendLspRequest(v.DOCUMENT_SYMBOL,e)}async diagnostic(e){return this.stdHandle.sendLspRequest(v.DIAGNOSTIC,e,120*1e3)}async sendFeatureRequest(e,t){return this.stdHandle.sendLspRequest(e,t)}reloadDependenciesOnly(e){let t=e?.fullReload??!1,n=new pn(this.rootUri,this.sdkPath),o=this.getModuleModelsByName();if(t){f.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let l=n.getDependenciesOnly();this.markDependencyTypesIncremental(l);let d=this.mergeDepsOnlyIntoModuleList(l,o);return this.applyModuleModelsUpdate(d),this.sendDidChangeConfiguration({moduleSet:d}),f.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${d.length}`),this.lastDepsOnlyForDiff=l,l}let i=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(i.length===0&&s.size===0)return f.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];f.info(`[LspServerProxy] Module-level deps changed, parsing: [${i.join(", ")}]`);let a=n.getDependenciesOnly(i);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),this.sendDidChangeConfiguration({moduleSet:c}),f.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}sendDidChangeConfiguration(e){this.stdHandle.sendDidChangeConfiguration(e)}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),n=new Map(this.lastDepsOnlyForDiff.map(o=>[o.moduleName??"",o]));for(let o of e){let i=o.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(i,t,n),c=o.dependencies??{},l=o.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(d,g)=>{(o.dependencies??={})[d]=this.makeDeleteEntry(d,g)}),this.markAddAndDeleteInDeps(a,l,(d,g)=>{(o.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,g)})}}getOldDepsForModule(e,t,n){let o=t.get(e),i=o?.moduleDependencies?.dependencies??{},s=o?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(i).length===0&&Object.keys(s).length===0){let a=n.get(e);a&&(i=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:i,oldDynamic:s}}markAddAndDeleteInDeps(e,t,n){for(let o of Object.keys(t))o in e||(t[o].type="add");for(let o of Object.keys(e))o in t||n(o,e[o])}makeDeleteEntry(e,t){return new ln({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Jn(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new Yn([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let n=[];for(let o of e){let i=o.moduleName??"",s=t.get(i);s?(s.modulePath=o.modulePath,s.moduleDependencies=o):s=this.createMinimalModelFromDepsItem(o),n.push(s)}return n}mergeIncrementalDeps(e,t,n){let o=new Map(n.map(s=>[s.moduleName??"",s])),i=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=o.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,o.delete(a)),i.push(s)}for(let[,s]of o)i.push(this.createMinimalModelFromDepsItem(s));return i}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,n=Pn(Ed.join(t,"default/openharmony/ets/build-tools/ets-loader")),o=Pn(Ed.join(t,"default/openharmony/ets/api")),i=Pn(Ed.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=n,s.sdkJsPath=o,s.hosSdkPath=i}sendRequest(e){switch(e.method){case v.HOVER:this.stdHandle.sendLspRequest(v.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;case v.DEFINITION:this.stdHandle.sendLspRequest(v.DEFINITION,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;case v.REFERENCES:this.stdHandle.sendLspRequest(v.REFERENCES,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;default:f.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!Gg(e)){f.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case v.DID_OPEN:this.handleDidOpenNotification(e);break;case v.DID_CHANGE:this.handleDidChangeNotification(e);break;case v.DID_CLOSE:this.handleDidCloseNotification(e);break;case v.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;case v.DID_CREATE_FILES:this.handleDidCreateFiles(e);break;case v.DID_DELETE_FILES:this.handleDidDeleteFiles(e);break;default:f.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didOpen params");return}this.stdHandle.sendDidOpen(t)}handleDidChangeNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didChange params");return}this.stdHandle.sendDidChange(t)}handleDidCloseNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didClose params");return}this.stdHandle.closeFile(t)}handleDidChangeWatchedFiles(e){let t=e.params;!t||!Array.isArray(t.changes)||this.messageHandle.onDidChangeWatchedFiles(t.changes)}handleDidCreateFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(v.DID_CREATE_FILES,t)}handleDidDeleteFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(v.DID_DELETE_FILES,t)}async dispose(){await this.messageHandle.stop()}};import*as Xt from"fs";import*as Ve from"path";import{createHash as pD}from"crypto";import{EventEmitter as mD}from"events";var Ba=class extends mD{constructor(t,n=500){super();this.projectRoot=t;this.debounceMs=n}watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),n=new Set(this.watchers.keys());for(let o of t)n.has(o)||this.watchFile(o);for(let o of n)t.has(o)||(this.unwatchFile(o),f.info(`[ConfigFileWatcher] Stopped watching: ${o}`));f.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!Xt.existsSync(t)){f.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Xt.watch(t,n=>{n==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",n=>{f.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${n.message}`)}),f.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(n){f.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${n instanceof Error?n.message:String(n)}`)}}emitModuleAddedEvents(t,n){for(let o of t){let i=Ve.resolve(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:i,relativePath:o.srcPath,timestamp:n,moduleName:o.name})}}emitModuleRemovedEvents(t,n){for(let o of t){let i=Ve.resolve(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:i,relativePath:o.srcPath,timestamp:n,removedModuleName:o.name})}}emitModuleRenamedEvents(t,n){for(let o of t){let i=Ve.resolve(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:i,relativePath:o.after.srcPath,timestamp:n,moduleName:o.after.name,removedModuleName:o.before.name})}}emitModuleMovedEvents(t,n){for(let o of t){let i=Ve.resolve(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:i,relativePath:o.after.srcPath,timestamp:n,moduleName:o.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let n=Date.now();this.emitModuleAddedEvents(t.added,n),this.emitModuleRemovedEvents(t.removed,n),this.emitModuleRenamedEvents(t.renamed,n),this.emitModuleMovedEvents(t.moved,n)}onBuildProfileChanged(){let t="__build_profile__",n=this.debounceTimers.get(t);n&&clearTimeout(n);let o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(i);if(s===this.lastModulesSnapshot){f.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,i);this.lastModules=i,this.lastModulesSnapshot=s,f.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,o)}computeModulesSnapshot(t){return t.map(o=>`${o.name}::${o.srcPath}`).sort().join("|")}diffModules(t,n){let o=this.buildModuleMatchState(n),i={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,o),this.matchRenamedModules(t,o,i),this.matchMovedModules(t,o,i),this.collectRemovedModules(t,o,i),this.collectAddedModules(n,o,i),i}buildModuleMatchState(t){let n=new Map,o=new Map;for(let i of t)n.set(i.srcPath,i),o.set(i.name,i);return{matchedOld:new Set,matchedNew:new Set,newBySrc:n,newByName:o}}matchExactModules(t,n){for(let o of t){let i=n.newBySrc.get(o.srcPath);i&&i.name===o.name&&(n.matchedOld.add(o),n.matchedNew.add(i))}}matchRenamedModules(t,n,o){for(let i of t){if(n.matchedOld.has(i))continue;let s=n.newBySrc.get(i.srcPath);s&&!n.matchedNew.has(s)&&s.name!==i.name&&(o.renamed.push({before:i,after:s}),n.matchedOld.add(i),n.matchedNew.add(s))}}matchMovedModules(t,n,o){for(let i of t){if(n.matchedOld.has(i))continue;let s=n.newByName.get(i.name);s&&!n.matchedNew.has(s)&&s.srcPath!==i.srcPath&&(o.moved.push({before:i,after:s}),n.matchedOld.add(i),n.matchedNew.add(s))}}collectRemovedModules(t,n,o){for(let i of t)n.matchedOld.has(i)||o.removed.push(i)}collectAddedModules(t,n,o){for(let i of t)n.matchedNew.has(i)||o.added.push(i)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let n=Xe(t);if(typeof n!="object"||n===null)return[];let o=n.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(n){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${n instanceof Error?n.message:String(n)}`),[]}}collectWatchTargets(){let t=[],n=Ve.join(this.projectRoot,F.OH_PACKAGE_JSON5);Xt.existsSync(n)&&t.push(n);let o=this.parseModulesFromBuildProfile();for(let i of o){let s=Ve.resolve(this.projectRoot,i.srcPath),a=Ve.join(s,F.OH_PACKAGE_JSON5);Xt.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Ve.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let n=Xt.readFileSync(t,"utf-8");return pD("sha256").update(n).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let n=this.computeFileHash(t);n&&this.contentHashes.set(t,n);let o=Xt.watch(t,i=>{i==="change"&&this.onFileChanged(t)});o.on("error",i=>{f.error(`[ConfigFileWatcher] Watch error for ${t}: ${i.message}`)}),this.watchers.set(t,o)}catch(n){f.error(`[ConfigFileWatcher] Failed to watch ${t}: ${n instanceof Error?n.message:String(n)}`)}}unwatchFile(t){let n=this.watchers.get(t);n&&(n.close(),this.watchers.delete(t)),this.contentHashes.delete(t);let o=this.debounceTimers.get(t);o&&(clearTimeout(o),this.debounceTimers.delete(t))}onFileChanged(t){let n=this.debounceTimers.get(t);n&&clearTimeout(n);let o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.computeFileHash(t);if(!i){f.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===i){f.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,i),f.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:Ve.basename(t),relativePath:Ve.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,o)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),f.info("[ConfigFileWatcher] All watchers stopped")}};import*as Cr from"fs";import*as wt from"path";import{createHash as fD}from"crypto";import{EventEmitter as hD}from"events";var Ua=class extends hD{constructor(t,n=500){super();this.projectRoot=t;this.debounceMs=n,this.coalesceMs=n+300,this.depMapDir=wt.join(t,hi)}dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!Cr.existsSync(this.depMapDir)){f.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=Cr.watch(this.depMapDir,{recursive:!0},(t,n)=>this.onDirEvent(t,n)),this.dirWatcher.on("error",t=>{f.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){f.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),f.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return J(wt.resolve(t))}onDirEvent(t,n){if(!n||typeof n!="string")return;let o=n.replace(/\\/g,"/"),i;if(o===F.OH_PACKAGE_JSON5)i="root-oh-package";else if(o===dn)i="dep-map-json";else{let a=o.match(/^([^/]+)\/oh-package\.json5$/);i=a?`module:${a[1]}`:""}if(!i)return;let s=wt.join(this.depMapDir,n);Cr.existsSync(s)&&this.scheduleDebouncedFullScan()}stop(){this.dirWatcher&&(this.dirWatcher.close(),this.dirWatcher=null),this.fullScanTimer&&(clearTimeout(this.fullScanTimer),this.fullScanTimer=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.coalesceTimer&&(clearTimeout(this.coalesceTimer),this.coalesceTimer=null),this.pendingTags=[],this.pendingRenames=[],this.contentHashes.clear(),this.initialScanDone=!1,f.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=wt.join(this.depMapDir,F.OH_PACKAGE_JSON5),n=wt.join(this.depMapDir,dn),o=this.parseModulesFromDepMap(),i=[{path:t,tag:"root-oh-package"},{path:n,tag:"dep-map-json"},...o.map(s=>({path:(E.assertModuleName(s.name),wt.join(this.depMapDir,s.name,F.OH_PACKAGE_JSON5)),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of i){if(!Cr.existsSync(s))continue;let c=this.canonicalPath(s),l=this.computeFileHash(s);if(!l)continue;let d=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,l);continue}d!==l&&(this.contentHashes.set(c,l),f.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=wt.join(this.depMapDir,dn);try{let n=Xe(t);if(typeof n!="object"||n===null)return[];let o=n.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(n){return f.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${n instanceof Error?n.message:String(n)}`),[]}}scheduleCoalescedReload(t){this.pendingTags.push(t),t==="dep-map-json"&&this.applyDepMapJsonDiff(),this.coalesceTimer&&clearTimeout(this.coalesceTimer),this.coalesceTimer=setTimeout(()=>{this.coalesceTimer=null,this.flushPendingReload()},this.coalesceMs)}collectPendingState(){let t=this.pendingTags,n=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:n}}processTagsIntoSets(t,n,o,i){for(let s of t)s.startsWith("module:")?(o.add(s.substring(7)),n.add("moduleDepsChanged")):s.startsWith("dep-added:")?(o.add(s.substring(10)),n.add("moduleAdded")):s.startsWith("dep-removed:")&&(i.add(s.substring(12)),n.add("moduleRemoved"))}processRenameEntries(t,n,o,i,s){for(let a of t)s.push(a.info),o.add(a.info.newName),i.add(a.info.oldName),n.add(a.kind)}buildAddedNamesSet(t,n){let o=new Set;for(let i of t)i.startsWith("dep-added:")&&o.add(i.substring(10));for(let i of n)o.add(i.info.newName);return o}emitIncrementalReload(t,n,o,i,s){f.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...n].join(",")}], removed=[${[...o].join(",")}], added=[${[...i].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...n],removedModuleNames:[...o],addedModuleNames:[...i],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:n}=this.collectPendingState();if(t.length===0&&n.length===0)return;if(f.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${n.length}`),t.includes("root-oh-package")){f.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let o=new Set,i=new Set,s=new Set,a=[];this.processTagsIntoSets(t,o,i,s),this.processRenameEntries(n,o,i,s,a);for(let l of i)s.delete(l);if(i.size===0&&s.size===0&&a.length===0){f.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,n);this.emitIncrementalReload(o,i,s,c,a)}normalizeSrcPath(t){return J(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let n=new Map(t.map(i=>[i.name,i])),o=new Map(t.map(i=>[this.normalizeSrcPath(i.srcPath),i]));return{byName:n,bySrcPath:o}}detectModuleRenames(t,n,o,i){for(let[s,a]of t){let c=n.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),o.add(a.name),i.add(c.name);let l=(E.assertModuleName(a.name),wt.join(this.depMapDir,a.name,F.OH_PACKAGE_JSON5));this.contentHashes.delete(this.canonicalPath(l)),f.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,n,o,i){for(let[s,a]of t){if(o.has(s))continue;let c=n.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),o.add(s),i.add(s),f.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,n,o){for(let[i]of t)o.has(i)||n.has(i)||(this.pendingTags.push(`dep-added:${i}`),o.add(i))}detectRemovedModules(t,n,o){for(let[i]of t)if(!o.has(i)&&!n.has(i)){this.pendingTags.push(`dep-removed:${i}`),o.add(i);let s=(E.assertModuleName(i),wt.join(this.depMapDir,i,F.OH_PACKAGE_JSON5));this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(o=>o.startsWith("dep-")),n=this.pendingRenames.map(o=>`${o.kind}(${o.info.oldName}\u2192${o.info.newName})`);f.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${n.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:n,bySrcPath:o}=this.buildModuleLookupMaps(this.lastModules),{byName:i,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(o,s,a,c),this.detectModuleMoves(n,i,a,c),this.detectAddedModules(i,n,c),this.detectRemovedModules(n,i,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let n=Cr.readFileSync(t,"utf-8");return fD("sha256").update(n).digest("hex")}catch{return null}}};import{spawn as gD}from"child_process";var yD=["install","--all"];async function vD(r,e,t,n){return new Promise(o=>{let i=gD(r,[e,...yD],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:n},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";i.stdout?.on("data",c=>{s+=c.toString()}),i.stderr?.on("data",c=>{a+=c.toString()}),i.on("close",c=>{let l=[s,a].filter(Boolean).join(`
1306
- `);o({exitCode:c??-1,output:l})}),i.on("error",c=>{let l=[s,a].filter(Boolean).join(`
1307
- `);o({exitCode:-1,output:l+`
1308
- `+c.message})})})}function wD(r){r.split(/\r?\n/).filter(Boolean).forEach(e=>f.info("[ohpm] %s",e))}async function ry(r,e,t,n){try{if(!t)return f.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;if(!n)return f.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:o,output:i}=await vD(t,n,r,e);return wD(i),o===0?(f.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(f.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",o),f.error("ohpm \u8F93\u51FA: %s",i),!1)}catch(o){return f.error("ohpm \u5B89\u88C5\u5F02\u5E38",o),!1}}var ny={UNINITIALIZED:-32099,UNKNOWN:-32e3},yi=class r extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new r(e,ny.UNINITIALIZED)}static unknown(e="Unknown error"){return new r(e,ny.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var eo=class{config;lspProxy=null;configWatcher=null;depMapWatcher=null;isInitialized=!1;lastEditorOpenFiles=[];onMessage=()=>{};onConfigChanged=null;disposeOnce=null;get aceServerPid(){return this.lspProxy?.lspPid??null}constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}async start(e=[]){this.lastEditorOpenFiles=e;try{this.startConfigWatcher(),this.startLspProxy(e)}catch(t){throw f.error(`[ArktsLspManager] start() synchronous failure: ${t instanceof Error?t.message:String(t)}`),t}}sendNotification(e){if(!this.lspProxy){f.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){f.warn("[ArktsLspManager] sendRequest before LSP ready, dropped");return}this.lspProxy.sendRequest(e)}async diagnostic(e){if(!this.lspProxy)throw new Error("[ArktsLspManager] diagnostic before LSP ready");return this.lspProxy.diagnostic(e)}async sendFeatureRequest(e,t){if(!this.useStandardProtocol)throw new Error(`Language feature '${e}' is not supported on the installed DevEco Studio. The standard LSP protocol entry (plugins/openharmony/ace-server/out/standardIndex/index.js) was not found. Please upgrade DevEco Studio to version 26.0.0.610 or later to use this tool.`);if(!this.lspProxy)throw new Error("LSP not ready");return this.lspProxy.sendFeatureRequest(e,t)}get useStandardProtocol(){return this.config.useStandardProtocol}onAsyncOpenFile(e){this.lspProxy?.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.lspProxy?.closeFileLegacy(e,t)}registerDiagnosticCallback(e){this.lspProxy?.registerDiagnosticCallback(e)}static async handleSyncProject(e,t,n,o,i,s){if(f.info("[ArktsLspManager] Received arkts/syncProject"),!e||!t)return f.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let a=s?.skipHvigorSync===!0,c=await hs(e,async()=>await ry(e,t,n??"",o??"")?a?(f.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await sm(e,t,n??"",i??"")?(f.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(f.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(f.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return c.acquired?c.result:(f.info("[ArktsLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){try{this.configWatcher?.stop()}catch(e){f.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){f.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){f.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new Ha(this.config.sdkPath,this.config.arktsLangServerPath,this.config.workspaceRoot,this.config.indexLogPath,this.config.nodeMaxOldSpaceSize,this.config.useStandardProtocol);t.setOnMessage(n=>this.handleLspMessage(n)),t.start(e,n=>this.handleLspInitialized(n)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)f.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:R,method:v.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();f.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let n=t?yi.uninitialized(t):yi.unknown();this.onMessage({jsonrpc:R,method:v.ARKTS_INITIALIZATION_FAILED,params:n.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(f.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:R,method:v.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Ba(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Ua(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){f.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let n=this.lspProxy.reloadDependenciesOnly(e).map(o=>({modulePath:o.modulePath??"",dependencies:o.dependencies??{},dynamicDependencies:o.dynamicDependencies??{}}));this.onMessage({jsonrpc:R,method:v.ARKTS_SYNC_COMPLETED,params:{success:!0,moduleSet:n}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){f.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var SD=10080*60*1e3,bD=7200*60*1e3,ED=120*1e3,to=class r{manager=null;get aceServerPid(){return this.manager?.aceServerPid??null}initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;sdkPath;arktsLangServerPath;nodeMaxOldSpaceSize;onConfigChangedCallback=null;useStandardProtocol=!0;diagnosticWaiters=new Map;documentVersion=0;static FEATURE_METHOD_MAP={hover:v.HOVER,definition:v.DEFINITION,declaration:v.DECLARATION,references:v.REFERENCES,implementation:v.IMPLEMENTATION,completion:v.COMPLETION,signatureHelp:v.SIGNATURE_HELP,documentHighlight:v.DOCUMENT_HIGHLIGHT};constructor(e,t,n,o){this.projectPath=e,this.sdkPath=t,this.arktsLangServerPath=n,this.nodeMaxOldSpaceSize=o}setOnConfigChanged(e){this.onConfigChangedCallback=e}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initializing=!0,this.initPromise=this.doInitialize().then(()=>{this.initialized=!0}).finally(()=>{this.initializing=!1}),await this.initPromise}}async doInitialize(){let{harmonyRoot:e,arktsLangServerPath:t,useStandardProtocol:n}=this.resolveProjectAndDeveco();this.useStandardProtocol=n;let o=ve(e),{logPath:i,indexPath:s}=this.getLogAndIndexPath(o);setImmediate(()=>{Bc(s,SD,"[ArkTS-Check]"),Bc(i,bD,"[ArkTS-Check]")}),ws(i);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a;h.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${c??"undefined \u2192 dynamic formula applies"}`);let l=this.sdkPath;h.info(`[ArktsCheck] sdkPath=${l}, arktsLangServerPath=${t}, useStandardProtocol=${n}`),this.manager=new eo({sdkPath:l,arktsLangServerPath:t,workspaceRoot:J(o),indexLogPath:s,nodeMaxOldSpaceSize:c,useStandardProtocol:n}),this.manager.setOnMessage(d=>this.handleLspMessage(d)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((d,g)=>{this.initResolve=d,this.initReject=g,this.armInitTimer(ot),this.manager.start([]).catch(y=>{let b=y instanceof Error?y:new Error(String(y));this.failInit(b)})})}resolveProjectAndDeveco(){let e=_t(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.arktsLangServerPath;if(!t)throw new Error("arkts-lang-server path not found");let n=rs(t);return h.info(`ArktsCheck protocol: ${n?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${n})`),{harmonyRoot:e,arktsLangServerPath:t,useStandardProtocol:n}}armInitTimer(e){this.initDeadlineTimer&&clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=setTimeout(()=>{let t=this.initReject;this.clearInitHandlers(),t?.(new Error("LSP initialize timeout"))},e)}clearInitHandlers(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async checkFile(e){this.initialized||await this.initialize();let t=this.manager;if(!t)throw new Error("ArktsLspManager not initialized");let n=Gr(e),o=await pt.promises.readFile(e,"utf8"),s=`deveco.apptool.${Ie.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,n,o,s):this.checkFileLegacy(t,e,n,o,s)}async checkFileStandard(e,t,n,o){h.debug(`textDocument/didOpen uri=${t} content_len=${n.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:n,languageId:o,version:++this.documentVersion}});try{h.debug(`textDocument/diagnostic uri=${t}`);let i=await e.diagnostic({textDocument:{uri:t}});return CD(i)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:t}})}}async checkFileLegacy(e,t,n,o,i){let s=n;e.registerDiagnosticCallback(n);let a=new Promise((c,l)=>{let d=setTimeout(()=>{this.diagnosticWaiters.delete(s)&&l(new Error("Wait for diagnostics timeout"))},ED);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});h.debug(`textDocument/didOpen(legacy) uri=${n} content_len=${o.length}`),e.onAsyncOpenFile({textDocument:{uri:n,text:o,languageId:i,version:o.length},editorFiles:[n],isFromEditor:!1});try{return await a}finally{e.closeFileLegacy(n,!1)}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],n=[],o=this.collectValidFiles(e.files,t);return o.length===0?{content:[{type:"text",text:t.length>0?t.join(`
1309
- `):"No valid .ets files"}],isError:!0}:(await this.runDiagnosticsForFiles(o,t,n),this.formatCallResult(t,n))}async handleLspFeature(e,t){if(!this.initialized)return this.buildNotReadyResponse();let n=this.resolveSingleFile(t.file);if(!n)return{content:[{type:"text",text:`File does not exist or is not a .ets file: ${t.file}`}],isError:!0};let o=r.FEATURE_METHOD_MAP[e];if(!o)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`handleLspFeature: ${e} file=${n} line=${t.line} char=${t.character}`);try{let i=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(o,c)});return{content:[{type:"text",text:i==null?`${e}: no result`:`${e}: ${JSON.stringify(i,null,2)}`}]}}catch(i){let s=i instanceof Error?i.message:String(i);return h.error(`handleLspFeature ${e} failed: ${s}`),{content:[{type:"text",text:`${e} failed: ${s}`}],isError:!0}}}async handleWorkspaceSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();h.info(`handleWorkspaceSymbol: query="${e}"`);try{let t=await this.manager.sendFeatureRequest(v.WORKSPACE_SYMBOL,{query:e});return{content:[{type:"text",text:t==null?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(t,null,2)}`}]}}catch(t){let n=t instanceof Error?t.message:String(t);return h.error(`handleWorkspaceSymbol failed: ${n}`),{content:[{type:"text",text:`workspaceSymbol failed: ${n}`}],isError:!0}}}async handleWorkspaceSymbolRaw(e){if(!this.initialized)return null;try{let t=await this.manager.sendFeatureRequest(v.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return h.error(`handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a .ets file: ${e}`}],isError:!0};h.info(`handleDocumentSymbol: file=${t}`);try{let n=await this.withOpenFile(t,async i=>this.manager.sendFeatureRequest(v.DOCUMENT_SYMBOL,{textDocument:{uri:i}}));return{content:[{type:"text",text:n==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(n,null,2)}`}]}}catch(n){let o=n instanceof Error?n.message:String(n);return h.error(`handleDocumentSymbol failed: ${o}`),{content:[{type:"text",text:`documentSymbol failed: ${o}`}],isError:!0}}}async handleCallHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a .ets file: ${e.file}`}],isError:!0};h.info(`handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let n=await this.withOpenFile(t,async i=>{let s=await this.manager.sendFeatureRequest(v.PREPARE_CALL_HIERARCHY,{textDocument:{uri:i},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],calls:[]};let c=e.direction==="incoming"?v.INCOMING_CALLS:v.OUTGOING_CALLS,l=[];for(let d of a){let g=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(g)?l.push(...g):g&&l.push(g)}return{items:a,calls:l}});return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(n,null,2)}`}]}}catch(n){let o=n instanceof Error?n.message:String(n);return h.error(`handleCallHierarchy failed: ${o}`),{content:[{type:"text",text:`callHierarchy failed: ${o}`}],isError:!0}}}async withOpenFile(e,t){let n=Gr(e),o=await pt.promises.readFile(e,"utf8"),s=`deveco.apptool.${Ie.extname(e).replace(/^\./,"")||"plaintext"}`;h.debug(`withOpenFile didOpen uri=${n} len=${o.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:n,text:o,languageId:s,version:++this.documentVersion}});try{return await t(n)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:n},isManual:!1})}}resolveSingleFile(e){let t=Ie.isAbsolute(e)?e:Ie.join(this.projectPath,e);return!pt.existsSync(t)||!pt.statSync(t).isFile()||!t.endsWith(".ets")?null:t}buildNotReadyResponse(){return{content:[{type:"text",text:this.initializing?"LSP is initializing, please retry later":this.projectPath?"LSP not initialized":"No project path configured; set the PROJECT_PATH parameter"}],isError:!0}}collectValidFiles(e,t){let n=Ie.resolve(this.projectPath),o=[];for(let i of e){let s=Ie.resolve(Ie.isAbsolute(i)?i:Ie.join(n,i));if(!pt.existsSync(s)){t.push(`File does not exist: ${i}`);continue}if(!pt.statSync(s).isFile()){t.push(`Not a regular file: ${i}`);continue}if(!s.endsWith(".ets")){t.push(`Not a .ets file: ${i}`);continue}o.push(s)}return o}async runDiagnosticsForFiles(e,t,n){for(let o of e){await bp(500);try{let i=await this.checkFile(o);n.push(PD(o,i))}catch(i){t.push(`${o} => wait for diagnostics failed: ${i.message}`)}}}formatCallResult(e,t){let n=[];e.length>0&&n.push(e.join(`
1310
- `)),t.length>0&&n.push(t.join(`
1311
- `));let o=n.join(`
1312
- `).trim(),i=e.length>0;return!i&&t.length===0&&(o="No diagnostics collected"),{content:[{type:"text",text:o}],isError:i}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){h.warn(`Failed to dispose ArktsLspManager: ${t}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,n=t.method;if(n)switch(n){case"textDocument/publishDiagnostics":{this.handleDiagnosticsNotification(t.params);break}case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(ot),h.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{h.info("Received arkts/initialized");let o=this.initResolve;this.clearInitHandlers(),o?.();break}case"arkts/initializationFailed":{let i=t.params?.message??"unknown";h.error(`LSP initialization failed: ${i}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${i}`));break}case"workspace/didChangeConfiguration":h.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let n=this.popDiagnosticWaiter(t);if(!n&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;n=this.popDiagnosticWaiter(s)}if(!n)return;if(typeof e.errorMessage=="string"){h.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),n.resolve({errorMessage:e.errorMessage});return}let o=e.diagnostics,i=Array.isArray(o)?o.length:0;h.debug(`diagnostics received uri=${t} count=${i}`),n.resolve(Array.isArray(o)?o:[])}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}getLogAndIndexPath(e){try{let t=Ie.join(rr(),"ArkTSCheck"),n=Ie.join(t,"mapping-config.properties"),o=Ep(e,n),i=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=Ie.join(t,"lsp-log",String(o),i),a=Ie.join(t,"lsp-index",String(o));return pt.mkdirSync(s,{recursive:!0}),pt.mkdirSync(a,{recursive:!0}),{logPath:ve(s),indexPath:ve(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function CD(r){if(Array.isArray(r))return r;if(r&&typeof r=="object"){let e=r;if(e.kind==="full"&&Array.isArray(e.items))return e.items}return[]}function PD(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)}`}import*as Pr from"fs";import*as mn from"path";import{z as Cd}from"zod";function ro(){return{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}function Wa(r,e){let t=e instanceof Error?e.message:String(e);return h.error(`[CppLsp] ${r} failed: ${t}`),{content:[{type:"text",text:`${r} failed: ${t}`}],isError:!0}}var AD=500,no=class{manager;constructor(e){this.manager=e}static getToolDefinition(){return{name:"check_cpp_files",description:"Perform static syntax checks on the provided C/C++ files and return clangd diagnostics.",inputSchema:Cd.object({files:Cd.array(Cd.string()).describe('List of C/C++ file paths to check, format: ["file1.cpp","file2.hpp",...]')})}}async handleCall(e){if(!this.manager.ready)return ro();let t=[],n=[],o=this.collectValidFiles(e.files,t);if(o.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
1313
- `):"No valid C/C++ files"}],isError:!0};for(let c of o){await kD(AD);try{let l=await this.checkFile(c);n.push(ID(c,l))}catch(l){t.push(`${c} => wait for diagnostics failed: ${l.message}`)}}let i=t.length>0,s=[];t.length>0&&s.push(t.join(`
1314
- `)),n.length>0&&s.push(n.join(`
1305
+ `,_O="6.1.0";function $O(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function FO(n){let e=n.trim();if(!xv.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${xv.join(", ")}`);return e}function Iv(n,e,t,r){let i=e.trim();if(!/^-?\d+$/.test(i))throw new Error(`${n} must be an integer in [${t}, ${r}].`);let o=Number(i);if(o<t||o>r)throw new Error(`${n} must be in [${t}, ${r}].`);return o}function Tv(n,e,t,r,i){let o=e.trim(),s=Number(o);if(!o||Number.isNaN(s))throw new Error(`${n} must be a number in [${t}, ${r}].`);if(i!==void 0&&!jO(o,i))throw new Error(`${n} supports at most ${i} decimal place(s).`);if(s<t||s>r)throw new Error(`${n} must be in [${t}, ${r}].`);return o}function jO(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function Yn(n,e,t,r,i){return Number(Tv(n,e,t,r,i))}var HO=["Name","Status","Serial","Device Type","OS Version"];function UO(n){return{cells:[n.name,n.status,n.serial??"-",n.deviceType??"-",n.osVersion??"-"],highlight:n.status==="running"}}async function BO(n,e){let t=await Promise.all(e.map(async r=>{let i=await Ei(n,r,NO);return[r,i]}));return new Map(t)}async function WO(n){let e=await sp(n),t=await BO(n,e);return{serials:e,params:t}}function VO(n,e,t,r,i){if(e)for(let o of["const.product.name","const.product.model"]){let s=e.get(o);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),i.set(s,n);let c=r.indexOf(n);c!==-1&&r.splice(c,1);return}}function GO(n,e,t){let r=new Map,i=new Map,o=[...n],s=[...t];for(let a of n){let c=e.get(a),l=c?.get("ohos.qemu.hvd.name");l&&i.set(l,a),t.length>0&&VO(a,c,s,o,r)}for(let a=0;a<s.length&&a<o.length;a++)r.set(s[a],o[a]);return{productSerialMap:r,hvdSerialMap:i}}function qO(n,e,t){let r=n.map(i=>({emu:i,serial:e.get(i.name)??t.get(i.name),effectiveRunning:i.isRunning===!0||t.has(i.name)}));return r.sort((i,o)=>i.effectiveRunning!==o.effectiveRunning?i.effectiveRunning?-1:1:i.emu.name.localeCompare(o.emu.name)),r.map(({emu:i,serial:o,effectiveRunning:s})=>({name:i.name,status:s?"running":"stopped",serial:o??null,deviceType:i.deviceType??null,osVersion:i.osVersion??null}))}async function zO(n,e,t,r){try{let[i,o]=await Promise.all([n.listEmulators(),WO(e)]);if(i.length===0){r?.stop(),console.log(t==="json"?"[]":tn(" No emulator instances found."));return}let s=i.filter(g=>g.isRunning).map(g=>g.name),{productSerialMap:a,hvdSerialMap:c}=GO(o.serials,o.params,s);r?.stop();let l=qO(i,a,c);if(t==="json"){console.log(JSON.stringify(l,null,2));return}let d=l.map(UO);console.log(Sr(HO,d))}catch(i){throw r?.stop(),new Error(`Failed to list emulators: ${i.message}`,{cause:i})}}function Ov(n,e,t){let r=!1;for(let i=0;i<n.length;i++){let o=n[i];if(o.status!=="rejected")continue;r=!0;let s=o.reason;console.error(sm(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(nm(s.stdout)),s.stderr&&console.error(nm(s.stderr))}return r}var JO=2e3,YO=6e4;async function KO(n,e){let t=Le(e);return(await ap(n)).some(i=>Le(i)===t)}async function Mv(n,e,t,r=YO,i=JO){let o=Date.now()+r;for(;Date.now()<o;){if(await KO(n,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}function XO(n){if(!n)return null;let e=n.indexOf("-bootmode");return e>=0&&e+1<n.length&&n[e+1]==="snapshot"}async function ZO(n,e,t,r){let i=await n.startEmulator(t,r);if(i.status==="already-running")return console.log(tn(`Emulator "${t}" is already running.`)),{started:!1,memoryBytes:0,hotBoot:null};console.log(Zi(`Starting emulator "${t}"...`));let o=i.tracker,s=0,a=XO(i.args);try{let c=await Mv(e,t,!0);console.log(c?xs(`Emulator "${t}" started successfully.`):tn(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}finally{if(o)try{s=await o.stop()}catch{}}return{started:!0,memoryBytes:s,hotBoot:a}}async function QO(n,e,t,r){let i=await Promise.allSettled(t.map(a=>ZO(n,e,a,r)));if(Ov(i,t,"start"))throw new y("One or more emulators failed to start.");let o=i.filter(a=>a.status==="fulfilled").map(a=>a.value).filter(a=>a.started);return{emulatorMemory:o.length===0||o.some(a=>a.memoryBytes===0)?"unknown":ce(o.reduce((a,c)=>a+c.memoryBytes,0)),hotBoot:o.length===0?null:o.every(a=>a.hotBoot===!0)}}async function Nv(n,e){let t=e.trim();if(!Jt(t))return t;let r=await le.withHdcPath(n).getDeviceName(t);if(r===t)throw new Error(`Cannot resolve a running emulator with serial "${t}". Use \`devecocli emulator list\` or pass the emulator name instead.`);return r}async function eM(n,e,t){let r=await Nv(e,t);if(console.log(Zi(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(tn(`Emulator "${r}" is already stopped.`));return}let o=await Mv(e,r,!1);console.log(o?xs(`Emulator "${r}" stopped successfully.`):tn(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function tM(n,e,t){let r=await Promise.allSettled(t.map(i=>eM(n,e,i)));Ov(r,t,"stop")}async function Pt(){let n=await P.new();return{manager:Bi.from(n),toolProvider:n}}async function kr(n,e,t){let r={event:v.CommandExecuted,args:["emulator",t,"--target"]};await Et(r,async()=>{let i=$O(n.target),o=e(),s=Array.isArray(o)?o:[o],{manager:a,toolProvider:c}=await Pt(),l=await Nv(c.hdcPath,i);for(let d of s)await a.controlEmulator(l,d);console.log(xs(`Emulator "${i}" operation completed.`))})}function rM(n){let e=[];if(el(e,"longitude",n.longitude,-180,180,8),el(e,"latitude",n.latitude,-90,90,8),el(e,"altitude",n.altitude,-1e4,1e4,2),el(e,"bearing",n.direction,0,359.99,2,"--direction"),e.length===0)throw new Error("Specify at least one geolocation option.");return(n.longitude===void 0||n.latitude===void 0)&&console.warn(tn("Warning: --longitude and --latitude should be specified together to form a valid location.")),e}function nM(n){let e=[];if(Rs(e,"light",n.lightIntensity,0,1e5,!1,"--light-intensity"),Rs(e,"humidity",n.humidity,0,100,!1),Rs(e,"temperature",n.temperature,-273.1,100,!1),Rs(e,"steps",n.steps,0,1e4,!0),Rs(e,"heartrate",n.heartrate,0,255,!0),e.length===0)throw new Error("Specify at least one sensor option.");return e}function el(n,e,t,r,i,o,s=`--${e}`){t!==void 0&&n.push({type:"gps",key:e,value:Tv(s,t,r,i,o)})}function Rs(n,e,t,r,i,o,s=`--${e}`){if(t===void 0)return;let a=o?Iv(s,t,r,i):Yn(s,t,r,i,1);n.push({type:"sensor",key:e,value:a})}function iM(n){let e=[];if(n.status!==void 0){let i=n.status==="charging"?1:0;e.push({type:"battery-status",status:i})}if(n.level!==void 0&&e.push({type:"battery",level:Iv("--level",n.level,0,100),assumedCharging:n.status==="charging"}),e.length===0)throw new Error("Specify --level or --status.");let t=e.some(i=>i.type==="battery"&&i.level===0),r=e.some(i=>i.type==="battery-status"&&i.status===0);if(t&&r)throw new Error("Battery level 0 is only allowed while charging; --level 0 cannot be combined with --status discharging.");return e}var Se=new om("emulator").description("Manage emulator instances");Se.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
1306
+ ${tn("Tip: ")}${nm("An option value containing spaces/parentheses must be quoted. Use:")}
1307
+ ${Zi('devecocli emulator <subcommand> --<option> "value with spaces"')}
1308
+ ${Zi('devecocli emulator <subcommand> --<option>="value with spaces"')}
1309
+ `)}});Se.hook("preAction",async()=>{(await P.new()).require({studio:_O})});var oM=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function am(n){let e=new We("--device-type <type>","Emulator device type").choices([...oM]);return n?e.makeOptionMandatory():e}function sM(){return new We("--device-type <type>","Emulator device type (case-insensitive)").argParser(n=>{if(!n.trim())throw new rm("--device-type must not be empty.");return n}).makeOptionMandatory()}function aM(n){if(n!==void 0){if(n.length>=4&&n.length%4===0&&n.every(e=>/^\d+(?:\.\d+)?$/.test(e)))throw new Error('--screen value must be quoted: --screen "1316 2832 560 6.9".');if(n.length>2)throw new Error("--screen accepts one or two configurations.");for(let[e,t]of n.entries()){let r=t.trim().split(/\s+/),i=n.length===1?"--screen":`--screen configuration ${e+1}`;if(r.length!==4||r.some(o=>o.length===0))throw new Error(`${i} must contain four values: width(px), height(px), DPI, and screen diagonal length(inch).`);Yn(`${i} width`,r[0],720,3500),Yn(`${i} height`,r[1],720,3500),Yn(`${i} DPI`,r[2],240,640),Yn(`${i} screen diagonal length`,r[3],3.5,9)}return n}}function cM(n){return["--device-type","--os-version",...n.instancePath!==void 0?["--instance-path"]:[],...n.imageRoot!==void 0?["--image-root"]:[],...n.screenProfile!==void 0?["--screen-profile"]:[],...n.screen!==void 0?["--screen"]:[],...n.storage!==void 0?["--storage"]:[],...n.memory!==void 0?["--memory"]:[],...n.hotBoot!==void 0?["--hot-boot"]:[],...n.force?["--force"]:[]]}function Xi(n,e){for(let t of e)if(t in n)return n[t]}function Ds(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function Av(n){let e=Ds(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var lM=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],dM="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";async function uM(n,e,t){if(!await n.hasAvailableEmulatorImage({deviceType:e,osVersion:t}))throw new Error(`Invalid --os-version value "${t}".
1310
+ Run \`devecocli emulator image list --all\` and use an exact OS Version value.`)}function Lv(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function _v(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let i=r,o=Ds(Xi(i,["osVersion","OsVersion","OSVersion","os_version"])),s=Ds(Xi(i,["deviceType","DeviceType","device_type"])),a=Av(Xi(i,["downloaded","Downloaded","isDownloaded"])),c=Ds(Xi(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=Ds(Xi(i,["releaseType","ReleaseType","release_type"])),d=Av(Xi(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,l,d,a],highlight:e&&a==="true"})}return t}function pM(n){let e=n.trim();if(!e)return!0;let t=Lv(e);return t===null?!1:t.length===0?!0:_v(t,!0).length===0}function mM(n,e){let t=n.trim();if(!t)return"";let r=Lv(t);if(!r)return n.trimEnd();let i=_v(r,e);return Sr(lM,i)}var tl=new om("image").description("HarmonyOS emulator system images (download, list, remove)");tl.command("download").description("Download system image").addOption(am(!1)).option("--os-version <version>","Example: HarmonyOS 5.1.1(19) or HarmonyOS 6.0.1(21) (required)").option("--force","Overwrite an existing image").action(async n=>{let e={event:v.CommandExecuted,args:["emulator","image","download",...n.deviceType?["--device-type"]:[],...n.osVersion?["--os-version"]:[],...n.force?["--force"]:[]]};await Et(e,async()=>{let{manager:t,toolProvider:r}=await Pt();await tm(r.emulatorPath,r.sdkPath);let i=n.deviceType?.trim(),o=n.osVersion?.trim();if(!i)throw new y("Error: missing required option '--device-type <type>'","Missing required device type.");if(!o)throw new y("Error: misssing required option '--os-version <version>'","Missing required OS version.");await uM(t,i,o),await t.installEmulatorImage({deviceType:i,osVersion:o,force:n.force===!0})})});tl.command("remove").description("Remove a downloaded system image").addOption(am(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let e={event:v.CommandExecuted,args:["emulator","image","remove","--device-type","--os-version"]};await Et(e,async()=>{let{manager:t}=await Pt();await t.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})})});tl.command("list").description("List system images").addOption(am(!1)).option("--all","List all images (local and remote)").addOption(new We("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:v.CommandExecuted,args:["emulator","image","list",...n.deviceType?["--device-type"]:[],...n.all?["--all"]:[],...n.format!=="table"?["--format"]:[]]};await Et(e,async()=>{let{manager:t}=await Pt(),r;n.all?r=void 0:r=!0;let i=await t.listEmulatorImages({deviceType:n.deviceType,downloaded:r});if(pM(i)){console.log(tn(dM));return}if(n.format==="json"){console.log(i.trimEnd());return}let o=mM(i,n.all===!0);console.log(o)})});Se.addCommand(tl);var rl=new om("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");rl.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let n={event:v.CommandExecuted,args:["emulator","license","view"]};await Et(n,async()=>{let{toolProvider:e}=await Pt(),t=await Cv(e.emulatorPath,e.sdkPath);process.exitCode=t})});rl.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let n={event:v.CommandExecuted,args:["emulator","license","accept"]};await Et(n,async()=>{let{toolProvider:e}=await Pt(),t=await Dv(e.emulatorPath,e.sdkPath);process.exitCode=t})});rl.action(async()=>{let n={event:v.CommandExecuted,args:["emulator","license"]};await Et(n,async()=>{let{toolProvider:e}=await Pt(),t=await Rv(e.emulatorPath,e.sdkPath);process.exitCode=t})});Se.addCommand(rl);Se.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>kr(n,()=>({type:"shake"}),"shake"));Se.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>kr(n,()=>({type:"power"}),"power"));Se.command("rotate").description("Rotate emulator").addOption(new We("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new im("<direction>").choices(["left","right"])).action((n,e)=>kr(e,()=>({type:"rotation",direction:n}),"rotate"));Se.command("volume").description("Change volume").addOption(new We("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new im("<direction>").choices(["up","down"])).action((n,e)=>kr(e,()=>({type:"volume",direction:n}),"volume"));Se.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",LO).action((n,e)=>kr(e,()=>({type:"folded-state",state:FO(n)}),"fold"));Se.command("battery").description("Set battery level and/or charging status").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--level <0-100>","Battery level, SOC (charging: 0-100; not charging: 1-100)").addOption(new We("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>kr(n,()=>iM(n),"battery"));Se.command("geolocation").description("Inject geographic coordinates and direction").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--longitude <value>","Longitude (-180.0 to 180.0)").option("--latitude <value>","Latitude (-90.0 to 90.0)").option("--altitude <value>","Altitude (-10000.0 to 10000.0)").option("--direction <value>","Heading direction in degrees (0.00 to 359.99)").action(n=>kr(n,()=>rM(n),"geolocation"));Se.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new im("<type>","Motion simulation scene").choices(["outdoorRunning","outdoorCycling","drivingNavigation"])).action((n,e)=>{let t={outdoorRunning:{type:"outdoor-running"},outdoorCycling:{type:"outdoor-cycling"},drivingNavigation:{type:"driving-navigation"}};return kr(e,()=>t[n],"scene")});Se.command("sensor").description("Inject sensor data").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--light-intensity <value>","Light sensor (0 to 100000)").option("--humidity <value>","Humidity sensor (0 to 100)").option("--temperature <value>","Temperature sensor (-273.1 to 100)").option("--steps <value>","Steps sensor (integer 0 to 10000)").option("--heartrate <value>","Heart rate sensor (integer 0 to 255)").action(n=>kr(n,()=>nM(n),"sensor"));Se.command("list").description("List all emulator instances").addOption(new We("--details","Output the raw JSON of `Emulator -list -details` without transformation").conflicts("format")).addOption(new We("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:v.CommandExecuted,args:["emulator","list",...n.details?["--details"]:[],...n.format!=="table"?["--format"]:[]]};await Et(e,async()=>{let{manager:t,toolProvider:r}=await Pt();if(n.details){let o=await t.listEmulatorDetails();console.log(o.trimEnd());return}let i=n.format==="table"?MO({text:"Listing emulators\u2026",color:"cyan"}).start():void 0;await zO(t,r.hdcPath,n.format,i)})});function fM(n){let e=n.trim();if(!/^\d+$/.test(e))throw new rm("--hdcport must be an integer in [10000, 16555].");let t=Number(e);if(t<1e4||t>16555)throw new rm("--hdcport must be in [10000, 16555].");return t}function hM(n){return{hdcPort:n.hdcport,bootMode:n.bootMode,noWindow:n.window===!1}}function gM(n){return[...n.hdcport!==void 0?["--hdcport"]:[],...n.bootMode!==void 0?["--boot-mode"]:[],...n.window===!1?["--no-window"]:[]]}Se.command("start [names...]").description("Start one or more emulator instances").addOption(new We("--hdcport <port>","hdc port of the emulator, 10000-16555 (Emulator -hdcport)").argParser(fM)).addOption(new We("--boot-mode <mode>","Boot mode (Emulator -bootMode): coldboot = cold start keeping user data, snapshot = hot start restoring the last snapshot (needs Quick Boot), reset = wipe data then cold start; overrides the mode chosen when the instance was created").choices(["coldboot","snapshot","reset"])).addOption(new We("--no-window","Start the emulator without a window (Emulator -noWindow); required on Linux hosts without a GUI")).action(async(n,e)=>{let t={event:v.CommandExecuted,args:["emulator","start",...gM(e)],emulatorMemory:"unknown",hotBoot:null};await Et(t,async()=>{let{manager:r,toolProvider:i}=await Pt();if(await em(i.emulatorPath,i.sdkPath),!n?.length)throw new y("Error: missing required argument 'names'","Missing required emulator name.");if(n.length>1&&e.hdcport!==void 0)throw new y(`Error: --hdcport cannot target ${n.length} emulators.`,"--hdcport sets the hdc port of a single emulator; pass one name, or omit --hdcport.");let o=await QO(r,i.hdcPath,n,hM(e));t.emulatorMemory=o.emulatorMemory,t.hotBoot=o.hotBoot})});Se.command("stop <names...>").description("Stop one or more emulator instances (by name or serial,e.g.,127.0.0.1:<port>)").action(async n=>{let e={event:v.CommandExecuted,args:["emulator","stop"]};await Et(e,async()=>{let{manager:t,toolProvider:r}=await Pt();if(!n?.length){console.error(sm("Error: missing required argument 'names'")),process.exitCode=1;return}await tM(t,r.hdcPath,n)})});var yM=Se.command("create <name>").description("Create a local emulator instance.").addOption(sM()).requiredOption("--os-version <version>",'Downloaded image label. which will be quoted in PowerShell (e.g. "HarmonyOS 6.0.1(21)") or be used in the format --os-version="\u2026";For details, run`devecocli emulator image list`').addOption(new We("--path, --instance-path <path>","Emulator instance path")).option("--image-root <path>","Emulator image path").option("--screen-profile <model>","Emulator screen profile").addOption(new We("--screen <config...>",'Screen: "width(px) height(px) DPI screen-diagonal-length(inch)" (720-3500, 720-3500, 240-640, 3.5-9); pass two values for a foldable device')).option("--storage <size>","Storage size in GB (2-1023)").option("--memory <size>","Memory size in GB (2-32)").addOption(new We("--hot-boot <boolean>","Enable or disable hot boot").choices(["true","false"])).option("--force","Overwrite an existing emulator instance");yM.action(async(n,e)=>{let t={event:v.CommandExecuted,args:["emulator","create",...cM(e)]};await Et(t,async()=>{if(!e.osVersion.trim())throw new Error("--os-version must not be empty.");let r={name:n,deviceType:e.deviceType,osVersion:e.osVersion,instancePath:e.instancePath,imageRoot:e.imageRoot,screenProfile:e.screenProfile,screen:aM(e.screen),storage:e.storage===void 0?void 0:Yn("--storage",e.storage,2,1023),memory:e.memory===void 0?void 0:Yn("--memory",e.memory,2,32),hotBoot:e.hotBoot===void 0?void 0:e.hotBoot==="true",force:e.force===!0},{manager:i}=await Pt();console.log(Zi(`Creating emulator "${n}"...`)),await i.createVirtualDevice(r),console.log(xs(`Emulator "${n}" created successfully.`))})});Se.command("delete <name>").description("Delete a local emulator instance").addOption(new We("--path, --instance-path <path>","Emulator instance path")).action(async(n,e)=>{let t={event:v.CommandExecuted,args:["emulator","delete",...e.instancePath!==void 0?["--instance-path"]:[]]};await Et(t,async()=>{let{manager:r}=await Pt();console.log(Zi(`Deleting emulator "${n}"...`));let i=await r.deleteVirtualDevice(n,e.instancePath);console.log(xs(`Emulator "${i}" deleted successfully.`))})});var $v=Se;import{Command as zM}from"commander";import{red as ym,cyan as Ft}from"colorette";import*as pb from"readline";import*as db from"crypto";import*as Fv from"http";import*as jv from"crypto";import{URL as wM}from"url";var nl=class{server=null;port=0;clientSecret;callbackPath="/callback";resolveCallback=null;rejectCallback=null;timeoutId=null;baseUrl;successRedirectUrl;failedRedirectUrl;constructor(e,t,r,i){this.clientSecret=e,this.baseUrl=t,this.successRedirectUrl=r,this.failedRedirectUrl=i}async start(){return new Promise((e,t)=>{let r=Fv.createServer((i,o)=>{this.handleRequest(i,o)});r.keepAliveTimeout=1,r.on("error",i=>{t(new Error("Failed to start local auth server",{cause:i}))}),r.listen(0,"127.0.0.1",()=>{this.server=r;let i=r.address();this.port=i.port,e()})})}async waitForCallback(e=3e4){return new Promise((t,r)=>{this.resolveCallback=i=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),t(i)},this.rejectCallback=i=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),r(i)},this.timeoutId=setTimeout(()=>{this.timeoutId=null,this.rejectCallback?.(new Error("Callback timeout"))},e)})}async stop(){return this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.server?new Promise(e=>{let t=this.server;this.server=null,typeof t.closeAllConnections=="function"&&t.closeAllConnections();let r=setTimeout(()=>{e()},100);t.close(()=>{clearTimeout(r),e()})}):Promise.resolve()}handleRequest(e,t){let r=e.headers.host||"";if(![`127.0.0.1:${this.port}`,`localhost:${this.port}`].includes(r.toLowerCase())){t.writeHead(400),t.end("Bad Host");return}let o=new wM(e.url??"",`http://${r}`);if(o.pathname!==this.callbackPath){t.writeHead(404),t.end("Not Found");return}try{let s=o.searchParams;e.method==="POST"?this.readBody(e,t,s):this.handleCallbackRequest(e,t,s,"")}catch(s){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(s)}}readBody(e,t,r){let i="",o=0,s=65536;e.on("data",a=>{if(o+=a.length,o>s){e.destroy(new Error("Request body too large"));return}i+=a.toString()}),e.on("end",()=>{this.handleCallbackRequest(e,t,r,i)})}handleCallbackRequest(e,t,r,i){try{let o=this.parseParams(r,i),s=o.get("code"),a=o.get("tempToken"),c=o.get("siteId"),l=o.get("quit");if(!this.validateCode(s)){t.writeHead(400),t.end("Bad Request");return}if(this.isQuitRequest(l)){this.handleQuitRequest(t);return}if(!a||!c){t.writeHead(400),t.end("Bad Request");return}let d={tempToken:a,siteId:c,quit:l??void 0};this.resolveCallback?.(d),this.sendSuccessResponse(t)}catch(o){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(o)}}parseParams(e,t){return t&&t.trim()?new URLSearchParams(t):e}validateCode(e){let t=Buffer.from(e||"","utf8"),r=Buffer.from(this.clientSecret,"utf8");return t.length===r.length&&jv.timingSafeEqual(t,r)}isQuitRequest(e){return e==="true"||e==="access_denied"||e==="quit"}handleQuitRequest(e){this.rejectCallback?.(new Error("User quit the login process")),e.writeHead(302,{Location:`${this.baseUrl}/${this.failedRedirectUrl}`}),e.end()}sendSuccessResponse(e){e.writeHead(302,{Location:`${this.baseUrl}/${this.successRedirectUrl}`}),e.end()}getPort(){return this.port}};import*as rt from"fs";import*as rn from"path";import{homedir as EM}from"os";var Rr={};KP(Rr,{LocalCrypto:()=>Rr,decryptForLocalStorage:()=>um,decryptForLocalStorageFromDirectory:()=>SM,encryptForLocalStorage:()=>dm,isEncryptedBlob:()=>pm});import*as pe from"fs";import*as Ge from"path";import*as tt from"crypto";import*as Uv from"os";import{homedir as Bv}from"os";var Ve=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var As=Dn.ALGORITHM,Wv=Dn.IV_LENGTH,Is=Dn.KEY_LENGTH,Ts=Dn.KEY_LENGTH,Kn=Dn.KEK_VERSIONS,il=process.env.DEVECO_CLI_DATA_DIR?W():Ge.join(Bv(),be.CONFIG_DIR_NAME,be.APP_NAME),ol=Ge.join(Bv(),".local","share",be.APP_NAME,"keys"),Qi=Ge.join(il,be.KEY_FILE_NAME);function Hv(n){return Uv.platform()==="win32"?`Permission denied. Please run as administrator or grant write permission to ${n}.`:`Permission denied. You can try: sudo chown -R $(whoami) ${n}`}function cm(n){return Ge.join(ol,`${n}.bin`)}function Vv(){if(!pe.existsSync(il))try{pe.mkdirSync(il,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new Ve(Hv(il)):n}if(!pe.existsSync(ol))try{pe.mkdirSync(ol,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new Ve(Hv(Ge.dirname(ol))):n}}function Gv(){Vv();for(let n of Kn){let e=cm(n);pe.existsSync(e)||pe.writeFileSync(e,tt.randomBytes(Is),{mode:384})}}function qv(n){if(!Kn.includes(n))throw new Error(`Invalid kekId: ${n}`);Gv();let e=cm(n),t=pe.readFileSync(e);if(t.length===Is)return t;let r=tt.randomBytes(Is);return pe.writeFileSync(e,r,{mode:384}),r}function lm(n,e){let t=tt.randomBytes(Wv),r=qv(e),i=tt.createCipheriv(As,r,t),o=Buffer.concat([i.update(n),i.final()]),s=i.getAuthTag();return{version:1,algorithm:As,kekId:e,encryptedDek:o.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function zv(n,e){return Jv(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function Jv(n,e,t,r){let i=tt.createDecipheriv(As,e,Buffer.from(t,"base64"));return i.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([i.update(n),i.final()])}function Yv(n,e){return Jv(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function vM(){if(Gv(),pe.existsSync(Qi))return;let n=tt.randomBytes(Ts),e=lm(n,Kn[0]);pe.writeFileSync(Qi,JSON.stringify(e,null,2),{mode:384})}function Kv(){vM();let n=JSON.parse(pe.readFileSync(Qi,"utf8")),e=zv(n,qv(n.kekId));if(e.length===Ts)return e;let t=tt.randomBytes(Ts),r=lm(t,Kn[0]);return pe.writeFileSync(Qi,JSON.stringify(r,null,2),{mode:384}),t}function bM(){Vv();for(let t of Kn){let r=cm(t);pe.existsSync(r)||pe.writeFileSync(r,tt.randomBytes(Is),{mode:384})}if(pe.existsSync(Qi))return;let n=tt.randomBytes(Ts),e=lm(n,Kn[0]);pe.writeFileSync(Qi,JSON.stringify(e,null,2),{mode:384})}function dm(n){let e=Kv(),t=tt.randomBytes(Wv),r=tt.createCipheriv(As,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o=r.getAuthTag();return{version:1,algorithm:As,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:o.toString("base64"),timeStamp:Date.now()}}function um(n){try{return Yv(n,Kv())}catch{throw bM(),new Error("Failed to decrypt local ciphertext")}}function SM(n,e){let t=Ge.join(e,be.KEY_FILE_NAME),r=JSON.parse(pe.readFileSync(t,"utf8"));if(!Kn.includes(r.kekId))throw new Error(`Invalid kekId: ${r.kekId}`);let i=Ge.join(e,"keys",`${r.kekId}.bin`),o=Ge.resolve(i),s=Ge.resolve(Ge.join(e,"keys"));if(!o.startsWith(s+Ge.sep)&&o!==s)throw new Error("kekId resolves outside the keys directory");let a=pe.readFileSync(o);if(a.length!==Is)throw new Error("Invalid external root key");let c=zv(r,a);if(c.length!==Ts)throw new Error("Invalid external data encryption key");return Yv(n,c)}function pm(n){if(!n||typeof n!="object")return!1;let e=n;return e.algorithm==="aes-256-gcm"&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}function nt(){return process.env.DEVECO_CLI_AUTH_SOURCE===be.AUTH_SOURCE_DEVECO_CODE}var sl=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR?W():rn.join(EM(),be.CONFIG_DIR_NAME,be.APP_NAME);return rn.join(e,be.TOKEN_FILE_NAME)}ensureConfigDir(){let e=rn.dirname(this.getLocalTokenFilePath());rt.existsSync(e)||rt.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=Rr.encryptForLocalStorage(e);this.ensureConfigDir();let r=this.getLocalTokenFilePath();rt.writeFileSync(r,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return nt()?this.loadDevecoCodeToken():this.loadLocalJwtToken()}loadDevecoCodeToken(){if(!nt())return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;let t=rn.resolve(e);try{let r=rn.join(t,be.TOKEN_FILE_NAME);if(!rt.existsSync(r))return null;let i=JSON.parse(rt.readFileSync(r,"utf8"));return Rr.isEncryptedBlob(i)?Rr.decryptForLocalStorageFromDirectory(i,e):null}catch{return null}}async loadLocalJwtToken(){let e=this.getLocalTokenFilePath();try{if(!rt.existsSync(e))return null;let t=JSON.parse(rt.readFileSync(e,"utf8"));return Rr.isEncryptedBlob(t)?Rr.decryptForLocalStorage(t):null}catch(t){let r=t.code;return r==="EACCES"||r==="EPERM"||r==="ENOENT"||await this.clearToken(),null}}async clearToken(){if(nt()){m("clearToken: skipped, session managed by DevEco Code");return}let e=this.getLocalTokenFilePath();try{rt.existsSync(e)&&rt.unlinkSync(e)}catch(t){throw new Error("Failed to clear token",{cause:t})}}},Dr=new sl;import{spawn as PM}from"child_process";function CM(n){try{let e=new URL(n);return!(!["http:","https:"].includes(e.protocol)||e.hostname===""||n.includes('"'))}catch{return!1}}function kM(n){return n.replace(/[&|<>()^%!]/g,e=>`^${e}`)}async function Xv(n){if(!CM(n))throw new Error(`Invalid URL: ${JSON.stringify(n)}`);let e,t;switch(process.platform){case"win32":e="cmd",t=["/c","start",'""',kM(n)];break;case"darwin":e="open",t=[n];break;default:e="xdg-open",t=[n];break}let r=PM(e,t,{stdio:"ignore",shell:!1,windowsHide:!0});return new Promise((i,o)=>{r.on("error",s=>{o(new Error("Failed to open browser",{cause:s}))}),r.on("close",s=>{s===0?i():o(new Error(`Browser process exited with code ${s}`))})})}import _M from"axios";var RM={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function DM(n){try{return new URL(n)}catch{return null}}function Zv(n){var e=(typeof n=="string"?DM(n):n)||{},t=e.protocol,r=e.host,i=e.port;if(typeof r!="string"||!r||typeof t!="string"||(t=t.split(":",1)[0],r=r.replace(/:\d*$/,""),i=parseInt(i)||RM[t]||0,!xM(r,i)))return"";var o=mm(t+"_proxy")||mm("all_proxy");return o&&o.indexOf("://")===-1&&(o=t+"://"+o),o}function xM(n,e){var t=mm("no_proxy").toLowerCase();return t?t==="*"?!1:t.split(/[,\s]/).every(function(r){if(!r)return!0;var i=r.match(/^(.+):(\d+)$/),o=i?i[1]:r,s=i?parseInt(i[2]):0;return s&&s!==e?!0:/^[.*]/.test(o)?(o.charAt(0)==="*"&&(o=o.slice(1)),!n.endsWith(o)):n!==o}):!0}function mm(n){return process.env[n.toLowerCase()]||process.env[n.toUpperCase()]||""}import{spawn as tb}from"child_process";import*as Xn from"fs";import*as rb from"os";import*as al from"path";var nb=6e4;async function AM(){if(process.platform!=="win32")return null;let n="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",e=await Qv(n,"ProxyServer");if(!e)return null;let t=await Qv(n,"ProxyEnable");return t!=="1"&&t!=="0x1"?null:e.trim()}function Qv(n,e){return new Promise(t=>{let r=tb("reg.exe",["query",n,"/v",e],{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),i="";r.stdout.on("data",o=>{i+=o.toString()}),r.on("error",()=>t(null)),r.on("close",o=>{if(o!==0){t(null);return}let s=/REG_\w+\s+(\S+)/.exec(i);t(s?s[1]:null)})})}function IM(){let n=process.env.HTTPS_PROXY??process.env.HTTP_PROXY??"";if(!n)return null;try{return new URL(n).host}catch{return n}}function TM(){return`${process.env.SystemRoot??"C:\\Windows"}\\System32\\curl.exe`}function eb(n){let e={},t=0,r="";for(let i of n.split(/\r?\n/)){let o=i.trim();if(!o)continue;let s=/^HTTP\/\d(?:\.\d)?\s+(\d{3})\s*(.*)$/.exec(o);if(s){t=parseInt(s[1],10),r=s[2]??"";continue}let a=/^([^:]+):\s*(.*)$/.exec(o);a&&(e[a[1].toLowerCase()]=a[2])}return{statusCode:t,statusText:r,headers:e}}function OM(n,e,t,r){let i=["--silent","--show-error","--location","--ssl-no-revoke","--insecure","-x",`http://${e}`,"--proxy-ntlm","--proxy-user",":","--max-time",String(Math.max(1,Math.floor((n.timeoutMs??nb)/1e3)))];return n.method&&n.method!=="GET"&&i.push("-X",n.method),n.data!==void 0&&i.push("--data-binary",n.data),i.push(...MM(n.headers,n.data!==void 0)),r?(i.push("--dump-header",t),i.push("--output",r)):i.push("--include"),i.push(n.url),i}function MM(n,e){let t=new Set(["content-length","host","connection","proxy-authorization","proxy-connection","accept-encoding"]),r=[],i=!1;for(let[o,s]of Object.entries(n??{})){let a=o.toLowerCase();a==="content-type"&&(i=!0),t.has(a)||r.push("-H",`${o}: ${s}`)}return e&&!i&&r.push("-H","Content-Type: application/json"),r}function NM(n,e,t){if(t){let l=Xn.readFileSync(e,"utf8"),d=Xn.readFileSync(t),g=eb(l);return{statusCode:g.statusCode,statusText:g.statusText,body:d.toString("base64"),headers:g.headers,bodyBuffer:d}}let r=n.lastIndexOf("HTTP/");if(r===-1)return null;let i=n.slice(r),o=i.indexOf(`\r
1311
+ \r
1312
+ `);if(o===-1)return null;let s=i.slice(0,o),a=i.slice(o+4),c=eb(s);return{statusCode:c.statusCode,statusText:c.statusText,body:a,headers:c.headers}}async function ib(n){if(process.platform!=="win32")return null;let e=IM()??await AM();if(!e)return null;let t;n.binary&&(t=Xn.mkdtempSync(al.join(rb.tmpdir(),"curl-")));let r=t?al.join(t,"header.tmp"):void 0,i=t?al.join(t,"body.tmp"):void 0;try{let o=OM(n,e,r,i),s=await LM(o,n.timeoutMs);return!s||s.code!==0?null:NM(s.stdout,r,i)}catch{return null}finally{t&&Xn.rmSync(t,{recursive:!0,force:!0})}}function LM(n,e){let t=TM();return new Promise(r=>{let i=tb(t,n,{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),o="",s=!1,a=setTimeout(()=>{s||(s=!0,i.kill())},e??nb);i.stdout.on("data",c=>{o+=c.toString()}),i.on("error",()=>{s||(s=!0,clearTimeout(a),r(null))}),i.on("close",c=>{if(clearTimeout(a),s){r(null);return}s=!0,r({code:c??-1,stdout:o})})})}function $M(n){let e=new URL(n);return{protocol:e.protocol,host:e.hostname,port:e.port?Number.parseInt(e.port,10):e.protocol==="https:"?443:80,auth:{username:decodeURIComponent(e.username),password:decodeURIComponent(e.password)}}}var fm=class{client;constructor(){let e={timeout:Ro.HTTP_TIMEOUT_MS,headers:{"User-Agent":ua.USER_AGENT,"accept-language":ua.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=_M.create(e),this.client.interceptors.request.use(t=>{let r=Zv(t.url??"");return t.proxy=r?$M(r):!1,t}),this.client.interceptors.response.use(t=>t,t=>{let r=`Network connection failed (${t.code}). Please check your proxy configuration or network settings`,i=new Error(`${t.message}
1313
+ ${r}`);throw i.code=t.code,i.response=t.response,i})}async get(e,t){try{let r=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}catch(r){return this.withCurlFallback(r,e,"GET",t)}}async post(e,t){try{let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}catch(r){return this.withCurlFallback(r,e,"POST",t)}}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,statusText:e.statusText??"",headers:e.headers}}parseJson(e){try{return JSON.parse(e.data)}catch(t){throw new Error(`Failed to parse JSON response: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}async getBinary(e,t){try{let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout});if(r.status!==200)throw new Error(`HTTP ${r.status}`);return Buffer.from(r.data)}catch(r){let i=await this.tryCurlFallback(r,e,"GET",t,!0);if(i?.bodyBuffer){if(i.statusCode!==200)throw new Error(`HTTP ${i.statusCode}`);return i.bodyBuffer}throw r}}async postAllowFailure(e,t){try{let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});if(r.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});return this.convertResponse(r)}catch(r){return this.withCurlFallback(r,e,"POST",t)}}async deleteAllowFailure(e,t){try{let r=await this.client.request({method:"DELETE",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});if(r.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});return this.convertResponse(r)}catch(r){return this.withCurlFallback(r,e,"DELETE",t)}}async getBinaryAllowFailure(e,t){try{let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});if(r.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});let i=Buffer.from(r.data),o=i.toString("utf8");return{statusCode:r.status,statusText:r.statusText??"",buffer:i,body:o}}catch(r){let i=await this.tryCurlFallback(r,e,"GET",t,!0);if(i?.bodyBuffer)return{statusCode:i.statusCode,statusText:i.statusText,buffer:i.bodyBuffer,body:i.bodyBuffer.toString("utf8")};throw r}}async withCurlFallback(e,t,r,i){let o=await this.tryCurlFallback(e,t,r,i,!1);if(o)return{data:o.body,statusCode:o.statusCode,statusText:o.statusText,headers:o.headers};throw e}async tryCurlFallback(e,t,r,i,o=!1){if(process.platform!=="win32"||!(e instanceof Error)||!FM(e))return null;let s,a=t;return r==="GET"?i?.params&&(a=jM(t,i.params)):i?.params!==void 0&&i.params!==null&&(s=typeof i.params=="string"?i.params:JSON.stringify(i.params)),ib({url:a,method:r,data:s,headers:i?.headers,timeoutMs:i?.timeout,binary:o})}},$=new fm;function FM(n){if(n.response?.status===407)return!0;let e=n.message??"";return/proxy auth(?:oriz|entic)/i.test(e)?!0:n.code==="SELF_SIGNED_CERT_IN_CHAIN"||n.code==="DEPTH_ZERO_SELF_SIGNED_CERT"||n.code==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||n.code==="CERT_HAS_EXPIRED"||n.code==="ERR_TLS_CERT_ALTNAME_INVALID"}function jM(n,e){if(!e||typeof e!="object")return n;let t=new URLSearchParams;for(let[o,s]of Object.entries(e))if(s!=null)if(Array.isArray(s))for(let a of s)t.append(`${o}[]`,String(a));else t.append(o,String(s));let r=t.toString();if(!r)return n;let i=n.includes("?")?"&":"?";return`${n}${i}${r}`}function ob(n){let e=n.split(".");return e.length===3&&e.every(t=>t.length>0)}var xr={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},Zn={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},cl={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},HM={[xr.CHINA]:Zn.CHINA,[xr.RUSSIA]:Zn.RUSSIA,[xr.EUROPE]:Zn.EUROPE,[xr.SINGAPORE]:Zn.CHINA},UM={[cl.CHINA]:xr.CHINA,[cl.SINGAPORE]:xr.SINGAPORE,[cl.EUROPE]:xr.EUROPE,[cl.RUSSIA]:xr.RUSSIA};function sb(n){return HM[n]??Zn.CHINA}function ab(n){return UM[n]??xr.CHINA}var hm=class{async getJwtToken(e,t,r,i,o){let s=e.split("&")[0],a=ab(t),c={tempToken:s,site:a,version:be.API_VERSION,appid:o},l=`${r}/${i}`,d=await $.get(l,{params:c});if(d.statusCode!==200)throw new Error(`Failed to get jwtToken: status=${d.statusCode}`);let g=d.data.trim();if(!ob(g))throw new Error("Invalid jwtToken format");return g}},cb=new hm;var gm=class{async checkJwtToken(e,t,r=!1){let i={refresh:String(r),jwtToken:e},o=`${t}/${oe.JWT_TOKEN_CHECK_PATH}`,s=await $.get(o,{headers:i});if(s.statusCode!==200)throw new Error(`Failed to check jwtToken: ${s.statusCode}`);return $.parseJson(s)}async refreshToken(e){let t=await Dr.loadJwtToken();return t?this.refreshTokenWithToken(t,e):null}async refreshTokenWithToken(e,t){try{let r={refresh:"true",jwtToken:e},i=`${t}/${oe.JWT_TOKEN_CHECK_PATH}`,o=await $.get(i,{headers:r});if(o.statusCode!==200)return null;let s=$.parseJson(o);return!s.status||!s.userInfo?null:{accessToken:s.userInfo.accessToken,refreshToken:s.userInfo.refreshToken??""}}catch(r){let i=r;return console.error(`Failed to refresh token: ${i.code??""} ${i.message??""}`),null}}async getUserInfoFromJwt(e,t,r=!1){let i=await this.checkJwtToken(e,t,r);return!i.status||!i.userInfo||!i.userInfo.accessToken?(m("jwtToken invalid."),await Dr.clearToken(),null):{userId:i.userInfo.userId??"",userName:i.userInfo.name??"",accessToken:i.userInfo.accessToken,refreshToken:i.userInfo.refreshToken??"",jwtToken:e,countryCode:i.userInfo.nationalCode,language:sb(i.userInfo.nationalCode),isRealName:String(i.userInfo.realName)==="true"}}async fetchUserInfo(e,t){let r=await Dr.loadJwtToken();return r?this.getUserInfoFromJwt(r,e,t):null}},eo=new gm;import BM from"querystring";import{spawn as WM}from"child_process";function lb(n){try{let e=JSON.stringify({signInfo:[{agrType:Do.PRIVACY_ID,country:"CN",language:"zh_CN",isAgree:!0}]}),t=BM.stringify({nsp_svc:"as.user.sign",access_token:n,request:e}),r=WM("curl",["-s","-X","POST",Do.TMS_URL,"-H","Content-Type: application/x-www-form-urlencoded","-d",t,"--max-time","5","-o","/dev/null","-w","%{http_code}"],{detached:!0,stdio:["ignore","pipe","ignore"]});r.unref(),r.stdout?.on("data",i=>{let o=i.toString().trim();o==="200"?m("Agreement sign reported successfully"):m(`Agreement sign failed: HTTP ${o}`)}).on("error",()=>{})}catch(e){m(`Agreement sign error: ${e.message}`)}}var ll=class{config;server=null;constructor(e){this.config={...xo,...e}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}async login(){try{m(`Login started, isDevecoCodeAuth: ${nt()}`);let e=this.generateClientSecret();this.server=new nl(e,oe.CN_LOGIN_URL,this.config.successRedirectUrl,this.config.failedRedirectUrl),await this.server.start(),m(`Local auth server started on port ${this.server.getPort()}`),await this.openLoginPage(this.server.getPort(),e),m("Browser opened for authentication");let t=await this.server.waitForCallback(this.config.timeout);if(m(`Callback received: siteId=${t.siteId}`),t.siteId!=="1")throw new Ve("Non-China accounts are not supported.");let r=await cb.getJwtToken(t.tempToken,t.siteId,oe.CN_LOGIN_URL,this.config.tempTokenCheckUrl,this.config.appId);m("JWT token received");let i=await eo.getUserInfoFromJwt(r,oe.CN_LOGIN_URL);if(!i)throw new Ve("Login failed: failed to get user info");return m(`User info received: ${i.userName}`),await Dr.saveJwtToken(r),m("JWT token saved"),lb(i.accessToken),i}finally{this.server&&(await this.server.stop(),this.server=null)}}async isLoggedIn(){return await this.getUserInfo(!0)!==null}async logout(){let e=await Dr.loadJwtToken();if(!e)return!1;let r=`${oe.CN_LOGIN_URL}/${this.config.logoutUrl}?jwtToken=${e}`;try{await $.post(r,{timeout:5e3})}catch{m("Logout: server notification failed, local token cleared")}finally{await Dr.clearToken()}return!0}async getUserInfo(e=!0){return eo.fetchUserInfo(oe.CN_LOGIN_URL,e)}generateClientSecret(){return db.randomUUID().replace(/-/g,"")}async openLoginPage(e,t){let i=`${oe.CN_LOGIN_URL}/${this.config.authUrl}?port=${e}&appid=${this.config.appId}&code=${t}`;await Xv(i)}async refreshToken(){return eo.refreshToken(oe.CN_LOGIN_URL)}},qe=new ll;function GM(){return nt()?"Not logged in. Please login via DevEco Code first.":"Please run `devecocli auth login` first."}function qM(n){if(n==null||typeof n!="object")return[];let e=n;if(e.ret&&e.ret.code!==0)throw new Error(`team list request failed: code=${e.ret.code}${e.ret.msg?`, msg=${e.ret.msg}`:""}`);return Array.isArray(e.teams)?e.teams.filter(t=>typeof t=="object"&&t!==null).map(t=>({id:String(t.id??""),upSiteId:Number(t.upSiteId??0),name:String(t.name??""),countryCode:String(t.countryCode??""),siteId:Number(t.siteId??0),userType:Number(t.userType??0),lastLoginTime:String(t.lastLoginTime??""),isMirror:t.isMirror===!0})).filter(t=>t.id.length>0):[]}var dl=class{config;constructor(e){this.config={...xo,...e}}updateConfig(e){this.config={...this.config,...e}}async listTeams(){let e=await eo.fetchUserInfo(oe.CN_LOGIN_URL,!0);if(!e)throw new Ve(GM());let t=await this.fetchTeamList(e.accessToken,e.userId),r=qM(t);return{userId:e.userId,teamList:r}}async fetchTeamList(e,t){let r=this.config.agcTeamListUrl,i;try{i=await $.get(r,{headers:{oauth2Token:e,uid:t,source:"cli",lang:Zn.CHINA},timeout:15e3})}catch(o){let s=o.message;throw s.includes("401")?new Ve("Token expired. Run `devecocli auth login` again."):new Error(`Network error while listing teams: ${s}`,{cause:o})}if(i.statusCode!==200)throw new Error(`Failed to list teams: HTTP ${i.statusCode}`);return typeof i.data=="string"?JSON.parse(i.data):i.data}},ub=new dl;async function nn(){return ub.listTeams()}async function ul(n,e,t){let r=Date.now(),i=!0,o=null;try{await e()}catch(s){i=!1,o=X(s);let a=t?.(s);if(a)throw a}finally{let s={duration_ms:Date.now()-r,success:i,error_code:o};await D.track(n,s)}}function JM(n){if(n.length===0)return Ft("No teams found for the current user.");let e=["Id","Name"],t=n.map(s=>[s.id,s.name]),r=e.map((s,a)=>Math.max(s.length,...t.map(c=>c[a].length))),i=s=>s.map((a,c)=>a.padEnd(r[c])).join(" "),o=r.map(s=>"-".repeat(s)).join(" ");return[i(e),o,...t.map(i)].join(`
1314
+ `)}function YM(){return new Promise(n=>{let e=pb.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}var Os=new zM("auth").description("Authentication commands (login, logout, status, team)");async function KM(n){if(n||!process.stdin.isTTY){console.log(Ft(n?"Opening browser for login... (--no-prompt: Enter confirmation skipped)":"Non-interactive terminal: opening browser for login without the Enter confirmation..."));return}console.log(Ft("Press Enter to open browser for login (or pass --no-prompt to skip)...")),await YM()}async function XM(n){if(nt()){console.log(ym("Login is managed by DevEco Code. Login from DevEco Code instead."));return}let e={event:v.CommandExecuted,args:["auth","login"]};await ul(e,async()=>{let t=await qe.getUserInfo();if(t){console.log(Ft(`Already logged in, User Name:${t.userName}`));return}console.log(Ft("Starting login process...")),await KM(n.prompt===!1);let r=await qe.login();console.log(Ft(`Login successful. Logged in as ${r.userName}.`))},t=>{throw t instanceof Ve||(t instanceof Error?t.message:String(t)).includes("Network connection failed")?t:new Error("Login failed",{cause:t})})}Os.command("login").description("Log in to your Huawei Developer account").option("--no-prompt","Open the browser immediately without the interactive Enter confirmation (agents and non-interactive terminals)").action(async n=>{await XM(n)});Os.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(nt()){console.log(ym("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}let n={event:v.CommandExecuted,args:["auth","logout"]};await ul(n,async()=>{let e=await qe.logout();console.log(e?Ft("Logout successful"):Ft("Already logged out."))},e=>new Error("Logout failed",{cause:e}))});Os.command("status").description("Show the currently logged-in user").action(async()=>{let n={event:v.CommandExecuted,args:["auth","status"]};await ul(n,async()=>{let e=await qe.getUserInfo();if(!e){console.log(Ft("Not logged in"));return}console.log(Ft(`Current user: ${e.userName}`))},()=>{console.log(Ft("Not logged in"))})});var ZM=Os.command("team").description("Team-related commands");ZM.command("list").description("List team accounts the current user has joined").action(async()=>{let n={event:v.CommandExecuted,args:["auth","team","list"]};await ul(n,async()=>{let e=await nn();console.log(JM(e.teamList))},e=>{if(e instanceof Ve){console.log(ym(e.message));return}throw new Error("Failed to list teams",{cause:e})})});var mb=Os;import{Command as gN}from"commander";import{green as yN,red as $s,cyan as Mb,yellow as Nb,dim as Lb}from"colorette";import wN from"p-limit";import QM from"ora";var mt=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=QM(e),this.spinner.start(),this.isRunning=!0}stop(){this.spinner&&this.isRunning&&(this.spinner.stop(),this.isRunning=!1)}succeed(e){this.spinner&&(this.spinner.succeed(e),this.isRunning=!1)}fail(e){this.spinner&&(this.spinner.fail(e),this.isRunning=!1)}};import*as hb from"fs";import*as wm from"path";import{homedir as fb}from"os";function on(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}var gb=["DevEco"];async function pl(){let n=await $.get(gt.TAGS_API_URL),t=ml(n,"Tags API").data.skill.filter(r=>r.name==="HMOS");if(t.length===0)throw new Error("No HMOS tag found.");return t.map(r=>r.id)}async function eN(n){let e=[],t=gt.DEFAULT_PAGE_SIZE,r=gt.DEFAULT_MAX_PAGES,i=1;for(;i<=r;){let o=await $.post(gt.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:i,pageSize:t,tagIds:[n]}}),s=ml(o,"Skills API");if(e.push(...s.data.list),s.data.list.length<t)break;i++}return e}async function vm(n){let e=new Map,t=n.map(i=>eN(i)),r=await Promise.all(t);for(let i of r)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=>!gb.includes(o.name)))}async function tN(n,e){let t=await $.post(gt.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:gt.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return ml(t,"Skills API").data.list}async function bm(n,e){let t=new Map,r=e.map(o=>tN(n,o)),i=await Promise.all(r);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=>!gb.includes(s.name)))}function yb(n){on(n);let e=[];for(let[,t]of Object.entries(Dt)){let r=E.ensurePathWithinRoot(wm.join(fb(),t.path),wm.join(fb(),t.path,n));hb.existsSync(r)&&e.push(t.displayName)}return e.sort()}function ml(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=$.parseJson(n);if(t.code!==gt.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function wb(n){on(n);let e=`${gt.SKILL_API_BASE}/${n}/checksum`,t=await $.get(e);return ml(t,"Checksum API").data}import rN from"adm-zip";import nN from"crypto";import{timingSafeEqual as iN}from"crypto";import Sm from"fs";import ye from"path";import{fileURLToPath as oN}from"url";import{homedir as bb}from"os";import{red as sN}from"colorette";var Ae=Sm.promises;function vb(n,e){let t=ye.resolve(e),r=ye.resolve(n),i=ye.relative(r,t);if(i.startsWith("..")||ye.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function Em(n){return ye.isAbsolute(n)?n:ye.resolve(process.cwd(),n)}function aN(n){return nN.createHash("sha256").update(n).digest("hex")}async function cN(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=aN(n),i=e.sha256.toLowerCase(),o=Buffer.from(r,"hex"),s=Buffer.from(i,"hex");if(o.length!==s.length||!iN(o,s))throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function Sb(n){on(n);let e=`${gt.SKILL_API_BASE}/${n}/install?format=zip`,t=await $.getBinary(e),r=await wb(n);return await cN(t,r),t}async function lN(n,e,t){on(t);let r=new rN(n),i=r.getEntries();try{await Ae.stat(e)}catch{await Ae.mkdir(e,{recursive:!0})}let o=ye.join(e,t);vb(e,o);for(let s of i){let a=ye.join(o,s.entryName);vb(o,a)}r.extractAllTo(o,!0)}async function Pm(n){let e=Dt[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(Dt).join(", ")}`);let t=ye.join(bb(),e.path.replace("/skills",""));try{return await Ae.access(t),!0}catch{return!1}}function Ms(n){let e=Dt[n];return ye.join(bb(),e.path)}function dN(n){let e=Dt[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(Dt).join(", ")}`);return e}function Cm(n,e){let t=dN(e),r="projectPath"in t?t.projectPath:ye.join("."+e,"skills");return ye.join(n,r)}async function uN(n,e,t){on(e);let r=ye.join(n,e);try{if(await Ae.access(r),t)await Ae.rm(r,{recursive:!0,force:!0});else return console.log(`Skill ${e} exists in ${n}.`),{skillDir:r,shouldSkip:!0}}catch{}return{skillDir:r,shouldSkip:!1}}async function km(n,e,t){await lN(n,e,t),console.log(`Skill ${t} installed to ${ye.join(e,t)}.`)}function pN(n,e){let t=o=>{let s=ye.resolve(o);return s.startsWith("\\\\?\\")&&(s=s.slice(4)),s.replace(/[\\/]+$/,"")},r=t(n),i=t(e);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}async function Rm(n,e){let t=process.platform==="win32"?"junction":"dir",r;try{r=await Ae.lstat(e)}catch{return await Ae.mkdir(ye.dirname(e),{recursive:!0}),await Ae.symlink(n,e,t),!0}if(r.isSymbolicLink()){let i;try{i=await Ae.realpath(e)}catch{return await Ae.rm(e,{force:!0}),await Ae.symlink(n,e,t),!0}return pN(i,n)?!1:(await Ae.rm(e,{force:!0}),await Ae.symlink(n,e,t),!0)}return await Ae.rm(e,{recursive:!0,force:!0}),await Ae.symlink(n,e,t),!0}async function Dm(n,e,t){let r=ye.join(e,t),i=await Rm(n,r);return i&&console.log(`Skill ${t} linked to ${n}.`),i}function Eb(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(sN(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function to(n,e,t,r,i=!1){try{let o=await e();if(i)return await t(o)===!1?{success:!0,skipped:!0}:{success:!0};let{shouldSkip:s}=await uN(o,n,r);return s?{success:!0,skipped:!0}:(await t(o),{success:!0})}catch(o){return Eb(n,o,"Installation failed")}}async function xm(n,e){try{on(n);let t=await e(),r=ye.join(t,n);try{await Ae.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await Ae.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return Eb(n,t,"Removal failed")}}async function Pb(n,e,t,r=!1){return to(n,()=>Ms(e),i=>km(t,i,n),r)}async function Cb(n,e,t,r=!1){return to(n,()=>t,i=>km(e,i,n),r)}async function kb(n,e,t,r,i=!1){return to(n,()=>Cm(t,r),o=>km(e,o,n),i)}async function Rb(n,e,t,r=!1){return to(n,()=>Ms(t),i=>Dm(e,i,n),r,!0)}async function Db(n,e,t,r,i=!1){return to(n,()=>Cm(t,r),o=>Dm(e,o,n),i,!0)}async function xb(n,e,t,r=!1){return to(n,()=>t,i=>Dm(e,i,n),r,!0)}async function Am(n,e){return xm(n,()=>Ms(e))}async function Ab(n,e){return xm(n,()=>e)}async function Ib(n,e,t){return xm(n,()=>Cm(e,t))}function fl(){let e=ye.dirname(oN(import.meta.url));for(;;){let t=ye.join(e,"skills","deveco-cli");if(Sm.existsSync(t)&&Sm.statSync(t).isDirectory())return t;let r=ye.dirname(e);if(r===e)break;e=r}throw new Error("skills/deveco-cli directory not found in deveco-cli package. Reinstall deveco-cli.")}import Im from"fs";import Tm from"path";import{cyan as mN}from"colorette";var hl=Im.promises,fN="deveco-cli";async function Ns(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await Pm(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function ro(){let n=[];for(let e of Object.keys(Dt))await Pm(e)&&n.push(e);return n}async function hN(){let n=fl(),e=0,t=0,r=0,i=await ro();for(let o of i){let s=Ms(o),a=Tm.join(s,fN);try{let c=!0;try{await hl.lstat(a)}catch{c=!1}if(!c){t++;continue}await Rm(n,a)?(console.error(`Converted ${o}/deveco-cli to symlink.`),e++):t++}catch(c){r++,console.error(`Skill link migration failed for ${o}: ${c.message}`)}}if(r>0)throw new Error(`${r} agent(s) failed skill-link migration; will retry next command`);return{updated:e,skipped:t}}async function Tb(){let n;try{n=Tm.join(W(),"skills","migration-version")}catch{return}let e="";try{e=(await hl.readFile(n,"utf-8")).trim()}catch{}let t=Zt();if(e!==t)try{await hN(),await hl.mkdir(Tm.dirname(n),{recursive:!0}),await hl.writeFile(n,t,"utf-8")}catch{}}function Ls(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(mN("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function sn(n,e,t){if(!Im.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!Im.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function _s(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?Em(n):void 0,resolvedProject:e?Em(e):void 0}}async function gl(n,e,t){let r=[],i=[],o;if(e?o=e:t&&n.agent?i=(await Ns(n.agent)).map(a=>({project:t,agent:a})):t?i=(await ro()).map(a=>({project:t,agent:a})):n.agent?r=await Ns(n.agent):r=await ro(),!o&&r.length===0&&i.length===0)throw new Error("No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location.");return{agents:r,projectAgents:i,customPath:o}}var _b="deveco";async function vN(n){let e=await pl();if(n.all)return(await vm(e)).map(r=>r.enName);{let r=(await bm(n.skill,e)).find(i=>i.enName===n.skill);if(!r)throw new Qn("errorCode",`Skill "${n.skill}" not found`);return[r.enName]}}async function bN(n,e,t,r){let i=[];if(t.customPath){let o=await Cb(n,e,t.customPath,r);return i.push(o),i}for(let o of t.agents){let s=await Pb(n,o,e,r);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await kb(n,e,o,s,r);i.push(a)}return i}function SN(n){if(n.all&&n.skill)throw new Qn("errorCode","`--all` and `--skill` cannot be specified together.");if(!n.all&&!n.skill)throw new Qn("errorCode","Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=_s(n.path,n.project,n.agent);return t&&sn(t,"Project directory",n.force),e&&sn(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}function EN(n,e,t){return!!(e||t||n.path||n.project||n.agent)}function PN(){return{agents:[_b],projectAgents:[],customPath:void 0}}async function CN(n,e,t){let r=nt()&&!EN(n,e,t)?PN():await gl(n,e,t);return{skillNames:await vN(n),targets:r}}async function kN(n,e,t,r){let i=[],o=0,s=n.length,a=wN(5),c=n.map(l=>a(()=>RN(l)));for(let l=0;l<n.length;l++){let d=n[l],g=s>1?` (${l+1}/${s})`:"";r.start(`Installing ${d}${g}...`);let w=await c[l];if(!w.success){r.fail(),console.log($s(`${d}: Download failed - ${w.error}`)),i.push({success:!1});continue}o+=w.buffer.length,r.stop();let R=await bN(d,w.buffer,e,t);i.push(...R)}return{results:i,diskBytes:o}}async function RN(n){try{let e=await Sb(n);return{name:n,buffer:e,success:!0}}catch(e){let t=e instanceof Error?e.message:"unknown error";return{name:n,error:t,success:!1}}}async function DN(n){let e=new mt;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=SN(n),{skillNames:i,targets:o}=await CN(n,t,r),{results:s,diskBytes:a}=await kN(i,o,n.force||!1,e);return e.stop(),Ls(s),{diskBytes:a,results:s}}catch(t){throw e.stop(),t}}function $b(n){let e=n.length,t=n.filter(s=>s.success&&!s.skipped).length,r=n.filter(s=>s.skipped).length,i=n.filter(s=>!s.success).length,o=[...new Set(n.filter(s=>!s.success&&typeof s.error=="string").map(s=>xN(s.error)))];return{opTotal:e,opSuccess:t,opFailed:i,opSkipped:r,...o.length>0?{failedErrors:o}:{}}}function xN(n){let e=/^([A-Za-z_][A-Za-z0-9_-]*)/.exec(n.trim());return e?e[1].slice(0,32):"error"}var Qn=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function AN(n){let e=n;return n instanceof Qn?n.code:e.code??e.name??"UnknownError"}function wl(n,e={}){return["skills",n,...e.all?["--all"]:[],...e.long?["--long"]:[],...e.skill?["--skill"]:[],...e.force?["--force"]:[],...e.agent?["--agent",e.agent]:[],...e.project?["--project"]:[],...e.path?["--path"]:[]]}async function vl(n,e,t){let r=Date.now(),i=!0,o=null,s={};try{s=await e()}catch(a){throw i=!1,o=AN(a),a}finally{let a={event:v.SkillOperation,subAction:n,args:t,...s};await D.track(a,{duration_ms:Date.now()-r,success:i,error_code:o})}}function IN(n){return vl("add",async()=>{let{diskBytes:e,results:t}=await DN(n);return{diskUsage:ce(e),...n.skill?{skillName:n.skill}:{},...$b(t)}},wl("add",n))}function TN(n){let{resolvedPath:e,resolvedProject:t}=_s(n.path,n.project,n.agent);return t&&sn(t,"Project directory"),e&&sn(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function ON(n,e){let t=new mt;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:i}=TN(e);t.stop();let o=await MN(e,n,r,i);return t.stop(),Ls(o),o}catch(r){throw t.stop(),r}}function Ob(n,e=""){if(n.length===0)throw new Qn("errorCode",`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function yl(n,e){let t=[];for(let r of e){let i=r.type==="agent"?await Am(n,r.agent):await Ib(n,r.project,r.agent);t.push(i)}return t}async function MN(n,e,t,r){if(t)return[await Ab(e,t)];if(r&&n.agent){let a=(await Ns(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return yl(e,a)}if(r){let s=await ro();Ob(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return yl(e,a)}if(n.agent){let a=(await Ns(n.agent)).map(c=>({type:"agent",agent:c}));return yl(e,a)}if(nt())return[await Am(e,_b)];let i=await ro();Ob(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return yl(e,o)}var Fs=new gN("skills").description("Manage HarmonyOS skills");Fs.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async n=>{try{await vl("list",async()=>{let e=new mt;try{e.start("Fetching skills...");let t=await pl(),r=await vm(t);if(r.length===0)return e.stop(),console.log(Nb("No skills available.")),{resultTotal:0};e.succeed(`Fetched ${r.length} skills`);for(let i of r)if(n.long){console.log(Mb(i.enName)),console.log(Lb(i.description));let o=yb(i.enName);o.length>0&&console.log(yN(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName);return{resultTotal:r.length}}finally{e.stop()}},wl("list",n))}catch(e){console.error($s(e.message)),process.exit(1)}});Fs.command("find <keyword>").description("Search skills by keyword").action(async n=>{try{await vl("find",async()=>{let e=new mt;try{e.start("Searching skills...");let t=await pl(),r=await bm(n,t);if(r.length===0)return console.log(Nb(`No skills found matching '${n}'.`)),e.stop(),{resultTotal:0,queryLen:n.length,keyword:n};e.succeed(`Found ${r.length} skills.`);for(let i of r)console.log(Mb(i.enName)),console.log(Lb(i.description)),console.log();return{resultTotal:r.length,queryLen:n.length,keyword:n}}finally{e.stop()}},wl("find"))}catch(e){console.error($s(e.message)),process.exit(1)}});Fs.command("add").description("Install skills to AI agents").option("--all","Install all available skills").option("--agent <agents>","Target agents, comma-separated; Omit to install to all available agents").option("--skill <skill-name>","Name of the skill to install").option("-f, --force","Overwrite an existing skill installation").option("--project <path>","Project root directory for skill installation").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").action(async n=>{try{await IN(n)}catch(e){console.error($s(e.message)),process.exit(1)}});Fs.command("remove").description("Remove an installed skill from AI agents").requiredOption("--skill <skill-name>","Name of the skill to remove").option("--agent <agents>","Target agents, comma-separated.Omit to remove from all available agents").option("--project <path>","Project root directory for skill removal").option("--path <path>","Path for skill removal").action(async n=>{try{await vl("remove",async()=>{let e=await ON(n.skill,n);return{skillName:n.skill,...$b(e)}},wl("remove",n))}catch(e){console.error($s(e.message)),process.exit(1)}});var Fb=Fs;import{Command as NN,InvalidArgumentError as bl}from"commander";import{cyan as Om,red as Hb}from"colorette";import LN from"ora";function _N(n){return["log",...n.device?["--device"]:[],...n.crash?["--crash"]:[],...n.level?["--level"]:[],...n.bundleName?["--bundle-name"]:[],...n.keyword?["--keyword"]:[],...n.tail!==void 0?["--tail"]:[],...n.from!==void 0?["--from"]:[],...n.to!==void 0?["--to"]:[],...n.follow?["--follow"]:[]]}function $N(n){return{event:v.CommandExecuted,args:_N(n),logType:n.crash?"crash":"common",level:n.level??"ALL",bundleName:n.bundleName??"ALL"}}function FN(n){return n instanceof y?n.traceMessage:n instanceof Error?n.code??n.name:"UnknownError"}async function jN(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=FN(o),console.error(Hb(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await D.track(n,o).catch(()=>{})}}function HN(n){try{return E.parsePositiveInteger(n,"tail")}catch{throw new bl("`tail` must be a positive integer.")}}function jb(n,e){try{return E.parseDurationToSeconds(n,e)}catch{throw new bl(`${e} must be a valid duration string (e.g.,30s, 5m or 2.5m).Supported units: s and m.when specified in seconds(with \`s\` or as a raw number), the value must be an integer.`)}}function UN(n){try{return E.assertHilogLevel(n),n}catch{throw new bl("`level` must be one of: D, I, W, E, F.")}}function BN(n){try{return E.assertBundleNameStrict(n),n}catch(e){throw new bl(e.message)}}function WN(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.")}async function VN(n,e,t,r,i){return t.crash?await n.getCrashLog(e,t.bundleName):await n.getHilog(e,{level:t.level,bundleName:t.bundleName,keyword:t.keyword,isFollow:!!t.follow,tail:t.tail,fromSeconds:r,toSeconds:i})}function GN(n,e,t,r){let i=E.filterLogsByRelativeWindow(n,t,r);return e.tail?E.getLastLines(i,e.tail):i}var qN=new NN("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(Hb(n))}).option("--device <device>","Target device (name or serial)").option("--crash","Only obtain crash logs").option("--level <level>","Log level filter: D, I, W, E, F",UN).option("--bundle-name <bundle-name>","Filter by application bundle name",BN).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",HN).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>jb(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>jb(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await jN($N(n),()=>zN(n))});async function zN(n){let e=LN({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};e.start();try{WN(n);let r=n.from,i=n.to,o=await P.new(),s=new Br(o),a=await s.selectDevice(n.device);if(!a)throw new y("No active devices found.","No active devices found.");m(Om(`deviceId: ${a}`)),m(Om(`type: ${n.crash?"Crash logs":"Common logs"}`)),m(Om("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await VN(s,a,n,r,i);t(),n.crash&&c&&(c=GN(c,n,r,i)),c&&console.log(c)}finally{t()}}var Ub=qN;import Hs from"path";import Ar from"fs";import Lm from"process";import Xb from"os";import{Command as aL}from"commander";import{green as zb,red as Mm,cyan as cL,yellow as Jb}from"colorette";import we from"fs-extra";import q from"path";import*as Vb from"os";import{fileURLToPath as JN}from"url";var Bb={17:{sdkVersion:"5.0.5(17)",modelVersion:"5.0.5"},18:{sdkVersion:"5.1.0(18)",modelVersion:"5.1.0"},19:{sdkVersion:"5.1.1(19)",modelVersion:"5.1.1"},20:{sdkVersion:"6.0.0(20)",modelVersion:"6.0.0"},21:{sdkVersion:"6.0.1(21)",modelVersion:"6.0.1"},22:{sdkVersion:"6.0.2(22)",modelVersion:"6.0.2"},23:{sdkVersion:"6.1.0(23)",modelVersion:"6.1.0"},24:{sdkVersion:"6.1.1(24)",modelVersion:"6.1.1"}},YN=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"],no=["phone","tablet","2in1","car","wearable","tv"],Wb=["entry","src","main","module.json5"];function KN(){let n=import.meta.url,e=JN(n);if(e.includes("dist")){let o=q.dirname(e),s=q.dirname(o);return q.join(s,"templates","application")}let t=q.dirname(e),r=q.dirname(t),i=q.dirname(r);return q.join(i,"templates","application")}function Gb(n,e){we.mkdirSync(e,{recursive:!0});for(let t of we.readdirSync(n,{withFileTypes:!0})){let r=q.join(n,t.name),i=q.join(e,t.name);if(t.isDirectory()){Gb(r,i);continue}we.existsSync(i)||(we.mkdirSync(q.dirname(i),{recursive:!0}),we.copyFileSync(r,i))}}function js(n,e){let t=we.readFileSync(n,"utf-8"),r=t;for(let[i,o]of e)r=r.replaceAll(i,o);r!==t&&we.writeFileSync(n,r,"utf-8")}function XN(n){if(Bb[n])return Bb[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function ZN(n,e){if(e===22)return;let t=XN(e);t&&(js(q.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),js(q.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),js(q.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function QN(n){return YN.filter(t=>!we.existsSync(q.join(n,t))).length===0}function eL(n,e){let t=Wb.join("/"),r=q.join(n,...Wb),i=we.readFileSync(r,"utf-8"),o=/^([ \t]*)"deviceTypes"\s*:\s*\[[\s\S]*?\]/m.exec(i);if(!o)throw new Error(`"deviceTypes" not found in ${t}.`);let s=i.includes(`\r
1315
+ `)?`\r
1316
+ `:`
1317
+ `,a=o[1],c=e.map((d,g)=>`${a} "${d}"${g<e.length-1?",":""}`).join(s),l=`${a}"deviceTypes": [${s}${c}${s}${a}]`;we.writeFileSync(r,i.replace(o[0],()=>l),"utf-8")}function tL(){return Buffer.from([137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,1,0,0,0,1,8,2,0,0,0,144,119,83,222,0,0,0,12,73,68,65,84,8,215,99,248,255,255,255,0,5,254,2,254,0,0,0,0,73,69,78,68,174,66,96,130])}function rL(n){return Vb.platform()==="darwin"?q.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):q.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function nL(n,e){let t=rL(e);if(!we.existsSync(t))return!1;let r=[["AppScope/resources/base/media/background.png","AppScope/resources/base/media/background.png"],["AppScope/resources/base/media/foreground.png","AppScope/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/background.png"],["entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/startIcon.png","entry/src/main/resources/base/media/startIcon.png"]];for(let[i,o]of r){let s=q.join(t,i),a=q.join(n,o);we.existsSync(s)&&(we.mkdirSync(q.dirname(a),{recursive:!0}),we.copyFileSync(s,a))}return!0}function iL(n){let e=tL(),t=["AppScope/resources/base/media/background.png","AppScope/resources/base/media/foreground.png","entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/startIcon.png"];for(let r of t){let i=q.join(n,r);we.mkdirSync(q.dirname(i),{recursive:!0}),we.writeFileSync(i,e)}}function oL(n,e){e&&nL(n,e)||iL(n)}function sL(n){let e=[q.join(n,"gitignore.txt"),q.join(n,"entry","gitignore.txt")];for(let t of e)if(we.existsSync(t)){let r=q.dirname(t);we.renameSync(t,q.join(r,".gitignore"))}}function qb(n,e,t,r,i,o){let s=KN();if(!we.existsSync(s))throw new Error(`Template directory not found: ${s}`);we.mkdirSync(n,{recursive:!0}),Gb(s,n),sL(n),oL(n,o),js(q.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),js(q.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),eL(n,i),ZN(n,r);let a=QN(n);if(!a)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,deviceTypes:i,verified:a}}function lL(n){if(n.length<1||n.length>200)throw new Ee("errorCode",`App name length must be 1-200 characters. Current: ${n.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(n))throw new Ee("errorCode","Application name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function dL(n){if(!n||n.length===0)return[no[0]];let e=n.map(r=>r.toLowerCase()),t=n.filter((r,i)=>!no.includes(e[i]));if(t.length>0)throw new Ee("errorCode",`Unsupported device type(s): ${t.map(r=>`"${r}"`).join(", ")}. Supported types: ${no.join(", ")}`);return[...new Set(e)]}function Zb(n){if(Xb.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function Yb(n){if(n.length===0)throw new Ee("errorCode","Project path cannot be empty.");if(n.length>120)throw new Ee("errorCode",`Project path cannot exceed 120 characters (current: ${n.length}).`);let e=Xb.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(n)){let o=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new Ee("errorCode",`Project path can only contain ${o}.`)}let r=Zb(n);if(/[\u4e00-\u9fff]/.test(r))throw new Ee("errorCode","Project path cannot contain Chinese characters.");if(r.endsWith("."))throw new Ee("errorCode","Project path cannot end with a dot (.)")}function uL(n){let e=n,t=Hs.parse(n).root;for(;e!==t;){if(Ar.existsSync(e))return e;e=Hs.dirname(e)}return Ar.existsSync(t)?t:null}function Kb(n){let e=uL(n);if(!e)throw new Ee("errorCode",`No existing parent directory found for '${n}'. Cannot create project directory.`);try{Ar.accessSync(e,Ar.constants.W_OK)}catch{throw new Ee("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}let t=Hs.join(e,`.deveco_write_test_${Date.now()}`);try{Ar.writeFileSync(t,"test"),Ar.unlinkSync(t)}catch{throw new Ee("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}}function pL(n){return`com.example.${n.toLowerCase()}`}function mL(n,e){if(e){let i=Zb(e),o=Hs.resolve(i);if(Ar.existsSync(o)){if(Ar.readdirSync(o).length>0)throw new Ee("errorCode",`Directory '${o}' is not empty. Cannot create project here.`)}else Kb(o);return o}let t=Lm.cwd(),r=Hs.join(t,n);if(Ar.existsSync(r))throw new Ee("errorCode",`Directory '${r}' already exists. Cannot create project here.`);return Kb(r),r}function fL(n,e){let t=e?.getMaxApiLevel(),r=23;if(n.apiLevel){let i=Number(n.apiLevel);if(!Number.isInteger(i)||i<17)throw new Ee("errorCode",`Invalid API version ${n.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(i>t)throw new Ee("errorCode",`Invalid API version ${n.apiLevel}. Your SDK supports API version 17-${t}`)}else if(i>r)throw new Ee("errorCode",`Invalid API version ${n.apiLevel}. Without DevEco Studio, supported range is API version 17-${r}`);return i}return t!==void 0?t:23}async function hL(){try{return await P.new()}catch(n){console.error(Jb(`DevEco Studio not found: ${n.message}`)),console.log(Jb("Use placeholder API level instead."));return}}var Ee=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};async function Nm(n,e,t,r){let i={event:v.CommandExecuted,args:["create"],apiLevel:r?.apiLevel??null},o={duration_ms:Date.now()-n,success:e,error_code:t};await D.track(i,o).catch(()=>{})}function gL(n){console.log(`
1318
+ `+zb("Project created successfully.")),console.log(`Project root: ${n.projectRoot}`),console.log(`App name: ${n.appName}`),console.log(`Bundle name: ${n.bundleName}`),console.log(`API level: ${n.apiLevel}`),console.log(`Device types: ${n.deviceTypes.join(", ")}`),console.log(zb("Template integrity check passed."))}var yL=new aL("create").description("Scaffold a new HarmonyOS application project").option("--project-path <path>","Project directory path (default: ./<app-name>)").option("--app-name <name>","Application name").option("--bundle-name <bundle>","Bundle name (auto-derived as com.example.<app-name> if omitted)").option("--api-level <level>","API level (auto-detected from SDK if omitted; minimum: 17)").option("--device-types <types...>",`Device types written to module.json5 (default: ${no[0]}; supported: ${no.join(", ")})`).action(async n=>{let e=Date.now();try{n.appName||(console.error(Mm("Error: --app-name is required")),await Nm(e,!1,"errorCode",n),Lm.exit(1));let t=n.appName;lL(t);let r=dL(n.deviceTypes),i=n.bundleName||pL(t);E.assertBundleNameStrict(i),n.projectPath&&Yb(n.projectPath);let o=mL(t,n.projectPath);Yb(o),console.log(cL("Initializing project...")),console.log(`Project path: ${o}`),console.log(`App name: ${t}`),console.log(`Bundle name: ${i}`),console.log(`Device types: ${r.join(", ")}`);let s=await hL(),a=fL(n,s);console.log(`API level: ${a}`);let c=s?.devecoStudioPath,l=qb(o,t,i,a,r,c);gL(l),await Nm(e,!0,null,n)}catch(t){let r=t,o=t instanceof Ee?t.code:r.code??r.name??"UnknownError";console.error(Mm(`
1319
+ Failed to create project.`)),console.error(Mm(r.message)),await Nm(e,!1,o,n),Lm.exit(1)}}),Qb=yL;import{Command as CL}from"commander";import{red as kL,cyan as aS}from"colorette";import wL from"fs";import Sl from"path";import{cyan as vL}from"colorette";import*as El from"smol-toml";var io=wL.promises;async function bL(n){try{let e=await io.readFile(n,"utf8");return e.trim()===""?{}:JSON.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read configuration file ${n}: ${e.message}`,{cause:e})}}async function SL(n){try{let e=await io.readFile(n,"utf8");return e.trim()===""?{}:El.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read TOML config file ${n}: ${e.message}`,{cause:e})}}async function EL(n,e){let t=Sl.dirname(n);await io.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await io.writeFile(n,r,"utf8")}async function PL(n,e){let t=Sl.dirname(n);await io.mkdir(t,{recursive:!0});let r=El.stringify(e);await io.writeFile(n,r,"utf8")}function eS(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function tS(n,e,t,r,i){(!n[e]||typeof n[e]!="object")&&(n[e]={});let o=n[e];return t in o&&!i?!1:(o[t]=r,!0)}async function rS(n,e){return n.format==="codex"?SL(e):bL(e)}async function nS(n,e,t){return n.format==="codex"?PL(e,t):EL(e,t)}async function iS(n,e,t=!1){let r=jr[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(jr).join(", ")}`};if(!r.supportsGlobal)return{success:!1,error:`${r.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let i=await rS(r,r.globalConfigPath);if(eS(i,r.mcpServersKey,qt)&&!t)return console.log(`MCP server ${qt} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let o=Aa(r,void 0);return tS(i,r.mcpServersKey,qt,o,t),await nS(r,r.globalConfigPath,i),console.log(`MCP server ${qt} configured in ${r.globalConfigPath}.`),{success:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${i.message}`}}}async function _m(n,e,t=!1){let r=jr[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(jr).join(", ")}`};let i=Sl.isAbsolute(r.projectConfigPath)?r.projectConfigPath:Sl.join(e,r.projectConfigPath);try{let o=await rS(r,i);if(eS(o,r.mcpServersKey,qt)&&!t)return console.log(`MCP server ${qt} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:n,installType:"project"};let s=Aa(r,e);return tS(o,r.mcpServersKey,qt,s,t),await nS(r,i,o),console.log(`MCP server ${qt} configured in ${i}.`),{success:!0,configPath:i,agentName:n,installType:"project"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${o.message}`}}}function oS(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(vL("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`);for(let i of n)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);r>0&&(process.exitCode=1)}var $m="deveco-cli";async function RL(n,e,t){if(n.customPath)return[await xb($m,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>Db($m,e,s,a,t.force)),...n.agents.map(s=>()=>Rb($m,e,s,t.force))],i=5,o=[];for(let s=0;s<r.length;s+=i){let a=r.slice(s,s+i);o.push(...await Promise.all(a.map(c=>c())))}return o}function DL(n){return[...new Set([...n.agents,...n.projectAgents.map(({agent:e})=>e)])]}async function sS(n,e,t,r){await D.track(n,{duration_ms:Date.now()-e,success:t,error_code:r}).catch(()=>{})}async function xL(n,e,t,r,i){let o={event:v.SkillConfigOperation,subAction:"install",targetType:r?"path":i?"project":"global",agents:DL(n)},s=Date.now();try{let a=await RL(n,e,t),c=a.every(l=>l.success||l.skipped);return await sS(o,s,c,c?null:"SKILL_INSTALL_FAILED"),a}catch(a){let c=a instanceof Error?a.code??a.name:"UnknownError";throw await sS(o,s,!1,c),a}}async function AL(n,e,t){let r=[];for(let{project:i,agent:o}of n.projectAgents){let s=await _m(o,i,t);r.push(s)}for(let i of n.agents){let o=await _m(i,e,t);r.push(o)}return r}async function IL(n,e){let t=[];for(let r of n){if(!jr[r])continue;let o=await iS(r,process.cwd(),e);t.push(o)}return t}async function TL(n,e,t){let r=["qoder","dsh"];if(t.agent){let l=t.agent.split(",").map(d=>d.trim());for(let d of r)if(l.includes(d))throw new Error(`${d} does not support MCP configuration via DevEco CLI. Use --skill instead, or use other supported agents for MCP.`)}let i=t.force??!1,o=n.projectAgents.filter(l=>!r.includes(l.agent)),s=n.agents.filter(l=>!r.includes(l)),a={...n,projectAgents:o,agents:s},c=e?await AL(a,e,i):await IL(a.agents,i);c.length>0&&(console.log(aS("MCP Configuration:")),oS(c))}async function OL(n,e,t){let r={event:v.Init,subAction:"install",targetType:e?"project":"global",agentName:t.agent},i=Date.now(),o=!0,s=null;try{await TL(n,e,t)}catch(a){throw o=!1,s=a instanceof Error?a.code??a.name:"UnknownError",a}finally{let a={duration_ms:Date.now()-i,success:o,error_code:s};await D.track(r,a)}}async function ML(n){if(n.skill&&n.mcp)throw new Error("Cannot use `--skill` and `--mcp` together. Use `--skill` for skill installation only, or `--mcp` for MCP configuration only.");let{resolvedPath:e,resolvedProject:t}=_s(n.path,n.project,n.agent);t&&sn(t,"Project directory",n.force),e&&sn(e,"Directory",n.force);let r=await gl(n,e,t);if(n.mcp){await OL(r,t,n);return}let i=fl(),o=await xL(r,i,n,e,t);console.log(),o.length>0&&(console.log(aS("Skill Installation:")),Ls(o))}var NL=new CL("init").description("Install the deveco-cli skill or configure the deveco-mcp server into AI agents").option("--agent <agents>","Target agents, comma-separated; installs to all available agents if omitted").option("--project <path>","Project root directory for skill or MCP configuration").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").option("--skill","Install the deveco-cli skill only (same as default behavior; explicit for symmetry with --mcp)").option("--mcp","Configure the deveco-mcp server (syntax checking for .ets and C/C++) only; no skill installation").option("-f, --force","Overwrite existing skill/MCP configuration").action(async n=>{try{await ML(n)}catch(e){console.error(kL(e instanceof Error?e.message:String(e))),process.exit(1)}}),cS=NL;import{Command as W_}from"commander";import{McpServer as x_}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as A_}from"@modelcontextprotocol/sdk/server/stdio.js";import*as Js from"fs";import*as bo from"path";import{z as ke}from"zod";import Pl from"path";function uS(n,e,t,r,i){if(e.isError)return{};let o=e.content?.[0]?.text??"";if(!o)return{};let s;switch(n){case"check":s=LL(o);break;case"hover":s={hit:oo(o)!=null};break;case"definition":case"declaration":s=lS(o,t,r,i,!0);break;case"references":s=$L(o);break;case"implementation":s=lS(o,t,r,i,!1);break;case"documentSymbol":s=FL(o);break;case"callHierarchy":s=jL(o,t,r,i);break;case"workspaceSymbol":s=HL(o,t);break;default:s={}}return s}function pS(n){let e=Array.isArray(n.files)?n.files[0]:n.file;return typeof e!="string"||!e?void 0:Pl.extname(e).toLowerCase().replace(/^\./,"")||void 0}function oo(n){let e=n.indexOf(": ");if(e<0)return;let t=n.slice(e+2).trim();if(!(!t||t==="no result"))try{return JSON.parse(t)}catch{return}}function LL(n){let e={total:0,error:0,warn:0,info:0},t=new Set,r=" => Diagnostic: ";for(let o of n.split(`
1320
+ `)){let s=o.indexOf(r);if(s<0)continue;let a;try{a=JSON.parse(o.slice(s+r.length))}catch{continue}if(Array.isArray(a))for(let c of a)c&&typeof c=="object"&&_L(c,e,t)}let i={diagTotal:e.total,diagError:e.error,diagWarn:e.warn,diagInfo:e.info};return t.size>0&&(i.rules=[...t]),i}function _L(n,e,t){e.total++;let r=n.severity;r===1?e.error++:r===2?e.warn++:(r===3||r===4)&&e.info++,typeof n.source=="string"&&t.add(n.source)}function $L(n){let e=oo(n),t=Array.isArray(e)?e:[],r=new Set;for(let i of t){let o=i?.uri;typeof o=="string"&&r.add(o)}return{refTotal:t.length,fileCount:r.size}}function lS(n,e,t,r,i){let o=oo(n);if(o==null)return{found:!1};let s=Array.isArray(o)?o:[o],a=s[0]?.uri;return i?{found:!0,sameFile:UL(a,e),sourceType:fS(a,t,r)}:{implTotal:s.length,found:!0}}function FL(n){let e=oo(n),t=Array.isArray(e)?e:[],r=0,i=new Map,o=s=>{for(let a of s){if(!a||typeof a!="object")continue;r++;let c=a.kind;typeof c=="number"&&i.set(c,(i.get(c)??0)+1);let l=a.children;Array.isArray(l)&&o(l)}};return o(t),{symbolTotal:r,kindDist:Fm(i)}}function jL(n,e,t,r){let o=oo(n)?.calls,s=Array.isArray(o)?o:[],a=e.direction,c=new Map;for(let l of s){if(!l||typeof l!="object")continue;let g=(a==="incoming"?l.from:l.to)?.uri,w=fS(g,t,r);c.set(w,(c.get(w)??0)+1)}return{callsTotal:s.length,calleeSrcDist:Fm(c)}}function HL(n,e){let t=oo(n),r=Array.isArray(t)?t:[],i=new Map,o=0;for(let c of r){if(!c||typeof c!="object")continue;let l=c.kind;typeof l=="number"&&i.set(l,(i.get(l)??0)+1);let d=c.tags;(Array.isArray(d)&&d.includes(1)||c.deprecated===!0)&&o++}let s={resultTotal:r.length,kindDist:Fm(i),deprecatedHit:o},a=e.query;return typeof a=="string"&&(s.queryLen=a.length),s}function mS(n){if(typeof n!="string"||!n)return null;let e=n;return e.startsWith("file://")&&(e=e.slice(7),process.platform==="win32"&&e.startsWith("/")&&(e=e.slice(1))),e}function fS(n,e,t){let r=mS(n);return r?e&&dS(r,e)?"user_project":t&&dS(r,t)?"sdk":"system":"unknown"}function UL(n,e){let t=mS(n),r=e.file;return!t||typeof r!="string"?!1:Cl(t)===Cl(r)}function Cl(n){try{return Pl.resolve(n).replace(/\\/g,"/").toLowerCase()}catch{return n.replace(/\\/g,"/").toLowerCase()}}function dS(n,e){let t=Pl.relative(Cl(e),Cl(n));return t!==""&&!t.startsWith("..")&&!Pl.isAbsolute(t)}function Fm(n){let e={};for(let[t,r]of n)e[String(t)]=r;return e}var kl=class{constructor(e,t,r,i){this.telemetry=e;this.getAceServerPid=t;this.getProjectPath=r;this.getSdkPath=i}tools=new Map;add(e,t){return this.tools.set(e.name,{definition:e,handler:t}),this}getAll(){return Array.from(this.tools.values())}registerToServer(e){for(let{definition:t,handler:r}of this.getAll())e.registerTool(t.name,{description:t.description,inputSchema:t.inputSchema},(async i=>this.invokeTool(t.name,i,r)))}async invokeTool(e,t,r){if(h.debug(`[telemetry] mcp tool call: ${e}`),!this.telemetry)return r(t);let i=ce(process.memoryUsage().rss),o=await this.resolveLspMemory(),s=Date.now(),a=!0,c=null,l;try{l=await r(t)}catch(d){throw a=!1,c=d instanceof Error?d.code??d.name:"UnknownError",d}finally{await this.trackToolCall(e,t,l,s,i,o,a,c)}return l}async trackToolCall(e,t,r,i,o,s,a,c){if(!this.telemetry)return;let l=r?.isError===!0,d=r&&!l?uS(e,r,t,this.getProjectPath?.()??"",this.getSdkPath?.()??""):{},g=l?!1:a,w=l&&r?BL(r):c,R={event:v.McpToolCall,subAction:e,mcpMemory:o,lspMemory:s,fileExt:pS(t),...d};typeof t.direction=="string"&&(R.direction=t.direction),await this.telemetry.track(R,{duration_ms:Date.now()-i,success:g,error_code:w})}async resolveLspMemory(){let e=this.getAceServerPid?.()??null;if(e===null)return"unknown";let t=await lt(e);return t===null?"unknown":ce(Number(t)*1024)}};function BL(n){let e=n.content.map(t=>t.text).join(`
1321
+ `);return/not ready|not initialized|initializing|please retry|retry \d+s|syncing|C\+\+ project initialization failed/i.test(e)?"NotReady":/No project detected|PROJECT_PATH|no project path/i.test(e)?"NoProject":/Missing.*parameter|invalid parameters|Unknown feature|must be|Must specify|cannot be used together|invalid/i.test(e)?"BadRequest":/Too many files|Maximum allowed/i.test(e)?"TooManyFiles":/does not exist|not exist|not found|No valid|not a .ets|not a supported|Unsupported/i.test(e)?"InvalidFile":"ToolError"}function jm(n,e,t,r){return new kl(n,e,t,r)}import*as Ct from"fs";import*as $e from"path";function hS(n){return"method"in n&&!("id"in n)}import{spawn as gS}from"child_process";import*as yS from"crypto";import{EventEmitter as WL}from"events";import*as Ir from"fs";import*as wS from"net";import*as jt from"path";var VL=50*1024*1024,GL=60*1e3,qL=10*1e3,zL=64*1024;function JL(n){let e=jt.resolve(n).replace(/\\/g,"/");return e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),process.platform==="win32"?e.toLowerCase():e}function YL(n){return yS.createHash("sha1").update(JL(n)).digest("hex").slice(0,12)}function KL(n){let e=jt.resolve(n),t=e.split(jt.sep),r=t.lastIndexOf("out");return r>0?t.slice(0,r+1).join(jt.sep):jt.dirname(e)}var an=class extends WL{constructor(t){super();this.config=t}process=null;buffer=Buffer.alloc(0);isClosing=!1;socket=null;_ownsProcess=!1;get pid(){return this.process?.pid??null}get ownsProcess(){return this._ownsProcess}get isSocketMode(){return this.socket!==null}ensureDirectories(){let t=jt.join(this.config.logPath,"lspLog");return Ir.existsSync(t)||Ir.mkdirSync(t,{recursive:!0}),Ir.existsSync(this.config.indexingDataLocation)||Ir.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){this.config.useSocket&&this.config.projectPath?await this.startSocket(t):await this.startStdio(t)}async startStdio(t){this._ownsProcess=!0;let r=this.ensureDirectories();f.debug(`[LspClient] serverMaxSize=${t}MB`);let i=$o({serverPath:this.config.serverPath,lspLogPath:r,serverMaxSize:t}),o=On(this.config.nodePath);f.debug(`[LspClient] Starting process: node ${i.join(" ")}`),f.debug(`[LspClient] nodePath: ${o}`),this.process=gS(o,i,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0}),this.bindProcessEvents(!0,!0),await new Promise(s=>setTimeout(s,500)),f.info("[LspClient] start lsp process success")}async startSocket(t){let r=this.ensureDirectories(),i=this.config.projectPath,o=KL(this.config.serverPath),s=jt.join(i,".idea",".deveco","arkts",".cache",`lsp-socket-${YL(o)}.properties`),a=this.tryReadPortFile(s);if(a!==null)try{f.info(`[LspClient] Port file found (lspSocketPort=${a}), connecting to existing server`),this._ownsProcess=!1,await this.connectSocket(a),f.info("[LspClient] Connected to existing socket server");return}catch(d){f.warn(`[LspClient] Failed to connect to existing socket server (port=${a}): ${d instanceof Error?d.message:d}, falling back to spawn`)}let c=3,l=null;for(let d=1;d<=c;d++)try{d===1?f.info("[LspClient] Spawning server in socket mode"):f.info(`[LspClient] Retry ${d}/${c} spawning socket server`),this._ownsProcess=!0,await this.spawnSocketServer(t,r,i),f.info("[LspClient] Socket server started and connected");return}catch(g){l=g instanceof Error?g:new Error(String(g)),f.warn(`[LspClient] Spawn attempt ${d}/${c} failed: ${l.message}`),this.cleanupSpawnResidue()}throw new Error(`Failed to start socket server after ${c} attempts: ${l?.message}`)}cleanupSpawnResidue(){if(this.process){try{this.process.exitCode===null&&this.process.signalCode===null&&this.process.kill()}catch{}this.process=null}if(this.socket){try{this.socket.destroy()}catch{}this.socket=null}}tryReadPortFile(t){try{if(!Ir.existsSync(t))return null;let i=Ir.readFileSync(t,"utf8").match(/lspSocketPort\s*=\s*(\d+)/);if(i){let o=parseInt(i[1],10);if(Number.isFinite(o)&&o>0)return o}return null}catch{return null}}async spawnSocketServer(t,r,i){f.debug(`[LspClient] serverMaxSize=${t}MB`);let o=$o({serverPath:this.config.serverPath,lspLogPath:r,serverMaxSize:t,transportFlag:"--scope=multi",projectPath:i}),s=On(this.config.nodePath);f.debug(`[LspClient] Starting process (socket): node ${o.join(" ")}`),f.debug(`[LspClient] nodePath: ${s}`),this.process=gS(s,o,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0,detached:!0});let a=await this.waitForPortFromStdout(GL);f.debug(`[LspClient] LSP_SOCKET_LISTENING port=${a}`),await this.connectSocket(a),this.bindProcessEvents(!0,!1)}waitForPortFromStdout(t){return new Promise((r,i)=>{let o=this.process?.stdout;if(!o){i(new Error("LSP server failed to start: no stdout"));return}let s=/LSP_SOCKET_LISTENING:(\d+)/,a="",c=setTimeout(()=>{o.removeListener("data",l),i(new Error("LSP server failed to start: port not received within timeout"))},t),l=d=>{a+=d.toString("utf8");let g=a.match(s);if(g){clearTimeout(c),o.removeListener("data",l),r(parseInt(g[1],10));return}a=a.slice(-zL)};o.on("data",l)})}connectSocket(t){return new Promise((r,i)=>{let o=wS.connect(t,"127.0.0.1"),s=setTimeout(()=>{o.destroy(),i(new Error(`TCP connection to LSP socket timed out (port ${t})`))},qL);o.on("connect",()=>{clearTimeout(s),this.socket=o,this.bindSocketEvents(o),r()}),o.on("error",a=>{clearTimeout(s),i(new Error(`TCP connection to LSP socket failed: ${a.message}`))})})}bindSocketEvents(t){t.on("data",r=>this.handleData(r)),t.on("error",r=>{f.error(`[LspClient] socket error: ${r.message}`),this.isClosing||this.emit("error",r)}),t.on("close",()=>{f.info("[LspClient] socket closed"),this.isClosing||this.emit("error",new Error("LSP socket closed"))})}attachProcess(t,r){if(this.process)throw new Error("[LspClient] process already attached");this._ownsProcess=!0,this.process=t,this.bindProcessEvents(r?.stderrAsError??!0,!0),f.info("[LspClient] attached to external process")}bindProcessEvents(t=!0,r=!0){this.process&&(r&&this.process.stdout?.on("data",i=>{this.handleData(i)}),this.process.stderr?.on("data",i=>{let o=i.toString("utf8").trim();f.error(`[LspClient] stderr: ${o}`),!this.isClosing&&t&&this.emit("error",new Error(`[LspClient] stderr: ${o}`))}),this.process.on("exit",i=>{f.info(`[LSP EXIT] code=${i}`),this.isClosing||this.emit("error",new Error(`LSP process exited with code ${i}`))}))}sendRaw(t,r){let i=this.buildLspMessage(t);if(this.socket&&!this.socket.destroyed&&this.socket.writable){f.debug(`[LspClient] [SOCKET SEND] ${r}: ${t.slice(0,200)}`),this.socket.write(i,"utf8");return}if(!this.process?.stdin?.writable){f.warn("[LspClient] Cannot send message, no writable transport");return}f.debug(`[LspClient] send message: ${r}`),this.process.stdin.write(i,"utf8")}send(t,r,i){let o={jsonrpc:"2.0",method:t,params:r};i!==void 0&&(o.id=i),this.sendRaw(JSON.stringify(o),t)}sendNotification(t,r){this.sendRaw(JSON.stringify({jsonrpc:"2.0",method:t,params:r}),t)}sendRequest(t,r,i){this.sendRaw(JSON.stringify({jsonrpc:"2.0",id:i,method:t,params:r}),t)}buildLspMessage(t){return`Content-Length: ${Buffer.from(t,"utf8").length}\r
1322
+ \r
1323
+ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this.buffer.indexOf(`\r
1324
+ \r
1325
+ `);if(r===-1)break;let o=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!o){f.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(o[1],10);if(!Number.isFinite(s)||s<0||s>VL){f.warn(`[LspClient] Invalid Content-Length: ${o[1]}, drop until next packet`),this.buffer=this.buffer.slice(r+4);continue}let a=r+4,c=a+s;if(this.buffer.length<c)break;let l=this.buffer.slice(a,c).toString("utf8"),d=this.recoverFramedJson(l);if(d&&d.rest.length>0){f.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${l.length}, restLen=${d.rest.length}`),this.logSocketRecv(d.json),this.emit("message",d.json),this.buffer=Buffer.concat([Buffer.from(d.rest,"utf8"),this.buffer.slice(c)]);continue}this.logSocketRecv(l),this.emit("message",l),this.buffer=this.buffer.slice(c)}}logSocketRecv(t){this.socket&&f.debug(`[LspClient] [SOCKET RECV] ${t.slice(0,200)}`)}waitForExitOrTimeout(t){let r=this.process;return!r||r.exitCode!==null||r.signalCode!==null?Promise.resolve():new Promise(i=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(c),r.off("exit",a),i())},a=()=>s();r.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let r=t.search(/\S/);if(r<0||t[r]!=="{"&&t[r]!=="[")return null;let i=0,o=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(o=!1);continue}if(c==='"'){o=!0;continue}if(c==="{"||c==="["){i++;continue}if((c==="}"||c==="]")&&(i--,i===0)){let l=t.slice(r,a+1),d=t.slice(a+1);return{json:l,rest:d}}}return null}stop(){if(this.isClosing=!0,this.socket){this.socket.destroy(),this.socket=null,this.process=null;return}let t=this.process;if(!t)return;if(this.process=null,t.exitCode===null&&t.signalCode===null)try{t.kill()}catch{}}};var cn=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,r){return new Promise((i,o)=>{let s;r>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),o(new Error(`LSP request '${t}' (id=${e}) timeout after ${r}ms`))},r),this.timeouts.set(e,s)),this.pending.set(e,{resolve:i,reject:o,method:t,timer:s})})}resolvePending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.resolve(t),this.pending.delete(e),!0):!1}rejectPending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.reject(t),this.pending.delete(e),!0):!1}register(e,t){this.callbacks.set(e,t)}emit(e,t,r){f.debug(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let i=this.callbacks.get(e);if(i)try{i(t,r)}finally{this.callbacks.delete(e)}else{let o=[...this.callbacks.keys()].map(s=>String(s));f.debug(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${o.join(",")}]`)}}registerTimeout(e,t,r,i){let o=this.timeouts.get(e);o&&clearTimeout(o);let s=setTimeout(()=>{f.debug(`[RequestCallbackManager] timeout, key=${e}, method=${t}`);try{i()}finally{this.timeouts.delete(e)}},r);this.timeouts.set(e,s)}clearTimeout(e){let t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e))}deleteCallback(e){this.callbacks.delete(e)}hasCallback(e){return this.callbacks.has(e)||this.pending.has(e)}clear(e){this.clearTimeout(e);let t=this.pending.get(e);t&&(t.reject(new Error(`Request '${t.method}' (id=${e}) cancelled`)),this.pending.delete(e)),this.callbacks.delete(e)}rejectAll(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear();for(let[,t]of this.timeouts)clearTimeout(t);this.timeouts.clear(),this.callbacks.clear()}};var Rl=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var so=class{map=new Map;register(e,t){let r=this.map.get(e);r||(r=new Set,this.map.set(e,r)),r.add(t)}unregister(e,t){let r=this.map.get(e);r&&(t!==void 0?r.delete(t):r.clear(),r.size===0&&this.map.delete(e))}invoke(e,...t){let r=this.map.get(e);if(r)for(let i of r)try{i(...t)}catch(o){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,o)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function N(n){return typeof n=="object"&&n!==null}var vS=20*1e3,XL=30*1e3,bS=300,ZL=300;function QL(){let n=process.env.DEVECO_CLI_LSP_STANDARD_EXIT_TIMEOUT_MS;if(n===void 0||n==="")return bS;let e=parseInt(n,10);return Number.isFinite(e)?Math.max(ZL,e):bS}var Dl=class{client;nextRequestId=1;stopOnce=null;callbacks=new so;requestCallbacks=new cn;diagnosticMap=new Map;initProgressReset=null;notificationWaiters=new Map;get lspPid(){return this.client.pid}constructor(e){this.client=new an(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{f.info("[ClientMessageHandle] Sending shutdown request"),this.client.sendRequest(b.SHUTDOWN,null,this.nextRequestId++),f.info("[ClientMessageHandle] Sending exit notification"),this.client.sendNotification(b.EXIT,null),f.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(QL()),f.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(b.BROADCAST),this.callbacks.register(b.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(b.BROADCAST,e)}async sendInitialize(e){let t=this.nextRequestId++,r=this.requestCallbacks.registerPending(t,b.INITIALIZE,Qe);return this.client.sendRequest(b.INITIALIZE,e,t),r}sendInitializeResettable(e,t){let r=this.nextRequestId++,i=this.requestCallbacks.registerPending(r,b.INITIALIZE,0);return this.client.sendRequest(b.INITIALIZE,e,r),new Promise((o,s)=>{let a,c=()=>{a=setTimeout(()=>{this.initProgressReset=null,s(new Error(`LSP initialization timeout after ${t}ms`))},t)},l=()=>{clearTimeout(a),c()};this.initProgressReset=l,c(),i.then(()=>{clearTimeout(a),this.initProgressReset=null,o()},d=>{clearTimeout(a),this.initProgressReset=null,s(d)})})}sendInitialized(){this.client.sendNotification(b.INITIALIZED,{})}sendInitializeAndWaitForNotification(e,t,r,i,o){return new Promise((s,a)=>{let c={initializeResolved:!1,notificationResolved:!1},l=this.startInitTimer(t,r,a);this.initProgressReset=()=>{l.reset(),o?.()};let d=()=>{c.initializeResolved&&c.notificationResolved&&(l.clear(),s())};this.notificationWaiters.set(t,()=>{c.notificationResolved=!0,d()});let g=this.nextRequestId++;this.client.sendRequest(b.INITIALIZE,e,g),this.requestCallbacks.registerPending(g,b.INITIALIZE,0).then(()=>{c.initializeResolved=!0;try{i()}catch(w){l.clear(),a(w instanceof Error?w:new Error(String(w)));return}d()},w=>{l.clear(),a(w)})})}startInitTimer(e,t,r){let i,o=()=>{clearTimeout(i),this.initProgressReset=null,this.notificationWaiters.delete(e)},s=()=>{i=setTimeout(()=>{o(),r(new Error(`LSP initialization timeout after ${t}ms`))},t)},a=()=>{clearTimeout(i),s()};return s(),{reset:a,clear:o}}sendDidOpen(e){let t=e.textDocument.uri;this.diagnosticMap.has(t)||(this.diagnosticMap.set(t,new Rl(t)),this.registerDiagnosticTimeout(t)),this.client.sendNotification(b.DID_OPEN,e)}sendDidChange(e){let t=e.textDocument.uri,r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t)),this.client.sendNotification(b.DID_CHANGE,e)}closeFile(e){this.cleanupDiagnosticState(e.textDocument.uri),this.client.sendNotification(b.DID_CLOSE,e)}sendLspRequest(e,t,r=XL){let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}onDidChangeWatchedFiles(e){e.length!==0&&this.client.sendNotification(b.WORKSPACE_DID_CHANGE_WATCHED_FILES,{changes:e})}sendDidChangeConfiguration(e){this.client.sendNotification(b.WORKSPACE_DID_CHANGE_CONFIGURATION,{settings:e})}sendNotification(e,t){this.client.sendNotification(e,t)}getDiagnosticMessages(e){let t=this.diagnosticMap.get(e);return t?t.get():[]}clearDiagnostic(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let i=r instanceof Error?r.message:String(r);f.error(`[LSP] JSON parse error: ${i}, raw: ${e}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotificationOrRequest(t):f.warn(`[LSP] Unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t===void 0)return;let r=t;if(e.error){let i=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(r,i)}else this.requestCallbacks.resolvePending(r,e.result)}handleNotificationOrRequest(e){let t=e.method;if(!t)return;this.initProgressReset?.();let r=this.notificationWaiters.get(t);if(r){this.notificationWaiters.delete(t),r();return}switch(t){case b.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case b.PROGRESS:this.handleProgress(e.params);break;case b.WINDOW_SHOW_MESSAGE:f.debug(`[LSP] window/showMessage: ${JSON.stringify(e.params)}`);break;case b.WINDOW_LOG_MESSAGE:f.debug(`[LSP] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.broadcastToClients(e)}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=e.uri,r=this.diagnosticMap.get(t);if(!r)return;let i=e.diagnostics||[];this.normalizeDiagnostics(i),r.set(i),this.finalizeDiagnostic(t,i)}normalizeDiagnostics(e){for(let t of e)if(t.severity!==void 0){let r={1:"Error",2:"Warning",3:"Information",4:"Hint"};t.severityStr=r[t.severity]||"Unknown"}}handleProgress(e){N(e)&&this.broadcastToClients({jsonrpc:L,method:b.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,b.PUBLISH_DIAGNOSTICS,vS,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${vS}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,r){let i={uri:e,diagnostics:t,...r?{errorMessage:r}:{}};this.requestCallbacks.emit(e,b.PUBLISH_DIAGNOSTICS,i),this.diagnosticMap.get(e)?.clear()}handleError(e){let t=Array.from(this.diagnosticMap.keys()).filter(r=>this.requestCallbacks.hasCallback(r));if(t.length>0){let r={range:{start:{line:0,character:0},end:{line:0,character:0}},severity:1,message:e.message};for(let i of t)this.finalizeDiagnostic(i,[r]);return}this.broadcastToClients({jsonrpc:L,method:b.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var xl=class{uri;messages=[];receivedTypes=new Set;uniqueMessages=new Set;isFromEditor=!1;constructor(e){this.uri=e}setReceivedType(e){this.receivedTypes.add(e)}addMessage(e,t){this.receivedTypes.add(e);let r=`${e}:${t}`;if(this.uniqueMessages.has(r)){f.info(`[LegacyDiagnostic] addMessage: duplicate message=${r}`);return}this.uniqueMessages.add(r),this.messages.push(new Hm(e,t))}clearMessages(){this.messages=[]}clear(){this.receivedTypes.clear(),this.uniqueMessages.clear(),this.messages=[]}hasReceivedAllTypes(e){for(let t of e)if(!this.receivedTypes.has(t))return!1;return!0}getMessages(){return this.messages.map(e=>e.diagnostics)}},Hm=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var e_={EXIT:"exit",INITIALIZED:"initialized",ON_DID_CHANGE_PACKAGE_DEPENDENCIES:"aceProject/onDidChangePackageDependencies",ON_ASYNC_DID_OPEN:"aceProject/onAsyncDidOpen",ON_ASYNC_DID_CHANGE:"aceProject/onAsyncDidChange",DID_CLOSE:"textDocument/didClose",ON_ASYNC_HOVER:"aceProject/onAsyncHover",ON_ASYNC_DEFINITION:"aceProject/onAsyncDefinition",ON_ASYNC_FIND_USAGES:"aceProject/onAsyncFindUsages"},t_={MODULE_INIT_FINISH:vi.MODULE_INIT_FINISH,INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing"},_={...e_,...t_},ln={EXIT:"exit",INITIALIZED:"initialized",EMPTY:"empty",ON_DID_CHANGE_PACKAGE_DEPENDENCIES:"onDidChangePackageDependencies",ON_ASYNC_DID_OPEN:"onAsyncDidOpen",ON_ASYNC_DID_CHANGE:"onAsyncDidChange",DID_CLOSE:"didClose",ON_ASYNC_HOVER:"onAsyncHover",ON_ASYNC_DEFINITION:"onAsyncDefinition",ON_ASYNC_FIND_USAGES:"onAsyncFindUsages"},SS=new Set([1e3,2e3,3e3,3001]);function r_(n){if(!N(n))return!1;let e=n.textDocument;return N(e)&&typeof e.uri=="string"}function n_(n){return N(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function i_(n){return N(n)&&typeof n.moduleName=="string"&&typeof n.current=="number"&&typeof n.total=="number"?`indexing module '${n.moduleName}', ${n.current} of total ${n.total} modules`:`params=${JSON.stringify(n??null)}`}var Al=class n{client;isInitialized=!1;stopOnce=null;callbacks=new so;requestCallbacks=new cn;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;get lspPid(){return this.client.pid}constructor(e){this.client=new an(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{f.info("[LegacyClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:L,method:_.EXIT,params:{}}),ln.EXIT),f.info("[LegacyClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),f.info("[LegacyClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(_.BROADCAST),this.callbacks.register(_.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(_.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(_.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(_.INDEXING_PROGRESS_UPDATE,e)}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}sendInitialize(e,t){this.client.send("initialize",e,t)}sendInitialized(e){this.client.sendRaw(JSON.stringify({jsonrpc:L,method:_.INITIALIZED,params:{editors:e}}),ln.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:L,id:0,result:{}}),ln.EMPTY)}sendAsyncRequest(e,t,r,i){if(!N(t)){f.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!r_(t)){f.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof r!="number"){f.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(r)}`);return}let o=t.textDocument.uri,s=xt(o);t.textDocument.uri=s,delete t.requestId;let a=i??e;f.info(`[LSP] sendAsyncRequest ${a}, filePath: ${o}`),this.client.sendRaw(JSON.stringify({jsonrpc:L,method:e,params:{params:t,requestId:r}}),a)}onDidChangeWatchedFiles(e){if(f.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let r of e){if(!n_(r)){f.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:L,method:_.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),_.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!N(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){f.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;f.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:L,method:_.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),ln.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let i=xt(t);e.textDocument.uri=i,f.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new xl(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,_.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:L,method:_.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),ln.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=xt(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,_.PUBLISH_DIAGNOSTICS)),f.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:L,method:_.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),ln.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=xt(e);f.info(`[LSP] didClose, uri: ${r}`);let i=this.diagnosticMap.get(r);if(!t&&(!i||i.isFromEditor)){f.info(`[LSP] closeFile skip, !diagnostic: ${!i}, isFromEditor: ${i?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:L,method:_.DID_CLOSE,params:{textDocument:{uri:r}}}),ln.DID_CLOSE)}getDiagnosticMessage(e){let t=xt(e),r=this.diagnosticMap.get(t);return r?r.getMessages():[]}clear(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){try{let t=JSON.parse(e);this.handleLspMessage(t)}catch(t){let r=t instanceof Error?t.message:String(t);f.error(`[LSP] JSON parse error: ${r}, raw: ${e}`)}}handleError(e){let t=this.getPendingDiagnosticUris();if(t.length>0){let r=JSON.stringify({message:e.message,severity:"Error",severityStr:"Error"});for(let i of t)this.finalizeDiagnostic(i,_.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:L,method:_.ARKTS_ERROR,params:{message:e.message}})}handleLspMessage(e){let t=e.method;t!==void 0&&(!this.isInitialized&&this.handlePreInitMessage(t,e)||this.handlePostInitMessage(t,e))}handlePreInitMessage(e,t){switch(e){case _.MODULE_INIT_FINISH:return f.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(_.MODULE_INIT_FINISH),this.callbacks.unregister(_.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case _.INDEXING_PROGRESS_UPDATE:return f.info(`[LSP] onIndexingProgressUpdate: ${i_(t.params)}`),this.callbacks.invoke(_.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case _.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case _.ON_PACKAGE_CHANGE_FINISH:f.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case _.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case _.ON_ASYNC_HOVER:this.handleAsyncResponse(t,_.HOVER);return;case _.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,_.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case _.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,_.REFERENCES);return;default:f.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){f.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;N(t)&&N(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){f.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,r={jsonrpc:L,method:_.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){f.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(r);return}if(!(t.length>0&&t[0]===!0)){f.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(r);return}f.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){f.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let r=e.params;if(!N(r)){f.warn("[LSP] aceProject/onAsyncHover message invalid");return}let i=r.requestId;if(typeof i!="number"){f.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(i,t,r)}handleForceOpenFile(e){if(!e){f.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,_.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){f.info("[LSP] publishDiagnostics uri is null");return}let r=e.version??-1;if(r===-1)return;let i=this.diagnosticMap.get(t);if(!i){f.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let o=e.diagnostics||[];o.length!==0?o.forEach(s=>{this.normalizeDiagnostic(s),i.addMessage(r,JSON.stringify(s))}):i.setReceivedType(r),i.hasReceivedAllTypes(SS)&&this.finalizeDiagnostic(t,_.PUBLISH_DIAGNOSTICS,i.getMessages())}normalizeDiagnostic(e){let t=e;if(delete t.source,t.severity!==void 0){let r=typeof t.severity=="number"?t.severity:parseInt(t.severity),o={1:"Error",2:"Warning",3:"Information",4:"Hint"}[r]||"Unknown";t.severityStr=o,t.severity=o}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let r=e[t];r&&typeof r.line=="number"&&(r.line=r.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,n.DIAGNOSTIC_TIMEOUT_MS,()=>{let r=this.diagnosticMap.get(e),i=r?r.getMessages():[];this.finalizeDiagnostic(e,t,i,i.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,i){let o={uri:e,diagnostics:r,...i?{errorMessage:i}:{}};this.requestCallbacks.emit(e,t,o),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import Um from"path";import*as _l from"path";var Il=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var Tl=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var Ol=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var Ml=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Nl=class{typeSetting=new Ol;parameterNames=new Ml};var Ll=class{constructor(e,t,r,i){this.rootUri=e;this.lspServerWorkspacePath=he(_l.dirname(t)),this.indexingDataLocation=he(i),this.loggerPath=he(_l.join(r,"lspLog"))}modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new Il;gutterIconsSetting=new Tl;inlayHintsSetting=new Nl;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as ES from"path";var Us=class{productName="default";buildModeName="debug";targetName="default";arkTSVersion="1.1";resourceDirectories=[];targetESVersion="ES2021";maxFlowDepth=2e3;caseSensitiveCheck=!0;tsImportSendable=!1;compatibleSdkVersionStage="";useNormalizedOHMUrl=!0;reExportCheckMode="noCheck";skipOhModulesLint=!1;byteCodeHar=!0;obfuscationRuleOptionsEnable=!1;enableStrictCheckOHModules=!1;sourceRoots=[];constructor(e){e&&this.resourceDirectories.push(he(ES.join(e,"src","main","resources")))}};var o_="OS",ao=class{deviceType=[5];aceLoaderPath;modulePath;jsComponentType="declarative";sdkJsPath;compatibleSdkVersion;compatibleSdkLevel;compileSdkLevel;compileSdkVersion="6.0.1.112";compileSdkType="Release";syscap={NDeviceSysCaps:[],addedSysCaps:[]};apiType="stageMode";hosSdkPath;runtimeOs=`Harmony${o_}`;moduleName;moduleType;compileMode="jsbundle";crossPlatform=!1;ignoreCrossPlatform=!1;packageManagerType="ohpm";permissions=[];testPermissions=[];buildProfileParam;appParam={bundleType:"app"};packageName;projectType="OHOS";projectName;moduleDependencies;moduleJsonParam=null;globalDeclarationFiles=[];constructor(e){e?(this.modulePath=e,this.buildProfileParam=new Us(e)):this.buildProfileParam=new Us}toString(){return JSON.stringify(this)}};var co=class{constructor(e=[]){this.pages=e}pagesFileName="main_pages.json";metaDataList=[]};import*as ze from"path";import*as po from"fs";var $l=class{modulePath;dependencies={};dynamicDependencies={}};var ei=class{registryType;resolved;name;version;type;constructor(e){let t=typeof e=="object"&&e!==null?e:{};this.name=typeof t.name=="string"?t.name:"",this.version=typeof t.version=="string"?t.version:"",typeof t.registryType=="string"?this.registryType=t.registryType:this.registryType=typeof t.path=="string"?"local":"ohpm",typeof t.resolved=="string"?this.resolved=t.resolved:typeof t.storePath=="string"?this.resolved=t.storePath:this.resolved="",this.type=typeof t.type=="string"?t.type:void 0}};var lo=class{constructor(e,t,r){this.projectPath=e;this.moduleName=t;this.modulePath=r}dependencies=[];devDependencies=[];dynamicDependencies=[];finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[]};import*as Tr from"path";import*as Fl from"fs";var uo=class{name="";version="";storePath="";dependencyPath="";path=""};var V={HVIGOR_CACHE:".hvigor",DEPENDENCY:"dependencyMap",JSON5:".json5",KEY_DEPENDENCY:"dependencies",KEY_DYNAMIC_DEPENDENCY:"dynamicDependencies",KEY_DEV_DEPENDENCY:"devDependencies",OH_MODULES_PATH:"oh_modules",OHPM_PATH:".ohpm",LOCK_JSON5_FILE:"lock.json5",OH_PACKAGE_JSON5:Pe.OH_PACKAGE_JSON5},Bs=`${V.HVIGOR_CACHE}/${V.DEPENDENCY}`,ti=`${V.DEPENDENCY}${V.JSON5}`,Cte=Pe.SYNC_OUTPUT_PATH;var Ws=class n{dependencyPath;modulePath;projectPath;static FILE_DEPENDENCY_PREFIX="file:";static PARAMETER_PREFIX="@param:";fileSpecPattern;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;static PACKAGE_JSON_PARSER_MAP=new Map;dependencies=[];devDependencies=[];dynamicDependencies=[];static getInstance(e,t,r){let i=this.PACKAGE_JSON_PARSER_MAP.get(e);return i||(i=new n(e,t,r),this.PACKAGE_JSON_PARSER_MAP.set(e,i)),i}constructor(e,t,r){this.dependencyPath=e,this.modulePath=t,this.projectPath=r,this.fileSpecPattern=n.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=Tr.join(this.dependencyPath,V.OH_PACKAGE_JSON5),r=ut(t);r&&(this.dependencies=this.getDependencyList(r,V.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(r,V.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(r,V.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let r=[];if(!N(e))return r;let i=e[t];if(!N(i))return r;for(let[o,s]of Object.entries(i)){if(typeof s!="string"){f.error(`${o} package dependency value is not String ${t}`);continue}let a=new uo;a.name=o;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(n.PARAMETER_PREFIX)||this.parseDependencyPath(o,c,a,!1),r.push(a)}return r}parseDependencyPath(e,t,r,i){if(!(!e||!t))try{let o=Tr.normalize(Tr.join(this.modulePath,V.OH_MODULES_PATH,e));if(!(t.startsWith(n.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){r.dependencyPath=o;return}if(r.path=t,this.fileNameForOhpm.test(t)){r.dependencyPath=o;return}let s=t;if(t.startsWith(n.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(n.FILE_DEPENDENCY_PREFIX.length)),Tr.isAbsolute(s)){r.dependencyPath=o;return}i||(o=Tr.resolve(this.modulePath,s)),Fl.existsSync(o)&&Fl.statSync(o).isDirectory()&&(r.dependencyPath=o)}catch(o){f.error("parser dependency path is invalid",o)}}};import*as ri from"fs";import*as dn from"path";import s_ from"json5";var jl=class n{projectPath;static FILE_DEPENDENCY_PREFIX="file:";static MAX_LOCK_FILE_SIZE=20*1024*1024;static MAX_KEYS_PER_OBJECT=5e4;static MAX_JSON_DEPTH=50;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[];storePathMap=new Map;lockFileCache=null;lockFileParsed=!1;constructor(e=""){this.projectPath=e}parseDependencies(e){if(!this.ensureLockFileParsed())return!1;let t=this.lockFileCache;return this.extractDependencies(t.modules,t.storePathMap,e),!0}ensureLockFileParsed(){if(this.lockFileParsed)return this.lockFileCache!==null;this.lockFileParsed=!0;let e=this.getLockFilePath(),t=this.readLockFile(e);if(!t)return!1;let r=this.validateLockFile(t);return r.valid?(this.lockFileCache={modules:r.modules,storePathMap:this.parseStorePathMap(r.packages)},!0):!1}getLockFilePath(){return dn.join(this.projectPath,V.OH_MODULES_PATH,V.OHPM_PATH,V.LOCK_JSON5_FILE)}static checkObjectDepth(e,t,r=0){if(r>t)return!1;if(typeof e!="object"||e===null)return!0;if(Array.isArray(e)){for(let i of e)if(!n.checkObjectDepth(i,t,r+1))return!1;return!0}for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i)&&!n.checkObjectDepth(e[i],t,r+1))return!1;return!0}readLockFile(e){if(!ri.existsSync(e))return f.error("lock file does not exist"),this.clearDependencies(),null;try{let t=ri.statSync(e);if(t.size>n.MAX_LOCK_FILE_SIZE)return f.error(`lock file is too large (${t.size} bytes), read aborted`),this.clearDependencies(),null}catch(t){return f.error(`Failed to stat lock file: ${t instanceof Error?t.message:String(t)}`),this.clearDependencies(),null}try{let t=ri.readFileSync(e,"utf8"),r=s_.parse(t);return r?n.checkObjectDepth(r,n.MAX_JSON_DEPTH)?r:(f.error("lock.json5 nesting depth exceeds limit"),this.clearDependencies(),null):(f.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return f.error(`Error parsing lock.json5: ${t instanceof Error?t.message:String(t)}`),this.clearDependencies(),null}}validateLockFile(e){if(!N(e))return f.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return f.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let r=e.packages;return r?{valid:!0,modules:t,packages:r}:(f.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,r){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,V.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,V.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,V.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!N(e))return t;let r=0;for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;let o=e[i];if(!N(o)){f.error(`${i} value is not json object`);continue}if(++r>n.MAX_KEYS_PER_OBJECT){f.warn("lock.json5 packages object exceeds key limit, truncating");break}typeof o.storePath=="string"&&t.set(i,o.storePath)}return t}getDependencyList(e,t,r){if(!N(e))return[];let i=0;for(let o in e){if(!Object.prototype.hasOwnProperty.call(e,o))continue;if(++i>n.MAX_KEYS_PER_OBJECT){f.warn("lock.json5 modules object exceeds key limit, truncating");break}let s=e[o];if(N(s)){let a=typeof s.name=="string"?s.name:"";if(r==="."&&a===""||a===r)return this.getFinalDependencyList(e,t,o)}}return[]}getFinalDependencyList(e,t,r){let i=e[r];if(!N(i))return f.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!N(s))return[];let a=0;for(let c in s){if(!Object.prototype.hasOwnProperty.call(s,c))continue;if(++a>n.MAX_KEYS_PER_OBJECT){f.warn("lock.json5 dependencies object exceeds key limit, truncating");break}let l=s[c];if(!N(l))continue;let d=typeof l.specifier=="string"?l.specifier:"",g=typeof l.version=="string"?l.version:"",w=new uo;w.name=c,w.version=g.startsWith(n.FILE_DEPENDENCY_PREFIX)?g.substring(n.FILE_DEPENDENCY_PREFIX.length):g,this.parseDependencyPath(w,r,c,d,g);let R=`${c}@${g}`;this.storePathMap.has(R)&&(w.storePath=this.storePathMap.get(R)||""),o.push(w)}return o}parseDependencyPath(e,t,r,i,o){let s=dn.resolve(this.projectPath,dn.join(t,V.OH_MODULES_PATH,r));try{let a=o.startsWith(n.FILE_DEPENDENCY_PREFIX)?o.substring(n.FILE_DEPENDENCY_PREFIX.length):o,c=dn.isAbsolute(a)?a:dn.resolve(this.projectPath,a);ri.existsSync(c)?(e.path=i,e.dependencyPath=this.fileNameForOhpm.test(o)?s:c):e.dependencyPath=s}catch(a){f.error("Invalid dependency path in lock.json5, msg:",a instanceof Error?a.message:String(a))}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function PS(n){return N(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var ni=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new ur(this.projectPath)}moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e,t){let r=this.projectPath,i=ze.join(r,Bs),o=ze.join(i,ti);if(!po.existsSync(i)||!po.existsSync(o)){let l="Dependency map or JSON not found";return f.warn(`[Parser] getAllDependencyMap failed: ${l}.`),{status:"ERROR",message:`${l}, please rebuild project`}}let s=new lo(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,s),this.parseLockJson(s);let a=this.moduleInfoParse.getAllModuleInfo();if(a.length===0){let l="No modules found in build-profile.json5";return f.warn(`[Parser] getAllDependencyMap failed: ${l}.`),{status:"ERROR",message:l}}let c=Date.now();for(let l=0;l<a.length;l++){let d=a[l];if(PS(d)){try{E.assertModuleName(d.name)}catch{f.warn(`[Parser] Skipping module with invalid name: ${d.name}`);continue}this.parseSingleModule(d,i,s,e),((l+1)%50===0||l+1===a.length)&&(f.info(`[Parser] getAllDependencyMap progress: ${l+1}/${a.length} (${Date.now()-c}ms)`),t?.(l+1,a.length))}}return f.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-c}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],r=this.projectPath,i=ze.join(r,Bs),o=ze.join(i,ti);if(!po.existsSync(i)||!po.existsSync(o))return f.warn("[Parser] Dependency map or JSON not found."),t;let s=e&&e.length>0?new Set(e.map(l=>l.trim()).filter(Boolean)):null,a=new lo(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return f.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let l of c){if(!PS(l))continue;let d=l.name;try{E.assertModuleName(d)}catch{f.warn(`[Parser] Skipping module with invalid name: ${d}`);continue}if(s&&!s.has(d))continue;let g=ze.resolve(this.projectPath,l.srcPath),w=ze.join(i,d),R=he(g),z=this.buildModuleDependencies(d,R,w,a);z.moduleName=d,t.push(z)}return t}parseSingleModule(e,t,r,i){let o=e.name,s=ze.resolve(this.projectPath,e.srcPath),a=ze.join(t,o),c=he(s),l=new ao(c),d=this.buildModuleDependencies(o,c,a,r);this.parseModuleJson5(c,l);let g=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=o,l.moduleType=o,l.packageName=o,l.moduleDependencies=d,l.moduleJsonParam=new co(g),i.push(l)}buildModuleDependencies(e,t,r,i){let o=new lo(this.projectPath,e,t);Ws.getInstance(r,t,this.projectPath).parseDependency(o),this.parseLockJson(o),o.finalDependencies.push(...i.finalDependencies),o.finalDevDependencies.push(...i.finalDevDependencies),o.finalDynamicDependencies.push(...i.finalDynamicDependencies),o.finalDependencies.push(...o.finalDevDependencies);let a=new $l;return a.modulePath=t,this.toModuleDependencies(o,a),a}toModuleDependencies(e,t){let r={},i={};for(let o of e.finalDependencies)r[o.name]=new ei(o);for(let o of e.finalDynamicDependencies)i[o.name]=new ei(o);t.dependencies=r,t.dynamicDependencies=i}parseProjectDependencies(e,t){let r=ze.join(e,V.OH_PACKAGE_JSON5);if(!po.existsSync(r))return;Ws.getInstance(e,this.projectPath,this.projectPath).parseDependency(t)}parseLockJson(e){let t=this.getLockJson5Parser();t.parseDependencies(e.moduleName)?(e.finalDependencies=t.finalDependencies,e.finalDevDependencies=t.finalDevDependencies,e.finalDynamicDependencies=t.finalDynamicDependencies):(e.finalDependencies=e.dependencies,e.finalDevDependencies=e.devDependencies,e.finalDynamicDependencies=e.dynamicDependencies)}getLockJson5Parser(){return this.lockJson5Parser||(this.lockJson5Parser=new jl(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=ze.join(e,"src","main","module.json5"),i=ut(r);if(!N(i)||!N(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(N(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)N(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=ze.join(e,"src","main","resources","base","profile","main_pages.json"),r=ut(t);return!N(r)||!Array.isArray(r.src)?[]:r.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!N(t)||!N(t.data))){if(typeof t.data.apiVersion=="string"){let r=parseInt(t.data.apiVersion,10);!Number.isNaN(r)&&r>=26&&typeof t.data.platformVersion=="string"?e.compileSdkLevel=t.data.platformVersion:e.compileSdkLevel=t.data.apiVersion}typeof t.data.releaseType=="string"&&(e.compileSdkType=t.data.releaseType),typeof t.data.version=="string"&&(e.compileSdkVersion=t.data.version)}}getSdkPkg(){if(this.sdkPkgCache===void 0){let e=ze.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=ut(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!N(t)||!N(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!N(r)||typeof r.compatibleSdkVersion!="string")return;let[i,o]=this.parseBySplit(r.compatibleSdkVersion);e.compatibleSdkVersion=i,e.compatibleSdkLevel=o}getBuildProfile(){if(this.buildProfileCache===void 0){let e=ze.join(this.projectPath,"build-profile.json5");this.buildProfileCache=ut(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,e];let r=e.substring(0,t),i=e.substring(t+1,e.length-1);return[r,i]}parseDeviceTypes(e){return!N(e)||!Array.isArray(e.deviceTypes)?[]:e.deviceTypes.filter(t=>typeof t=="string").map(t=>this.getDeviceType(t))}getDeviceType(e){return{liteWearable:1,wearable:2,tv:3,car:4,phone:5,default:5,smartVision:6,tablet:7,router:8,pc:9,"2in1":10}[e]||0}};var Hl=class{constructor(e=[]){this.valueSet=e}};var mo=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var CS=(x=>(x[x.File=1]="File",x[x.Module=2]="Module",x[x.Namespace=3]="Namespace",x[x.Package=4]="Package",x[x.Class=5]="Class",x[x.Method=6]="Method",x[x.Property=7]="Property",x[x.Field=8]="Field",x[x.Constructor=9]="Constructor",x[x.Enum=10]="Enum",x[x.Interface=11]="Interface",x[x.Function=12]="Function",x[x.Variable=13]="Variable",x[x.Constant=14]="Constant",x[x.String=15]="String",x[x.Number=16]="Number",x[x.Boolean=17]="Boolean",x[x.Array=18]="Array",x[x.Object=19]="Object",x[x.Key=20]="Key",x[x.Null=21]="Null",x[x.EnumMember=22]="EnumMember",x[x.Struct=23]="Struct",x[x.Event=24]="Event",x[x.Operator=25]="Operator",x[x.TypeParameter=26]="TypeParameter",x))(CS||{}),kS=()=>Object.values(CS).filter(n=>typeof n=="number");var Ul=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Bl=class{applyEdit=!0;workspaceEdit=new Ul;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Hl(kS());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new mo;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Wl=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Vl=class{constructor(e=[]){this.valueSet=e}};var Gl=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var RS=(I=>(I[I.Text=1]="Text",I[I.Method=2]="Method",I[I.Function=3]="Function",I[I.Constructor=4]="Constructor",I[I.Field=5]="Field",I[I.Variable=6]="Variable",I[I.Class=7]="Class",I[I.Interface=8]="Interface",I[I.Module=9]="Module",I[I.Property=10]="Property",I[I.Unit=11]="Unit",I[I.Value=12]="Value",I[I.Enum=13]="Enum",I[I.Keyword=14]="Keyword",I[I.Snippet=15]="Snippet",I[I.Color=16]="Color",I[I.File=17]="File",I[I.Reference=18]="Reference",I[I.Folder=19]="Folder",I[I.EnumMember=20]="EnumMember",I[I.Constant=21]="Constant",I[I.Struct=22]="Struct",I[I.Event=23]="Event",I[I.Operator=24]="Operator",I[I.TypeParameter=25]="TypeParameter",I))(RS||{}),DS=()=>Object.values(RS).filter(n=>typeof n=="number");var ql=class{completionItemKind=new Vl(DS());completionItem=new Gl;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var zl=class{synchronization=new Wl;completion=new ql;hover={contentFormat:{},dynamicRegistration:{}};signatureHelp={signatureInformation:{},contextSupport:{},dynamicRegistration:{}};references={dynamicRegistration:{}};documentHighlight={dynamicRegistration:!0};documentSymbol=null;formatting={dynamicRegistration:{}};rangeFormatting={dynamicRegistration:{}};onTypeFormatting={dynamicRegistration:{}};declaration={};definition={linkSupport:{},dynamicRegistration:{}};codeLens=null;documentLink={tooltipSupport:{},dynamicRegistration:{}};colorProvider=null;rename={prepareSupport:!0,prepareSupportDefaultBehavior:null,honorsChangeAnnotations:null,dynamicRegistrationSupport:null};publishDiagnostics=null;foldingRage=null;typeHierarchy=null;callHierarchy={dynamicRegistration:{}};selectionRange=null;semanticTokens=new mo;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var Jl=class{workspace=new Bl;textDocument=new zl;notebookDocument=null;window=null;general=null;experimental=null};var Yl=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}};var Kl=class{constructor(e,t,r,i,o,s=!0,a,c=!1){this.sdkPath=e;this.rootUri=r;this.nodeMaxOldSpaceSize=o;this.useStandardProtocol=s;this.nodePath=a;this.useSocket=c;this.serverPath=mi(t,this.useStandardProtocol),this.logPath=ng(),this.indexLogPath=i||this.logPath,f.debug(`[LspServerProxy] arktsLangServer=${t}`),f.debug(`[LspServerProxy] useStandardProtocol=${this.useStandardProtocol}, useSocket=${this.useSocket}`),f.debug(`[LspServerProxy] serverPath=${this.serverPath}`);let l={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath,projectPath:this.rootUri,useSocket:this.useSocket,nodePath:this.nodePath};this.messageHandle=this.useStandardProtocol?new Dl(l):new Al(l),this.messageHandle.setBroadcastToClients(d=>this.onLspMessage(d))}messageHandle;get stdHandle(){return this.messageHandle}get legacyHandle(){return this.messageHandle}get lspPid(){return this.messageHandle.lspPid}onAsyncOpenFile(e){this.legacyHandle.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.legacyHandle.closeFile(e,t)}serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}async start(e,t,r){let i=!1;try{f.debug(`serverPath: ${this.serverPath}`),f.debug(`rootUri: ${this.rootUri}`),f.debug(`sdkPath: ${this.sdkPath}`),f.debug(`logPath: ${this.logPath}`);let o=xt(this.rootUri),s=new Ll(o,this.serverPath,this.logPath,this.indexLogPath),a=[],l=new ni(this.rootUri,this.sdkPath).getAllDependencyMap(a,r);if(l.status==="ERROR")throw new Error(`${l.message}`);this.fillModuleModelsPaths(a),s.modules=a;let d=ja(a.length,this.nodeMaxOldSpaceSize);await this.messageHandle.start(d),this.currentParams=new Yl(o,s,new Jl),this.useStandardProtocol?await this.startStandardProtocol(this.currentParams):await this.startLegacy(this.currentParams,e),i=!0}catch(o){this.lastStartErrorMessage=o instanceof Error?o.message:String(o),f.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(i)}async startStandardProtocol(e){let t=this.messageHandle,r=()=>t.broadcastToClients({jsonrpc:L,method:b.ARKTS_INDEXING_PROGRESS,params:{}});this.useSocket?(f.info("[LSP] socket mode: waiting for initialize response + aceProject/onModuleInitFinish"),await t.sendInitializeAndWaitForNotification(e,vi.MODULE_INIT_FINISH,Qe,()=>{f.info("[LSP] initialize response received"),r(),t.sendInitialized()},r),f.info("[LSP] initialize response + onModuleInitFinish received, initialization complete")):(await t.sendInitializeResettable(e,Qe),f.info("[LSP] initialize response received"),r(),t.sendInitialized())}async startLegacy(e,t){let r=this.messageHandle;r.sendInitialize(e,1),r.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:L,method:b.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((i,o)=>{r.onIndexingProgressUpdate(o),r.onInitializationCompleted(i)},"LSP initialization",Qe),r.sendInitialized(t)}withResettableTimeout(e,t,r){return new Promise((i,o)=>{let s,a=()=>{s=setTimeout(()=>{o(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),i()},c)})}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){f.debug(`[LSP] registerDiagnosticCallback uri='${e}', useStandardProtocol=${this.useStandardProtocol}`),this.messageHandle.registerRequestCallback(e,(t,r)=>{let i=N(r)?r:{};f.debug(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let o={jsonrpc:L,method:t,params:{uri:typeof i.uri=="string"?i.uri:e,diagnostics:Array.isArray(i.diagnostics)?i.diagnostics:[],...typeof i.errorMessage=="string"?{errorMessage:i.errorMessage}:{}}};this.onLspMessage(o)})}async hover(e){let t=e.textDocument.uri;return this.registerDiagnosticCallback(t),this.stdHandle.sendLspRequest(b.HOVER,e)}async definition(e){return this.stdHandle.sendLspRequest(b.DEFINITION,e)}async references(e){return this.stdHandle.sendLspRequest(b.REFERENCES,e)}async completion(e){return this.stdHandle.sendLspRequest(b.COMPLETION,e)}async documentSymbol(e){return this.stdHandle.sendLspRequest(b.DOCUMENT_SYMBOL,e)}async diagnostic(e){return this.stdHandle.sendLspRequest(b.DIAGNOSTIC,e,120*1e3)}async sendFeatureRequest(e,t){return this.stdHandle.sendLspRequest(e,t)}reloadDependenciesOnly(e){let t=e?.fullReload??!1,r=new ni(this.rootUri,this.sdkPath),i=this.getModuleModelsByName();if(t){f.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let l=r.getDependenciesOnly();this.markDependencyTypesIncremental(l);let d=this.mergeDepsOnlyIntoModuleList(l,i);return this.applyModuleModelsUpdate(d),this.sendDidChangeConfiguration({moduleSet:d}),f.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${d.length}`),this.lastDepsOnlyForDiff=l,l}let o=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(o.length===0&&s.size===0)return f.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];f.info(`[LspServerProxy] Module-level deps changed, parsing: [${o.join(", ")}]`);let a=r.getDependenciesOnly(o);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),this.sendDidChangeConfiguration({moduleSet:c}),f.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}sendDidChangeConfiguration(e){this.stdHandle.sendDidChangeConfiguration(e)}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),r=new Map(this.lastDepsOnlyForDiff.map(i=>[i.moduleName??"",i]));for(let i of e){let o=i.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(o,t,r),c=i.dependencies??{},l=i.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(d,g)=>{(i.dependencies??={})[d]=this.makeDeleteEntry(d,g)}),this.markAddAndDeleteInDeps(a,l,(d,g)=>{(i.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,g)})}}getOldDepsForModule(e,t,r){let i=t.get(e),o=i?.moduleDependencies?.dependencies??{},s=i?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(o).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(o=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:o,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let i of Object.keys(t))i in e||(t[i].type="add");for(let i of Object.keys(e))i in t||r(i,e[i])}makeDeleteEntry(e,t){return new ei({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new ao(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new co([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let i of e){let o=i.moduleName??"",s=t.get(o);s?(s.modulePath=i.modulePath,s.moduleDependencies=i):s=this.createMinimalModelFromDepsItem(i),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let i=new Map(r.map(s=>[s.moduleName??"",s])),o=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=i.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,i.delete(a)),o.push(s)}for(let[,s]of i)o.push(this.createMinimalModelFromDepsItem(s));return o}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=Si(Um.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=Si(Um.join(t,"default/openharmony/ets/api")),o=Si(Um.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=i,s.hosSdkPath=o}sendRequest(e){switch(e.method){case b.HOVER:this.stdHandle.sendLspRequest(b.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:L,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:L,id:e.id,error:{code:-32603,message:t.message}}));break;case b.DEFINITION:this.stdHandle.sendLspRequest(b.DEFINITION,e.params).then(t=>this.onLspMessage({jsonrpc:L,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:L,id:e.id,error:{code:-32603,message:t.message}}));break;case b.REFERENCES:this.stdHandle.sendLspRequest(b.REFERENCES,e.params).then(t=>this.onLspMessage({jsonrpc:L,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:L,id:e.id,error:{code:-32603,message:t.message}}));break;default:f.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!hS(e)){f.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case b.DID_OPEN:this.handleDidOpenNotification(e);break;case b.DID_CHANGE:this.handleDidChangeNotification(e);break;case b.DID_CLOSE:this.handleDidCloseNotification(e);break;case b.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;case b.DID_CREATE_FILES:this.handleDidCreateFiles(e);break;case b.DID_DELETE_FILES:this.handleDidDeleteFiles(e);break;default:f.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didOpen params");return}this.stdHandle.sendDidOpen(t)}handleDidChangeNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didChange params");return}this.stdHandle.sendDidChange(t)}handleDidCloseNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didClose params");return}this.stdHandle.closeFile(t)}handleDidChangeWatchedFiles(e){let t=e.params;!t||!Array.isArray(t.changes)||this.messageHandle.onDidChangeWatchedFiles(t.changes)}handleDidCreateFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(b.DID_CREATE_FILES,t)}handleDidDeleteFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(b.DID_DELETE_FILES,t)}async dispose(){await this.messageHandle.stop()}};import*as Or from"fs";import*as it from"path";import{createHash as c_}from"crypto";import{EventEmitter as l_}from"events";var Xl=class extends l_{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r}watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),r=new Set(this.watchers.keys());for(let i of t)r.has(i)||this.watchFile(i);for(let i of r)t.has(i)||(this.unwatchFile(i),f.info(`[ConfigFileWatcher] Stopped watching: ${i}`));f.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!Or.existsSync(t)){f.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Or.watch(t,r=>{r==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",r=>{f.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${r.message}`)}),f.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(r){f.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${r instanceof Error?r.message:String(r)}`)}}emitModuleAddedEvents(t,r){for(let i of t){let o=it.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:o,relativePath:i.srcPath,timestamp:r,moduleName:i.name})}}emitModuleRemovedEvents(t,r){for(let i of t){let o=it.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:o,relativePath:i.srcPath,timestamp:r,removedModuleName:i.name})}}emitModuleRenamedEvents(t,r){for(let i of t){let o=it.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name,removedModuleName:i.before.name})}}emitModuleMovedEvents(t,r){for(let i of t){let o=it.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let r=Date.now();this.emitModuleAddedEvents(t.added,r),this.emitModuleRemovedEvents(t.removed,r),this.emitModuleRenamedEvents(t.renamed,r),this.emitModuleMovedEvents(t.moved,r)}onBuildProfileChanged(){let t="__build_profile__",r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(o);if(s===this.lastModulesSnapshot){f.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,o);this.lastModules=o,this.lastModulesSnapshot=s,f.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,i)}computeModulesSnapshot(t){return t.map(i=>`${i.name}::${i.srcPath}`).sort().join("|")}diffModules(t,r){let i=this.buildModuleMatchState(r),o={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,i),this.matchRenamedModules(t,i,o),this.matchMovedModules(t,i,o),this.collectRemovedModules(t,i,o),this.collectAddedModules(r,i,o),o}buildModuleMatchState(t){let r=new Map,i=new Map;for(let o of t)r.set(o.srcPath,o),i.set(o.name,o);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:i}}matchExactModules(t,r){for(let i of t){let o=r.newBySrc.get(i.srcPath);o&&o.name===i.name&&(r.matchedOld.add(i),r.matchedNew.add(o))}}matchRenamedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newBySrc.get(o.srcPath);s&&!r.matchedNew.has(s)&&s.name!==o.name&&(i.renamed.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}matchMovedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newByName.get(o.name);s&&!r.matchedNew.has(s)&&s.srcPath!==o.srcPath&&(i.moved.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}collectRemovedModules(t,r,i){for(let o of t)r.matchedOld.has(o)||i.removed.push(o)}collectAddedModules(t,r,i){for(let o of t)r.matchedNew.has(o)||i.added.push(o)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=ut(t);if(typeof r!="object"||r===null)return[];let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=it.join(this.projectRoot,V.OH_PACKAGE_JSON5);Or.existsSync(r)&&t.push(r);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=it.resolve(this.projectRoot,o.srcPath),a=it.join(s,V.OH_PACKAGE_JSON5);Or.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return it.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Or.readFileSync(t,"utf-8");return c_("sha256").update(r).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let r=this.computeFileHash(t);r&&this.contentHashes.set(t,r);let i=Or.watch(t,o=>{o==="change"&&this.onFileChanged(t)});i.on("error",o=>{f.error(`[ConfigFileWatcher] Watch error for ${t}: ${o.message}`)}),this.watchers.set(t,i)}catch(r){f.error(`[ConfigFileWatcher] Failed to watch ${t}: ${r instanceof Error?r.message:String(r)}`)}}unwatchFile(t){let r=this.watchers.get(t);r&&(r.close(),this.watchers.delete(t)),this.contentHashes.delete(t);let i=this.debounceTimers.get(t);i&&(clearTimeout(i),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.computeFileHash(t);if(!o){f.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===o){f.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,o),f.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:it.basename(t),relativePath:it.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,i)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),f.info("[ConfigFileWatcher] All watchers stopped")}};import*as un from"fs";import*as Ht from"path";import{createHash as d_}from"crypto";import{EventEmitter as u_}from"events";var Zl=class extends u_{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=Ht.join(t,Bs)}dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!un.existsSync(this.depMapDir)){f.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=un.watch(this.depMapDir,{recursive:!0},(t,r)=>this.onDirEvent(t,r)),this.dirWatcher.on("error",t=>{f.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){f.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),f.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return he(Ht.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let i=r.replace(/\\/g,"/"),o;if(i===V.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===ti)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=Ht.join(this.depMapDir,r);un.existsSync(s)&&this.scheduleDebouncedFullScan()}stop(){this.dirWatcher&&(this.dirWatcher.close(),this.dirWatcher=null),this.fullScanTimer&&(clearTimeout(this.fullScanTimer),this.fullScanTimer=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.coalesceTimer&&(clearTimeout(this.coalesceTimer),this.coalesceTimer=null),this.pendingTags=[],this.pendingRenames=[],this.contentHashes.clear(),this.initialScanDone=!1,f.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=Ht.join(this.depMapDir,V.OH_PACKAGE_JSON5),r=Ht.join(this.depMapDir,ti),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...i.map(s=>({path:(E.assertModuleName(s.name),Ht.join(this.depMapDir,s.name,V.OH_PACKAGE_JSON5)),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!un.existsSync(s))continue;let c=this.canonicalPath(s),l=this.computeFileHash(s);if(!l)continue;let d=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,l);continue}d!==l&&(this.contentHashes.set(c,l),f.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=Ht.join(this.depMapDir,ti);try{let r=ut(t);if(typeof r!="object"||r===null)return[];let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return f.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${r instanceof Error?r.message:String(r)}`),[]}}scheduleCoalescedReload(t){this.pendingTags.push(t),t==="dep-map-json"&&this.applyDepMapJsonDiff(),this.coalesceTimer&&clearTimeout(this.coalesceTimer),this.coalesceTimer=setTimeout(()=>{this.coalesceTimer=null,this.flushPendingReload()},this.coalesceMs)}collectPendingState(){let t=this.pendingTags,r=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:r}}processTagsIntoSets(t,r,i,o){for(let s of t)s.startsWith("module:")?(i.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(i.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(o.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,i,o,s){for(let a of t)s.push(a.info),i.add(a.info.newName),o.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let i=new Set;for(let o of t)o.startsWith("dep-added:")&&i.add(o.substring(10));for(let o of r)i.add(o.info.newName);return i}emitIncrementalReload(t,r,i,o,s){f.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...i].join(",")}], added=[${[...o].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...i],addedModuleNames:[...o],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:r}=this.collectPendingState();if(t.length===0&&r.length===0)return;if(f.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${r.length}`),t.includes("root-oh-package")){f.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let i=new Set,o=new Set,s=new Set,a=[];this.processTagsIntoSets(t,i,o,s),this.processRenameEntries(r,i,o,s,a);for(let l of o)s.delete(l);if(o.size===0&&s.size===0&&a.length===0){f.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(i,o,s,c,a)}normalizeSrcPath(t){return he(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(o=>[o.name,o])),i=new Map(t.map(o=>[this.normalizeSrcPath(o.srcPath),o]));return{byName:r,bySrcPath:i}}detectModuleRenames(t,r,i,o){for(let[s,a]of t){let c=r.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),i.add(a.name),o.add(c.name);let l=(E.assertModuleName(a.name),Ht.join(this.depMapDir,a.name,V.OH_PACKAGE_JSON5));this.contentHashes.delete(this.canonicalPath(l)),f.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,r,i,o){for(let[s,a]of t){if(i.has(s))continue;let c=r.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),i.add(s),o.add(s),f.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,i){for(let[o]of t)i.has(o)||r.has(o)||(this.pendingTags.push(`dep-added:${o}`),i.add(o))}detectRemovedModules(t,r,i){for(let[o]of t)if(!i.has(o)&&!r.has(o)){this.pendingTags.push(`dep-removed:${o}`),i.add(o);let s=(E.assertModuleName(o),Ht.join(this.depMapDir,o,V.OH_PACKAGE_JSON5));this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(i=>i.startsWith("dep-")),r=this.pendingRenames.map(i=>`${i.kind}(${i.info.oldName}\u2192${i.info.newName})`);f.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:i}=this.buildModuleLookupMaps(this.lastModules),{byName:o,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(i,s,a,c),this.detectModuleMoves(r,o,a,c),this.detectAddedModules(o,r,c),this.detectRemovedModules(r,o,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=un.readFileSync(t,"utf-8");return d_("sha256").update(r).digest("hex")}catch{return null}}};import*as sr from"fs";import*as Ql from"path";import{EventEmitter as p_}from"events";var Bm={Created:1,Changed:2,Deleted:3},m_=new Set(["oh_modules","node_modules","build",".hvigor",".git",".idea",".cxx",".preview"]);function f_(n){let e=n.replace(/\\/g,"/");return e.endsWith("/ets")&&e.includes("/src/")}var ed=class extends p_{projectRoot;debounceMs;pollMs;sourceDirs=[];watchers=new Map;snapshot=new Map;debounceTimer=null;pollInterval=null;initialScanDone=!1;constructor(e,t=500,r=1e4){super(),this.projectRoot=e,this.debounceMs=t,this.pollMs=r}start(){if(this.sourceDirs=this.discoverSourceDirs(),this.sourceDirs.length===0){f.warn("[SourceFileWatcher] No src/main/ets dir found, skip watching");return}this.refreshSnapshot(),this.initialScanDone=!0;for(let e of this.sourceDirs)this.addSourceDirWatcher(e);this.pollInterval=setInterval(()=>this.scanAndEmit(),this.pollMs),f.info(`[SourceFileWatcher] Started, watching ${this.sourceDirs.length} source dir(s), ${this.snapshot.size} ets file(s)`)}stop(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null);for(let[,e]of this.watchers)e.close();this.watchers.clear(),this.snapshot.clear(),this.initialScanDone=!1,f.info("[SourceFileWatcher] Stopped")}addSourceDirWatcher(e){if(!this.watchers.has(e))try{let t=sr.watch(e,{recursive:!0},(r,i)=>this.onFsEvent(i));t.on("error",r=>{f.error(`[SourceFileWatcher] watch error for ${e}: ${r.message}`)}),this.watchers.set(e,t)}catch(t){f.error(`[SourceFileWatcher] Failed to watch ${e}: ${t instanceof Error?t.message:String(t)}`)}}refreshSourceDirs(){if(!this.initialScanDone)return;let e=this.discoverSourceDirs(),t=new Set(this.sourceDirs),r=new Set(e),i=e.filter(s=>!t.has(s)),o=[...t].filter(s=>!r.has(s));if(!(i.length===0&&o.length===0)){for(let s of i)this.addSourceDirWatcher(s);for(let s of o){let a=this.watchers.get(s);a&&(a.close(),this.watchers.delete(s))}this.sourceDirs=e,this.refreshSnapshot(),f.info(`[SourceFileWatcher] Module dirs changed: +${i.length} -${o.length}, now ${this.sourceDirs.length} source dir(s)`)}}discoverSourceDirs(){let e=[];return this.collectSourceDirs(Ql.resolve(this.projectRoot),e,new Set,new Set),e}collectSourceDirs(e,t,r,i){let o;try{o=sr.realpathSync(e)}catch{return}if(i.has(o))return;i.add(o);let s;try{s=sr.readdirSync(e,{withFileTypes:!0})}catch{return}for(let a of s){if(!a.isDirectory()||m_.has(a.name))continue;let c=Ql.resolve(e,a.name);if(!f_(c)){this.collectSourceDirs(c,t,r,i);continue}r.has(c)||(r.add(c),t.push(c))}}onFsEvent(e){!e||typeof e!="string"||e.replace(/\\/g,"/").toLowerCase().endsWith(".ets")&&this.scheduleScan()}scheduleScan(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.scanAndEmit()},this.debounceMs)}scanAndEmit(){if(!this.initialScanDone)return;let e=this.diffScan();e.length>0&&this.emit("sourceChanged",{changes:e})}refreshSnapshot(){let e=new Map;for(let t of this.sourceDirs)this.collectEtsFiles(t,e);this.snapshot=e}diffScan(){let e=new Map;for(let r of this.sourceDirs)this.collectEtsFiles(r,e);let t=[];for(let[r,i]of e){let o=this.snapshot.get(r);o?(o.mtimeMs!==i.mtimeMs||o.size!==i.size)&&t.push({uri:Rt(r),type:Bm.Changed}):t.push({uri:Rt(r),type:Bm.Created})}for(let[r]of this.snapshot)e.has(r)||t.push({uri:Rt(r),type:Bm.Deleted});return this.snapshot=e,t}collectEtsFiles(e,t){this.collectEtsFilesInto(e,t,new Set)}collectEtsFilesInto(e,t,r){let i;try{i=sr.realpathSync(e)}catch{return}if(r.has(i))return;r.add(i);let o;try{o=sr.readdirSync(e,{withFileTypes:!0})}catch{return}for(let s of o){let a=Ql.resolve(e,s.name);if(s.isDirectory()){this.collectEtsFilesInto(a,t,r);continue}!s.isFile()||!s.name.toLowerCase().endsWith(".ets")||this.recordSnapshot(a,t)}}recordSnapshot(e,t){let r;try{r=sr.statSync(e)}catch{return}t.set(e,{mtimeMs:r.mtimeMs,size:r.size})}};import{spawn as h_}from"child_process";var xS=["install","--all"];function AS(n,e){let t=n.split(/\r?\n/),r=t.pop()??"";for(let i of t)i&&(f.info("[ohpm] %s",i),e?.(i));return r}async function g_(n,e,t,r,i){return new Promise(o=>{f.info("[ohpm] spawning: %s %s %s, cwd=%s",n,e,xS.join(" "),t);let s=h_(n,[e,...xS],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),a="",c="";s.stdout?.on("data",l=>{a=AS(a+l.toString(),i)}),s.stderr?.on("data",l=>{c=AS(c+l.toString(),i)}),s.on("close",l=>{a&&(f.info("[ohpm] %s",a),i?.(a)),c&&(f.info("[ohpm] %s",c),i?.(c)),f.info("[ohpm] process exited, code=%s",l),o({exitCode:l??-1})}),s.on("error",l=>{f.error("[ohpm] process error: %s",l.message),o({exitCode:-1})})})}async function IS(n,e,t,r,i){try{if(!t)return f.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;if(!r)return f.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:o}=await g_(t,r,n,e,i);return o===0?(f.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(f.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",o),!1)}catch(o){return f.error("ohpm \u5B89\u88C5\u5F02\u5E38",o),!1}}var TS={UNINITIALIZED:-32099,UNKNOWN:-32e3},Vs=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,TS.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,TS.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var fo=class{config;lspProxy=null;configWatcher=null;depMapWatcher=null;sourceFileWatcher=null;isInitialized=!1;lastEditorOpenFiles=[];onMessage=()=>{};onConfigChanged=null;disposeOnce=null;get aceServerPid(){return this.lspProxy?.lspPid??null}constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}async start(e=[],t){this.lastEditorOpenFiles=e;try{this.startConfigWatcher(),this.startLspProxy(e,t)}catch(r){throw f.error(`[ArktsLspManager] start() synchronous failure: ${r instanceof Error?r.message:String(r)}`),r}}sendNotification(e){if(!this.lspProxy){f.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){f.warn("[ArktsLspManager] sendRequest before LSP ready, dropped");return}this.lspProxy.sendRequest(e)}async diagnostic(e){if(!this.lspProxy)throw new Error("[ArktsLspManager] diagnostic before LSP ready");return this.lspProxy.diagnostic(e)}async sendFeatureRequest(e,t){if(!this.useStandardProtocol)throw new Error(`Language feature '${e}' is not supported on the installed DevEco Studio. The standard LSP protocol entry (plugins/openharmony/ace-server/out/standardIndex/index.js) was not found. Please upgrade DevEco Studio to version 26.0.0.610 or later to use this tool.`);if(!this.lspProxy)throw new Error("LSP not ready");return this.lspProxy.sendFeatureRequest(e,t)}get useStandardProtocol(){return this.config.useStandardProtocol}onAsyncOpenFile(e){this.lspProxy?.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.lspProxy?.closeFileLegacy(e,t)}registerDiagnosticCallback(e){this.lspProxy?.registerDiagnosticCallback(e)}static async handleSyncProject(e,t,r,i,o,s,a,c){if(f.info("[ArktsLspManager] Received arkts/syncProject"),!e||!t)return f.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let l=s?.skipHvigorSync===!0,d=await La(e,async()=>await IS(e,t,r??"",i??"",a)?l?(f.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await lg(e,t,r??"",o??"",c)?(f.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(f.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(f.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return d.acquired?d.result:(f.info("[ArktsLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){try{this.configWatcher?.stop()}catch(e){f.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){f.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}try{this.sourceFileWatcher?.stop()}catch(e){f.warn(`[ArktsLspManager] sourceFileWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.sourceFileWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){f.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e,t){let r=new Kl(this.config.sdkPath,this.config.arktsLangServerPath,this.config.workspaceRoot,this.config.indexLogPath,this.config.nodeMaxOldSpaceSize,this.config.useStandardProtocol,this.config.nodePath,this.config.useSocket??!1);r.setOnMessage(i=>this.handleLspMessage(i)),r.start(e,i=>this.handleLspInitialized(i),t),this.lspProxy=r}handleLspInitialized=e=>{if(this.isInitialized=e,e)f.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.startSourceFileWatcher(),this.onMessage({jsonrpc:L,method:b.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();f.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?Vs.uninitialized(t):Vs.unknown();this.onMessage({jsonrpc:L,method:b.ARKTS_INITIALIZATION_FAILED,params:r.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(f.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:L,method:b.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Xl(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Zl(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){f.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let r=this.lspProxy.reloadDependenciesOnly(e).map(i=>({modulePath:i.modulePath??"",dependencies:i.dependencies??{},dynamicDependencies:i.dynamicDependencies??{}}));this.onMessage({jsonrpc:L,method:b.ARKTS_SYNC_COMPLETED,params:{success:!0,moduleSet:r}})}),this.depMapWatcher.start())}startSourceFileWatcher(){this.sourceFileWatcher||(this.sourceFileWatcher=new ed(this.config.workspaceRoot),this.sourceFileWatcher.on("sourceChanged",e=>{if(!this.lspProxy){f.warn("[ArktsLspManager] LspServerProxy not initialized, skip didChangeWatchedFiles");return}this.sendNotification({jsonrpc:L,method:b.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:e.changes}}),f.info(`[ArktsLspManager] Notified didChangeWatchedFiles: ${e.changes.length} change(s)`)}),this.sourceFileWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){f.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),e.kind!==4&&this.sourceFileWatcher?.refreshSourceDirs(),this.onConfigChanged?.()}};var y_=10080*60*1e3,w_=7200*60*1e3,v_=120*1e3,ho=class n{manager=null;get aceServerPid(){return this.manager?.aceServerPid??null}initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;sdkPath;arktsLangServerPath;nodePath;nodeMaxOldSpaceSize;onConfigChangedCallback=null;onInitProgress=null;onDepParseProgress=null;useStandardProtocol=!0;useSocket;diagnosticWaiters=new Map;documentVersion=0;static FEATURE_METHOD_MAP={hover:b.HOVER,definition:b.DEFINITION,declaration:b.DECLARATION,references:b.REFERENCES,implementation:b.IMPLEMENTATION,completion:b.COMPLETION,signatureHelp:b.SIGNATURE_HELP,documentHighlight:b.DOCUMENT_HIGHLIGHT};constructor(e,t,r,i,o,s=!1){this.projectPath=e,this.sdkPath=t,this.arktsLangServerPath=r,this.nodeMaxOldSpaceSize=i,this.nodePath=o,this.useSocket=s}setOnConfigChanged(e){this.onConfigChangedCallback=e}setOnInitProgress(e){this.onInitProgress=e}setOnDepParseProgress(e){this.onDepParseProgress=e}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initializing=!0,this.initPromise=this.doInitialize().then(()=>{this.initialized=!0}).finally(()=>{this.initializing=!1}),await this.initPromise}}async doInitialize(){let{harmonyRoot:e,arktsLangServerPath:t,useStandardProtocol:r}=this.resolveProjectAndDeveco();this.useStandardProtocol=r;let i=De(e),{logPath:o,indexPath:s}=this.getLogAndIndexPath(i);setImmediate(()=>{Jd(s,y_,"[ArkTS-Check]"),Jd(o,w_,"[ArkTS-Check]")}),Fa(o);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a;h.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${c??"undefined \u2192 dynamic formula applies"}`);let l=this.sdkPath;h.info(`[ArktsCheck] sdkPath=${l}, arktsLangServerPath=${t}, useStandardProtocol=${r}, useSocket=${this.useSocket}`),this.manager=new fo({sdkPath:l,arktsLangServerPath:t,workspaceRoot:he(i),indexLogPath:s,nodeMaxOldSpaceSize:c,useStandardProtocol:r,nodePath:this.nodePath,useSocket:this.useSocket}),this.manager.setOnMessage(d=>this.handleLspMessage(d)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((d,g)=>{this.initResolve=d,this.initReject=g,this.armInitTimer(Qe),this.manager.start([],this.onDepParseProgress??void 0).catch(w=>{let R=w instanceof Error?w:new Error(String(w));this.failInit(R)})})}resolveProjectAndDeveco(){let e=lr(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.arktsLangServerPath;if(!t)throw new Error("arkts-lang-server path not found");let r=wa(t);return{harmonyRoot:e,arktsLangServerPath:t,useStandardProtocol:r}}armInitTimer(e){this.initDeadlineTimer&&clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=setTimeout(()=>{let t=this.initReject;this.clearInitHandlers(),t?.(new Error("LSP initialize timeout"))},e)}clearInitHandlers(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async checkFile(e){this.initialized||await this.initialize();let t=this.manager;if(!t)throw new Error("ArktsLspManager not initialized");let r=Rt(e),i=await Ct.promises.readFile(e,"utf8"),s=`deveco.apptool.${$e.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,r,i,s):this.checkFileLegacy(t,e,r,i,s)}async checkFileStandard(e,t,r,i){h.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:i,version:++this.documentVersion}});try{h.debug(`textDocument/diagnostic uri=${t}`);let o=await e.diagnostic({textDocument:{uri:t}});return b_(o)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:t}})}}async checkFileLegacy(e,t,r,i,o){let s=r;e.registerDiagnosticCallback(r);let a=new Promise((c,l)=>{let d=setTimeout(()=>{this.diagnosticWaiters.delete(s)&&l(new Error("Wait for diagnostics timeout"))},v_);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});h.debug(`textDocument/didOpen(legacy) uri=${r} content_len=${i.length}`),e.onAsyncOpenFile({textDocument:{uri:r,text:i,languageId:o,version:i.length},editorFiles:[r],isFromEditor:!1});try{return await a}finally{e.closeFileLegacy(r,!1)}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],r=[],i=this.collectValidFiles(e.files,t);return i.length===0?{content:[{type:"text",text:t.length>0?t.join(`
1326
+ `):"No valid .ets files"}],isError:!0}:(await this.runDiagnosticsForFiles(i,t,r),this.formatCallResult(t,r))}async handleLspFeature(e,t){if(!this.initialized)return this.buildNotReadyResponse();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`File does not exist or is not a .ets file: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,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){let s=o instanceof Error?o.message:String(o);return h.error(`handleLspFeature ${e} failed: ${s}`),{content:[{type:"text",text:`${e} failed: ${s}`}],isError:!0}}}async handleWorkspaceSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();h.info(`handleWorkspaceSymbol: query="${e}"`);try{let t=await this.manager.sendFeatureRequest(b.WORKSPACE_SYMBOL,{query:e});return{content:[{type:"text",text:t==null?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(t,null,2)}`}]}}catch(t){let r=t instanceof Error?t.message:String(t);return h.error(`handleWorkspaceSymbol failed: ${r}`),{content:[{type:"text",text:`workspaceSymbol failed: ${r}`}],isError:!0}}}async handleWorkspaceSymbolRaw(e){if(!this.initialized)return null;try{let t=await this.manager.sendFeatureRequest(b.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return h.error(`handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a .ets file: ${e}`}],isError:!0};h.info(`handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(b.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return h.error(`handleDocumentSymbol failed: ${i}`),{content:[{type:"text",text:`documentSymbol failed: ${i}`}],isError:!0}}}async handleCallHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a .ets file: ${e.file}`}],isError:!0};h.info(`handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,async o=>{let s=await this.manager.sendFeatureRequest(b.PREPARE_CALL_HIERARCHY,{textDocument:{uri:o},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],calls:[]};let c=e.direction==="incoming"?b.INCOMING_CALLS:b.OUTGOING_CALLS,l=[];for(let d of a){let g=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(g)?l.push(...g):g&&l.push(g)}return{items:a,calls:l}});return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return h.error(`handleCallHierarchy failed: ${i}`),{content:[{type:"text",text:`callHierarchy failed: ${i}`}],isError:!0}}}async withOpenFile(e,t){let r=Rt(e),i=await Ct.promises.readFile(e,"utf8"),s=`deveco.apptool.${$e.extname(e).replace(/^\./,"")||"plaintext"}`;h.debug(`withOpenFile didOpen uri=${r} len=${i.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,text:i,languageId:s,version:++this.documentVersion}});try{return await t(r)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:r},isManual:!1})}}resolveSingleFile(e){let t=$e.isAbsolute(e)?e:$e.join(this.projectPath,e);return!Ct.existsSync(t)||!Ct.statSync(t).isFile()||!t.endsWith(".ets")?null:t}buildNotReadyResponse(){return{content:[{type:"text",text:this.initializing?"LSP is initializing, please retry later":this.projectPath?"LSP not initialized":"No project path configured; set the PROJECT_PATH parameter"}],isError:!0}}collectValidFiles(e,t){let r=$e.resolve(this.projectPath),i=[];for(let o of e){let s=$e.resolve($e.isAbsolute(o)?o:$e.join(r,o));if(!Ct.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!Ct.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!s.endsWith(".ets")){t.push(`Not a .ets file: ${o}`);continue}i.push(s)}return i}async runDiagnosticsForFiles(e,t,r){for(let i of e){await bh(500);try{let o=await this.checkFile(i);r.push(S_(i,o))}catch(o){t.push(`${i} => wait for diagnostics failed: ${o.message}`)}}}formatCallResult(e,t){let r=[];e.length>0&&r.push(e.join(`
1327
+ `)),t.length>0&&r.push(t.join(`
1328
+ `));let i=r.join(`
1329
+ `).trim(),o=e.length>0;return!o&&t.length===0&&(i="No diagnostics collected"),{content:[{type:"text",text:i}],isError:o}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){h.warn(`Failed to dispose ArktsLspManager: ${t}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":this.handleDiagnosticsNotification(t.params);break;case"arkts/indexingProgress":this.handleIndexingProgress(t.params);break;case vi.INDEXING_PROGRESS_UPDATE:this.handleIndexingProgress(t.params);break;case b.PROGRESS:this.handleProgressNotification(t.params);break;case"arkts/initialized":{h.info("Received arkts/initialized");let i=this.initResolve;this.clearInitHandlers(),i?.();break}case"arkts/initializationFailed":{let i=t.params?.message??"unknown";h.error(`LSP initialization failed: ${i}`);let o=this.initReject;this.clearInitHandlers(),o?.(new Error(`LSP initialize failed: ${i}`));break}case"workspace/didChangeConfiguration":h.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleIndexingProgress(e){let t=e;if(t?.current!=null&&t?.total!=null&&t.total>0){let r=Math.round(t.current/t.total*100),i=`indexing ${t.current}/${t.total} modules`+(t.moduleName?` (${t.moduleName})`:"");this.onInitProgress?.(i,r)}this.initResolve&&this.armInitTimer(Qe)}handleProgressNotification(e){let t=e?.value;if(t&&(t.kind==="report"||t.kind==="begin")){let r=typeof t.percentage=="number"?Math.round(t.percentage):null,i=t.message??(r!==null?`${r}%`:"indexing");this.onInitProgress?.(i,r)}this.initResolve&&this.armInitTimer(Qe)}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let r=this.popDiagnosticWaiter(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.popDiagnosticWaiter(s)}if(!r)return;if(typeof e.errorMessage=="string"){h.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let i=e.diagnostics,o=Array.isArray(i)?i.length:0;h.debug(`diagnostics received uri=${t} count=${o}`),r.resolve(Array.isArray(i)?i:[])}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}getLogAndIndexPath(e){try{let t=$e.join(Lr(),"ArkTSCheck"),r=$e.join(t,"mapping-config.properties"),i=Sh(e,r),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=$e.join(t,"lsp-log",String(i),o),a=$e.join(t,"lsp-index",String(i));return Ct.mkdirSync(s,{recursive:!0}),Ct.mkdirSync(a,{recursive:!0}),{logPath:De(s),indexPath:De(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function b_(n){if(Array.isArray(n))return n;if(n&&typeof n=="object"){let e=n;if(e.kind==="full"&&Array.isArray(e.items))return e.items}return[]}function S_(n,e){if(Array.isArray(e))return e.length===0?`${n} => no diagnostics`:`${n} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${n} diagnostic failed, error_message: ${t}`}return`${n} => diagnostic failed, result: ${JSON.stringify(e)}`}import*as pn from"fs";import*as ii from"path";import{z as Wm}from"zod";function go(){return{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}function td(n,e){let t=e instanceof Error?e.message:String(e);return h.error(`[CppLsp] ${n} failed: ${t}`),{content:[{type:"text",text:`${n} failed: ${t}`}],isError:!0}}var E_=500,yo=class{manager;constructor(e){this.manager=e}static getToolDefinition(){return{name:"check_cpp_files",description:"Perform static syntax checks on the provided C/C++ files and return clangd diagnostics.",inputSchema:Wm.object({files:Wm.array(Wm.string()).describe('List of C/C++ file paths to check, format: ["file1.cpp","file2.hpp",...]')})}}async handleCall(e){if(!this.manager.ready)return go();let t=[],r=[],i=this.collectValidFiles(e.files,t);if(i.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
1330
+ `):"No valid C/C++ files"}],isError:!0};for(let c of i){await C_(E_);try{let l=await this.checkFile(c);r.push(P_(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(`
1331
+ `)),r.length>0&&s.push(r.join(`
1315
1332
  `));let a=s.join(`
1316
- `).trim();return!i&&n.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:i}}async checkFile(e){let t=Gr(e),n=await Pr.promises.readFile(e,"utf8"),o=ns(e),i=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:n,languageId:o,version:n.length}}});try{return await i}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let n=mn.resolve(this.manager.projectRoot),o=[];for(let i of e){let s=mn.resolve(mn.isAbsolute(i)?i:mn.join(n,i));if(!Pr.existsSync(s)){t.push(`File does not exist: ${i}`);continue}if(!Pr.statSync(s).isFile()){t.push(`Not a regular file: ${i}`);continue}if(!Vr(s)){t.push(`Not a supported C/C++ file: ${i}`);continue}try{o.push(Pr.realpathSync(s))}catch{o.push(s)}}return o}};function ID(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 kD(r){return new Promise(e=>setTimeout(e,r))}import*as io from"fs";import*as Va from"path";var oo=class r{manager;static FEATURE_METHOD_MAP={hover:v.HOVER,definition:v.DEFINITION,declaration:v.DECLARATION,references:v.REFERENCES,implementation:v.IMPLEMENTATION};constructor(e){this.manager=e}async handleLspFeature(e,t){if(!this.manager.ready)return ro();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 o=r.FEATURE_METHOD_MAP[e];if(!o)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 i=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(o,c)});return{content:[{type:"text",text:i==null?`${e}: no result`:`${e}: ${JSON.stringify(i,null,2)}`}]}}catch(i){return Wa(e,i)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(v.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 ro();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 i=>this.manager.sendFeatureRequest(v.DOCUMENT_SYMBOL,{textDocument:{uri:i}}));return{content:[{type:"text",text:n==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(n,null,2)}`}]}}catch(n){return Wa("documentSymbol",n)}}async handleCallHierarchy(e){if(!this.manager.ready)return ro();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,i=>this.fetchCallHierarchyResult(i,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(n,null,2)}`}]}}catch(n){return Wa("callHierarchy",n)}}async fetchCallHierarchyResult(e,t){let n=await this.manager.sendFeatureRequest(v.PREPARE_CALL_HIERARCHY,{textDocument:{uri:e},position:{line:t.line,character:t.character}}),o=this.normalizeCallHierarchyItems(n);if(o.length===0)return{items:[],calls:[]};let i=await this.collectIncomingCalls(o);return{items:o,calls:i}}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(v.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let n=Gr(e),o=await io.promises.readFile(e,"utf8"),i=ns(e);h.info(`[ClangdLspTool] withOpenFile didOpen uri=${n} langId=${i} len=${o.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:n,text:o,languageId:i,version:o.length}}});try{return await t(n)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:n}}})}}resolveSingleFile(e){let t=Va.isAbsolute(e)?e:Va.join(this.manager.projectRoot,e);return!io.existsSync(t)||!io.statSync(t).isFile()||!Vr(t)?null:t}};import{spawn as DD}from"child_process";import*as za from"fs";import*as oy from"path";var TD=30*1e3,RD=30*1e3,Ga=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new Sr;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{f.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),f.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),f.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 wr(n),this.client.on("message",i=>this.handleRawMessage(i)),this.client.on("error",i=>this.handleError(i)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let o=this.buildInitializeParams();await this.sendLspRequest(v.INITIALIZE,o,ot),f.info("[ClangdLspProxy] initialize response received"),this.sendNotification(v.INITIALIZED,{}),t=!0}catch(n){this.lastStartErrorMessage=n instanceof Error?n.message:String(n),f.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(v.HOVER,e)}async definition(e){return this.sendLspRequest(v.DEFINITION,e)}async declaration(e){return this.sendLspRequest(v.DECLARATION,e)}async references(e){return this.sendLspRequest(v.REFERENCES,e)}async implementation(e){return this.sendLspRequest(v.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(v.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(v.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(v.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(v.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(v.DID_OPEN,e)}sendDidChange(e){this.sendNotification(v.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(v.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){f.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){f.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,o)=>{let i=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&o(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},RD);this.diagnosticWaiters.set(t,{resolve:n,reject:o,timer:i})})}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(v.SHUTDOWN,null,3e3).catch(e=>{f.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(v.EXIT,null),await this.client.waitForExitOrTimeout(300)}catch(e){f.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=${J(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];f.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=DD(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=Pn(this.config.workspaceRoot),t=gt(e),n=oy.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"0.1.7"},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=TD){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let o=this.nextRequestId++,i=this.requestCallbacks.registerPending(o,e,n);return this.client.sendRequest(e,t,o),i}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(n){let o=n instanceof Error?n.message:String(n);f.error(`[ClangdLspProxy] JSON parse error: ${o}, raw: ${e.slice(0,200)}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotification(t):f.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 o=e.error;f.warn(`[ClangdLspProxy] LSP error id=${n}: code=${o.code??-1} message=${o.message??"unknown"}`),this.requestCallbacks.rejectPending(n,new Error(`LSP error ${o.code??-1}: ${o.message??"unknown"}`))}else this.requestCallbacks.resolvePending(n,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case v.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case v.PROGRESS:this.onMessage({jsonrpc:R,method:v.PROGRESS,params:e.params});break;case v.WINDOW_SHOW_MESSAGE:f.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case v.WINDOW_LOG_MESSAGE:f.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:R,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 o=Array.isArray(e.diagnostics)?e.diagnostics:[],i=o.length;f.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${i}`),n.resolve(o)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:R,method:v.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{za.existsSync(this.config.logPath)||za.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)),gt(n)}}catch{}return e}};import*as vi from"path";import*as Pd from"fs";var wi=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){f.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,o,i){if(f.info("[ClangdLspManager] Received cpp/syncProject"),!e||!t)return f.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};if(ar(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let a=i?.skipCompileNative===!0,c=await hs(e,a?async()=>(f.info("[ClangdLspManager] compileNative skipped (C++ project up-to-date)"),{status:"success"}):async()=>r.executeCompileNative(e,t,n,o));return c.acquired?c.result:(f.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,o){try{return await dm(e,t,n,o),f.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(i){let s=i instanceof Error?i.message:String(i);return f.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(ot);try{this.startProxy()}catch(n){this.failInit(n instanceof Error?n:new Error(String(n)))}})}startProxy(){let e=_t(this.config.workspaceRoot);this.resolvedRoot=e?ve(e):ve(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();ws(t);let n=this.config.clangdPath;if(!n){let s="clangd not found (install DevEco Studio / CLT)";f.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let o=vi.dirname(Wr(this.resolvedRoot));try{Pd.mkdirSync(o,{recursive:!0})}catch(s){f.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}f.info(`[ClangdLspManager] clangdPath: ${n}`),f.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),f.info(`[ClangdLspManager] compileCommandsDir: ${o}`);let i=new Ga({clangdPath:n,workspaceRoot:this.resolvedRoot,compileCommandsDir:o,logPath:t});i.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=i,i.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,f.info("[ClangdLspManager] clangd initialized");let n=this.initResolve;this.clearInitHandlers(),n?.()}else{let n=t??this.proxy?.consumeStartErrorMessage()??"unknown error";f.error(`[ClangdLspManager] clangd initialization failed: ${n}`),this.isInitialized=!1,this.proxy=null;let o=this.initReject;this.clearInitHandlers(),o?.(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){f.warn("[ClangdLspManager] dispatchNotification: missing method");return}let o=t.params;switch(n){case v.DID_OPEN:this.proxy.sendDidOpen(o);break;case v.DID_CHANGE:this.proxy.sendDidChange(o);break;case v.DID_CLOSE:this.proxy.sendDidClose(o);break;default:this.proxy.sendNotification(n,o)}}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){f.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){try{let e=vi.join(rr(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,n=vi.join(e,"lsp-log",t);return Pd.mkdirSync(n,{recursive:!0}),ve(n)}catch{return"auto"}}};function iy(r){let e=ys(r);return f.info(`[SyncGuard] ${e.reason}`),e}var kd=(s=>(s[s.IDLE=0]="IDLE",s[s.DISCOVERING=1]="DISCOVERING",s[s.SYNCING=2]="SYNCING",s[s.INITIALIZING=3]="INITIALIZING",s[s.READY=4]="READY",s[s.ERROR=5]="ERROR",s))(kd||{}),sy=(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))(sy||{}),Ot=3,Ad=600*1e3,Id=100,qa=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;standardProtocolAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;cppEnabled;constructor(e={}){this.config=e,zr(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 o=_t(t);h.info(`Constructor: findHarmonyProject('${t}') => ${o??"null"}`),this.config.projectPath=o??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}`),this.server=new xD({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=Sd(e.telemetry,()=>this.arktsCheckTool?.aceServerPid??null,()=>this.config.projectPath??"",()=>this.sdkPath??""),this.standardProtocolAvailable=this.detectStandardProtocolAvailable(),this.registerTools()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools(),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:ye.object({target:ye.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:ye.object({files:ye.array(ye.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=ye.object({file:ye.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:ye.number().describe("Line number (0-based)"),character:ye.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:n,feature:o}of this.getPositionFeatures())this.toolRouter.add({name:t,description:n,inputSchema:e},async i=>this.handleLspFeatureCall(o,i));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:ye.object({query:ye.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:ye.object({file:ye.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:ye.object({file:ye.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:ye.number().describe("Line number (0-based)"),character:ye.number().describe("Character offset in the line (0-based)"),direction:ye.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=rs(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 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>Id)return h.warn(`check tool called with ${t.length} files (max: ${Id})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${Id}.`}],isError:!0};let{etsFiles:n,cppFiles:o,unsupported:i}=ND(t);i.length>0&&h.warn(`Unsupported file types in check request: ${i.join(", ")}`);let s=i.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),o.length>0&&this.mergeCheckResult(await this.callCppCheck(o),s,a);let c=s.length>0;return{content:[{type:"text",text:[a.join(`
1333
+ `).trim();return!o&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:o}}async checkFile(e){let t=Rt(e),r=await pn.promises.readFile(e,"utf8"),i=va(e),o=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:r,languageId:i,version:r.length}}});try{return await o}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let r=ii.resolve(this.manager.projectRoot),i=[];for(let o of e){let s=ii.resolve(ii.isAbsolute(o)?o:ii.join(r,o));if(!pn.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!pn.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!An(s)){t.push(`Not a supported C/C++ file: ${o}`);continue}try{i.push(pn.realpathSync(s))}catch{i.push(s)}}return i}};function P_(n,e){if(Array.isArray(e))return e.length===0?`${n} => no diagnostics`:`${n} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${n} diagnostic failed, error_message: ${t}`}return`${n} => diagnostic failed, result: ${JSON.stringify(e)}`}function C_(n){return new Promise(e=>setTimeout(e,n))}import*as vo from"fs";import*as rd from"path";var wo=class n{manager;static FEATURE_METHOD_MAP={hover:b.HOVER,definition:b.DEFINITION,declaration:b.DECLARATION,references:b.REFERENCES,implementation:b.IMPLEMENTATION};constructor(e){this.manager=e}async handleLspFeature(e,t){if(!this.manager.ready)return go();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`[ClangdLspTool] handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,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 td(e,o)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(b.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 go();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 r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(b.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return td("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return go();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 r=await this.withOpenFile(t,o=>this.fetchCallHierarchyResult(o,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return td("callHierarchy",r)}}async fetchCallHierarchyResult(e,t){let r=await this.manager.sendFeatureRequest(b.PREPARE_CALL_HIERARCHY,{textDocument:{uri:e},position:{line:t.line,character:t.character}}),i=this.normalizeCallHierarchyItems(r);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 r of e)t.push(...await this.fetchIncomingCalls(r));return t}async fetchIncomingCalls(e){let t=await this.manager.sendFeatureRequest(b.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let r=Rt(e),i=await vo.promises.readFile(e,"utf8"),o=va(e);h.info(`[ClangdLspTool] withOpenFile didOpen uri=${r} langId=${o} len=${i.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:r,text:i,languageId:o,version:i.length}}});try{return await t(r)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:r}}})}}resolveSingleFile(e){let t=rd.isAbsolute(e)?e:rd.join(this.manager.projectRoot,e);return!vo.existsSync(t)||!vo.statSync(t).isFile()||!An(t)?null:t}};import{spawn as k_}from"child_process";import*as id from"fs";import*as OS from"path";var R_=30*1e3,D_=30*1e3,nd=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new cn;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{f.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),f.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),f.info(`[ClangdLspProxy] compileCommandsDir: ${this.config.compileCommandsDir}`),this.ensureLogDir(),this.clangdProcess=this.spawnClangd();let r={serverPath:"",logPath:this.config.logPath,indexingDataLocation:this.config.logPath,cwd:this.config.workspaceRoot};this.client=new an(r),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(b.INITIALIZE,i,Qe),f.info("[ClangdLspProxy] initialize response received"),this.sendNotification(b.INITIALIZED,{}),t=!0}catch(r){this.lastStartErrorMessage=r instanceof Error?r.message:String(r),f.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(b.HOVER,e)}async definition(e){return this.sendLspRequest(b.DEFINITION,e)}async declaration(e){return this.sendLspRequest(b.DECLARATION,e)}async references(e){return this.sendLspRequest(b.REFERENCES,e)}async implementation(e){return this.sendLspRequest(b.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(b.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(b.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(b.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(b.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(b.DID_OPEN,e)}sendDidChange(e){this.sendNotification(b.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(b.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){f.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){f.warn(`[ClangdLspProxy] overwrite existing diagnostic waiter for ${t}`);let r=this.diagnosticWaiters.get(t);clearTimeout(r.timer),this.diagnosticWaiters.delete(t)}return new Promise((r,i)=>{let o=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&i(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},D_);this.diagnosticWaiters.set(t,{resolve:r,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(b.SHUTDOWN,null,3e3).catch(e=>{f.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(b.EXIT,null),await this.client.waitForExitOrTimeout(300)}catch(e){f.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=${he(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];f.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=k_(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=Si(this.config.workspaceRoot),t=xt(e),r=OS.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.6-Test.1"},rootPath:e,rootUri:t,workspaceFolders:[{uri:t,name:r}],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,r=R_){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let i=r instanceof Error?r.message:String(r);f.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):f.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 r=t;if(e.error!==void 0&&e.error!==null){let i=e.error;f.warn(`[ClangdLspProxy] LSP error id=${r}: code=${i.code??-1} message=${i.message??"unknown"}`),this.requestCallbacks.rejectPending(r,new Error(`LSP error ${i.code??-1}: ${i.message??"unknown"}`))}else this.requestCallbacks.resolvePending(r,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case b.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case b.PROGRESS:this.onMessage({jsonrpc:L,method:b.PROGRESS,params:e.params});break;case b.WINDOW_SHOW_MESSAGE:f.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case b.WINDOW_LOG_MESSAGE:f.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:L,method:t,params:e.params})}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=this.normalizeClangdUri(e.uri),r=this.diagnosticWaiters.get(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.diagnosticWaiters.get(s),r&&this.diagnosticWaiters.delete(s)}else r&&this.diagnosticWaiters.delete(t);if(!r)return;clearTimeout(r.timer);let i=Array.isArray(e.diagnostics)?e.diagnostics:[],o=i.length;f.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${o}`),r.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:L,method:b.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{id.existsSync(this.config.logPath)||id.mkdirSync(this.config.logPath,{recursive:!0})}catch{}}normalizeClangdUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=decodeURIComponent(t.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(r)&&(r=r.slice(1)),xt(r)}}catch{}return e}};import*as Gs from"path";import*as Vm from"fs";var qs=class n{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){f.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,r,i,o){if(f.info("[ClangdLspManager] Received cpp/syncProject"),!e||!t)return f.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};if(Ur(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let a=o?.skipCompileNative===!0,c=await La(e,a?async()=>(f.info("[ClangdLspManager] compileNative skipped (C++ project up-to-date)"),{status:"success"}):async()=>n.executeCompileNative(e,t,r,i));return c.acquired?c.result:(f.info("[ClangdLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}static async executeCompileNative(e,t,r,i){try{return await mg(e,t,r,i),f.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(o){let s=o instanceof Error?o.message:String(o);return f.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(Qe);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=lr(this.config.workspaceRoot);this.resolvedRoot=e?De(e):De(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();Fa(t);let r=this.config.clangdPath;if(!r){let s="clangd not found (install DevEco Studio / CLT)";f.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let i=this.config.compileCommandsDir??Gs.dirname(xn(this.resolvedRoot));try{Vm.mkdirSync(i,{recursive:!0})}catch(s){f.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}f.info(`[ClangdLspManager] clangdPath: ${r}`),f.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),f.info(`[ClangdLspManager] compileCommandsDir: ${i}`);let o=new nd({clangdPath:r,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,f.info("[ClangdLspManager] clangd initialized");let r=this.initResolve;this.clearInitHandlers(),r?.()}else{let r=t??this.proxy?.consumeStartErrorMessage()??"unknown error";f.error(`[ClangdLspManager] clangd initialization failed: ${r}`),this.isInitialized=!1,this.proxy=null;let i=this.initReject;this.clearInitHandlers(),i?.(new Error(`C++ LSP initialize failed: ${r}`))}};handleLspMessage(e){this.onMessage(e)}dispatchNotification(e){if(!this.proxy)return;let t=e,r=t.method;if(!r){f.warn("[ClangdLspManager] dispatchNotification: missing method");return}let i=t.params;switch(r){case b.DID_OPEN:this.proxy.sendDidOpen(i);break;case b.DID_CHANGE:this.proxy.sendDidChange(i);break;case b.DID_CLOSE:this.proxy.sendDidClose(i);break;default:this.proxy.sendNotification(r,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){f.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){try{let e=Gs.join(Lr(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=Gs.join(e,"lsp-log",t);return Vm.mkdirSync(r,{recursive:!0}),De(r)}catch{return"auto"}}};function MS(n){let e=_a(n);return f.info(`[SyncGuard] ${e.reason}`),e}var LS=(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))(LS||{}),ar=3,Gm=600*1e3,qm=100,od=["ohpm","hvigor","dep-parse","lsp-init"],NS={ohpm:"ohpm install",hvigor:"hvigor sync","dep-parse":"dependency parse","lsp-init":"LSP init"},zs=15,sd=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="";constructor(e={}){this.config=e,In(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),h.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",h.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,h.info(`Constructor: using configured path as startPath: '${t}'`));let i=lr(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 x_({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=jm(e.telemetry,()=>this.arktsCheckTool?.aceServerPid??null,()=>this.config.projectPath??"",()=>this.sdkPath??""),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:ke.object({target:ke.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:ke.object({files:ke.array(ke.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=ke.object({file:ke.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:ke.number().describe("Line number (0-based)"),character:ke.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature:i}of this.getPositionFeatures())this.toolRouter.add({name:t,description:r,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:ke.object({query:ke.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:ke.object({file:ke.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:ke.object({file:ke.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:ke.number().describe("Line number (0-based)"),character:ke.number().describe("Character offset in the line (0-based)"),direction:ke.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=wa(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 vh(e,On(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>qm)return h.warn(`check tool called with ${t.length} files (max: ${qm})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${qm}.`}],isError:!0};let{etsFiles:r,cppFiles:i,unsupported:o}=I_(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=[];r.length>0&&this.mergeCheckResult(await this.callArktsCheck(r),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(`
1317
1334
  `),s.join(`
1318
1335
  `)].filter(d=>d.trim().length>0).join(`
1319
- `).trim()||"No diagnostics collected"}],isError:c}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS check rejected: project is ${kd[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],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,o=t.line,i=t.character;return typeof n!="string"||typeof o!="number"||typeof i!="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:o,character:i});let s=e;return this.cppLspTool.handleLspFeature(s,{file:n,line:o,character:i})})}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 o=[],i=new Set;if(t)try{this.mergeSymbolItems(await this.arktsCheckTool.handleWorkspaceSymbolRaw(e),i,o)}catch(a){h.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(n)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),i,o)}catch(a){h.warn(`workspaceSymbol C++ query failed: ${a.message}`)}return{content:[{type:"text",text:o.length===0?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(o,null,2)}`}]}}symbolDedupKey(e){let t=e,n=t?.location?.uri??"",o=t?.location?.range?.start?.line??0,i=t?.location?.range?.start?.character??0;return`${n}:${o}:${i}`}mergeSymbolItems(e,t,n){if(e)for(let o of e){let i=this.symbolDedupKey(o);t.has(i)||(t.add(i),n.push(o))}}describeArktsState(){switch(this.projectState){case 0:return"idle";case 1:return"discovering";case 2:return"syncing (retry 10s)";case 3:return"initializing (retry 10s)";case 5:return`error (${this.initRetryCount}/${Ot})`;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}/${Ot})`;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,o=e.character,i=e.direction;return typeof t!="string"||typeof n!="number"||typeof o!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:i!=="incoming"&&i!=="outgoing"?{content:[{type:"text",text:'Parameter direction must be "incoming" or "outgoing".'}],isError:!0}:this.routeLspRequest(t,`callHierarchy(${i})`,async()=>t.endsWith(".ets")?this.arktsCheckTool.handleCallHierarchy({file:t,line:n,character:o,direction:i}):this.cppLspTool.handleCallHierarchy({file:t,line:n,character:o,direction:i}))}async routeArktsRequest(e,t){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS ${e} rejected: project is ${kd[this.projectState]}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS ${e} rejected: LSP is initializing`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],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="Config file changed, resyncing project, please retry in 10 seconds",t="config changed",this.configChangedTriggeredResync=!1):(e="HarmonyOS project detected, syncing, please retry in 10 seconds",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, please retry in 10 seconds"}],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>=Ot?(h.error(`Init retry limit reached (${this.initRetryCount}/${Ot}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${Ot}). 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}/${Ot})`),this.ensureProjectReady(),{content:[{type:"text",text:"Project initialization failed, auto-retrying, please retry in 10 seconds"}],isError:!0})}async routeCppRequest(e,t){switch(this.cppProjectState){case 0:return this.handleCppIdleCheck();case 1:case 2:return h.warn(`C++ ${e} rejected: C++ project is ${sy[this.cppProjectState]}`),{content:[{type:"text",text:"C++ project is syncing (compileNative), please retry in 25 seconds"}],isError:!0};case 3:return h.warn(`C++ ${e} rejected: clangd is initializing`),{content:[{type:"text",text:"C++ LSP (clangd) is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleCppErrorCheck();case 4:return this.cppEnabled?this.cppHasNoCppCode?{content:[{type:"text",text:"No C++ code in this project"}],isError:!0}:this.cppLspManager?.ready?t():{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}:{content:[{type:"text",text:"C++ LSP is disabled. Set DEVECO_CLI_CPP_ENABLED=true to enable."}],isError:!0};default:return h.warn(`C++ ${e} rejected: unknown C++ project state ${this.cppProjectState}`),{content:[{type:"text",text:"Unknown C++ project state, please retry"}],isError:!0}}}async routeLspRequest(e,t,n){return e.endsWith(".ets")?this.routeArktsRequest(t,n):Vr(e)?this.routeCppRequest(t,n):{content:[{type:"text",text:`Unsupported file type: ${e} (only .ets and C/C++ source/header files are supported)`}],isError:!0}}async handleCppIdleCheck(){if(this.ensureCppProjectReady(),this.config.projectPath){let e;return this.cppSyncSkippedDueToLock?(e=`Another build process is running, C++ sync deferred (waiting ${this.cppSyncSkipStartedAt>0?Math.round((Date.now()-this.cppSyncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,this.cppSyncSkippedDueToLock=!1):e="C++ project detected, syncing (compileNative), please retry in 25 seconds",h.info(`C++ idle check: project '${this.config.projectPath}', triggering C++ init`),{content:[{type:"text",text:e}],isError:!0}}return{content:[{type:"text",text:"No HarmonyOS project detected for C++ tools."}],isError:!0}}async handleCppErrorCheck(){return this.cppInitRetryCount>=Ot?(h.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${Ot}), will not auto-retry`),{content:[{type:"text",text:`C++ project initialization failed repeatedly (auto-retry exhausted: ${this.cppInitRetryCount}/${Ot}). Ask the user to investigate and confirm \`hvigor compileNative\` succeeds 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(`C++ error check: auto-retrying (${this.cppInitRetryCount}/${Ot})`),this.ensureCppProjectReady(),{content:[{type:"text",text:"C++ project initialization failed, auto-retrying, please retry in 25 seconds"}],isError:!0})}async callCppCheck(e){return this.routeCppRequest("check",async()=>this.cppCheckTool.handleCall({files:e}))}mergeCheckResult(e,t,n){let o=e.content.map(i=>i.text).filter(i=>i&&i.trim().length>0).join(`
1320
- `);o&&(e.isError?t.push(o):n.push(o))}assertRestartAllowed(e){if(e==="arkts"||e==="all"){let t=this.projectState;if(t!==4&&t!==0&&t!==5)return{content:[{type:"text",text:`ArkTS project state: ${this.describeArktsState()}, sync/init in progress, restart unavailable (would interrupt the current flow). Wait for the state to become ready and retry other tools directly\u2014no restart needed. restart is only available in ready/idle/error states.`}],isError:!0}}if(e==="cpp"||e==="all"){let t=this.cppProjectState;if(t!==4&&t!==0&&t!==5)return{content:[{type:"text",text:`C++ project state: ${this.describeCppState()}, sync/init in progress, restart unavailable (would interrupt the current flow). Wait for the state to become ready and retry other tools directly\u2014no restart needed. restart is only available in ready/idle/error states.`}],isError:!0}}return null}async handleRestartCall(e){let t=e.target,n=t==="cpp"?"cpp":t==="arkts"?"arkts":"all";if(n==="cpp"&&!this.cppEnabled)return{content:[{type:"text",text:"C++ LSP is disabled, cannot restart. Set DEVECO_CLI_CPP_ENABLED=true to enable."}],isError:!0};let o=this.assertRestartAllowed(n);return o||(this.restartProject(n),{content:[{type:"text",text:`MCP server is restarting in-place (${n==="all"?"ArkTS + C++":n==="cpp"?"C++":"ArkTS"}): re-sync project + re-initialize LSP. Client connection preserved\u2014no need to exit the agent. Please retry tools in ~10 seconds.`}]})}restartProject(e){h.info(`[restart] resetting tools + state, re-init (target=${e})`),(e==="arkts"||e==="all")&&this.restartArkts(),(e==="cpp"||e==="all")&&this.cppEnabled&&this.restartCpp()}restartArkts(){this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(e=>h.warn("Failed to shutdown ArktsCheckTool during restart:",e)),this.arktsCheckTool=null),this.initRetryCount=0,this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.configChangedTriggeredResync=!1,this.initPromise?(this.needsReinit=!0,h.info("[restart] ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(e=>h.warn("Failed to re-init ArkTS project during restart:",e)))}restartCpp(){this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(e=>h.warn("Failed to dispose ClangdLspManager during restart:",e)),this.cppLspManager=null),this.cppInitRetryCount=0,this.cppHasNoCppCode=!1,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitPromise?(this.cppNeedsReinit=!0,h.info("[restart] C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>h.warn("Failed to re-init C++ project during restart:",e)))}async start(){this.toolRouter.registerToServer(this.server);let e=new LD;if(await this.server.connect(e),h.info("devecocli-mcp-server started"),!this.config.debug){let t=Ip();t&&h.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let n=_t(t);n?(h.info(`Detected project path from client root: ${n}`),this.config.projectPath=n):h.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?h.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):h.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{h.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return h.warn("Client did not provide any roots"),null;let n=t.uri;return this.resolveFileUri(n)}catch(e){return h.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let n=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(n)?n.substring(1):n}}catch(t){h.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,h.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{h.info("shutdown completed, exiting process"),process.exit(0)}).catch(n=>{h.error("shutdown failed:",n),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{h.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?_t(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=_t(this.originalProjectPath),t&&h.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(!this.discoverProject()||!await this.ensureProjectSynced())return;this.ensureCppProjectReady().catch(t=>{h.warn("Background C++ project init failed:",t)}),this.projectState=3,this.arktsCheckTool=new to(this.config.projectPath,this.sdkPath,this.arktsLangServerPath,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{h.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});let e=Date.now();try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,h.info("Project fully initialized, check tool is available"),await this.trackInit("init_arkts",e,!0,null,this.arktsCheckTool?.aceServerPid??null)}catch(t){h.error("LSP initialization failed:",t);let n=q(t),o=this.arktsCheckTool?.aceServerPid??null;this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5,await this.trackInit("init_arkts",e,!1,n,o)}}async ensureProjectSynced(){let e=this.config.projectPath,t=iy(e),n=Si.existsSync(so.join(e,"oh-package-lock.json5")),o=Si.existsSync(so.join(e,"oh_modules"))&&Si.readdirSync(so.join(e,"oh_modules")).length>0;if(n&&o)return t.required?(h.info(`Sync required: ${t.reason}`),this.runSync(e,{skipHvigorSync:!1})):(h.info(`Sync skipped: ${t.reason}`),!0);let i=!t.required;return h.info(`Sync check: skipHvigor=${i}, ohpm install forced (lock=${n}, ohModules=${o}), reason=${t.reason}`),this.runSync(e,{skipHvigorSync:i})}async runSync(e,t){this.projectState=2,h.info("Starting project sync...");let n=await eo.handleSyncProject(e,this.sdkPath,this.nodePath,this.ohpmJsPath,this.hvigorJsPath,t);switch(n.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let o=Date.now()-this.syncSkipStartedAt,i=Math.round(o/1e3);return o>=Ad?(h.error(`Sync skipped for ${i}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(h.warn(`Sync skipped: ${n.reason}, resetting to IDLE for retry (elapsed ${i}s / ${Ad/1e3}s)`),this.projectState=0,!1)}case"failed":return h.error(`Project sync failed: ${n.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return h.error(`Project sync: unknown status ${n.status}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}async ensureCppProjectReady(){if(!this.cppEnabled){h.info("[Cpp] C++ LSP disabled by config, skipping initialization"),this.cppHasNoCppCode=!0,this.cppProjectState=4;return}if(!this.cppInitPromise){this.cppInitPromise=this.doEnsureCppProjectReady();try{await this.cppInitPromise}finally{this.cppInitPromise=null}this.cppNeedsReinit&&(this.cppNeedsReinit=!1,this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>{h.warn("Failed to re-init C++ project after cppNeedsReinit:",e)}))}}async doEnsureCppProjectReady(){let e=this.config.projectPath;if(!e){h.info("[Cpp] No project path, skipping C++ init");return}this.cppProjectState=1;let t=ar(e);if(t.length===0){h.info('[Cpp] No C++ modules found, C++ tools will return "no C++ code"'),this.cppHasNoCppCode=!0,this.cppProjectState=4,this.cppInitRetryCount=0;return}this.cppHasNoCppCode=!1,h.info(`[Cpp] Found ${t.length} C++ module(s): ${t.map(i=>i.name).join(", ")}`);let n=fm(e),o=!n.required;h.info(`[Cpp] C++ sync check: skipCompileNative=${o}, reason=${n.reason}`),await this.runSyncCpp(e,{skipCompileNative:o})&&await this.initCppLsp(e)}async initCppLsp(e){this.cppProjectState=3,this.cppLspManager=new wi({workspaceRoot:e,clangdPath:this.clangdPath??""});let t=Date.now();try{await this.cppLspManager.start(),this.cppCheckTool=new no(this.cppLspManager),this.cppLspTool=new oo(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,h.info("[Cpp] C++ project fully initialized, C++ tools are available"),await this.trackInit("init_cpp",t,!0,null,this.cppLspManager?.clangdPid??null)}catch(n){h.error("[Cpp] C++ LSP initialization failed:",n);let o=q(n),i=this.cppLspManager?.clangdPid??null;this.cppLspManager&&this.cppLspManager.dispose().catch(()=>{}),this.cppLspManager=null,this.cppCheckTool=null,this.cppLspTool=null,this.cppInitRetryCount++,this.cppProjectState=5,await this.trackInit("init_cpp",t,!1,o,i)}}async trackInit(e,t,n,o,i){if(!this.config.telemetry)return;let s="unknown";if(i!==null){let l=await $e(i);l!==null&&(s=te(Number(l)*1024))}let a={event:S.McpToolCall,subAction:e,mcpMemory:te(process.memoryUsage().rss),lspMemory:s},c={duration_ms:Date.now()-t,success:n,error_code:o};await this.config.telemetry.track(a,c).catch(()=>{})}async runSyncCpp(e,t){this.cppProjectState=2,h.info("[Cpp] Starting C++ project sync (compileNative)...");let n=await wi.handleSyncCppProject(e,this.sdkPath,this.nodePath,this.hvigorJsPath,t);switch(n.status){case"success":return this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,!0;case"skipped":{this.cppSyncSkippedDueToLock=!0,this.cppSyncSkipStartedAt===0&&(this.cppSyncSkipStartedAt=Date.now());let o=Date.now()-this.cppSyncSkipStartedAt,i=Math.round(o/1e3);return o>=Ad?(h.error(`[Cpp] C++ sync skipped for ${i}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(h.warn(`[Cpp] C++ sync skipped: ${n.reason}, resetting to IDLE_CPP for retry (elapsed ${i}s)`),this.cppProjectState=0,!1)}case"failed":return h.error(`[Cpp] C++ project sync failed: ${n.reason}`),this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitRetryCount++,this.cppProjectState=5,!1}return!1}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppLspManager&&await this.cppLspManager.dispose(),this.cppCheckTool=null,this.cppLspTool=null;try{await this.server.close()}catch(e){h.warn("Failed to close MCP server connection:",e)}h.info("devecocli-mcp-server stopped"),Ap(),Pp()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function ND(r){let e=[],t=[],n=[];for(let o of r)so.extname(o).toLowerCase()===".ets"?e.push(o):Vr(o)?t.push(o):n.push(o);return{etsFiles:e,cppFiles:t,unsupported:n}}function Dd(r={}){return new qa(r)}import*as Td from"fs";import*as bi from"path";import{spawn as OD}from"child_process";async function ay(r){zr(!1);let{serverPath:e,logPath:t,projectPath:n,sdkPath:o,serverMaxSize:i}=await MD(r),s=jD(e,t,n,o,i);h.info("ace-server started, bridging stdio (initialize is left to the client)"),HD(s),await xd(s.pid,Rd("--arkts",r))}function Rd(r,e){return[r,...e.projectPath?["--project-path"]:[],...e.autoDetect?["--auto-detect"]:[]]}async function xd(r,e){let t="unknown";if(r!==null){let o=await $e(r);o!==null&&(t=te(Number(o)*1024))}let n={event:S.ServeLsp,args:e,lspMemory:t};await I.track(n)}async function MD(r){let e=await k.new(),t;if(r.projectPath)t=ve(bi.resolve(r.projectPath)),h.info(`projectPath=specified ('${t}'), no search`);else if(r.autoDetect){let c=ts(process.cwd());t=ve(c??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=ve(process.cwd()),h.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let n=e.sdkPath,o=e.arktsLangServerPath;o||(h.error("ace-server not found (install DevEco Studio / CLT)."),process.exit(1));let i=Io(o,!0),s=bi.join(rr(),"lsp-server",String(Date.now()));Td.mkdirSync(s,{recursive:!0});let a=_D(t,n);return h.info(`projectPath=${t}, sdkPath=${n}, arktsLangServerPath=${o}, serverPath=${i}, logPath=${s}, serverMaxSize=${a}MB`),{projectPath:t,sdkPath:n,serverPath:i,logPath:s,serverMaxSize:a}}function _D(r,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,n=t?parseInt(t,10):NaN,o=Number.isFinite(n)&&n>0?n:void 0,i=FD(r,e),s=Ss(i,o);return h.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${i}, override=${o??"none"})`),s}function FD(r,e){try{let t=[];return new pn(r,e).getAllDependencyMap(t).status==="OK"?t.length:new Ft(r).getAllModuleInfo().length}catch{return 0}}function jD(r,e,t,n,o){let i=bi.join(e,"lspLog");Td.mkdirSync(i,{recursive:!0});let s=$D(r,i,t,n,o),a=process.execPath??"node";return h.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),OD(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function $D(r,e,t,n,o){let i=J(e);return["--expose-gc",`--max-old-space-size=${o}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${i}`,r,"--stdio",`--logger-path=${i}`,"--logger-level=TRACE",`--projectPath=${J(t)}`,`--sdkPath=${J(n)}`]}function HD(r){r.on("error",e=>{h.error(`[ace-server] spawn error: ${e.message}`),process.exit(1)}),r.stdout?.on("error",e=>{h.error(`[ace-server] stdout error: ${e.message}`)}),r.stdout?.on("data",e=>process.stdout.write(e)),r.stderr?.on("error",e=>{h.error(`[ace-server] stderr error: ${e.message}`)}),r.stderr?.on("data",e=>{h.error(`[ace-server] ${e.toString("utf8").trim()}`)}),r.stdin?.on("error",e=>{h.error(`[ace-server] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{r.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),r.kill(),process.exit(0)}),r.on("exit",e=>{h.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as cy from"fs";import*as fn from"path";import{spawn as BD}from"child_process";async function ly(r){zr(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:n}=await UD(r),o=fn.join(t,"compile_commands.json");cy.existsSync(o)||h.warn(`compile_commands.json not found at ${o}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let i=VD(e,t,n);h.info("clangd started, bridging stdio (initialize is left to the client)"),zD(i),await xd(i.pid,Rd("--cpp",r))}async function UD(r){let e=await WD();e?.clangdPath||(h.error("clangd not found. Ensure DevEco Studio / CLT is installed."),process.exit(1));let t;if(r.projectPath)t=ve(fn.resolve(r.projectPath)),h.info(`projectPath=specified ('${t}'), no search`);else if(r.autoDetect){let a=ts(process.cwd());t=ve(a??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${a??"null, fallback to cwd"}`)}else t=ve(fn.resolve(process.cwd())),h.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let n=e.sdkPath,o=e.clangdPath,i=Wr(t),s=fn.dirname(i);return h.info(`projectPath=${t}, sdkPath=${n}, clangdPath=${o}, compileCommandsDir=${s}`),{projectPath:t,clangdPath:o,compileCommandsDir:s}}async function WD(){try{return await k.new()}catch{let r=Sp();if(!r)return null;try{return k.fromIDE(r)}catch{return null}}}function VD(r,e,t){let n=GD(e);return h.info(`[serve-lsp-cpp] spawn: ${r} ${n.join(" ")}`),BD(r,n,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function GD(r){return[`--compile-commands-dir=${J(r)}`,"--log=info","--pch-storage=memory"]}function zD(r){r.on("error",e=>{h.error(`[clangd] spawn error: ${e.message}`),process.exit(1)}),r.stdout?.on("error",e=>{h.error(`[clangd] stdout error: ${e.message}`)}),r.stdout?.on("data",e=>process.stdout.write(e)),r.stderr?.on("error",e=>{h.error(`[clangd] stderr error: ${e.message}`)}),r.stderr?.on("data",e=>{h.error(`[clangd] ${e.toString("utf8").trim()}`)}),r.stdin?.on("error",e=>{h.error(`[clangd] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{r.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),r.kill(),process.exit(0)}),r.on("exit",e=>{h.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function JD(){let r=process.env.PROJECT_PATH||"",e=process.env.NODE_MAX_OLD_SPACE_SIZE,t=process.env.DEBUG==="true"||process.env.DEBUG==="1",n=process.env.DEVECO_CLI_CPP_ENABLED!=="false"&&process.env.DEVECO_CLI_CPP_ENABLED!=="0",o=r,i=await k.new(),s=Dd({projectPath:o,sdkPath:i.sdkPath,arktsLangServerPath:i.arktsLangServerPath??void 0,nodePath:i.nodePath,ohpmJsPath:i.ohpmJsPath,hvigorJsPath:i.hvigorJsPath,clangdPath:i.clangdPath??void 0,nodeMaxOldSpaceSize:e,debug:t,cppEnabled:n,telemetry:I}),a,c=new Promise(d=>{a=d}),l=async()=>{await s.shutdown(),a()};process.once("SIGINT",l),process.once("SIGTERM",l),process.platform==="win32"&&process.once("SIGBREAK",l);try{await s.start()}catch(d){console.error("Failed to start MCP server:",d instanceof Error?d.message:String(d)),process.exit(1)}await c}var Ld=new qD("serve").description("Host bundled auxiliary protocol servers");Ld.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await JD()});Ld.command("lsp").description("Start a bundled LSP language server").option("--arkts","Start the ArkTS language server (ace-server)").option("--cpp","Start the C/C++ language server (clangd)").option("--project-path <path>","project root path (used as-is, no search)").option("--auto-detect","When --project-path is not specified, search the current directory and its subdirectories for the project root (no upward search)").action(async r=>{r.arkts&&r.cpp&&(console.error("--arkts and --cpp are mutually exclusive. Specify only one."),process.exit(1)),r.arkts?await ay({projectPath:r.projectPath,autoDetect:r.autoDetect}):r.cpp?await ly({projectPath:r.projectPath,autoDetect:r.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var dy=Ld;import{Command as zR,InvalidArgumentError as gu}from"commander";import{red as qR,dim as JR}from"colorette";var Zt=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],Ar={"harmonyos-guides":"\u5F00\u53D1\u6307\u5357","harmonyos-references":"API\u53C2\u8003","best-practices":"\u6700\u4F73\u5B9E\u8DF5","harmonyos-faqs":"FAQ","harmonyos-releases":"\u7248\u672C\u8BF4\u660E","harmonyos-roadmap":"\u53D8\u66F4\u9884\u544A"};import*as $i from"fs";import OR from"proper-lockfile";import xv from"ora";import*as St from"fs";import*as Di from"path";var ao="1.9.1",YD=48*1024*1024;var co=200,uy=12,py=4,Nd=8,my=6;var fy=1320,hy=120,gy=450,yy=250,vy=500,wy=480,Sy=80,by=200,Ey=60,Cy=200;var Py=200,Ay=40,Od=500,KD=Object.fromEntries(Zt.map((r,e)=>[Ar[r],e])),Ir=Object.fromEntries(Zt.map((r,e)=>[r,e]));import*as Ei from"fs";import*as Y from"path";import{fileURLToPath as Iy}from"url";var XD="docs";function Md(){return Y.join(ct(),XD)}function ke(){return Y.join(Md(),".index")}function Ja(){return Y.join(ke(),"build.lock")}function Ci(){return Y.join(ke(),"build-status.json")}function lo(){return Y.join(ke(),"build-meta.json")}function kr(){return Y.join(ke(),"search.db")}function uo(){return Y.join(ke(),".tmp")}function ZD(r,e){let t=e;for(;!t.endsWith(`${Y.sep}dist`)&&t!==Y.dirname(t);)t=Y.dirname(t);return t}function ky(r,e){return Y.dirname(ZD(r,e))}function Dy(){let r=Iy(import.meta.url),e=Y.dirname(r);return r.includes(`${Y.sep}dist${Y.sep}`)?ky(r,e):Y.join(e,"..","..","..")}function QD(...r){let e=Iy(import.meta.url),t=Y.dirname(e);return e.includes(`${Y.sep}dist${Y.sep}`)?[Y.join(ky(e,t),...r)]:[Y.join(t,"..","..","..",...r)]}function Ty(...r){let e=Dy(),t=Ei.realpathSync(e);for(let n of QD(...r))try{let o=Ei.lstatSync(n);if(o.isSymbolicLink()||!o.isFile())throw new Error(`Unsafe documentation package asset: ${r.join("/")} must be a regular file.`);let i=Ei.realpathSync(n);if(!xo(i,t))throw new Error(`Unsafe documentation package asset: ${r.join("/")} is outside the package.`);return i}catch(o){if(o.code!=="ENOENT")throw o}return null}function Dr(){return Ty("docs.zip")}function _d(){return Ty("index.zip")}function Ry(){return Y.join(Dy(),"index","data")}import*as hn from"fs";import*as Pi from"path";var Qt=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Fd=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};var xy=null;function eT(){if(xy)return xy;let r=ke();if(Qt.every(o=>hn.existsSync(Pi.join(r,o))))return r;let t=Ry();if(Qt.every(o=>hn.existsSync(Pi.join(t,o))))return t;throw new Fd("Lexicon files not found. Install the documentation index first (index.zip).")}function po(r){let e=Pi.join(eT(),r);return hn.readFileSync(e,"utf-8")}function Ly(r,e){return hn.readFileSync(Pi.join(e,r),"utf-8")}import*as Ya from"fs";import*as Ny from"path";import*as Oy from"yauzl";var Ai=null;function tT(r){return new Promise((e,t)=>{Oy.open(r,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(n,o)=>{if(n||!o){t(n??new Error(`Failed to open zip: ${r}`));return}e(o)})})}function rT(r){let e=r.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function nT(r){let e=new Map;return new Promise((t,n)=>{r.readEntry(),r.on("entry",o=>{let i=rT(o);i.endsWith("/")||e.set(i,o),r.readEntry()}),r.on("end",()=>{t(e)}),r.on("error",n)})}function oT(){Ai?.zipfile.close(),Ai=null}async function iT(r){let e=Ny.resolve(r),t=await Ya.promises.stat(e),n=Ai;if(n&&n.zipPath===e&&n.mtimeMs===t.mtimeMs&&n.size===t.size)return n;oT();let o=await tT(e),i;try{i=await nT(o)}catch(s){throw o.close(),new Error(`Failed to read entries from zip: ${e}`,{cause:s})}return Ai={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:o,entries:i,readChain:Promise.resolve()},Ai}function sT(r,e){return new Promise((t,n)=>{r.openReadStream(e,(o,i)=>{if(o||!i){n(o??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];i.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),i.on("end",()=>{t(Buffer.concat(s))}),i.on("error",n)})})}async function aT(r,e){let t=r.readChain,n;r.readChain=new Promise(o=>{n=o}),await t;try{return await sT(r.zipfile,e)}finally{n()}}function cT(r){let e=r.replace(/\\/g,"/").replace(/\.md$/,"");if(e.split("/").includes(".."))throw new Error("Invalid document ID: path traversal is not allowed.");return[`docs/${e}.md`,`${e}.md`,`docs/${e}`,e]}function lT(r,e){for(let t of e){let n=r.get(t.replace(/\\/g,"/"));if(n)return n}return null}async function jd(r){let e=Dr();if(!e)throw new Error("docs.zip not found");let t=await iT(e),n=lT(t.entries,cT(r));if(!n)throw new Error(`Document not found: ${r}`);return(await aT(t,n)).toString("utf-8")}function $d(){let r=Dr();return r!==null&&Ya.existsSync(r)}import*as Ge from"fs";import*as Tr from"path";import My from"adm-zip";import*as Ii from"fs";import*as Xa from"path";var Ka=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function mo(r){return r instanceof rn||r instanceof Ka||r instanceof Error&&(r.name==="CliDataDirError"||r.name==="DocPathSafetyError")}function Ud(r){return new Ka(r)}function dT(){return kt(ct())}function Bd(r,e,t){let n=us(r,e);if(n===null)throw Ud(`${t} resolves outside the data directory.`);return n}async function Hd(r,e){await Ii.promises.mkdir(r,{recursive:!0});let t=Bd(r,e,"directory");if(!(await Ii.promises.stat(t)).isDirectory())throw Ud("path must be a directory.")}function uT(r){let e=dT();try{let t=Bd(r,e,"file");if(!Ii.statSync(t).isFile())throw Ud("path must be a regular file.")}catch(t){if(t.code==="ENOENT"){Bd(Xa.dirname(r),e,"file parent");return}throw t}}async function fo(r={}){let e=r.mode??"write",t=await bf();await Hd(Md(),t),await Hd(ke(),t),e==="write"&&await Hd(uo(),t);for(let n of[kr(),lo(),Ci(),Ja(),...Qt.map(o=>Xa.join(ke(),o))])uT(n)}var Wd=["search.db","build-meta.json",...Qt],pT=["corpus.json","corpus-offsets.json","orama.dpack"];async function mT(r){for(let e of pT)await Ge.promises.rm(Tr.join(r,e),{force:!0})}function _y(r){let t=new My(r).getEntry("build-meta.json");if(!t)throw new Error("index.zip is missing build-meta.json");return JSON.parse(t.getData().toString("utf-8"))}async function fT(r){let e=ke();await Ge.promises.mkdir(e,{recursive:!0});for(let t of Wd){let n=Tr.join(e,t);await Ge.promises.rm(n,{force:!0}),await Ge.promises.rename(Tr.join(r,t),n)}await mT(e),await Ge.promises.rm(uo(),{recursive:!0,force:!0})}function Fy(r){let e=_d();if(!e)return!1;try{let t=_y(e);return t.indexVersion===ao&&t.docsZipSha256===r&&t.segmentCount>0}catch{return!1}}async function jy(r){await fo({mode:"write"});let e=_d();if(!e)throw new Error("index.zip not found");let t=_y(e);if(t.docsZipSha256!==r)throw new Error("Bundled index.zip does not match docs.zip. Rebuild index.zip with npm run build:index.");if(t.segmentCount<=0)throw new Error("Bundled index.zip is empty");let n=uo();await Ge.promises.rm(n,{recursive:!0,force:!0}),await Ge.promises.mkdir(n,{recursive:!0});let o=new My(e);for(let s of Wd){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await Ge.promises.writeFile(Tr.join(n,s),a.getData())}let i=JSON.parse(await Ge.promises.readFile(Tr.join(n,"build-meta.json"),"utf-8"));if(!Ge.existsSync(Tr.join(n,"search.db")))throw new Error("index.zip is missing search.db");return await fT(n),i}async function $y(){await Ge.promises.rm(uo(),{recursive:!0,force:!0});let r=ke();for(let e of Wd)await Ge.promises.rm(Tr.join(r,e),{force:!0})}import{createHash as Hy}from"crypto";import*as By from"fs";async function ki(r){return new Promise((e,t)=>{let n=Hy("sha256"),o=By.createReadStream(r);o.on("data",i=>n.update(i)),o.on("error",t),o.on("end",()=>e(n.digest("hex")))})}function Uy(r){return Hy("sha256").update(r,"utf8").digest("hex")}var Vd=null;function hT(){let r=po("harmonyos-synonyms.json");return JSON.parse(r)}function gT(r){let e=new Map;for(let t of r){let n=t.map(o=>o.trim()).filter(Boolean);for(let o of n){let i=n.filter(s=>s!==o);e.set(o.toLowerCase(),i),o!==o.toLowerCase()&&e.set(o,i)}}return e}function yT(){let r=gT(hT()),e=new Map;for(let[t,n]of r)e.set(t,new Set(n));return e}function vT(){return Vd||(Vd=yT()),Vd}function Gd(r,e){let t=vT(),n=r.split(/\s+/).filter(Boolean),o=new Set,i=Number.isFinite(e)?e:n.length;for(let s=0;s<n.length&&o.size<i;s+=1){let a=n[s];o.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(o.size>=i)break;o.add(l)}}return[...o].join(" ")}function Wy(r,e){let t=e?Ly(r,e):po(r);return Uy(t)}function zd(r){return Wy("harmonyos-synonyms.json",r)}function qd(r){return Wy("harmonyos-terms.txt",r)}var wT={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function Za(){try{let r=await St.promises.readFile(Ci(),"utf-8");return JSON.parse(r)}catch{return{...wT}}}async function Jd(r){let e=Ci();await St.promises.mkdir(Di.dirname(e),{recursive:!0}),await St.promises.writeFile(e,JSON.stringify(r,null,2))}function Vy(r){let e=Date.now();return{state:"installing",phase:1,phaseLabel:"Preparing documentation index",current:0,total:0,message:r,startedAt:e,updatedAt:e,error:null}}async function Ti(r){let t={...await Za(),...r,updatedAt:Date.now()};return await Jd(t),t}async function Yd(){let r=Dr();return r?ki(r):null}async function Kd(){try{let r=await St.promises.readFile(lo(),"utf-8");return JSON.parse(r)}catch{return null}}async function Qa(r=!1){if(r)return"no-index";let e=await Kd();if(!e||e.segmentCount===0)return"no-index";let t=await Yd();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==ao?"engine-upgraded":e.termsHash!==qd()?"terms-changed":e.synonymsHash!==zd()?"synonyms-changed":null}function Ri(){if(!$d()||!St.existsSync(kr())||!St.existsSync(lo()))return!1;let r=Di.dirname(kr());if(!Qt.every(e=>St.existsSync(Di.join(r,e))))return!1;try{let e=St.readFileSync(lo(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function Xd(r=!1){return r?!0:$d()?Ri()?await Qa()!==null:!0:!1}async function Gy(){let r=await Za();return["installing","indexing","persisting"].includes(r.state)}var zy=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),Zd=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),qy=new Set(["a","an","and","api","app","application","arkts","arkui","for","get","harmonyos","how","in","oh","ohos","on","or","set","the","to","use","using","what","when","where","which","with","without","data","file","main","model","name","network","stage","system","type","user"]),Jy=new Set(["ability","extension","module","service","context","options","config","info","event","code","state","type","data","request","response","client","server","handler","helper","utils","factory","builder","listener","callback","observer","provider","consumer","delegate","adapter","driver","buffer","stream","channel","session","task","worker","controller","component","container","attribute","descriptor","modifier","validator","parser","formatter","encoder","decoder","filter","converter","generator","iterator","dispatcher","resolver","scanner","tracker","monitor","scheduler","renderer","loader","subscriber","proxy","button","surface","stack","heap","map","set","array","list"]);var ST=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,bT=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,ET=/[A-Z][a-zA-Z0-9]{2,}/g,CT=/@[A-Z][a-zA-Z0-9]*/g,PT=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,Yy=6,AT=/^[a-z][a-z0-9]{2,}$/,IT=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,kT=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,DT=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,TT=/^[A-Z][a-zA-Z0-9]+$/;function RT(r){return`"${r.replace(/"/g,'""')}"`}function Li(r,e){let t=[...new Set(r.filter(Boolean))];return t.length===0?'""':t.map(RT).join(` ${e} `)}function xi(r){return Li(r,"OR")}function Ky(r,e){let t=[...new Set(r.filter(Boolean))],n=[...new Set(e.filter(Boolean))];return t.length===0||n.length===0?xi([...t,...n]):`(${xi(t)}) AND (${xi(n)})`}function Ni(r){return kT.test(r)}function Xy(r){return DT.test(r)&&r.length>=Yy}function xT(r){return TT.test(r)}function Oi(r){return Ni(r)||Xy(r)||xT(r)}function LT(r){let e=r.trim().toLowerCase();return Jy.has(e)?!1:zy.has(e)}function NT(r,e){let t=e.trim().charAt(0).toUpperCase(),n=e.trim().slice(1).toLowerCase();return`${r.trim().toLowerCase()}${t}${n}`}function Qd(r){let t=r.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function Zy(r){return[...r.matchAll(ST)].map(e=>e[0])}function Qy(r,e=Yy){let t=[];for(let n of r.matchAll(bT))n[0].length>=e&&t.push(n[0]);return t}function Mi(r){return r.filter(e=>{let t=e.toLowerCase();return!r.some(n=>{if(n===e)return!1;let o=n.toLowerCase();return o.length>t.length&&o.endsWith(t)&&t.length>=4})})}function Rr(r,e){let t=e.trim();if(!t)return;r.add(t);let n=t.toLowerCase();n!==t&&r.add(n)}function OT(r){let e=new Set;Rr(e,r);let t=Qd(r);return t&&Rr(e,t),Mi([...e])}function ec(r){if(Ni(r))return OT(r);let e=new Set;return Rr(e,r),Mi([...e])}function tc(r){let e=r.trim();if(/[A-Z]/.test(e))return null;let t=e.match(IT);if(!t)return null;let n=t[1].toLowerCase(),o=t[2].toLowerCase();if(!AT.test(n)||qy.has(n)||!LT(o))return null;let i=NT(n,o);return{first:n,second:o,camelCase:i,lower:i.toLowerCase()}}function eu(r){let e=tc(r.trim());return!e||e.second!=="manager"?null:e}function MT(r){let e=r.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function ev(r){let e=r.trim(),t=eu(e);if(t&&Zd.has(t.first))return!0;if(Xy(e)){let n=MT(e);return n!==null&&Zd.has(n)}return!1}function tu(r,e,t){let n=t.toLowerCase(),o=new RegExp(`@ohos\\.[^\\s(]*${t}`,"i");for(let i of[r,e])if(i&&(i.toLowerCase().includes(n)||o.test(i)))return!0;return!1}function ru(r){let e=r.trim();if(Oi(e))return ec(e);let t=new Set;for(let n of Zy(r)){Rr(t,n);let o=Qd(n);o&&Rr(t,o)}for(let n of Qy(r))Rr(t,n);for(let n of r.matchAll(CT))t.add(n[0]);for(let n of r.matchAll(PT))t.add(n[0]);for(let n of r.matchAll(ET))n[0].length>=4&&t.add(n[0]);return Mi([...t])}function tv(r){let e=r.trim();if(Oi(e))return ec(e);let t=new Set,n=tc(e);n&&Rr(t,n.camelCase);for(let o of ru(e))t.add(o);for(let o of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let i=o[0];i!==i.toLowerCase()&&t.add(i)}return Mi([...t])}function rv(r){return Oi(r)}var ie={pureApiSymbol:/^[A-Z][a-zA-Z0-9]+$/,stageModelExact:/^Stage\s*模型$/i,stageModelEnglishExact:/^stage\s+model$/i,stageModel:/Stage\s*模型/i,stageModelEntryPage:/Stage\s*模型.*EntryAbility.*(页面|新页面)/,declarePermissionBoost:/声明.*权限|应用权限.*声明|如何声明应用权限/,declarePermissionCatalog:/如何声明应用权限/,declarePermissionTokens:/如何声明应用权限|声明应用权限/,uiAbilityLifecycleBoost:/UIAbility.*生命周期|生命周期.*UIAbility|UIAblity/i,uiAbilityLifecycleCatalog:/UIAblity.*生命周期|UIAbility.*生命周期/i,entryAbilityPage:/EntryAbility.*(页面|启动|跳转|新页面)/,stateDecoratorBoost:/@State|@Prop|@Link|@Provide|@Consume/,stateDecoratorCatalog:/@State\s*装饰器|@Prop\s*装饰器|@Link\s*装饰器/,stateManagement:/状态管理原理/,routerRoute:/Router\s+路由/,dialogPopupExact:/^Dialog\s+弹窗$/,dialogPopupBoost:/Dialog\s+弹窗/};function nv(r){return ie.pureApiSymbol.test(r.trim())}function _i(r){let e=r.trim();return ie.stageModelExact.test(e)||ie.stageModelEnglishExact.test(e)}function ov(r){let e=[];return _i(r.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),ie.declarePermissionTokens.test(r)&&e.push("\u58F0\u660E\u6743\u9650"),ie.stageModelEntryPage.test(r)&&e.push("\u9875\u9762\u8DEF\u7531","pushUrl"),/UIAblity|UIAbility/.test(r)&&/生命周期/.test(r)&&e.push("UIAbility\u7EC4\u4EF6\u751F\u547D\u5468\u671F"),e}function iv(r){return _i(r)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var _T=[{matches:r=>ie.uiAbilityLifecycleBoost.test(r),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:r=>_i(r),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:r=>!_i(r)&&ie.stageModel.test(r),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:r=>ie.entryAbilityPage.test(r),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:r=>ie.declarePermissionBoost.test(r),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:r=>ie.stateDecoratorBoost.test(r),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:r=>ie.stateManagement.test(r),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:r=>ie.routerRoute.test(r),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:1.4},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]},{matches:r=>ie.dialogPopupBoost.test(r),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function FT(r,e){for(let{catalog:t,multiplier:n}of e){let o=Ir[t];r.set(o,(r.get(o)??1)*n)}}function sv(r,e){for(let t of _T)t.matches(r)&&FT(e,t.weights)}function av(r,e){if(e!==void 0)return!1;let t=r.trim();return Ni(t)||ie.pureApiSymbol.test(t)||ev(t)}function cv(r){let e=r.trim();if(Ni(e)||ie.pureApiSymbol.test(e))return"harmonyos-references";if(_i(e)||ie.uiAbilityLifecycleCatalog.test(e)||ie.stateDecoratorCatalog.test(e)||ie.stateManagement.test(e)||ie.declarePermissionCatalog.test(e)||ie.stageModelEntryPage.test(e)||ie.routerRoute.test(e)||ie.dialogPopupExact.test(e))return"harmonyos-guides"}import{createRequire as jT}from"module";var $T=jT(import.meta.url),rc=null,nu=null,ou=null;function HT(){if(rc)return rc;let r=po("harmonyos-stopwords.txt");return rc=new Set(r.split(`
1321
- `).map(e=>e.trim()).filter(Boolean)),rc}function BT(r){let e=[];for(let t=0;t<r.length;t++){let n=r[t]?.trim();if(!n)continue;let o=r[t+1]?.trim();if(n==="@"&&o&&/^[A-Z][a-zA-Z0-9]*$/.test(o)){e.push(`@${o}`),t+=1;continue}e.push(n)}return e}function lv(r){let e=HT(),t=[];for(let n of BT(r)){let o=n.trim();!o||e.has(o)||(t.push(o.toLowerCase()),/[A-Z]/.test(o)&&/[a-zA-Z]/.test(o)&&t.push(o))}return t}async function UT(){let{cut:r,cut_for_search:e,with_dict:t}=$T("jieba-wasm"),n=po("harmonyos-terms.txt");return t(n),m("doc-index: using jieba-wasm backend"),{cut:(o,i)=>r(o,i),cutForSearch:(o,i)=>e(o,i)}}async function Fi(){return nu||(ou||(ou=UT().then(r=>(nu=r,r))),ou)}async function WT(r){let e=await Fi();return lv(e.cutForSearch(r,!0))}async function dv(r){let e=await Fi();return lv(e.cut(r,!0))}async function nc(r,e){let t=r.trim();if(!t||e<=0)return"";let n=(await WT(t)).join(" ");return n.length<=e?n:n.slice(0,e)}async function VT(r,e){let t=[];for(let o of r){let i=o.trim();i&&(t.push(i.toLowerCase()),/[A-Z]/.test(i)&&t.push(i))}let n=[...new Set(t)].join(" ");return n.length<=e?n:n.slice(0,e)}async function uv(r){let e=!!r.sectionTitle.trim(),t=r.titleTokens.trim(),n=e?wy:fy,o=e?by:gy,i=e?await VT(r.apiSymbols,o):await nc(r.apiSymbols.join(" "),o),a=(await Promise.all([nc(t,e?Sy:hy),Promise.resolve(i),nc(r.headingsText,e?Ey:yy),nc(r.bodySample,e?Cy:vy)])).filter(Boolean).join(" ");return a.length<=n?a:a.slice(0,n)}function GT(r){return r.join(" ").replace(/\s+/g," ").trim().slice(0,co)}function iu(r,e){let t=new Set,n=[];for(let o of[...r,...e]){let i=o.toLowerCase();if(!(!o||t.has(i))&&(t.add(i),n.push(o),n.length>=uy))break}return n}function zT(r){return r.length>=2&&r.length<=py}function qT(r,e){let t=Gd(r,Nd),n=t.split(/\s+/).filter(Boolean),o=[e.first,...n.filter(a=>a!==e.second),e.lower,e.camelCase],i=[e.second,e.lower,e.camelCase],s=iu(o,i);return{rawQuery:r,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:Ky(o,i)}}function JT(r,e){let t=iu(ec(e),[]);return{rawQuery:r,expandedQuery:r,tokens:t,preferAnd:!1,ftsMatch:xi(t)}}async function pv(r){let e=GT(r),t=e.trim(),n=iv(t);if(n)return{rawQuery:e,expandedQuery:n.expandedQuery,tokens:n.tokens,preferAnd:!1};let o=tc(t);if(o)return qT(e,o);if(Oi(t))return JT(e,t);let i=ov(e),s=[...ru(e),...i],c=rv(t)?e:Gd(e,Nd),l=await dv(c),d=iu(s,l);return{rawQuery:e,expandedQuery:c,tokens:d,preferAnd:i.length===0&&zT(d)}}var mv=["harmonyos-releases","harmonyos-roadmap"],YT=new Set(mv.map(r=>Ir[r])),KT=mv.map(r=>`${Ar[r]}/`);function XT(r){return YT.has(r)}function ZT(r){return KT.some(e=>r.startsWith(e))}function fv(r){let e=[],t=[];for(let n of r)XT(n.catalog_id)?t.push(n):e.push(n);return[...e,...t]}function hv(r){let e=[],t=[];for(let n of r)ZT(n.documentId)?t.push(n):e.push(n);return[...e,...t]}var QT=[{pattern:/@ohos\./i,catalog:"harmonyos-references",multiplier:1.5},{pattern:/@[A-Z][a-zA-Z]+/,catalog:"harmonyos-guides",multiplier:1.35},{pattern:/(如何|怎么|怎样|步骤)/,catalog:"harmonyos-guides",multiplier:1.45},{pattern:/(生命周期|原理|概述|什么是|模型|介绍)/,catalog:"harmonyos-guides",multiplier:1.35},{pattern:/(报错|失败|错误|异常|排查)/,catalog:"harmonyos-guides",multiplier:1.25},{pattern:/(报错|失败|FAQ)/i,catalog:"harmonyos-faqs",multiplier:1.2},{pattern:/(构建|签名|打包|发布|上架|应用市场|hvigor|ohpm)/i,catalog:"harmonyos-guides",multiplier:1.3},{pattern:/(行为变更|changelog|升级|适配|版本说明)/i,catalog:"harmonyos-releases",multiplier:1.3},{pattern:/(路由|弹窗|手势|页面|权限|装饰器)/,catalog:"harmonyos-guides",multiplier:1.25,skipForPureApiSymbol:!0}];function ji(r,e,t){let n=Ir[e];r.set(n,(r.get(n)??1)*t)}function eR(r,e){let t=r.trim(),n=/[\u4e00-\u9fff]/.test(t),o=/\b[A-Z][a-zA-Z0-9]{2,}\b/.test(t),i=/\b[a-z][a-zA-Z0-9]{3,}\b/.test(t);if(n&&(o||i)){ji(e,"harmonyos-guides",1.45),ji(e,"harmonyos-references",1.35);return}(o||i)&&ji(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&ji(e,"harmonyos-references",1.75)}function gv(r){let e=new Map,t=r.trim();if(!t)return e;let n=nv(t);eR(t,e),sv(t,e);for(let o of QT)o.pattern.test(t)&&(o.skipForPureApiSymbol&&n||ji(e,o.catalog,o.multiplier));return e}function yv(r){return cv(r)}import{readFile as bR,stat as ER,writeFile as CR}from"fs/promises";var tR=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function rR(r,e){let t=-1;for(let n of tR){let o=r.lastIndexOf(n);o>t&&(t=o)}return t>=e?t:-1}function vv(r,e,t={}){let{maxLen:n=Py,contextChars:o=Ay,excerptTruncated:i=!1}=t,s=r.replace(/\s+/g," ").trim();if(!s)return"";if(s.length<=n)return i?`${s}...`:s;let a=e.split(/\s+/).map(me=>me.trim()).filter(Boolean),c=0;for(let me of a){let Te=s.toLowerCase().indexOf(me.toLowerCase());if(Te>=0){c=Te;break}}let l=Math.max(0,c-o),d=Math.min(s.length,l+n),g=s.slice(l,d),y=rR(g,n-25);y>=0&&(d=l+y);let b=s.slice(l,d).trim(),N=l>0?"...":"",$=d<s.length||i?"...":"";return`${N}${b}${$}`}var nR=`
1322
- SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
1323
- d.catalog_id, bm25(segments_fts) AS bm25
1324
- FROM segments_fts
1325
- JOIN segments s ON s.id = segments_fts.rowid
1326
- JOIN documents d ON d.id = s.doc_id
1327
- WHERE segments_fts MATCH ?
1328
- ORDER BY bm25(segments_fts)
1329
- LIMIT ?
1330
- `,oR=`
1331
- SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
1332
- d.catalog_id, bm25(segments_fts) AS bm25
1333
- FROM segments_fts
1334
- JOIN segments s ON s.id = segments_fts.rowid
1335
- JOIN documents d ON d.id = s.doc_id
1336
- WHERE segments_fts MATCH ? AND d.catalog_id = ?
1337
- ORDER BY bm25(segments_fts)
1338
- LIMIT ?
1339
- `,iR=3.5,sR=1.4,aR=4,cR=1.8,lR=1.35,dR=3.5,uR=1.8,pR=120,wv=6;function au(r){return r.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function mR(r){return r.split(/[^\p{L}\p{N}@.]+/u).map(au).filter(e=>e.length>=2)}function fR(r,e){return e.length>1&&e.every(t=>r.includes(t))}function hR(r){return/^[a-z0-9]{1,4}$/.test(r.trim().toLowerCase())}function gR(r,e){return r===e?dR:r.startsWith(e)||r.includes(`@ohos.${e}`)?uR:1}function yR(r,e){let t=au(e);if(t.length<2)return 1;let n=au(r.doc_title);if(hR(e))return gR(n,t);if(n.includes(t))return aR;if(t.length>=wv&&n.includes(t.slice(0,wv)))return cR;let o=mR(e);return fR(n,o)?lR:1}function vR(r,e){return e<=1?r:r<0?r*e:r/e}function oc(r,e,t,n){let o=r.bm25/(e.get(r.catalog_id)??1);return o=vR(o,yR(r,t)),n&&tu(r.doc_title,r.section_title,n)&&(o/=iR,r.catalog_id===Ir["harmonyos-references"]&&(o/=sR)),o}function su(r,e,t,n){return r.reduce((o,i)=>oc(i,e,t,n)<oc(o,e,t,n)?i:o)}function wR(r,e){return e.some(t=>r.section_title.includes(t)||r.doc_title.includes(t))}function SR(r,e,t,n,o){if(o){let i=r.filter(s=>tu(s.doc_title,s.section_title,o));if(i.length>0)return su(i,t,n,o)}if(e.length>0){let i=r.filter(s=>wR(s,e));if(i.length>0)return su(i,t,n,o)}return su(r,t,n,o)}function Sv(r,e,t,n,o){let i=gv(e),s=tv(e),c=eu(e)?.camelCase,l=new Map;for(let b of r){let N=l.get(b.document_id)??[];N.push(b),l.set(b.document_id,N)}let d=[];for(let b of l.values())d.push(SR(b,s,i,t,c));let g=d.sort((b,N)=>oc(b,i,t,c)-oc(N,i,t,c));return(o?fv(g):g).slice(0,n)}function bv(r,e,t,n,o,i){let s=e?Ir[e]:void 0,a=Math.max(t,t*my,pR),c=s===void 0?r.all(nR,n,a):r.all(oR,n,s,a);return(s===void 0?Sv(c,i,o,t,!0):Sv(c,i,o,t,!1)).map(d=>({title:d.doc_title,documentId:d.document_id,sectionTitle:d.section_title||void 0,snippet:vv(d.lead_text,o,{excerptTruncated:!!d.excerpt_truncated})}))}var Ev=`
1340
- CREATE TABLE documents (
1341
- id INTEGER PRIMARY KEY,
1342
- document_id TEXT NOT NULL UNIQUE,
1343
- catalog_id INTEGER NOT NULL,
1344
- doc_title TEXT NOT NULL
1345
- );
1346
-
1347
- CREATE TABLE segments (
1348
- id INTEGER PRIMARY KEY,
1349
- doc_id INTEGER NOT NULL REFERENCES documents(id),
1350
- section_title TEXT NOT NULL DEFAULT '',
1351
- lead_text TEXT NOT NULL DEFAULT '',
1352
- search_text TEXT NOT NULL,
1353
- excerpt_truncated INTEGER NOT NULL DEFAULT 0
1354
- );
1355
-
1356
- CREATE VIRTUAL TABLE segments_fts USING fts5(
1357
- search_text,
1358
- content='segments',
1359
- content_rowid='id',
1360
- tokenize='unicode61'
1361
- );
1362
-
1363
- CREATE TRIGGER segments_ai AFTER INSERT ON segments BEGIN
1364
- INSERT INTO segments_fts(rowid, search_text) VALUES (new.id, new.search_text);
1365
- END;
1366
-
1367
- CREATE TRIGGER segments_ad AFTER DELETE ON segments BEGIN
1368
- INSERT INTO segments_fts(segments_fts, rowid, search_text) VALUES('delete', old.id, old.search_text);
1369
- END;
1370
-
1371
- CREATE TRIGGER segments_au AFTER UPDATE ON segments BEGIN
1372
- INSERT INTO segments_fts(segments_fts, rowid, search_text) VALUES('delete', old.id, old.search_text);
1373
- INSERT INTO segments_fts(rowid, search_text) VALUES (new.id, new.search_text);
1374
- END;
1375
-
1376
- CREATE INDEX segments_doc_id_idx ON segments(doc_id);
1377
- `;var cu=null,xr=null,Cv=Promise.resolve();async function lu(){return cu||(cu=(async()=>{let r=(await import("@sqlite.org/sqlite-wasm")).default;return r()})()),cu}function PR(r){return{all(e,...t){let n=r.prepare(e);t.length>0&&n.bind(t);let o=[];for(;n.step();)o.push(n.get({}));return n.finalize(),o}}}async function AR(r){let e=await ER(r);if(xr&&xr.dbPath===r&&xr.mtimeMs===e.mtimeMs)return xr.db;xr?.db.close();let t=await lu(),n=t.capi,o=t.wasm,i=new Uint8Array(await bR(r)),s=o.allocFromTypedArray(i),a,c=!1;try{a=new t.oo1.DB(":memory:");let l=n.SQLITE_DESERIALIZE_READONLY|n.SQLITE_DESERIALIZE_RESIZEABLE|n.SQLITE_DESERIALIZE_FREEONCLOSE,d=n.sqlite3_deserialize(a.pointer,"main",s,i.byteLength,i.byteLength,l);if(d!==n.SQLITE_OK)throw new Error(`Failed to open readonly database: sqlite3_deserialize returned code ${d} for: ${r}`);return xr={dbPath:r,mtimeMs:e.mtimeMs,db:a},c=!0,a}finally{c||(a?.close(),o.dealloc(s))}}async function IR(r){let e,t=Cv;Cv=new Promise(n=>{e=n}),await t;try{return await AR(r)}finally{e()}}function Pv(){xr?.db.close(),xr=null}async function kR(r,e,t,n){r.exec("BEGIN");for(let o of n){let i=t(o.source);e.bind([i,o.source.sectionTitle,o.source.leadText,o.searchText,o.source.excerptTruncated?1:0]),e.step(),e.reset()}r.exec("COMMIT")}function DR(r,e,t){return n=>{let o=e.get(n.documentId);if(o!==void 0)return o;let i=r.selectValue("SELECT id FROM documents WHERE document_id = ?",[n.documentId]);if(i!=null){let a=Number(i);return e.set(n.documentId,a),a}t.bind([n.documentId,n.catalogId,n.docTitle]),t.step(),t.reset();let s=Number(r.selectValue("SELECT last_insert_rowid()"));return e.set(n.documentId,s),s}}async function TR(r,e,t){await Fi();let n=await lu(),o=new n.oo1.DB(":memory:","c");o.exec(Ev);let i=new Map,s=o.prepare("INSERT INTO documents(document_id, catalog_id, doc_title) VALUES (?, ?, ?)"),a=o.prepare("INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated) VALUES (?, ?, ?, ?, ?)"),c=DR(o,i,s),l=e.length;for(let g=0;g<l;g+=Od){let y=e.slice(g,g+Od),b=await Promise.all(y.map(async N=>({source:N,searchText:await uv(N)})));await kR(o,a,c,b),await t?.(Math.min(g+y.length,l),l)}o.exec("ANALYZE");let d=n.capi.sqlite3_js_db_export(o);await CR(r,d),o.close(),Pv()}async function RR(r,e,t,n,o,i){let s=await IR(r);return bv(PR(s),e,t,n,o,i)}async function Av(){return await lu(),{resetCache:Pv,buildSearchIndex:TR,searchIndex:(r,e,t,n,o,i,s)=>RR(n,e,t,o,i,s)}}var ic=null,du=null;async function uu(){return ic||(ic=Av().then(r=>(du=r,r))),ic}function pu(){du?.resetCache(),ic=null,du=null}async function xR(r,e,t,n,o,i,s){let a=await uu(),c=s??kr();return a.searchIndex(r,e,t,c,n,o,i)}function ho(){pu()}function kv(r,e,t){let n=new Set,o=[];for(let i of[...r,...e])if(!n.has(i.documentId)&&(n.add(i.documentId),o.push(i),o.length>=t))break;return o}function sc(r,e,t,n,o,i){return xR(r,e,t,o,n.expandedQuery,n.rawQuery,i)}async function LR(r,e,t,n,o){let i=await sc(r,e,t,n,Li(n.tokens,"AND"),o);if(i.length>=t)return i;let s=await sc(r,e,t,n,Li(n.tokens,"OR"),o);return kv(i,s,t)}async function mu(r,e,t,n,o){return n.ftsMatch?sc(r,e,t,n,n.ftsMatch,o):n.preferAnd?LR(r,e,t,n,o):sc(r,e,t,n,Li(n.tokens,"OR"),o)}async function NR(r,e,t,n){let o=await mu(r,"harmonyos-references",e,t,n);if(o.length>=e)return o;let i=await mu(r,void 0,e,t,n);return kv(o,i,e)}function Iv(r,e){return e!==void 0?r:hv(r)}async function fu(r,e,t=10,n){let o=await pv(r);if(av(o.rawQuery,e)){let a=await NR(r,t,o,n);return Iv(a,e)}let i=e??yv(o.rawQuery),s=await mu(r,i,t,o,n);return Iv(s,e)}var ac=class extends Error{constructor(t,n){super(n);this.code=t;this.name="DocNotReadyError"}};function MR(r){return new Promise(e=>setTimeout(e,r))}async function Dv(r,e,t){e?.start(t),await Ti({state:"installing",phase:1,phaseLabel:"Installing index",message:t}),await jy(r),ho(),e&&(e.text="Documentation index installed.")}async function _R(r,e){try{return await Dv(r,e,"Installing documentation index\u2026"),await Tv(e),!0}catch(t){if(mo(t))throw t}try{return await $y(),ho(),await Dv(r,e,"Retrying documentation index install\u2026"),await Tv(e),!0}catch(t){if(mo(t))throw t;return!1}}async function Tv(r){await Ti({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),r?.succeed("Documentation ready.")}async function FR(r){let e=await Kd(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";r?.succeed(t),await Ti({state:"done",message:t,error:null})}async function jR(r,e){let t=r instanceof Error?r.message:String(r);throw await Ti({state:"error",error:t}),e?.fail(t),r}async function $R(){let r=ke();await $i.promises.mkdir(r,{recursive:!0});let e=Ja();return $i.existsSync(e)||await $i.promises.writeFile(e,"","utf-8"),e}async function HR(){let r=await $R();return OR.lock(r,{stale:1800*1e3})}async function BR(){let r=Dr(),e=(r?await ki(r):null)??await Yd();if(!e)throw new Error("docs.zip not found");return e}async function UR(r,e){let t=await BR(),n=r.force||await Xd(r.force),o=await Qa(r.force);if(!n&&!o&&Ri()){await FR(e);return}if(!(Fy(t)&&await _R(t,e)))throw new Error("Documentation index bundle is unavailable or corrupted. Reinstall the package with: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>")}var go=class{static async run(e={}){let t=e.background??!1,o=e.quiet??t?void 0:xv({text:"Checking documentation\u2026",color:"cyan"}),i;try{e.assumeStorageSafe||await fo({mode:"write"}),i=await HR(),await Jd(Vy("Starting documentation setup\u2026")),await UR(e,o)}catch(s){throw i&&await jR(s,o),s}finally{i&&await i()}}};async function WR(r){for(;;){let e=await Za();if(e.state==="done"&&Ri())return;if(e.state==="error")throw new ac("build-failed",e.error??"Documentation setup failed. Try your docs command again in a moment.");r.text=e.message||"Documentation is being prepared\u2026",await MR(500)}}async function Rv(r,e=!1){r.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await go.run({builtBy:"doc-init",force:e,quiet:!0})}async function VR(){let r=await Qa()!==null;if(Ri()&&!r)return;let e=xv({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await Gy()){await WR(e),e.succeed("Documentation ready.");return}if(await Xd()){await Rv(e),e.succeed("Documentation ready.");return}await Rv(e,!0),e.succeed("Documentation ready.")}catch(t){throw e.fail(t.message),t}}async function yo(){await fo({mode:"read"}),await VR()}function GR(r){let e=r instanceof Error?r.message:String(r);return/file is not a database|database disk image is malformed|SQLITE_CORRUPT/i.test(e)}var hu=class{async search(e,t,n=10){await yo();try{return await fu(e,t,n)}catch(o){if(!GR(o))throw o;return ho(),await go.run({builtBy:"doc-init",force:!0,quiet:!0,assumeStorageSafe:!0}),fu(e,t,n)}}async readDocument(e){return await yo(),jd(e)}},cc=new hu;import W4 from"adm-zip";import{unified as P4}from"unified";import I4 from"remark-parse";import D4 from"remark-gfm";import{toString as R4}from"mdast-util-to-string";async function yu(r,e){let t=Date.now();try{let n=await e();return await Lv(r,Date.now()-t,!0,null),n}catch(n){let o=n instanceof Error?n.code??n.name:"UnknownError";throw await Lv(r,Date.now()-t,!1,o),n}}async function Lv(r,e,t,n){await I.track(r,{duration_ms:e,success:t,error_code:n}).catch(()=>{})}function vu(r){console.error(qR(ZR(r))),process.exitCode=1}function Nv(...r){return e=>{if(!r.includes(e))throw new gu(`Allowed values: ${r.join(", ")}`);return e}}function YR(r){let e=Number(r);if(!Number.isInteger(e)||e<=0)throw new gu("Must be a positive integer.");return e}var KR=Nv("json","default"),XR=Nv("json","default");function ZR(r){let e=r instanceof Error?r.message:String(r);return mo(r)?e:/\b(EACCES|EPERM|ENOSPC|ENOTDIR|ELOOP)\b/.test(e)?"Documentation data directory is unavailable. Check DEVECO_CLI_DATA_DIR and retry.":e}var lc=new zR("docs").description("Search and read HarmonyOS documentation from local docs directory");lc.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",ex,"all").option("--format <fmt>","Output format (default, json)",KR,"default").option("--limit <n>","Max number of results",YR,10).action(async(r,e)=>{let t=r.map(o=>o.trim()).filter(Boolean),n={event:S.DocOperation,subAction:"search",keywords:t,queryLen:t.join(" ").length,catalog:e.catalog??"all"};try{await yu(n,async()=>{let o=QR(r),i=e.catalog&&e.catalog!=="all"?e.catalog:void 0,s=await cc.search(o,i,e.limit);e.format==="json"?console.log(JSON.stringify(s,null,2)):tx(s)})}catch(o){vu(o)}});lc.command("read <documentId>").description("Read full content of a document by document ID").action(async r=>{let e=r.trim(),t={event:S.DocOperation,subAction:"read",documentId:e};try{await yu(t,async()=>{if(!e)throw new Error("Document ID cannot be empty.");let n=await cc.readDocument(e);console.log(n)})}catch(n){vu(n)}});lc.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",XR,"default").action(async r=>{let e={event:S.DocOperation,subAction:"catalog",fmt:r.format??"default"};try{await yu(e,async()=>{if(await yo(),r.format==="json"){let t=Zt.map(n=>({name:n,title:Ar[n]}));console.log(JSON.stringify(t,null,2))}else for(let t of Zt)console.log(` ${t.padEnd(20)} ${JR(Ar[t])}`)})}catch(t){vu(t)}});function QR(r){let e=r.map(n=>n.trim()).filter(Boolean);if(e.length===0)throw new Error("Keywords cannot be empty.");if(e.join(" ").length>co)throw new Error(`Query exceeds ${co} characters.`);return e}function ex(r){if(r==="all")return"all";if(!Zt.includes(r))throw new gu(`Invalid catalog "${r}". Allowed: all, ${Zt.join(", ")}`);return r}function tx(r){for(let e=0;e<r.length;e++){let t=r[e];console.log(t.documentId),console.log(` Title: ${t.title}`),t.snippet&&console.log(` Content: ${t.snippet}`),e<r.length-1&&console.log()}}var Ov=lc;import{Command as _x}from"commander";import{Command as rx,InvalidArgumentError as nx,Option as wu}from"commander";import ox from"ora";function ix(r){let e=parseInt(r,10);if(!Number.isInteger(e)||e<0||String(e)!==r.trim())throw new nx("depth must be a non-negative integer");return e}function sx(r){let e=[];(r.type||r.id)&&e.push(r.type?r.id?`${r.type}#${r.id}`:r.type:`#${r.id}`),e.push(r.bounds?`[${r.bounds.join(",")}]`:"[]"),r.text&&e.push(`"${JSON.stringify(r.text).slice(1,-1)}"`);let t=[];return r.clickable&&t.push("clickable"),r.longClickable&&t.push("longClickable"),r.scrollable&&t.push("scrollable"),r.checkable&&t.push("checkable"),t.length>0&&e.push(...t),e.join(" ")}function Mv(r,e=0){let t=[],n=" ".repeat(e);for(let o of r)t.push(`${n}${sx(o)}`),o.children.length>0&&t.push(...Mv(o.children,e+1).split(`
1336
+ `).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 r=t.file,i=t.line,o=t.character;return typeof r!="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(r,e,async()=>{if(r.endsWith(".ets"))return this.arktsCheckTool.handleLspFeature(e,{file:r,line:i,character:o});let s=e;return this.cppLspTool.handleLspFeature(s,{file:r,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,r=this.cppProjectState===4&&!this.cppHasNoCppCode&&this.cppLspTool!==null;if(!t&&!r){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(r)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,r=t?.location?.uri??"",i=t?.location?.range?.start?.line??0,o=t?.location?.range?.start?.character??0;return`${r}:${i}:${o}`}mergeSymbolItems(e,t,r){if(e)for(let i of e){let o=this.symbolDedupKey(i);t.has(o)||(t.add(o),r.push(i))}}describeArktsState(){switch(this.projectState){case 0:return"idle";case 1:return"discovering";case 2:return`syncing (retry ${zs}s)`;case 3:return`initializing (retry ${zs}s)`;case 5:return`error (${this.initRetryCount}/${ar})`;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}/${ar})`;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,r=e.line,i=e.character,o=e.direction;return typeof t!="string"||typeof r!="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:r,character:i,direction:o}):this.cppLspTool.handleCallHierarchy({file:t,line:r,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>=ar?(h.error(`Init retry limit reached (${this.initRetryCount}/${ar}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${ar}). 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}/${ar})`),this.arktsInitProgress=null,this.ensureProjectReady(),{content:[{type:"text",text:`Project initialization failed, auto-retrying.${this.buildRetrySuffix()}`}],isError:!0})}buildRetrySuffix(){return` Retry in ${zs}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=od.indexOf(e.phase)+1,r=Math.round((Date.now()-e.startedAt)/1e3),i=this.arktsPipelineStartedAt?Math.round((Date.now()-this.arktsPipelineStartedAt)/1e3):r,o=e.percent!==null?` (${e.percent}%)`:"";return[`ArkTS init [${t}/4] ${NS[e.phase]}: ${e.detail}${o} [${r}s, total ${i}s]`,this.buildPipelineLine(e.phase),`Retry in ${zs}s. Expected total: 30s\u201310min (depends on project size).`].join(`
1337
+ `)}buildPipelineLine(e){return`Pipeline: ${od.map(r=>{let i=od.indexOf(r)<od.indexOf(e),o=r===e,s=NS[r];return i?`${s} \u2713`:o?`${s}(\u2026)`:s}).join(" \u2192 ")}`}async routeCppRequest(e,t){switch(this.cppProjectState){case 0:return this.handleCppIdleCheck();case 1:case 2:return h.warn(`C++ ${e} rejected: C++ project is ${LS[this.cppProjectState]}`),{content:[{type:"text",text:"C++ project is syncing (compileNative), please retry in 25 seconds"}],isError:!0};case 3:return h.warn(`C++ ${e} rejected: clangd is initializing`),{content:[{type:"text",text:"C++ LSP (clangd) is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleCppErrorCheck();case 4:return this.cppEnabled?this.cppHasNoCppCode?{content:[{type:"text",text:"No C++ code in this project"}],isError:!0}:this.cppLspManager?.ready?t():{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}:{content:[{type:"text",text:"C++ LSP is disabled. Set DEVECO_CLI_CPP_ENABLED=true to enable."}],isError:!0};default:return h.warn(`C++ ${e} rejected: unknown C++ project state ${this.cppProjectState}`),{content:[{type:"text",text:"Unknown C++ project state, please retry"}],isError:!0}}}async routeLspRequest(e,t,r){return e.endsWith(".ets")?this.routeArktsRequest(t,r):An(e)?this.routeCppRequest(t,r):{content:[{type:"text",text:`Unsupported file type: ${e} (only .ets and C/C++ source/header files are supported)`}],isError:!0}}async handleCppIdleCheck(){if(this.ensureCppProjectReady(),this.config.projectPath){let e;return this.cppSyncSkippedDueToLock?(e=`Another build process is running, C++ sync deferred (waiting ${this.cppSyncSkipStartedAt>0?Math.round((Date.now()-this.cppSyncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,this.cppSyncSkippedDueToLock=!1):e="C++ project detected, syncing (compileNative), please retry in 25 seconds",h.info(`C++ idle check: project '${this.config.projectPath}', triggering C++ init`),{content:[{type:"text",text:e}],isError:!0}}return{content:[{type:"text",text:"No HarmonyOS project detected for C++ tools."}],isError:!0}}async handleCppErrorCheck(){return this.cppInitRetryCount>=ar?(h.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${ar}), will not auto-retry`),{content:[{type:"text",text:`C++ project initialization failed repeatedly (auto-retry exhausted: ${this.cppInitRetryCount}/${ar}). Ask the user to investigate and confirm \`hvigor compileNative\` succeeds 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(`C++ error check: auto-retrying (${this.cppInitRetryCount}/${ar})`),this.ensureCppProjectReady(),{content:[{type:"text",text:"C++ project initialization failed, auto-retrying, please retry in 25 seconds"}],isError:!0})}async callCppCheck(e){return this.routeCppRequest("check",async()=>this.cppCheckTool.handleCall({files:e}))}mergeCheckResult(e,t,r){let i=e.content.map(o=>o.text).filter(o=>o&&o.trim().length>0).join(`
1338
+ `);i&&(e.isError?t.push(i):r.push(i))}assertRestartAllowed(e){if(e==="arkts"||e==="all"){let t=this.projectState;if(t!==4&&t!==0&&t!==5)return{content:[{type:"text",text:`ArkTS project state: ${this.describeArktsState()}, sync/init in progress, restart unavailable (would interrupt the current flow). Wait for the state to become ready and retry other tools directly\u2014no restart needed. restart is only available in ready/idle/error states.`}],isError:!0}}if(e==="cpp"||e==="all"){let t=this.cppProjectState;if(t!==4&&t!==0&&t!==5)return{content:[{type:"text",text:`C++ project state: ${this.describeCppState()}, sync/init in progress, restart unavailable (would interrupt the current flow). Wait for the state to become ready and retry other tools directly\u2014no restart needed. restart is only available in ready/idle/error states.`}],isError:!0}}return null}async handleRestartCall(e){let t=e.target,r=t==="cpp"?"cpp":t==="arkts"?"arkts":"all";if(r==="cpp"&&!this.cppEnabled)return{content:[{type:"text",text:"C++ LSP is disabled, cannot restart. Set DEVECO_CLI_CPP_ENABLED=true to enable."}],isError:!0};let i=this.assertRestartAllowed(r);return i||(this.restartProject(r),{content:[{type:"text",text:`MCP server is restarting in-place (${r==="all"?"ArkTS + C++":r==="cpp"?"C++":"ArkTS"}): re-sync project + re-initialize LSP. Client connection preserved\u2014no need to exit the agent. Please retry tools in ~${zs}s.`}]})}restartProject(e){h.info(`[restart] resetting tools + state, re-init (target=${e})`),(e==="arkts"||e==="all")&&this.restartArkts(),(e==="cpp"||e==="all")&&this.cppEnabled&&this.restartCpp()}restartArkts(){this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(e=>h.warn("Failed to shutdown ArktsCheckTool during restart:",e)),this.arktsCheckTool=null),this.initRetryCount=0,this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.configChangedTriggeredResync=!1,this.initPromise?(this.needsReinit=!0,h.info("[restart] ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(e=>h.warn("Failed to re-init ArkTS project during restart:",e)))}restartCpp(){this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(e=>h.warn("Failed to dispose ClangdLspManager during restart:",e)),this.cppLspManager=null),this.cppInitRetryCount=0,this.cppHasNoCppCode=!1,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitPromise?(this.cppNeedsReinit=!0,h.info("[restart] C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>h.warn("Failed to re-init C++ project during restart:",e)))}async start(){await this.detectSocketAvailable(),this.registerTools(),this.toolRouter.registerToServer(this.server);let e=new A_;if(await this.server.connect(e),h.info("devecocli-mcp-server started"),!this.config.debug){let t=kh();t&&h.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=lr(t);r?(h.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):h.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?h.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):h.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{h.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return h.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return h.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){h.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,h.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{h.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{h.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{h.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?lr(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=lr(this.originalProjectPath),t&&h.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(!this.discoverProject())return;if(this.arktsPipelineStartedAt=Date.now(),this.arktsInitProgress={phase:"ohpm",detail:"installing dependencies",percent:null,startedAt:Date.now(),updatedAt:Date.now()},!await this.ensureProjectSynced()){this.arktsInitProgress=null;return}this.ensureCppProjectReady().catch(t=>{h.warn("Background C++ project init failed:",t)}),this.projectState=3,this.arktsInitProgress={phase:"dep-parse",detail:"parsing dependency map",percent:null,startedAt:Date.now(),updatedAt:Date.now()},this.arktsCheckTool=this.createArktsCheckTool();let e=Date.now();try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,this.arktsInitProgress=null,h.info("Project fully initialized, check tool is available"),await this.trackInit("init_arkts",e,!0,null,this.arktsCheckTool?.aceServerPid??null)}catch(t){h.error("LSP initialization failed:",t);let r=X(t),i=this.arktsCheckTool?.aceServerPid??null;this.arktsCheckTool=null,this.arktsInitProgress=null,this.initRetryCount++,this.projectState=5,await this.trackInit("init_arkts",e,!1,r,i)}}createArktsCheckTool(){let e=new ho(this.config.projectPath,this.sdkPath,this.arktsLangServerPath,this.config.nodeMaxOldSpaceSize,this.nodePath,this.socketAvailable);return e.setOnConfigChanged(()=>{h.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0}),e.setOnInitProgress((t,r)=>{this.arktsInitProgress&&(this.arktsInitProgress.phase="lsp-init",this.arktsInitProgress.detail=t,this.arktsInitProgress.percent=r,this.arktsInitProgress.updatedAt=Date.now())}),e.setOnDepParseProgress((t,r)=>{this.arktsInitProgress&&(this.arktsInitProgress.phase="dep-parse",this.arktsInitProgress.detail=`${t}/${r} modules`,this.arktsInitProgress.percent=r>0?Math.round(t/r*100):null,this.arktsInitProgress.updatedAt=Date.now())}),e}async ensureProjectSynced(){let e=this.config.projectPath,t=MS(e),r=Js.existsSync(bo.join(e,"oh-package-lock.json5")),i=Js.existsSync(bo.join(e,"oh_modules"))&&Js.readdirSync(bo.join(e,"oh_modules")).length>0;if(r&&i)return t.required?(h.info(`Sync required: ${t.reason}`),this.runSync(e,{skipHvigorSync:!1})):(h.info(`Sync skipped: ${t.reason}`),!0);let o=!t.required;return h.info(`Sync check: skipHvigor=${o}, ohpm install forced (lock=${r}, ohModules=${i}), reason=${t.reason}`),this.runSync(e,{skipHvigorSync:o})}async runSync(e,t){this.projectState=2,h.info("Starting project sync...");let r=s=>{this.arktsInitProgress&&(this.arktsInitProgress.phase="ohpm",this.arktsInitProgress.detail=s,this.arktsInitProgress.percent=null,this.arktsInitProgress.updatedAt=Date.now())},i=s=>{this.arktsInitProgress&&(this.arktsInitProgress.phase="hvigor",this.arktsInitProgress.detail=s,this.arktsInitProgress.percent=null,this.arktsInitProgress.updatedAt=Date.now())},o=await fo.handleSyncProject(e,this.sdkPath,this.nodePath,this.ohpmJsPath,this.hvigorJsPath,t,r,i);return this.handleSyncResult(o)}handleSyncResult(e){switch(e.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let t=Date.now()-this.syncSkipStartedAt,r=Math.round(t/1e3);return t>=Gm?(h.error(`Sync skipped for ${r}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(h.warn(`Sync skipped: ${e.reason}, resetting to IDLE for retry (elapsed ${r}s / ${Gm/1e3}s)`),this.projectState=0,!1)}case"failed":return h.error(`Project sync failed: ${e.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return h.error(`Project sync: unknown status ${e.status}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}async ensureCppProjectReady(){if(!this.cppEnabled){h.info("[Cpp] C++ LSP disabled by config, skipping initialization"),this.cppHasNoCppCode=!0,this.cppProjectState=4;return}if(!this.cppInitPromise){this.cppInitPromise=this.doEnsureCppProjectReady();try{await this.cppInitPromise}finally{this.cppInitPromise=null}this.cppNeedsReinit&&(this.cppNeedsReinit=!1,this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>{h.warn("Failed to re-init C++ project after cppNeedsReinit:",e)}))}}resolveCppCustomDir(){let e=`${this.config.cppCompileCommandsPath??""}|${this.config.projectPath??""}`;return e!==this.cppCustomDirResolvedFor&&(this.cppCustomDirResolvedFor=e,this.cppCustomCompileCommandsDir=Ba(this.config.cppCompileCommandsPath,this.config.projectPath),this.cppCustomCompileCommandsDir&&h.info(`[Cpp] Custom compile_commands dir resolved: ${this.cppCustomCompileCommandsDir}`)),this.cppCustomCompileCommandsDir}async doEnsureCppProjectReady(){let e=this.config.projectPath;if(!e){h.info("[Cpp] No project path, skipping C++ init");return}let t=this.resolveCppCustomDir();if(t){h.info(`[Cpp] Custom compile_commands.json configured, skipping compileNative sync (dir: ${t})`),this.cppHasNoCppCode=!1,await this.initCppLsp(e);return}this.cppProjectState=1;let r=Ur(e);if(r.length===0){h.info('[Cpp] No C++ modules found, C++ tools will return "no C++ code"'),this.cppHasNoCppCode=!0,this.cppProjectState=4,this.cppInitRetryCount=0;return}this.cppHasNoCppCode=!1,h.info(`[Cpp] Found ${r.length} C++ module(s): ${r.map(s=>s.name).join(", ")}`);let i=yg(e),o=!i.required;h.info(`[Cpp] C++ sync check: skipCompileNative=${o}, reason=${i.reason}`),await this.runSyncCpp(e,{skipCompileNative:o})&&await this.initCppLsp(e)}async initCppLsp(e){this.cppProjectState=3,this.cppLspManager=new qs({workspaceRoot:e,clangdPath:this.clangdPath??"",...this.cppCustomCompileCommandsDir?{compileCommandsDir:this.cppCustomCompileCommandsDir}:{}});let t=Date.now();try{await this.cppLspManager.start(),this.cppCheckTool=new yo(this.cppLspManager),this.cppLspTool=new wo(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,h.info("[Cpp] C++ project fully initialized, C++ tools are available"),await this.trackInit("init_cpp",t,!0,null,this.cppLspManager?.clangdPid??null)}catch(r){h.error("[Cpp] C++ LSP initialization failed:",r);let i=X(r),o=this.cppLspManager?.clangdPid??null;this.cppLspManager&&this.cppLspManager.dispose().catch(()=>{}),this.cppLspManager=null,this.cppCheckTool=null,this.cppLspTool=null,this.cppInitRetryCount++,this.cppProjectState=5,await this.trackInit("init_cpp",t,!1,i,o)}}async trackInit(e,t,r,i,o){if(!this.config.telemetry)return;let s="unknown";if(o!==null){let l=await lt(o);l!==null&&(s=ce(Number(l)*1024))}let a={event:v.McpToolCall,subAction:e,mcpMemory:ce(process.memoryUsage().rss),lspMemory:s},c={duration_ms:Date.now()-t,success:r,error_code:i};await this.config.telemetry.track(a,c).catch(()=>{})}async runSyncCpp(e,t){this.cppProjectState=2,h.info("[Cpp] Starting C++ project sync (compileNative)...");let r=await qs.handleSyncCppProject(e,this.sdkPath,this.nodePath,this.hvigorJsPath,t);switch(r.status){case"success":return this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,!0;case"skipped":{this.cppSyncSkippedDueToLock=!0,this.cppSyncSkipStartedAt===0&&(this.cppSyncSkipStartedAt=Date.now());let i=Date.now()-this.cppSyncSkipStartedAt,o=Math.round(i/1e3);return i>=Gm?(h.error(`[Cpp] C++ sync skipped for ${o}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(h.warn(`[Cpp] C++ sync skipped: ${r.reason}, resetting to IDLE_CPP for retry (elapsed ${o}s)`),this.cppProjectState=0,!1)}case"failed":return h.error(`[Cpp] C++ project sync failed: ${r.reason}`),this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitRetryCount++,this.cppProjectState=5,!1}return!1}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppLspManager&&await this.cppLspManager.dispose(),this.cppCheckTool=null,this.cppLspTool=null;try{await this.server.close()}catch(e){h.warn("Failed to close MCP server connection:",e)}h.info("devecocli-mcp-server stopped"),Ch(),Ph()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function I_(n){let e=[],t=[],r=[];for(let i of n)bo.extname(i).toLowerCase()===".ets"?e.push(i):An(i)?t.push(i):r.push(i);return{etsFiles:e,cppFiles:t,unsupported:r}}function zm(n={}){return new sd(n)}import*as Jm from"fs";import*as Ys from"path";import{spawn as T_}from"child_process";async function _S(n){In(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:i,serverMaxSize:o,nodePath:s}=await O_(n),a=L_(e,t,r,i,o,s);h.info("ace-server started, bridging stdio (initialize is left to the client)"),__(a),await Km(a.pid,Ym("--arkts",n))}function Ym(n,e){return[n,...e.projectPath?["--project-path"]:[],...e.autoDetect?["--auto-detect"]:[]]}async function Km(n,e){let t="unknown";if(n!==null){let i=await lt(n);i!==null&&(t=ce(Number(i)*1024))}let r={event:v.ServeLsp,args:e,lspMemory:t};await D.track(r)}async function O_(n){let e=await P.new(),t;if(n.projectPath)t=De(Ys.resolve(n.projectPath)),h.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let c=ya(process.cwd());t=De(c??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=De(process.cwd()),h.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,i=e.arktsLangServerPath;i||(h.error("ace-server not found (install DevEco Studio / CLT)."),process.exit(1));let o=mi(i,!0),s=Ys.join(Lr(),"lsp-server",String(Date.now()));Jm.mkdirSync(s,{recursive:!0});let a=M_(t,r);return h.info(`projectPath=${t}, sdkPath=${r}, arktsLangServerPath=${i}, serverPath=${o}, logPath=${s}, serverMaxSize=${a}MB`),{projectPath:t,sdkPath:r,serverPath:o,logPath:s,serverMaxSize:a,nodePath:e.nodePath}}function M_(n,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=t?parseInt(t,10):NaN,i=Number.isFinite(r)&&r>0?r:void 0,o=N_(n,e),s=ja(o,i);return h.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${o}, override=${i??"none"})`),s}function N_(n,e){try{let t=[];return new ni(n,e).getAllDependencyMap(t).status==="OK"?t.length:new ur(n).getAllModuleInfo().length}catch{return 0}}function L_(n,e,t,r,i,o){let s=Ys.join(e,"lspLog");Jm.mkdirSync(s,{recursive:!0});let a=$o({serverPath:n,lspLogPath:s,serverMaxSize:i,projectPath:t,sdkPath:r}),c=On(o);return h.info(`[serve-lsp] spawn: ${c} ${a.join(" ")}`),T_(c,a,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function __(n){n.on("error",e=>{h.error(`[ace-server] spawn error: ${e.message}`),process.exit(1)}),n.stdout?.on("error",e=>{h.error(`[ace-server] stdout error: ${e.message}`)}),n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("error",e=>{h.error(`[ace-server] stderr error: ${e.message}`)}),n.stderr?.on("data",e=>{h.error(`[ace-server] ${e.toString("utf8").trim()}`)}),n.stdin?.on("error",e=>{h.error(`[ace-server] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{h.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as $S from"fs";import*as oi from"path";import{spawn as $_}from"child_process";async function FS(n){In(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await F_(n),i=oi.join(t,"compile_commands.json");$S.existsSync(i)||h.warn(`compile_commands.json not found at ${i}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let o=H_(e,t,r);h.info("clangd started, bridging stdio (initialize is left to the client)"),B_(o),await Km(o.pid,Ym("--cpp",n))}async function F_(n){let e=await j_();e?.clangdPath||(h.error("clangd not found. Ensure DevEco Studio / CLT is installed."),process.exit(1));let t;if(n.projectPath)t=De(oi.resolve(n.projectPath)),h.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let c=ya(process.cwd());t=De(c??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=De(oi.resolve(process.cwd())),h.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,i=e.clangdPath,o=xn(t),s=oi.dirname(o),a=Ba(process.env.DEVECO_CLI_CPP_COMPILE_COMMANDS,t);return a&&(h.info(`Using custom compile_commands dir: ${a}`),s=a),h.info(`projectPath=${t}, sdkPath=${r}, clangdPath=${i}, compileCommandsDir=${s}`),{projectPath:t,clangdPath:i,compileCommandsDir:s}}async function j_(){try{return await P.new()}catch{let n=wh();if(!n)return null;try{return P.fromIDE(n)}catch{return null}}}function H_(n,e,t){let r=U_(e);return h.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),$_(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function U_(n){return[`--compile-commands-dir=${he(n)}`,"--log=info","--pch-storage=memory"]}function B_(n){n.on("error",e=>{h.error(`[clangd] spawn error: ${e.message}`),process.exit(1)}),n.stdout?.on("error",e=>{h.error(`[clangd] stdout error: ${e.message}`)}),n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("error",e=>{h.error(`[clangd] stderr error: ${e.message}`)}),n.stderr?.on("data",e=>{h.error(`[clangd] ${e.toString("utf8").trim()}`)}),n.stdin?.on("error",e=>{h.error(`[clangd] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{h.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function V_(){let n=process.env.PROJECT_PATH||"",e=process.env.NODE_MAX_OLD_SPACE_SIZE,t=process.env.DEBUG==="true"||process.env.DEBUG==="1",r=process.env.DEVECO_CLI_CPP_ENABLED!=="false"&&process.env.DEVECO_CLI_CPP_ENABLED!=="0",i=process.env.DEVECO_CLI_CPP_COMPILE_COMMANDS?.trim()||"",o=n,s=await P.new(),a=zm({projectPath:o,sdkPath:s.sdkPath,arktsLangServerPath:s.arktsLangServerPath??void 0,nodePath:s.nodePath,ohpmJsPath:s.ohpmJsPath,hvigorJsPath:s.hvigorJsPath,clangdPath:s.clangdPath??void 0,nodeMaxOldSpaceSize:e,debug:t,cppEnabled:r,cppCompileCommandsPath:i||void 0,telemetry:D}),c,l=new Promise(g=>{c=g}),d=async()=>{await a.shutdown(),c()};process.once("SIGINT",d),process.once("SIGTERM",d),process.platform==="win32"&&process.once("SIGBREAK",d);try{await a.start()}catch(g){console.error("Failed to start MCP server:",g instanceof Error?g.message:String(g)),process.exit(1)}await l}var Xm=new W_("serve").description("Host bundled auxiliary protocol servers");Xm.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await V_()});Xm.command("lsp").description("Start a bundled LSP language server").option("--arkts","Start the ArkTS language server (ace-server)").option("--cpp","Start the C/C++ language server (clangd)").option("--project-path <path>","project root path (used as-is, no search)").option("--auto-detect","When --project-path is not specified, search the current directory and its subdirectories for the project root (no upward search)").action(async n=>{n.arkts&&n.cpp&&(console.error("--arkts and --cpp are mutually exclusive. Specify only one."),process.exit(1)),n.arkts?await _S({projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await FS({projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var jS=Xm;import{Command as X_,InvalidArgumentError as WS}from"commander";import{red as Z_,dim as Q_}from"colorette";import{Command as G_}from"commander";import{cyan as ad,yellow as cd}from"colorette";import*as HS from"path";function q_(n){return cd(`If you want the latest docs(${n}), please update CLI first: run \`devecocli update\` to update`)}function z_(n){console.log(cd(`Latest docs v${n.version} (apiVersion ${n.apiVersion}) is incompatible with current CLI.`)),console.log(q_(n.version))}function J_(n,e,t){console.log(t?ad(`New docs version ${n} found (current v${e??"none"})`):ad(`Documentation is already up to date v${n}`))}async function Y_(n){let e=Tt();console.log(ad("Checking for documentation updates..."));let{latest:t,compatible:r}=await $i(e);if(!r){z_(t);return}let i=await _i(),o=!i||_r(r.version,i)>0;if(n.check){J_(r.version,i,o);return}if(!n.force&&!o){console.log(cd(`Docs is already up to date v${r.version}`));return}console.log(ad(`Downloading documentation package v${r.version}...`)),await Dc({version:r.version,apiVersion:r.apiVersion,dist:r.dist},HS.join(W(),"doc-data"),"docs-update"),console.log(cd(`Docs successfully upgrade to ${r.version}`))}var K_=new G_("update").description("Update documentation to the latest compatible version").option("--force","Force re-download even if up to date").option("--check","Check for updates without installing").action(async n=>{await Y_(n)}),US=K_;async function Zm(n,e){let t=Date.now();try{let r=await e();return await BS(n,Date.now()-t,!0,null),r}catch(r){let i=r instanceof Error?r.code??r.name:"UnknownError";throw await BS(n,Date.now()-t,!1,i),r}}async function BS(n,e,t,r){await D.track(n,{duration_ms:e,success:t,error_code:r}).catch(()=>{})}function e0(n){return n instanceof Error&&(n.name==="CacheDirError"||n.name==="DocPathSafetyError")}function Qm(n){console.error(Z_(t0(n))),process.exitCode=1}function t0(n){let e=n instanceof Error?n.message:String(n);return e0(n)?e:/\b(EACCES|EPERM|ENOSPC|ENOTDIR|ELOOP)\b/.test(e)?"Documentation data directory is unavailable. Check DEVECO_CLI_DATA_DIR and retry.":e}function VS(...n){return e=>{if(!n.includes(e))throw new WS(`Allowed values: ${n.join(", ")}`);return e}}function r0(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new WS("Must be a positive integer.");return e}var n0=VS("json","default"),i0=VS("json","default");function o0(n){let e=n.map(t=>t.trim()).filter(Boolean);if(e.length===0)throw new Error("Keywords cannot be empty.");return e}function s0(n){for(let e=0;e<n.length;e++){let t=n[e];console.log(t.documentId),console.log(` Title: ${t.title}`),t.snippet&&console.log(` Content: ${t.snippet}`),e<n.length-1&&console.log()}}var Ks=new X_("docs").description("HarmonyOS documentation commands (search, read, catalog, update)");Ks.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)","all").option("--format <fmt>","Output format (default, json)",n0,"default").option("--limit <n>","Max number of results",r0,10).action(async(n,e)=>{let t={event:v.DocOperation,subAction:"search",keywords:n,queryLen:n.join(" ").length,catalog:e.catalog??"all"};try{await Zm(t,async()=>{let r=o0(n),i=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await Cc(),s=o.CATALOG_NAMES;if(i&&s&&!s.includes(i))throw new Error(`Invalid catalog "${e.catalog}". Allowed: all, ${s.join(", ")}`);let a=await o.createDocsEngine({cacheDir:W()});try{let c=await a.search({keywords:r,catalog:i,limit:e.limit});e.format==="json"?console.log(JSON.stringify(c,null,2)):s0(c)}finally{await a.close()}})}catch(r){Qm(r)}});Ks.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{let e=n.trim(),t={event:v.DocOperation,subAction:"read",documentId:e};try{await Zm(t,async()=>{if(!e)throw new Error("Document ID cannot be empty.");let i=await(await Cc()).createDocsEngine({cacheDir:W()});try{let o=await i.read({relativePath:e});console.log(o)}finally{await i.close()}})}catch(r){Qm(r)}});Ks.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",i0,"default").action(async n=>{let e={event:v.DocOperation,subAction:"catalog",fmt:n.format??"default"};try{await Zm(e,async()=>{let r=await(await Cc()).createDocsEngine({cacheDir:W()});try{let i=await r.catalog();if(n.format==="json")console.log(JSON.stringify(i.map(o=>({name:o.nodeId,title:o.nodeName})),null,2));else for(let o of i)console.log(` ${o.nodeId.padEnd(20)} ${Q_(o.nodeName)}`)}finally{await r.close()}})}catch(t){Qm(t)}});Ks.addCommand(US);var GS=Ks;import{Command as X0}from"commander";import{Command as rf,InvalidArgumentError as ef,Option as Xs}from"commander";import nf from"ora";var zS=["Selector DSL (common cases):"," key=value exact text=Login"," key*=value contains text*=Log"," key^=value prefix text^=Log"," key$=value suffix text$=in"," key/=regex[/flags] regex search text/=^Login$ text/=login/i"," a,b AND text=Login,type=Button"," [n] nth match (at end) text=Login[0] [last]/[-1]"," keys: text key desc id type enabled focused checked selected visible clickable scrollable",' value with , [ ] or quotes -> quote it: text="a,b" text="a[b]"'," regex backslashes must be doubled",' xpath= prefix -> use xpath expression: xpath=//Button[@id="login"]'," base64= prefix -> base64-encoded selector for shell-safe special chars"," shell special chars -> wrap whole selector in quotes, or use base64= prefix"].join(`
1339
+ `);function a0(n){let e=parseInt(n,10);if(!Number.isInteger(e)||e<0||String(e)!==n.trim())throw new ef("depth must be a non-negative integer");return e}function tf(n){let e=Number(n);if(!Number.isFinite(e)||e<=0)throw new ef("timeout must be a positive number");if(e>36e4)throw new ef("timeout must not exceed 360000ms");return e}function JS(n){let e=[];(n.type||n.id)&&e.push(n.type?n.id?`${n.type}#${n.id}`:n.type:`#${n.id}`),e.push(n.bounds?`[${n.bounds.join(",")}]`:"[]"),n.text&&e.push(`"${JSON.stringify(n.text).slice(1,-1)}"`);let t=[];return n.clickable&&t.push("clickable"),n.longClickable&&t.push("longClickable"),n.scrollable&&t.push("scrollable"),n.checkable&&t.push("checkable"),t.length>0&&e.push(...t),e.join(" ")}function YS(n,e=0){let t=[],r=" ".repeat(e);for(let i of n)t.push(`${r}${JS(i)}`),i.children.length>0&&t.push(...YS(i.children,e+1).split(`
1378
1340
  `));return t.join(`
1379
- `)}function ax(r){if(r.allWindows&&r.window)throw new Error("--all-windows and --window are mutually exclusive.")}function cx(r,e){let t=Tn(r,e);if(t.length===0)throw new Error(`Node '${e}' not found.`);let n=t.map(o=>({...o,children:[]}));return JSON.stringify(n,null,2)}function lx(r,e){return e.id?cx(r,e.id):e.format==="json"?JSON.stringify(r,null,2):Mv(r)}async function dx(r){ax(r);let e=ox({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let o=await k.new(),i=await yt(o,r.device),s=new en(o.hdcPath);t=r.mode==="full"?await s.dumpFullTree(i,r.depth,r.window,r.allWindows):await s.dumpCollapsedTree(i,r.depth,r.window,r.allWindows)}catch(o){throw e.stop(),new Error(`Failed to dump layout: ${o.message}`,{cause:o})}e.stop();let n=lx(t,r);return console.log(n),Buffer.byteLength(n,"utf8")}function ux(r){return{event:S.CommandExecuted,args:["ui","layout",...r.device?["--device"]:[]],mode:r.mode,outputSize:0}}async function px(r){let e=ux(r),t=Date.now(),n=!0,o=null;try{e.outputSize=await dx(r)}catch(i){throw n=!1,o=q(i),i}finally{let i={duration_ms:Date.now()-t,success:n,error_code:o};await I.track(e,i)}}var _v=new rx("layout").description("Inspect on-screen node(s) for UI testing").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Layout node id").option("--window <windowId>","Target window id").option("--all-windows","Include all windows (mutually exclusive with --window)").addOption(new wu("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(ix).default(0)).addOption(new wu("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new wu("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async r=>{await px(r)});import{Command as mx,Option as fx}from"commander";import{yellow as hx}from"colorette";import gx from"ora";var yx=["Id","Name","Pid","DisplayId","Focused"];function vx(r,e){if(e==="json"){let n=r.map(o=>({id:o.id,name:o.name,pid:o.pid,displayId:o.displayId,focused:o.focused}));console.log(JSON.stringify(n,null,2));return}let t=r.map(n=>({cells:[String(n.id),n.name,String(n.pid),String(n.displayId),String(n.focused)],highlight:n.focused}));console.log(Ut(yx,t))}async function wx(r){let e=gx({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let n=await k.new(),o=await yt(n,r.device);t=await new $t(n.hdcPath,o).listWindows({all:r.all})}catch(n){throw e.stop(),new Error(`Failed to list windows: ${n.message}`,{cause:n})}if(e.stop(),t.length===0){console.log(hx(" No windows found."));return}vx(t,r.format)}function Sx(r){let e=[];return r.device&&e.push("--device"),r.format!=="default"&&e.push("--format"),r.all&&e.push("--all"),{event:S.CommandExecuted,args:["ui","window","list",...e]}}async function bx(r){let e=Sx(r),t=Date.now(),n=!0,o=null;try{await wx(r)}catch(i){throw n=!1,o=q(i),i}finally{let i={duration_ms:Date.now()-t,success:n,error_code:o};await I.track(e,i)}}var Su=new mx("window").description("Manage device windows");Su.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new fx("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async r=>{await bx(r)});import{Command as Ex}from"commander";import{green as Cx}from"colorette";function Px(r){return{event:S.CommandExecuted,args:["ui","screenshot",...r.device?["--device"]:[]]}}function Ax(r){let e=r.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}async function Ix(r){let e=Px(r),t=Date.now(),n=!0,o=null;try{if(r.device!==void 0&&!r.device.trim())throw new Error("--device must not be empty.");let i=r.display!==void 0?Ax(r.display):void 0,s=await k.new(),a=new tn(s),c=a.resolveDestinationPath(r.path),l=await yt(s,r.device);await a.captureToPath(l,c,i),console.log(Cx(`Screenshot saved to ${c}`))}catch(i){throw n=!1,o=q(i),i}finally{let i={duration_ms:Date.now()-t,success:n,error_code:o};await I.track(e,i)}}var Fv=new Ex("screenshot").description("Capture a screenshot of the device screen").option("--device <name|serial>","Target device name or serial; required when multiple devices are connected").option("--display <displayId>","Target display id; omit for default screen").option("--path <path>","Required directory or PNG file path; destination must be writable").action(Ix);import{Command as Lr}from"commander";function Nr(r,e){let t=[];return"device"in e&&e.device&&t.push("--device"),"id"in e&&e.id&&t.push("--id"),"window"in e&&e.window&&t.push("--window"),"speed"in e&&e.speed&&t.push("--speed"),{event:S.CommandExecuted,args:["ui",r,...t]}}function kx(r){let t=`"$(printf '%s' '${Buffer.from(r,"utf8").toString("base64")}' | base64 -d)"`;return m(`escapeShellText: ${r} -> ${t}`),t}async function Or(r,e,t,n){let o=new Qe;o.start(r);let i=Date.now(),s=!0,a=null;try{await n(o)}catch(c){throw o.stop(),s=!1,a=q(c),new Error(`${e}: ${c.message}`,{cause:c})}finally{let c={duration_ms:Date.now()-i,success:s,error_code:a};await I.track(t,c)}}async function Dx(r,e,t){let n=Nr("click",t);await Or("Executing click...","click failed",n,async o=>{Rn(r,e,t.id,t.window);let{hdcPath:i,deviceId:s}=await Lt(t.device),{x:a,y:c}=await xn(i,s,r!==void 0?Number(r):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await at(i,s,["uitest","uiInput","click",String(a),String(c)]),o.succeed(`click at (${a}, ${c})`)})}async function Tx(r,e,t){let n=Nr("doubleclick",t);await Or("Executing doubleclick...","doubleclick failed",n,async o=>{Rn(r,e,t.id,t.window);let{hdcPath:i,deviceId:s}=await Lt(t.device),{x:a,y:c}=await xn(i,s,r!==void 0?Number(r):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await at(i,s,["uitest","uiInput","doubleClick",String(a),String(c)]),o.succeed(`doubleclick at (${a}, ${c})`)})}async function Rx(r,e,t){let n=Nr("longclick",t);await Or("Executing longclick...","longclick failed",n,async o=>{Rn(r,e,t.id,t.window);let{hdcPath:i,deviceId:s}=await Lt(t.device),{x:a,y:c}=await xn(i,s,r!==void 0?Number(r):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await at(i,s,["uitest","uiInput","longClick",String(a),String(c)]),o.succeed(`longclick at (${a}, ${c})`)})}async function xx(r,e,t,n,o){let i=Nr("swipe",o);await Or("Executing swipe...","swipe failed",i,async s=>{Le(r,"x1"),Le(e,"y1"),Le(t,"x2"),Le(n,"y2");let a=$o(o.speed),{hdcPath:c,deviceId:l}=await Lt(o.device),d=["uitest","uiInput","swipe",r,e,t,n];a&&d.push(a),await at(c,l,d),s.succeed(`swipe from (${r}, ${e}) to (${t}, ${n})`)})}async function Lx(r,e,t,n,o){let i=Nr("fling",o);await Or("Executing fling...","fling failed",i,async s=>{Le(r,"x1"),Le(e,"y1"),Le(t,"x2"),Le(n,"y2");let a=$o(o.speed),{hdcPath:c,deviceId:l}=await Lt(o.device),d=["uitest","uiInput","fling",r,e,t,n];a&&d.push(a),await at(c,l,d),s.succeed(`fling from (${r}, ${e}) to (${t}, ${n})`)})}async function Nx(r,e,t,n,o){let i=Nr("drag",o);await Or("Executing drag...","drag failed",i,async s=>{Le(r,"x1"),Le(e,"y1"),Le(t,"x2"),Le(n,"y2");let a=$o(o.speed),{hdcPath:c,deviceId:l}=await Lt(o.device),d=["uitest","uiInput","drag",r,e,t,n];a&&d.push(a),await at(c,l,d),s.succeed(`drag from (${r}, ${e}) to (${t}, ${n})`)})}async function Ox(r,e){let t=Nr("dircfling",e);await Or("Executing dircfling...","dircfling failed",t,async n=>{let o=Os[r];if(o===void 0)throw new Error(`Invalid direction "${r}". Valid values: ${Object.keys(Os).join(", ")}`);let{hdcPath:i,deviceId:s}=await Lt(e.device);await at(i,s,["uitest","uiInput","dircFling",o]),n.succeed(`dircfling ${r}`)})}async function Mx(r,e,t,n){let o=Nr("text",n);await Or("Executing text input...","input failed",o,async i=>{Rn(e,t,n.id,n.window,!1),Ms(r,"text");let{hdcPath:s,deviceId:a}=await Lt(n.device),c=kx(r);if(e!==void 0)await at(s,a,[`uitest uiInput inputText ${e} ${t} ${c}`]),i.succeed(`input ${r} at (${e}, ${t})`);else if(n.id){let{x:l,y:d}=await xn(s,a,void 0,void 0,n.id,n.window);await at(s,a,[`uitest uiInput inputText ${l} ${d} ${c}`]),i.succeed(`input ${r} at (${l}, ${d})`)}else await at(s,a,[`uitest uiInput text ${c}`]),i.succeed(`input ${r}`)})}var jv=new Lr("click").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Tap at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(Dx),$v=new Lr("doubleclick").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Double-tap at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(Tx),Hv=new Lr("longclick").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Long-press at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(Rx),Bv=new Lr("swipe").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Swipe from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(xx),Uv=new Lr("fling").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Fling from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(Lx),Wv=new Lr("drag").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Drag from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(Nx),Vv=new Lr("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action(Ox),Gv=new Lr("text").argument("<text>","Text to input").argument("[x]","Optional X coordinate").argument("[y]","Optional Y coordinate").description("Input text at a target location or the currently focused field").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id to target before input (auto-resolves to center)").option("--window <windowId>","Target window id (used with --id)").action(Mx);var mt=new _x("ui").description("Inspect and interact with UI on a connected device");mt.addCommand(_v);mt.addCommand(Su);mt.addCommand(Fv);mt.addCommand(jv);mt.addCommand($v);mt.addCommand(Hv);mt.addCommand(Bv);mt.addCommand(Uv);mt.addCommand(Wv);mt.addCommand(Vv);mt.addCommand(Gv);var zv=mt;import{Command as kw,InvalidArgumentError as LN}from"commander";import{execa as sL}from"execa";import Mt from"fs";import*as Au from"os";import*as M from"path";var Fx=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),jx=/\r/g,$x=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,Hx=/^<+\s*/,Bx=/\s*>+$/,Ux=[/^The configuration file .+ is in use\.$/,/^The configuration file .+ in the project is in use\.$/,/^Currently active product: ?.+$/,/^Writing the result to .+\.$/,/^Write finished\.$/,/^CodeLinter found some defects in your code\.$/],Wx=new Set([1]);function Eu(r){if(!r)return"";let e=r.replace(Fx,"").replace(jx,`
1341
+ `)}function c0(n){if(n.allWindows&&n.window)throw new Error("--all-windows and --window are mutually exclusive.")}function l0(n,e){let t=Ri(n,e);if(t.length===0)throw new Error(`Node '${e}' not found.`);let r=t.map(i=>({...i,children:[]}));return JSON.stringify(r,null,2)}function d0(n,e){return e.id?l0(n,e.id):e.format==="json"?JSON.stringify(n,null,2):YS(n)}async function u0(n){c0(n);let e=nf({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let i=await P.new(),o=await T(i,n.device),s=new fr(i.hdcPath);t=n.mode==="full"?await s.dumpFullTree(o,n.depth,n.window,n.allWindows):await s.dumpCollapsedTree(o,n.depth,n.window,n.allWindows)}catch(i){throw e.stop(),new Error(`Failed to dump layout: ${i.message}`,{cause:i})}e.stop();let r=d0(t,n);return console.log(r),Buffer.byteLength(r,"utf8")}function p0(n){return{event:v.CommandExecuted,args:["ui","layout",...n.device?["--device"]:[]],mode:n.mode,outputSize:0}}async function m0(n){let e=p0(n),t=Date.now(),r=!0,i=null;try{e.outputSize=await u0(n)}catch(o){throw r=!1,i=X(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await D.track(e,o)}}var KS=new rf("layout").description("Inspect on-screen node(s) for UI testing").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Layout node id").option("--window <windowId>","Target window id").option("--all-windows","Include all windows (mutually exclusive with --window)").addOption(new Xs("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(a0).default(0)).addOption(new Xs("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new Xs("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async n=>{await m0(n)});function XS(n){let e={id:n.id,type:n.type,text:n.text,bounds:n.bounds,clickable:n.clickable==="true"||void 0,longClickable:n.longClickable==="true"||void 0,scrollable:n.scrollable==="true"||void 0,checkable:n.checkable==="true"||void 0,children:[]};return JS(e)}function qS(n){let e={};return n.id!==void 0&&(e.id=n.id),n.type!==void 0&&(e.type=n.type),n.text!==void 0&&(e.text=n.text),n.bounds!==void 0&&(e.bounds=n.bounds),n.clickable!==void 0&&(e.clickable=n.clickable==="true"),n.longClickable!==void 0&&(e.longClickable=n.longClickable==="true"),n.scrollable!==void 0&&(e.scrollable=n.scrollable==="true"),n.checkable!==void 0&&(e.checkable=n.checkable==="true"),n.checked!==void 0&&(e.checked=n.checked==="true"),e}function Zs(){for(let n of Lu())console.warn(n)}async function f0(n){if(!n.selector)throw new Error("Provide a selector expression.");let e=nf({text:"Finding element\u2026",color:"cyan"}).start(),t;try{let r=await P.new(),i=await T(r,n.device);t=await new xi(r.hdcPath).find(i,n.selector,{window:n.window,all:n.all,timeoutMs:n.timeout})}catch(r){throw e.stop(),Zs(),new Error(`Failed to find element: ${r.message}`,{cause:r})}if(e.stop(),Zs(),n.format==="json"){let r=n.all?t.map(i=>qS(i)):qS(t[0]);console.log(JSON.stringify(r,null,2))}else{let r=n.all===!0;for(let i of t){let o=XS(i);console.log(r?`#${i.index} ${o}`:o)}}}var ZS=new rf("find").description('Find on-screen element(s) by a selector (e.g. "text=Login,type=Button")').argument("[selector]","Selector DSL, xpath=, or base64= expression").option("--device <name|serial>","Target device (name or serial)").option("--window <windowId>","Target window id").option("--all","Print all matches instead of the first/indexed one").addOption(new Xs("--timeout <ms>","Max wait time in milliseconds for the element to appear").argParser(tf).default(3e3)).addOption(new Xs("--format <format>","Output format").choices(["default","json"]).default("default")).action(async(n,e)=>{await f0({...e,selector:n})}).addHelpText("after",zS);function h0(n){return XS(n)}async function g0(n){await new Promise(e=>setTimeout(e,n)),console.log(`Waited ${n}ms`)}async function y0(n,e,t,r,i){await n.waitForDisappear(e,t,r,i),console.log(`Element disappeared: ${t}`)}async function w0(n,e,t,r,i){let o=await n.waitForAppearance(e,t,r,i);console.log(h0(o))}async function v0(n,e){if(n.length===0)throw new Error("Usage: ui wait [timeoutMs] | ui wait <selector> [timeoutMs]");let t=n[0];if(/^\d+$/.test(t)){if(e.disappear)throw new Error("--disappear requires a selector.");let a=tf(t);Zs(),await g0(a);return}let i=t,o=n[1]?tf(n[1]):3e3,s=nf({text:"Waiting\u2026",color:"cyan"}).start();try{let a=await P.new(),c=await T(a,e.device),l=new xi(a.hdcPath);e.disappear?await y0(l,c,i,o,e.window):await w0(l,c,i,o,e.window),s.stop(),Zs()}catch(a){throw s.stop(),Zs(),new Error(`Failed to wait: ${a.message}`,{cause:a})}}var QS=new rf("wait").description("Wait: sleep [timeoutMs], or wait for element <selector> [timeoutMs] [--disappear]").argument("[args...]","Args: [timeoutMs] for sleep, or <selector> [timeoutMs] for element wait").option("--disappear","Wait for element to disappear (requires selector)").option("--device <name|serial>","Target device (name or serial)").option("--window <windowId>","Target window id").action(async(n,e)=>{await v0(n,e)}).addHelpText("after",zS);import{Command as b0,Option as S0}from"commander";import{yellow as E0}from"colorette";import P0 from"ora";var C0=["Id","Name","Pid","DisplayId","Focused"];function k0(n,e){if(e==="json"){let r=n.map(i=>({id:i.id,name:i.name,pid:i.pid,displayId:i.displayId,focused:i.focused}));console.log(JSON.stringify(r,null,2));return}let t=n.map(r=>({cells:[String(r.id),r.name,String(r.pid),String(r.displayId),String(r.focused)],highlight:r.focused}));console.log(Sr(C0,t))}async function R0(n){let e=P0({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let r=await P.new(),i=await T(r,n.device);t=await new mr(r.hdcPath,i).listWindows({all:n.all})}catch(r){throw e.stop(),new Error(`Failed to list windows: ${r.message}`,{cause:r})}if(e.stop(),t.length===0){console.log(E0(" No windows found."));return}k0(t,n.format)}function D0(n){let e=[];return n.device&&e.push("--device"),n.format!=="default"&&e.push("--format"),n.all&&e.push("--all"),{event:v.CommandExecuted,args:["ui","window","list",...e]}}async function x0(n){let e=D0(n),t=Date.now(),r=!0,i=null;try{await R0(n)}catch(o){throw r=!1,i=X(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await D.track(e,o)}}var of=new b0("window").description("Manage device windows");of.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new S0("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async n=>{await x0(n)});import{Command as A0}from"commander";import{green as I0}from"colorette";function T0(n){return{event:v.CommandExecuted,args:["ui","screenshot",...n.device?["--device"]:[]]}}function O0(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}async function M0(n){let e=T0(n),t=Date.now(),r=!0,i=null;try{if(n.device!==void 0&&!n.device.trim())throw new Error("--device must not be empty.");let o=n.display!==void 0?O0(n.display):void 0,s=await P.new(),a=new $n(s),c=a.resolveDestinationPath(n.path),l=await T(s,n.device);await a.captureToPath(l,c,o),console.log(I0(`Screenshot saved to ${c}`))}catch(o){throw r=!1,i=X(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await D.track(e,o)}}var eE=new A0("screenshot").description("Capture a screenshot of the device screen").option("--device <name|serial>","Target device name or serial; required when multiple devices are connected").option("--display <displayId>","Target display id; omit for default screen").option("--path <path>","Required directory or PNG file path; destination must be writable").action(M0);import{Command as ld,Option as N0}from"commander";import{green as sf,yellow as L0}from"colorette";import rE from"ora";var dd=["--device <name|serial>","Target physical device name or serial; required when multiple devices are connected"],nE=["--path <dir|file.mp4>","Required writable destination: existing directory or a new .mp4 file"];function ud(n){return new S("INVALID_ARGUMENT",n)}function tE(n){if(n!==void 0&&!n.trim())throw ud("--device must not be empty.")}function pd(n,e){let t=n.parent?.opts()?.device;if(tE(t),tE(e),t&&e&&t!==e)throw ud(`Conflicting --device values: ${JSON.stringify(t)} and ${JSON.stringify(e)}`);return e??t}function iE(n,e){if(n.parent?.opts()?.path!==void 0)throw ud(`--path is not valid for ui screenrecord ${e}.`)}function oE(n,e){let t=n.parent?.opts()?.path;if(t!==void 0&&e!==void 0&&t!==e)throw ud(`Conflicting --path values: ${JSON.stringify(t)} and ${JSON.stringify(e)}`);return e??t}function md(n,e){let t=n.parent?.opts();return e.filter(r=>r.value!==void 0||t?.[r.name.slice(2)]!==void 0).map(r=>r.name)}function _0(n,e){return n.getOptionValueSource(e)==="cli"}async function fd(n,e,t){let r={event:v.CommandExecuted,args:["ui","screenrecord",...n,...e]},i=Date.now(),o=!0,s=null;try{await t()}catch(a){throw o=!1,s=X(a),a}finally{let a={duration_ms:Date.now()-i,success:o,error_code:s};await D.track(r,a)}}function sE(n){if(n.kind==="saved"){console.log(sf(`Saved successfully to ${n.localPath}`));for(let e of n.warnings??[])console.error(L0(`Warning: ${e}`))}else n.kind==="external-stopped"&&console.log(sf("Recording stopped. View the file in the device gallery; this CLI cannot retrieve it."))}async function $0(n,e){let t=md(e,[{name:"--device",value:n.device},{name:"--path",value:n.path}]);await fd([],t,async()=>{let r=pd(e,n.device),i=oE(e,n.path),o=new Vr(await P.new()),s,a;try{a=await o.recordInteractively(r,i,{onStarted:()=>{console.log("Recording... press Ctrl+C to stop and save")},onStopRequested:()=>{s=rE({text:"Stopping and saving the recording\u2026",color:"cyan"}).start()}})}finally{s?.stop()}sE(a)})}async function F0(n,e){let t=md(e,[{name:"--device",value:n.device},{name:"--path",value:n.path}]);await fd(["start"],t,async()=>{let r=pd(e,n.device),i=oE(e,n.path);await new Vr(await P.new()).startDetached(r,i),console.log(sf("Recording started. Stop with devecocli ui screenrecord stop"))})}async function j0(n,e){let t=[...md(e,[{name:"--device",value:n.device}]),...n.force?["--force"]:[]];await fd(["stop"],t,async()=>{let r=pd(e,n.device);iE(e,"stop");let i=new Vr(await P.new()),o=rE({text:"Stopping recording\u2026",color:"cyan"}).start(),s;try{s=await i.stopRecording(r,n.force??!1)}finally{o.stop()}sE(s)})}var H0={recording:"Status: recording - a recording started by this CLI is in progress",busy:"Status: busy - a recording started outside this CLI is in progress",idle:"Status: idle - no recording is in progress"};async function U0(n,e){let t=[...md(e,[{name:"--device",value:n.device}]),..._0(e,"format")?["--format"]:[]];await fd(["status"],t,async()=>{let r=pd(e,n.device);iE(e,"status");let o=await new Vr(await P.new()).getRecordingStatus(r);if(n.format==="json"){console.log(JSON.stringify(o));return}console.log(H0[o.status]),o.status==="idle"&&o.note&&console.log(o.note)})}var Qs=new ld("screenrecord").description("Record the screen of a physical device to an MP4 file").option(...dd).option(...nE).action($0);Qs.addCommand(new ld("start").description("Start recording and return immediately (detached)").option(...dd).option(...nE).action(F0));Qs.addCommand(new ld("stop").description("Stop the current recording and save the file").option(...dd).option("--force","Stop a recording that was not started by this CLI (no download)").action(j0));Qs.addCommand(new ld("status").description("Show the recording status without changing it").option(...dd).addOption(new N0("--format <format>","Output format").choices(["table","json"]).default("table")).action(U0));import{Command as mn}from"commander";function fn(n,e){let t=[];return"device"in e&&e.device&&t.push("--device"),"id"in e&&e.id&&t.push("--id"),"window"in e&&e.window&&t.push("--window"),"speed"in e&&e.speed&&t.push("--speed"),{event:v.CommandExecuted,args:["ui",n,...t]}}function B0(n){let t=`"$(printf '%s' '${Buffer.from(n,"utf8").toString("base64")}' | base64 -d)"`;return m(`escapeShellText: ${n} -> ${t}`),t}async function hn(n,e,t,r){let i=new mt;i.start(n);let o=Date.now(),s=!0,a=null;try{await r(i)}catch(c){throw i.stop(),s=!1,a=X(c),new Error(`${e}: ${c.message}`,{cause:c})}finally{let c={duration_ms:Date.now()-o,success:s,error_code:a};await D.track(t,c)}}async function W0(n,e,t){let r=fn("click",t);await hn("Executing click...","click failed",r,async i=>{Ti(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await Xt(t.device),{x:a,y:c}=await Oi(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await vt(o,s,["uitest","uiInput","click",String(a),String(c)]),i.succeed(`click at (${a}, ${c})`)})}async function V0(n,e,t){let r=fn("doubleclick",t);await hn("Executing doubleclick...","doubleclick failed",r,async i=>{Ti(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await Xt(t.device),{x:a,y:c}=await Oi(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await vt(o,s,["uitest","uiInput","doubleClick",String(a),String(c)]),i.succeed(`doubleclick at (${a}, ${c})`)})}async function G0(n,e,t){let r=fn("longclick",t);await hn("Executing longclick...","longclick failed",r,async i=>{Ti(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await Xt(t.device),{x:a,y:c}=await Oi(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await vt(o,s,["uitest","uiInput","longClick",String(a),String(c)]),i.succeed(`longclick at (${a}, ${c})`)})}async function q0(n,e,t,r,i){let o=fn("swipe",i);await hn("Executing swipe...","swipe failed",o,async s=>{He(n,"x1"),He(e,"y1"),He(t,"x2"),He(r,"y2");let a=Yo(i.speed),{hdcPath:c,deviceId:l}=await Xt(i.device),d=["uitest","uiInput","swipe",n,e,t,r];a&&d.push(a),await vt(c,l,d),s.succeed(`swipe from (${n}, ${e}) to (${t}, ${r})`)})}async function z0(n,e,t,r,i){let o=fn("fling",i);await hn("Executing fling...","fling failed",o,async s=>{He(n,"x1"),He(e,"y1"),He(t,"x2"),He(r,"y2");let a=Yo(i.speed),{hdcPath:c,deviceId:l}=await Xt(i.device),d=["uitest","uiInput","fling",n,e,t,r];a&&d.push(a),await vt(c,l,d),s.succeed(`fling from (${n}, ${e}) to (${t}, ${r})`)})}async function J0(n,e,t,r,i){let o=fn("drag",i);await hn("Executing drag...","drag failed",o,async s=>{He(n,"x1"),He(e,"y1"),He(t,"x2"),He(r,"y2");let a=Yo(i.speed),{hdcPath:c,deviceId:l}=await Xt(i.device),d=["uitest","uiInput","drag",n,e,t,r];a&&d.push(a),await vt(c,l,d),s.succeed(`drag from (${n}, ${e}) to (${t}, ${r})`)})}async function Y0(n,e){let t=fn("dircfling",e);await hn("Executing dircfling...","dircfling failed",t,async r=>{let i=hc[n];if(i===void 0)throw new Error(`Invalid direction "${n}". Valid values: ${Object.keys(hc).join(", ")}`);let{hdcPath:o,deviceId:s}=await Xt(e.device);await vt(o,s,["uitest","uiInput","dircFling",i]),r.succeed(`dircfling ${n}`)})}async function K0(n,e,t,r){let i=fn("text",r);await hn("Executing text input...","input failed",i,async o=>{Ti(e,t,r.id,r.window,!1),gc(n,"text");let{hdcPath:s,deviceId:a}=await Xt(r.device),c=B0(n);if(e!==void 0)await vt(s,a,[`uitest uiInput inputText ${e} ${t} ${c}`]),o.succeed(`input ${n} at (${e}, ${t})`);else if(r.id){let{x:l,y:d}=await Oi(s,a,void 0,void 0,r.id,r.window);await vt(s,a,[`uitest uiInput inputText ${l} ${d} ${c}`]),o.succeed(`input ${n} at (${l}, ${d})`)}else await vt(s,a,[`uitest uiInput text ${c}`]),o.succeed(`input ${n}`)})}var aE=new mn("click").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Tap at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(W0),cE=new mn("doubleclick").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Double-tap at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(V0),lE=new mn("longclick").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Long-press at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(G0),dE=new mn("swipe").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Swipe from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(q0),uE=new mn("fling").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Fling from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(z0),pE=new mn("drag").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Drag from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(J0),mE=new mn("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action(Y0),fE=new mn("text").argument("<text>","Text to input").argument("[x]","Optional X coordinate").argument("[y]","Optional Y coordinate").description("Input text at a target location or the currently focused field").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id to target before input (auto-resolves to center)").option("--window <windowId>","Target window id (used with --id)").action(K0);var Je=new X0("ui").description("Inspect and interact with UI on a connected device");Je.addCommand(KS);Je.addCommand(ZS);Je.addCommand(QS);Je.addCommand(of);Je.addCommand(eE);Je.addCommand(Qs);Je.addCommand(aE);Je.addCommand(cE);Je.addCommand(lE);Je.addCommand(dE);Je.addCommand(uE);Je.addCommand(pE);Je.addCommand(mE);Je.addCommand(fE);var hE=Je;import{Command as KE,InvalidArgumentError as zF}from"commander";import{execa as S$}from"execa";import cr from"fs";import*as uf from"os";import*as U from"path";var Z0=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),Q0=/\r/g,e$=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,t$=/^<+\s*/,r$=/\s*>+$/,n$=[/^The configuration file .+ is in use\.$/,/^The configuration file .+ in the project is in use\.$/,/^Currently active product: ?.+$/,/^Writing the result to .+\.$/,/^Write finished\.$/,/^CodeLinter found some defects in your code\.$/],i$=new Set([1]);function cf(n){if(!n)return"";let e=n.replace(Z0,"").replace(Q0,`
1380
1342
  `).split(`
1381
- `).map(Vx).map(t=>t.trimEnd()).filter(t=>zx(t));return e.length>0?`${e.join(`
1343
+ `).map(o$).map(t=>t.trimEnd()).filter(t=>a$(t));return e.length>0?`${e.join(`
1382
1344
  `)}
1383
- `:""}function Vx(r){let e=r.trim();if(!e.startsWith("{"))return r;try{let t=JSON.parse(e);return typeof t.content!="string"||typeof t.messageType!="number"?r:Wx.has(t.messageType)?"":t.content}catch{return r}}var qv=50*1024*1024;function Xv(r){let e=Eu(r).trim();if(!e)return{jsonText:void 0,diagnostics:""};if(e.length>qv)return{jsonText:void 0,diagnostics:`${e.slice(0,1024)}
1384
- [output truncated: exceeded ${qv} bytes]
1385
- `};if(bu(e))return{jsonText:e,diagnostics:""};let t=e.split(`
1386
- `);if(t.length>1&&t.every(bu))return{jsonText:JSON.stringify(t.map(i=>JSON.parse(i))),diagnostics:""};let n=qx(e);if(!n)return{jsonText:void 0,diagnostics:`${e}
1387
- `};let o=[e.slice(0,n.start).trim(),e.slice(n.end).trim()].filter(Boolean).join(`
1388
- `);return{jsonText:e.slice(n.start,n.end),diagnostics:o?`${o}
1389
- `:""}}function Gx(r){return $x.test(r.trim())}function zx(r){let e=r.trim();return!!e&&!Gx(e)&&!Ux.some(t=>t.test(e))}function bu(r){try{return JSON.parse(r),!0}catch{return!1}}function qx(r){for(let e=0;e<r.length;e++){let t=r[e];if(t!=="["&&t!=="{")continue;let o=Jx(r,e,t,t==="["?"]":"}");if(o!==-1&&bu(r.slice(e,o+1)))return{start:e,end:o+1}}}function Jx(r,e,t,n){let o=0,i=!1,s=!1;for(let a=e;a<r.length;a++){let c=r[a];if(s){s=!1;continue}if(c==="\\"&&i){s=!0;continue}if(c==='"'){i=!i;continue}if(!i){if(c===t)o++;else if(c===n&&(o--,o===0))return a}}return-1}var Jv=["Error","Warning","Suggestion","Info","Off","Unknown"];function Zv(r){let e=Cu(r);return{issues:Zx(e),summary:Yx(r,e)}}function Yx(r,e){let t=eL(e);return{filesChecked:tL(r).size,issues:e.length,errors:t.get("Error")??0,warnings:t.get("Warning")??0,suggestions:t.get("Suggestion")??0}}function Cu(r,e=""){if(Array.isArray(r))return r.flatMap(i=>Cu(i,e));if(!Qv(r))return[];let t=Hi(r,["filePath","file","path"])??e,n=Kx(r,t);if(n.length>0)return n;let o=Xx(r,t);return o?[o]:[]}function Kx(r,e){let t=["messages","defects","issues","results","files"];for(let n of t){let o=r[n];if(Array.isArray(o)){let i=o.flatMap(s=>Cu(s,e));if(i.length>0)return i}}return[]}function Xx(r,e){let t=Hi(r,["message","description","desc","detail"])??"",n=iL(Hi(r,["rule","ruleId","ruleName"])),o=nL(r,["severity","level"]),i=Hi(r,["filePath","file","path"])??e;if(!(!t&&!n&&o==="Unknown"))return{file:i,line:Kv(r,["line","reportLine"]),column:Kv(r,["column","reportColumn"]),severity:o,rule:n,message:t}}function Zx(r){return[...r].sort((e,t)=>{let n=Yv(e.severity)-Yv(t.severity);return n===0?Qx(e,t):n})}function Qx(r,e){let t=r.file.localeCompare(e.file);if(t!==0)return t;let n=(r.line??Number.MAX_SAFE_INTEGER)-(e.line??Number.MAX_SAFE_INTEGER);return n!==0?n:(r.column??Number.MAX_SAFE_INTEGER)-(e.column??Number.MAX_SAFE_INTEGER)}function eL(r){let e=new Map;for(let t of r){let n=t.severity;e.set(n,(e.get(n)??0)+1)}return e}function tL(r){let e=new Set;return Pu(e,r,""),e}function Pu(r,e,t){if(Array.isArray(e)){for(let o of e)Pu(r,o,t);return}if(!Qv(e))return;let n=Hi(e,["filePath","file","path"])??t;n&&r.add(n),rL(r,e,n)}function rL(r,e,t){let n=["messages","defects","issues","results","files"];for(let o of n){let i=e[o];if(Array.isArray(i))for(let s of i)Pu(r,s,t)}}function nL(r,e){for(let t of e){let n=r[t];if(typeof n=="string"||typeof n=="number")return oL(n)}return"Unknown"}function oL(r){let e=String(r).normalize("NFKC").trim().toLowerCase();return e==="2"||e==="error"||e==="err"?"Error":e==="1"||e==="warn"||e==="warning"?"Warning":e==="3"||e==="suggest"||e==="suggestion"?"Suggestion":e==="info"||e==="information"?"Info":e==="0"||e==="off"?"Off":"Unknown"}function iL(r){let e=r?.normalize("NFKC").trim();if(e)return e.replace(Hx,"").replace(Bx,"").toLowerCase()}function Yv(r){let e=Jv.indexOf(r);return e===-1?Jv.length:e}function Hi(r,e){for(let t of e){let n=r[t];if(typeof n=="string")return n}}function Kv(r,e){for(let t of e){let n=r[t];if(typeof n=="number")return n}}function Qv(r){return typeof r=="object"&&r!==null}var Mr=class extends Error{code;constructor(e,t,n){super(t,n),this.name="ValidationError",this.code=e}},ew="deveco-codelinter-",tw=[".ets",".ts",".js"],Bi=class r{resolution;cwd;toolProvider;constructor(e,t){this.toolProvider=e,this.resolution=r.resolveWithToolProvider(e),this.cwd=t}get supportsReportOptions(){return!this.resolution.isLegacyStudioArgs}static resolveProjectRoot(e){try{return V.discover(e).rootDir}catch{return e}}async check(e){let t=Mt.mkdtempSync(M.join(Au.tmpdir(),ew)),n=M.join(t,"report.json");try{let o=r.resolveProjectRoot(this.cwd),i=this.resolveLintTarget(e.lintPath,o),s=this.resolveConfigPath(e.configPath,i),a=this.buildNativeArgs(e,i.path,s,n,t,i.projectRoot??o),c=await this.run(a),l=Xv(c.stdout),d=l.diagnostics+Eu(c.stderr);try{let g=this.readJsonReport(n,l.jsonText);return{exitCode:c.exitCode,diagnostics:d,report:Zv(g)}}catch(g){return{exitCode:c.exitCode,diagnostics:d,reportError:g}}}finally{this.removeTempDir(t)}}resolveLintTarget(e,t){let n=e?M.resolve(this.cwd,e):t,o=this.resolveRealPath(n,"Lint path"),i=Mt.statSync(o);if(!i.isFile()&&!i.isDirectory())throw new Mr("errorCode",`Lint path must be a file or directory: ${n}`);if(i.isFile()){let a=M.extname(o).toLowerCase();if(!tw.some(l=>l===a))throw new Error(`Unsupported lint file extension "${a||"<none>"}": ${o}. Supported extensions: ${tw.join(", ")}.`)}let s=this.discoverProjectRoot(o,i.isDirectory());if(e!==void 0&&s===void 0)throw new Mr("errorCode",`Lint path is not in a valid project directory (project-level build-profile.json5 not found or invalid): ${o}`);return{path:o,projectRoot:s}}resolveConfigPath(e,t){let n=e?M.resolve(this.cwd,e):M.join(t.projectRoot??this.cwd,"code-linter.json5"),o=this.resolveRealPath(n,"`--config-path`");if(!Mt.statSync(o).isFile())throw new Mr("errorCode",`--config-path must point to a file: ${n}`);if(t.projectRoot){let i=this.discoverProjectRoot(o,!1);if(i===void 0||M.relative(t.projectRoot,i)!=="")throw new Mr("errorCode",`\`--config-path\` must belong to the same project as the lint path. Lint project: ${t.projectRoot}; Config project: ${i??"not found"}.`)}return o}discoverProjectRoot(e,t){let n=t?e:M.dirname(e);try{return Mt.realpathSync(V.discover(n).rootDir)}catch{return}}resolveRealPath(e,t){try{return Mt.realpathSync(e)}catch(n){throw new Mr("errorCode",`${t} does not exist or cannot be resolved: ${e}`,{cause:n})}}buildNativeArgs(e,t,n,o,i,s){if(this.resolution.isLegacyStudioArgs)return this.buildLegacyNativeArgs(e,t,n,i,s);let a=["--config",n];return e.fix&&a.push("--fix"),e.incremental&&a.push("--incremental"),a.push("--product",e.product,"--format","json","--output",o,t),a}buildLegacyNativeArgs(e,t,n,o,i){let s=String(this.toolProvider.getMaxApiLevel()),a=this.toolProvider.getSdkPlatformVersion(),c=M.join(o,"check-paths.json");Mt.writeFileSync(c,JSON.stringify([t]),"utf8");let l=["--dir",c,"--isTooManyFiles","true","--config",n,"--product",e.product,"--sdkPath",this.toolProvider.sdkPath,"--sdkNumberVersion",s,"--sdkStringVersion",a,"--project",i,"--logPath",M.join(o,"codelinter.log"),"--workdir",M.dirname(this.toolProvider.codelinterPath),"--inIde","true"];return e.fix&&l.push("--fix","true"),e.incremental&&l.push("--incremental","true"),l}async run(e){let t=this.resolution.isLegacyStudioArgs?[this.resolution.argsPrefix[0],...e]:[...this.resolution.argsPrefix,...e],n=this.resolution.workingDirectory??this.cwd;this.prepareRuntimeDirectories(),m(`Executing: ${this.resolution.command} ${t.join(" ")}`),m(`[CodelinterAdapter] Working directory: ${n}`);let o=await sL(this.resolution.command,t,{cwd:n,env:this.resolution.env,stdout:"pipe",stderr:"pipe",reject:!1});return{exitCode:o.exitCode??1,stdout:o.stdout,stderr:o.stderr}}prepareRuntimeDirectories(){for(let e of this.resolution.runtimeDirectories??[])Mt.mkdirSync(e,{recursive:!0})}readJsonReport(e,t){let o=(Mt.existsSync(e)?Mt.readFileSync(e,"utf-8").trim():void 0)||t?.trim();if(!o)throw new Mr("errorCode","Native JSON report was not generated.");return JSON.parse(o)}removeTempDir(e){let t=M.resolve(e),n=M.resolve(Au.tmpdir());!(t.startsWith(`${n}${M.sep}`)||t===n)||!M.basename(t).startsWith(ew)||Mt.rmSync(t,{recursive:!0,force:!0})}static isModernStudioEntry(e){let t=["plugins","codelinter","run","index.js"],n=M.normalize(e).split(M.sep).slice(-t.length);return t.every((o,i)=>n[i]?.toLowerCase()===o)}static resolveWithToolProvider(e){let t=r.getSource(e),n=e.toolchainRoot,o=e.codelinterPath,i=e.sdkPath,s=r.getPathEntries(e,t),a=t==="ide"?"DevEco Studio":"DevEco Command Line Tools",c=t==="ide"&&!r.isModernStudioEntry(o),l={command:e.nodePath,argsPrefix:[o,i],env:{...process.env,PATH:[...s,process.env.PATH||""].join(M.delimiter),DEVECO_SDK_HOME:i},isLegacyStudioArgs:c};return t==="command-line-tools"&&(l.workingDirectory=n,l.runtimeDirectories=[r.getResultDirectory(o)]),m(`[CodelinterAdapter] Selected ${a} entry: ${o}`),l}static getPathEntries(e,t){let n=[M.dirname(e.nodePath)];return t==="ide"&&e.javaPath&&n.unshift(M.dirname(e.javaPath)),n}static getResultDirectory(e){return M.resolve(e,"..","linter","result")}static getSource(e){return e.sourceType==="studio"?"ide":"command-line-tools"}};import{red as uc,yellow as lw}from"colorette";import{Argument as yL,Command as vL,InvalidArgumentError as Fr}from"commander";import Wi from"fs";import*as ze from"path";import*as Ui from"path";var rw="n/a",nw=/\\/g,aL=/\|/g,cL=/\r?\n/g;function ow(r,e){if(r.issues.length===0)return`No defects found.
1390
- ${Iu(r.summary)}
1391
- `;let t=e===void 0?r.issues:r.issues.slice(0,e),n=[dL(t),Iu(r.summary)];return e!==void 0&&t.length<r.issues.length&&n.push(lL(r.issues.length,t.length)),`${n.join(`
1345
+ `:""}function o$(n){let e=n.trim();if(!e.startsWith("{"))return n;try{let t=JSON.parse(e);return typeof t.content!="string"||typeof t.messageType!="number"?n:i$.has(t.messageType)?"":t.content}catch{return n}}var gE=50*1024*1024;function bE(n){let e=cf(n).trim();if(!e)return{jsonText:void 0,diagnostics:""};if(e.length>gE)return{jsonText:void 0,diagnostics:`${e.slice(0,1024)}
1346
+ [output truncated: exceeded ${gE} bytes]
1347
+ `};if(af(e))return{jsonText:e,diagnostics:""};let t=e.split(`
1348
+ `);if(t.length>1&&t.every(af))return{jsonText:JSON.stringify(t.map(o=>JSON.parse(o))),diagnostics:""};let r=c$(e);if(!r)return{jsonText:void 0,diagnostics:`${e}
1349
+ `};let i=[e.slice(0,r.start).trim(),e.slice(r.end).trim()].filter(Boolean).join(`
1350
+ `);return{jsonText:e.slice(r.start,r.end),diagnostics:i?`${i}
1351
+ `:""}}function s$(n){return e$.test(n.trim())}function a$(n){let e=n.trim();return!!e&&!s$(e)&&!n$.some(t=>t.test(e))}function af(n){try{return JSON.parse(n),!0}catch{return!1}}function c$(n){for(let e=0;e<n.length;e++){let t=n[e];if(t!=="["&&t!=="{")continue;let i=l$(n,e,t,t==="["?"]":"}");if(i!==-1&&af(n.slice(e,i+1)))return{start:e,end:i+1}}}function l$(n,e,t,r){let i=0,o=!1,s=!1;for(let a=e;a<n.length;a++){let c=n[a];if(s){s=!1;continue}if(c==="\\"&&o){s=!0;continue}if(c==='"'){o=!o;continue}if(!o){if(c===t)i++;else if(c===r&&(i--,i===0))return a}}return-1}var yE=["Error","Warning","Suggestion","Info","Off","Unknown"];function SE(n){let e=lf(n);return{issues:m$(e),summary:d$(n,e)}}function d$(n,e){let t=h$(e);return{filesChecked:g$(n).size,issues:e.length,errors:t.get("Error")??0,warnings:t.get("Warning")??0,suggestions:t.get("Suggestion")??0}}function lf(n,e=""){if(Array.isArray(n))return n.flatMap(o=>lf(o,e));if(!EE(n))return[];let t=ea(n,["filePath","file","path"])??e,r=u$(n,t);if(r.length>0)return r;let i=p$(n,t);return i?[i]:[]}function u$(n,e){let t=["messages","defects","issues","results","files"];for(let r of t){let i=n[r];if(Array.isArray(i)){let o=i.flatMap(s=>lf(s,e));if(o.length>0)return o}}return[]}function p$(n,e){let t=ea(n,["message","description","desc","detail"])??"",r=b$(ea(n,["rule","ruleId","ruleName"])),i=w$(n,["severity","level"]),o=ea(n,["filePath","file","path"])??e;if(!(!t&&!r&&i==="Unknown"))return{file:o,line:vE(n,["line","reportLine"]),column:vE(n,["column","reportColumn"]),severity:i,rule:r,message:t}}function m$(n){return[...n].sort((e,t)=>{let r=wE(e.severity)-wE(t.severity);return r===0?f$(e,t):r})}function f$(n,e){let t=n.file.localeCompare(e.file);if(t!==0)return t;let r=(n.line??Number.MAX_SAFE_INTEGER)-(e.line??Number.MAX_SAFE_INTEGER);return r!==0?r:(n.column??Number.MAX_SAFE_INTEGER)-(e.column??Number.MAX_SAFE_INTEGER)}function h$(n){let e=new Map;for(let t of n){let r=t.severity;e.set(r,(e.get(r)??0)+1)}return e}function g$(n){let e=new Set;return df(e,n,""),e}function df(n,e,t){if(Array.isArray(e)){for(let i of e)df(n,i,t);return}if(!EE(e))return;let r=ea(e,["filePath","file","path"])??t;r&&n.add(r),y$(n,e,r)}function y$(n,e,t){let r=["messages","defects","issues","results","files"];for(let i of r){let o=e[i];if(Array.isArray(o))for(let s of o)df(n,s,t)}}function w$(n,e){for(let t of e){let r=n[t];if(typeof r=="string"||typeof r=="number")return v$(r)}return"Unknown"}function v$(n){let e=String(n).normalize("NFKC").trim().toLowerCase();return e==="2"||e==="error"||e==="err"?"Error":e==="1"||e==="warn"||e==="warning"?"Warning":e==="3"||e==="suggest"||e==="suggestion"?"Suggestion":e==="info"||e==="information"?"Info":e==="0"||e==="off"?"Off":"Unknown"}function b$(n){let e=n?.normalize("NFKC").trim();if(e)return e.replace(t$,"").replace(r$,"").toLowerCase()}function wE(n){let e=yE.indexOf(n);return e===-1?yE.length:e}function ea(n,e){for(let t of e){let r=n[t];if(typeof r=="string")return r}}function vE(n,e){for(let t of e){let r=n[t];if(typeof r=="number")return r}}function EE(n){return typeof n=="object"&&n!==null}var gn=class extends Error{code;constructor(e,t,r){super(t,r),this.name="ValidationError",this.code=e}},PE="deveco-codelinter-",CE=[".ets",".ts",".js"],ta=class n{resolution;cwd;toolProvider;constructor(e,t){this.toolProvider=e,this.resolution=n.resolveWithToolProvider(e),this.cwd=t}get supportsReportOptions(){return!this.resolution.isLegacyStudioArgs}static resolveProjectRoot(e){try{return B.discover(e).rootDir}catch{return e}}async check(e){let t=cr.mkdtempSync(U.join(uf.tmpdir(),PE)),r=U.join(t,"report.json");try{let i=n.resolveProjectRoot(this.cwd),o=this.resolveLintTarget(e.lintPath,i),s=this.resolveConfigPath(e.configPath,o),a=this.buildNativeArgs(e,o.path,s,r,t,o.projectRoot??i),c=await this.run(a),l=bE(c.stdout),d=l.diagnostics+cf(c.stderr);try{let g=this.readJsonReport(r,l.jsonText);return{exitCode:c.exitCode,diagnostics:d,report:SE(g)}}catch(g){return{exitCode:c.exitCode,diagnostics:d,reportError:g}}}finally{this.removeTempDir(t)}}resolveLintTarget(e,t){let r=e?U.resolve(this.cwd,e):t,i=this.resolveRealPath(r,"Lint path"),o=cr.statSync(i);if(!o.isFile()&&!o.isDirectory())throw new gn("errorCode",`Lint path must be a file or directory: ${r}`);if(o.isFile()){let a=U.extname(i).toLowerCase();if(!CE.some(l=>l===a))throw new Error(`Unsupported lint file extension "${a||"<none>"}": ${i}. Supported extensions: ${CE.join(", ")}.`)}let s=this.discoverProjectRoot(i,o.isDirectory());if(e!==void 0&&s===void 0)throw new gn("errorCode",`Lint path is not in a valid project directory (project-level build-profile.json5 not found or invalid): ${i}`);return{path:i,projectRoot:s}}resolveConfigPath(e,t){let r=e?U.resolve(this.cwd,e):U.join(t.projectRoot??this.cwd,"code-linter.json5"),i=this.resolveRealPath(r,"`--config-path`");if(!cr.statSync(i).isFile())throw new gn("errorCode",`--config-path must point to a file: ${r}`);if(t.projectRoot){let o=this.discoverProjectRoot(i,!1);if(o===void 0||U.relative(t.projectRoot,o)!=="")throw new gn("errorCode",`\`--config-path\` must belong to the same project as the lint path. Lint project: ${t.projectRoot}; Config project: ${o??"not found"}.`)}return i}discoverProjectRoot(e,t){let r=t?e:U.dirname(e);try{return cr.realpathSync(B.discover(r).rootDir)}catch{return}}resolveRealPath(e,t){try{return cr.realpathSync(e)}catch(r){throw new gn("errorCode",`${t} does not exist or cannot be resolved: ${e}`,{cause:r})}}buildNativeArgs(e,t,r,i,o,s){if(this.resolution.isLegacyStudioArgs)return this.buildLegacyNativeArgs(e,t,r,o,s);let a=["--config",r];return e.fix&&a.push("--fix"),e.incremental&&a.push("--incremental"),a.push("--product",e.product,"--format","json","--output",i,t),a}buildLegacyNativeArgs(e,t,r,i,o){let s=String(this.toolProvider.getMaxApiLevel()),a=this.toolProvider.getSdkPlatformVersion(),c=U.join(i,"check-paths.json");cr.writeFileSync(c,JSON.stringify([t]),"utf8");let l=["--dir",c,"--isTooManyFiles","true","--config",r,"--product",e.product,"--sdkPath",this.toolProvider.sdkPath,"--sdkNumberVersion",s,"--sdkStringVersion",a,"--project",o,"--logPath",U.join(i,"codelinter.log"),"--workdir",U.dirname(this.toolProvider.codelinterPath),"--inIde","true"];return e.fix&&l.push("--fix","true"),e.incremental&&l.push("--incremental","true"),l}async run(e){let t=this.resolution.isLegacyStudioArgs?[this.resolution.argsPrefix[0],...e]:[...this.resolution.argsPrefix,...e],r=this.resolution.workingDirectory??this.cwd;this.prepareRuntimeDirectories(),m(`Executing: ${this.resolution.command} ${t.join(" ")}`),m(`[CodelinterAdapter] Working directory: ${r}`);let i=await S$(this.resolution.command,t,{cwd:r,env:this.resolution.env,stdout:"pipe",stderr:"pipe",reject:!1});return{exitCode:i.exitCode??1,stdout:i.stdout,stderr:i.stderr}}prepareRuntimeDirectories(){for(let e of this.resolution.runtimeDirectories??[])cr.mkdirSync(e,{recursive:!0})}readJsonReport(e,t){let i=(cr.existsSync(e)?cr.readFileSync(e,"utf-8").trim():void 0)||t?.trim();if(!i)throw new gn("errorCode","Native JSON report was not generated.");return JSON.parse(i)}removeTempDir(e){let t=U.resolve(e),r=U.resolve(uf.tmpdir());!(t.startsWith(`${r}${U.sep}`)||t===r)||!U.basename(t).startsWith(PE)||cr.rmSync(t,{recursive:!0,force:!0})}static isModernStudioEntry(e){let t=["plugins","codelinter","run","index.js"],r=U.normalize(e).split(U.sep).slice(-t.length);return t.every((i,o)=>r[o]?.toLowerCase()===i)}static resolveWithToolProvider(e){let t=n.getSource(e),r=e.toolchainRoot,i=e.codelinterPath,o=e.sdkPath,s=n.getPathEntries(e,t),a=t==="ide"?"DevEco Studio":"DevEco Command Line Tools",c=t==="ide"&&!n.isModernStudioEntry(i),l={command:e.nodePath,argsPrefix:[i,o],env:{...process.env,PATH:[...s,process.env.PATH||""].join(U.delimiter),DEVECO_SDK_HOME:o},isLegacyStudioArgs:c};return t==="command-line-tools"&&(l.workingDirectory=r,l.runtimeDirectories=[n.getResultDirectory(i)]),m(`[CodelinterAdapter] Selected ${a} entry: ${i}`),l}static getPathEntries(e,t){let r=[U.dirname(e.nodePath)];return t==="ide"&&e.javaPath&&r.unshift(U.dirname(e.javaPath)),r}static getResultDirectory(e){return U.resolve(e,"..","linter","result")}static getSource(e){return e.sourceType==="studio"?"ide":"command-line-tools"}};import{red as gd,yellow as OE}from"colorette";import{Argument as O$,Command as M$,InvalidArgumentError as wn}from"commander";import na from"fs";import*as ot from"path";import*as ra from"path";var kE="n/a",RE=/\\/g,E$=/\|/g,P$=/\r?\n/g;function DE(n,e){if(n.issues.length===0)return`No defects found.
1352
+ ${pf(n.summary)}
1353
+ `;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[k$(t),pf(n.summary)];return e!==void 0&&t.length<n.issues.length&&r.push(C$(n.issues.length,t.length)),`${r.join(`
1392
1354
  `)}
1393
- `}function iw(r,e){return[Iu(r.summary),`Full report: ${ku(e)}`,""].join(`
1394
- `)}function sw(r){let e=["# CodeLinter report",""];return r.issues.length===0?e.push("No defects found.",""):e.push(...uL(r.issues),""),e.push("## Summary","",...mL(r.summary),""),e.join(`
1395
- `)}function aw(r){return`${JSON.stringify(r,null,2)}
1396
- `}function Iu(r){return`Summary: Issues: ${ft(r.issues)} | Errors: ${ft(r.errors)} | Warnings: ${ft(r.warnings)} | Suggestions: ${ft(r.suggestions)} | Files checked: ${ft(r.filesChecked)}`}function lL(r,e){return`Showing ${ft(e)} of ${ft(r)} issues. Use --output-path <path> to write all results.`}function dL(r){let e=["No","File","Line","Column","Severity","Rule","Message"],t=r.map((n,o)=>({cells:hL(n,o+1)}));return["CodeLinter report","",Ut(e,t)].join(`
1397
- `)}function uL(r){let e=["| No | File | Line | Column | Severity | Rule | Message |","| ---: | --- | ---: | ---: | --- | --- | --- |"];for(let[t,n]of r.entries())e.push(pL(n,t+1));return e}function pL(r,e){return`| ${[String(e),ku(_r(r.file)),dc(r.line),dc(r.column),_r(r.severity),_r(r.rule),_r(r.message)].map(fL).join(" | ")} |`}function mL(r){return[`- Issues: ${ft(r.issues)}`,`- Errors: ${ft(r.errors)}`,`- Warnings: ${ft(r.warnings)}`,`- Suggestions: ${ft(r.suggestions)}`,`- Files checked: ${ft(r.filesChecked)}`]}function fL(r){return r.replace(nw,"\\\\").replace(aL,"\\|").replace(cL,"<br>")}function hL(r,e){return[String(e),ku(_r(gL(r.file))),dc(r.line),dc(r.column),_r(r.severity),_r(r.rule),_r(r.message)]}function gL(r){if(!Ui.isAbsolute(r))return r;let e=Ui.relative(process.cwd(),r);return!e||e.startsWith("..")||Ui.isAbsolute(e)?r:e}function ku(r){return r.replace(nw,"/")}function _r(r){let e=r?.trim();return e||rw}function dc(r){return r===void 0?rw:String(r)}function ft(r){return r.toLocaleString("en-US")}var Du=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function wL(r){let e=r;return r instanceof Du?r.code:e.code??e.name??"UnknownError"}async function cw(r,e,t,n){let o=await $e(process.pid),i=o!==null?te(Number(o)*1024):"unknown",s={event:S.CheckCommand,args:n,mcpMemory:i,lspMemory:"unknown"},a={duration_ms:Date.now()-r,success:e,error_code:t};await I.track(s,a).catch(()=>{})}var SL=/^-?\d+$/;function Tu(){return new vL("lint").description("Run DevEco Code Linter checks for TS/ArkTS code").helpOption("-h, --help","display help for command").addArgument(new yL("[path]","File or directory to lint").argParser(AL)).option("--fix","Auto-fix fixable code issues").option("--incremental","Only check uncommitted files").option("--config-path <path>","Path to lint configuration file",EL).option("--product <product>","Product name defined in build-profile.json5",CL,"default").option("--format <format>","Report format (choices: default, json)",bL,"default").option("--output-path <path>","Complete report file or directory",PL).option("--limit <number>","Maximum terminal issues to display when --output-path is omitted",IL).action(kL)}function bL(r){if(r==="default"||r==="json")return r;throw new Fr("Invalid --format. Expected one of: default, json.")}function EL(r){Ru(r,"--config-path");let e=ze.extname(r).toLowerCase();if(e!==".json"&&e!==".json5")throw new Fr("`--config-path` must point to a .json or .json5 file.");return r}function CL(r){return dw(r,"product"),r}function PL(r){return Ru(r,"--output-path"),r}function AL(r){return Ru(r,"path"),r}function IL(r){if(dw(r,"limit"),!SL.test(r))throw new Fr("`--limit` must be a positive integer.");let e=Number.parseInt(r,10);if(e<=0||!Number.isSafeInteger(e))throw new Fr("`--limit` must be an integer greater than 0.");return e}function dw(r,e){if(r.trim().length===0||mw(r))throw new Fr(`Invalid --${e} value.`)}function Ru(r,e){let t=`\`${e}\``;if(r.length===0||mw(r))throw new Fr(`${t} must be a non-empty path without control characters.`)}async function kL(r,e,t){let n=Date.now(),o=["check","lint"];try{let i=process.cwd(),s=await k.new(),a=new Bi(s,i),c=RL(s,a,t,e),l=OL(c.outputPath,c.format,i);e.fix&&console.warn(lw("Running codelinter with --fix. Ensure your project source is trusted."));let d=await DL(a,r,e);$L(d.diagnostics),process.exitCode=LL(d,l,c.format,e.limit,i),await cw(n,!0,null,o)}catch(i){let s=wL(i);throw await cw(n,!1,s,o),i}}async function DL(r,e,t){return xL(r,{lintPath:e,configPath:t.configPath,product:t.product,fix:t.fix,incremental:t.incremental})}function TL(r){return[["format","--format"],["outputPath","--output-path"]].filter(([e])=>r.getOptionValueSource(e)==="cli").map(([,e])=>e)}function RL(r,e,t,n){let o=TL(t);if(o.length===0||e.supportsReportOptions)return n;let i=nr(r.toolchainRoot),s=o.length===1?"option":"options";return console.warn(lw(`Warning: The detected DevEco Studio version is: ${i??"unknown"}. The bundled legacy Code Linter does not support ${s}: ${o.join(", ")}. Action: ignore the unsupported ${s} and continue the lint check with default terminal output.`)),{format:o.includes("--format")?"default":n.format,outputPath:o.includes("--output-path")?void 0:n.outputPath}}async function xL(r,e){let t=new Qe;process.stderr.isTTY&&t.start("Checking code...");try{let n=await r.check(e);return t.stop(),n}catch(n){throw t.fail("Code check failed"),n}}function LL(r,e,t,n,o){if(!r.report)return console.error(uc("Failed to generate Code Linter report.")),console.error(uc(r.reportError?.message??"Native JSON report was not generated.")),r.exitCode===0?1:r.exitCode;try{if(e){NL(e,t,r.report);let i=pw(e,o);process.stdout.write(iw(r.report,i))}else process.stdout.write(ow(r.report,n));return r.exitCode}catch(i){return console.error(uc("Failed to generate Code Linter report.")),console.error(uc(i.message)),r.exitCode===0?1:r.exitCode}}function NL(r,e,t){Wi.mkdirSync(ze.dirname(r),{recursive:!0});let n=e==="json"?aw(t):sw(t);try{Wi.writeFileSync(r,n,{encoding:"utf-8",flag:"wx"})}catch(o){throw o.code==="EEXIST"?new Error(`Output file already exists: ${r}`,{cause:o}):o}}function OL(r,e,t){if(!r)return;let n=FL(r,t),o=_L(r,n),i=o?ze.join(n,jL(e)):n;if(o||ML(r,e),Wi.existsSync(i))throw new Fr(`Output file already exists: ${pw(i,t)}`);return i}function ML(r,e){let t=uw(e);if(ze.extname(r).toLowerCase()!==t)throw new Fr(`--output-path must use the ${t} extension for --format ${e}.`)}function _L(r,e){return Wi.existsSync(e)?Wi.statSync(e).isDirectory():r.endsWith("/")||r.endsWith("\\")||ze.extname(r)===""}function FL(r,e){return ze.resolve(e,r)}function jL(r){let e=new Date,t=[e.getFullYear(),e.getMonth()+1,e.getDate()].map((i,s)=>String(i).padStart(s===0?4:2,"0")).join(""),n=[e.getHours(),e.getMinutes(),e.getSeconds()].map(i=>String(i).padStart(2,"0")).join(""),o=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${n}-${o}${uw(r)}`}function uw(r){return r==="json"?".json":".md"}function pw(r,e){let t=ze.relative(e,r);return t&&!t.startsWith("..")&&!ze.isAbsolute(t)?t:r}function $L(r){r&&process.stderr.write(r)}function mw(r){for(let e of r){let t=e.charCodeAt(0);if(t<=31||t===127)return!0}return!1}import{execa as HL}from"execa";import er from"fs";import BL from"os";import*as z from"path";import{fileURLToPath as UL}from"url";var fw=z.join("resources","arkts-check.cjs"),Vi=class{toolProvider;cwd;constructor(e,t){this.toolProvider=e,this.cwd=t}async check(e){let t=this.resolveProjectRoot(e.projectRoot,e.files),n=this.resolveFiles(t,e.files),o=this.resolveScriptPath(),i=this.buildArgs(o,t,n,e.fix),s=this.buildEnv();m(`Executing: ${this.toolProvider.nodePath} ${i.join(" ")}`);let a=await HL(this.toolProvider.nodePath,i,{cwd:t,env:s,stdout:"pipe",stderr:"pipe",reject:!1});return this.parseResult(a.stdout,a.stderr,a.exitCode??1)}resolveProjectRoot(e,t){if(e){let o=z.resolve(this.cwd,e);if(!er.existsSync(o))throw new Error(`Project path not found: ${o}`);if(er.statSync(o).isFile()){let s=this.discoverRootFrom(z.dirname(o));if(s)return s;throw new Error(`--project path is a file, not a project root: ${o}
1398
- Could not find a project-level build-profile.json5 above it. Pass the project root directory instead.`)}if(this.discoverRootFrom(o)!==o)throw new Error(`Not a valid Harmony project root: ${o}
1399
- (project-level build-profile.json5 not found).`);return o}if(t&&t.length>0)for(let o of t){let i=z.isAbsolute(o)?o:z.resolve(this.cwd,o),s=this.discoverRootFrom(z.dirname(i));if(s)return s}let n=this.discoverRootFrom(this.cwd);if(n)return n;throw new Error("Not in a valid Harmony project directory (project-level build-profile.json5 not found). Run this command inside a project, or pass --project <path>.")}discoverRootFrom(e){try{return V.discover(e).rootDir}catch{return}}resolveFiles(e,t){if(t.length===0)return[];let n=t.map(a=>{if(z.isAbsolute(a))return a;let c=z.resolve(this.cwd,a);return er.existsSync(c)?c:z.resolve(e,a)}),o=n.filter(a=>!er.existsSync(a));if(o.length>0)throw new Error(`File(s) not found:
1400
- `+o.map(a=>` ${a}`).join(`
1401
- `));let i=n.filter(a=>{let c=z.relative(e,a);return c.startsWith("..")||z.isAbsolute(c)});if(i.length>0)throw new Error(`File(s) outside the project root ${e}:
1355
+ `}function xE(n,e){return[pf(n.summary),`Full report: ${mf(e)}`,""].join(`
1356
+ `)}function AE(n){let e=["# CodeLinter report",""];return n.issues.length===0?e.push("No defects found.",""):e.push(...R$(n.issues),""),e.push("## Summary","",...x$(n.summary),""),e.join(`
1357
+ `)}function IE(n){return`${JSON.stringify(n,null,2)}
1358
+ `}function pf(n){return`Summary: Issues: ${kt(n.issues)} | Errors: ${kt(n.errors)} | Warnings: ${kt(n.warnings)} | Suggestions: ${kt(n.suggestions)} | Files checked: ${kt(n.filesChecked)}`}function C$(n,e){return`Showing ${kt(e)} of ${kt(n)} issues. Use --output-path <path> to write all results.`}function k$(n){let e=["No","File","Line","Column","Severity","Rule","Message"],t=n.map((r,i)=>({cells:I$(r,i+1)}));return["CodeLinter report","",Sr(e,t)].join(`
1359
+ `)}function R$(n){let e=["| No | File | Line | Column | Severity | Rule | Message |","| ---: | --- | ---: | ---: | --- | --- | --- |"];for(let[t,r]of n.entries())e.push(D$(r,t+1));return e}function D$(n,e){return`| ${[String(e),mf(yn(n.file)),hd(n.line),hd(n.column),yn(n.severity),yn(n.rule),yn(n.message)].map(A$).join(" | ")} |`}function x$(n){return[`- Issues: ${kt(n.issues)}`,`- Errors: ${kt(n.errors)}`,`- Warnings: ${kt(n.warnings)}`,`- Suggestions: ${kt(n.suggestions)}`,`- Files checked: ${kt(n.filesChecked)}`]}function A$(n){return n.replace(RE,"\\\\").replace(E$,"\\|").replace(P$,"<br>")}function I$(n,e){return[String(e),mf(yn(T$(n.file))),hd(n.line),hd(n.column),yn(n.severity),yn(n.rule),yn(n.message)]}function T$(n){if(!ra.isAbsolute(n))return n;let e=ra.relative(process.cwd(),n);return!e||e.startsWith("..")||ra.isAbsolute(e)?n:e}function mf(n){return n.replace(RE,"/")}function yn(n){let e=n?.trim();return e||kE}function hd(n){return n===void 0?kE:String(n)}function kt(n){return n.toLocaleString("en-US")}var ff=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function N$(n){let e=n;return n instanceof ff?n.code:e.code??e.name??"UnknownError"}async function TE(n,e,t,r){let i=await lt(process.pid),o=i!==null?ce(Number(i)*1024):"unknown",s={event:v.CheckCommand,args:r,mcpMemory:o,lspMemory:"unknown"},a={duration_ms:Date.now()-n,success:e,error_code:t};await D.track(s,a).catch(()=>{})}var L$=/^-?\d+$/;function hf(){return new M$("lint").description("Run DevEco Code Linter checks for TS/ArkTS code").helpOption("-h, --help","display help for command").addArgument(new O$("[path]","File or directory to lint").argParser(H$)).option("--fix","Auto-fix fixable code issues").option("--incremental","Only check uncommitted files").option("--config-path <path>","Path to lint configuration file",$$).option("--product <product>","Product name defined in build-profile.json5",F$,"default").option("--format <format>","Report format (choices: default, json)",_$,"default").option("--output-path <path>","Complete report file or directory",j$).option("--limit <number>","Maximum terminal issues to display when --output-path is omitted",U$).action(B$)}function _$(n){if(n==="default"||n==="json")return n;throw new wn("Invalid --format. Expected one of: default, json.")}function $$(n){gf(n,"--config-path");let e=ot.extname(n).toLowerCase();if(e!==".json"&&e!==".json5")throw new wn("`--config-path` must point to a .json or .json5 file.");return n}function F$(n){return ME(n,"product"),n}function j$(n){return gf(n,"--output-path"),n}function H$(n){return gf(n,"path"),n}function U$(n){if(ME(n,"limit"),!L$.test(n))throw new wn("`--limit` must be a positive integer.");let e=Number.parseInt(n,10);if(e<=0||!Number.isSafeInteger(e))throw new wn("`--limit` must be an integer greater than 0.");return e}function ME(n,e){if(n.trim().length===0||_E(n))throw new wn(`Invalid --${e} value.`)}function gf(n,e){let t=`\`${e}\``;if(n.length===0||_E(n))throw new wn(`${t} must be a non-empty path without control characters.`)}async function B$(n,e,t){let r=Date.now(),i=["check","lint"];try{let o=process.cwd(),s=await P.new(),a=new ta(s,o),c=G$(s,a,t,e),l=Y$(c.outputPath,c.format,o);e.fix&&console.warn(OE("Running codelinter with --fix. Ensure your project source is trusted."));let d=await W$(a,n,e);eF(d.diagnostics),process.exitCode=z$(d,l,c.format,e.limit,o),await TE(r,!0,null,i)}catch(o){let s=N$(o);throw await TE(r,!1,s,i),o}}async function W$(n,e,t){return q$(n,{lintPath:e,configPath:t.configPath,product:t.product,fix:t.fix,incremental:t.incremental})}function V$(n){return[["format","--format"],["outputPath","--output-path"]].filter(([e])=>n.getOptionValueSource(e)==="cli").map(([,e])=>e)}function G$(n,e,t,r){let i=V$(t);if(i.length===0||e.supportsReportOptions)return r;let o=$r(n.toolchainRoot),s=i.length===1?"option":"options";return console.warn(OE(`Warning: The detected DevEco Studio version is: ${o??"unknown"}. The bundled legacy Code Linter does not support ${s}: ${i.join(", ")}. Action: ignore the unsupported ${s} and continue the lint check with default terminal output.`)),{format:i.includes("--format")?"default":r.format,outputPath:i.includes("--output-path")?void 0:r.outputPath}}async function q$(n,e){let t=new mt;process.stderr.isTTY&&t.start("Checking code...");try{let r=await n.check(e);return t.stop(),r}catch(r){throw t.fail("Code check failed"),r}}function z$(n,e,t,r,i){if(!n.report)return console.error(gd("Failed to generate Code Linter report.")),console.error(gd(n.reportError?.message??"Native JSON report was not generated.")),n.exitCode===0?1:n.exitCode;try{if(e){J$(e,t,n.report);let o=LE(e,i);process.stdout.write(xE(n.report,o))}else process.stdout.write(DE(n.report,r));return n.exitCode}catch(o){return console.error(gd("Failed to generate Code Linter report.")),console.error(gd(o.message)),n.exitCode===0?1:n.exitCode}}function J$(n,e,t){na.mkdirSync(ot.dirname(n),{recursive:!0});let r=e==="json"?IE(t):AE(t);try{na.writeFileSync(n,r,{encoding:"utf-8",flag:"wx"})}catch(i){throw i.code==="EEXIST"?new Error(`Output file already exists: ${n}`,{cause:i}):i}}function Y$(n,e,t){if(!n)return;let r=Z$(n,t),i=X$(n,r),o=i?ot.join(r,Q$(e)):r;if(i||K$(n,e),na.existsSync(o))throw new wn(`Output file already exists: ${LE(o,t)}`);return o}function K$(n,e){let t=NE(e);if(ot.extname(n).toLowerCase()!==t)throw new wn(`--output-path must use the ${t} extension for --format ${e}.`)}function X$(n,e){return na.existsSync(e)?na.statSync(e).isDirectory():n.endsWith("/")||n.endsWith("\\")||ot.extname(n)===""}function Z$(n,e){return ot.resolve(e,n)}function Q$(n){let e=new Date,t=[e.getFullYear(),e.getMonth()+1,e.getDate()].map((o,s)=>String(o).padStart(s===0?4:2,"0")).join(""),r=[e.getHours(),e.getMinutes(),e.getSeconds()].map(o=>String(o).padStart(2,"0")).join(""),i=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${r}-${i}${NE(n)}`}function NE(n){return n==="json"?".json":".md"}function LE(n,e){let t=ot.relative(e,n);return t&&!t.startsWith("..")&&!ot.isAbsolute(t)?t:n}function eF(n){n&&process.stderr.write(n)}function _E(n){for(let e of n){let t=e.charCodeAt(0);if(t<=31||t===127)return!0}return!1}import{execa as tF}from"execa";import Mr from"fs";import rF from"os";import*as te from"path";import{fileURLToPath as nF}from"url";var $E=te.join("resources","arkts-check.cjs"),ia=class{toolProvider;cwd;constructor(e,t){this.toolProvider=e,this.cwd=t}async check(e){let t=this.resolveProjectRoot(e.projectRoot,e.files),r=this.resolveFiles(t,e.files),i=this.resolveScriptPath(),o=this.buildArgs(i,t,r,e.fix),s=this.buildEnv();m(`Executing: ${this.toolProvider.nodePath} ${o.join(" ")}`);let a=await tF(this.toolProvider.nodePath,o,{cwd:t,env:s,stdout:"pipe",stderr:"pipe",reject:!1});return this.parseResult(a.stdout,a.stderr,a.exitCode??1)}resolveProjectRoot(e,t){if(e){let i=te.resolve(this.cwd,e);if(!Mr.existsSync(i))throw new Error(`Project path not found: ${i}`);if(Mr.statSync(i).isFile()){let s=this.discoverRootFrom(te.dirname(i));if(s)return s;throw new Error(`--project path is a file, not a project root: ${i}
1360
+ Could not find a project-level build-profile.json5 above it. Pass the project root directory instead.`)}if(this.discoverRootFrom(i)!==i)throw new Error(`Not a valid Harmony project root: ${i}
1361
+ (project-level build-profile.json5 not found).`);return i}if(t&&t.length>0)for(let i of t){let o=te.isAbsolute(i)?i:te.resolve(this.cwd,i),s=this.discoverRootFrom(te.dirname(o));if(s)return s}let r=this.discoverRootFrom(this.cwd);if(r)return r;throw new Error("Not in a valid Harmony project directory (project-level build-profile.json5 not found). Run this command inside a project, or pass --project <path>.")}discoverRootFrom(e){try{return B.discover(e).rootDir}catch{return}}resolveFiles(e,t){if(t.length===0)return[];let r=t.map(a=>{if(te.isAbsolute(a))return a;let c=te.resolve(this.cwd,a);return Mr.existsSync(c)?c:te.resolve(e,a)}),i=r.filter(a=>!Mr.existsSync(a));if(i.length>0)throw new Error(`File(s) not found:
1402
1362
  `+i.map(a=>` ${a}`).join(`
1403
- `));let s=n.filter(a=>er.statSync(a).isFile()&&a.endsWith(".ets")&&!a.endsWith(".d.ets"));if(s.length===0)throw new Error(`No .ets files found in the given file(s):
1404
- `+n.map(a=>` ${a}`).join(`
1405
- `));return s}buildArgs(e,t,n,o){let i=[e,"--project",t];return i.push(o?"--fix":"--no-fix"),n.length>0&&i.push("--files",...n),i}buildEnv(){return{...process.env,DEVECO_HOME:this.resolveDevecoHome()}}resolveDevecoHome(){let e=this.toolProvider.toolchainRoot;if(BL.platform()==="darwin"&&!er.existsSync(z.join(e,"sdk"))){let t=z.join(e,"Contents");if(er.existsSync(z.join(t,"sdk")))return t}return e}parseResult(e,t,n){let o=e.trim();if(!o){let i=t.trim();throw new Error(`arkts-check exited with code ${n} but produced no output`+(i?`: ${i}`:""))}try{let i=JSON.parse(o);return{success:i.success??!1,error:i.error,errors:i.errors??[],fixed:i.fixed??[],alsoModified:i.alsoModified??[],summary:{errorCount:i.summary?.errorCount??0,warnCount:i.summary?.warnCount??0,fixedCount:i.summary?.fixedCount??0,checkerDiagCount:i.summary?.checkerDiagCount,fileCount:i.summary?.fileCount??0}}}catch(i){throw new Error(`Failed to parse arkts-check output: ${o.slice(0,500)}`,{cause:i})}}resolveScriptPath(){let e=UL(import.meta.url),t=z.dirname(e);if(e.includes("dist")){let s=z.dirname(t),a=z.join(s,"src",fw);if(er.existsSync(a))return a}let n=z.dirname(t),o=z.dirname(n),i=z.join(o,"src",fw);if(er.existsSync(i))return i;throw new Error("arkts-check.cjs not found in deveco-cli package resources. Reinstall deveco-cli.")}};import{red as Lu,yellow as Nu,green as hw}from"colorette";import{Command as WL}from"commander";function VL(r){let e=r;return e.code??e.name??"UnknownError"}async function xu(r,e,t,n){let o=await $e(process.pid),i=o!==null?te(Number(o)*1024):"unknown",s={event:S.CheckCommand,args:n,mcpMemory:i,lspMemory:"unknown"},a={duration_ms:Date.now()-r,success:e,error_code:t};await I.track(s,a).catch(()=>{})}function Ou(){return new WL("arkts").description("Run ArkTS static checks on .ets source files").arguments("[files...]").option("--fix","Auto-fix high-confidence errors before reporting").option("--project <path>","Project root directory (default: auto-detected from cwd)").action(async(r,e)=>{await GL(r,e)})}async function GL(r,e){let t=Date.now(),n=["check","arkts"];try{let o=await k.new(),i=new Vi(o,process.cwd()),s=new Qe;process.stderr.isTTY&&s.start("Checking ArkTS...");let a;try{a=await i.check({files:r,fix:e.fix,projectRoot:e.project})}catch(c){throw s.fail("ArkTS check failed"),c}if(a.error&&a.errors.length===0){s.fail("ArkTS check failed"),console.error(Lu(a.error)),process.exitCode=1,await xu(t,!1,"CheckFailed",n);return}s.stop(),zL(a),await xu(t,!0,null,n)}catch(o){throw await xu(t,!1,VL(o),n),o}}function zL(r){let{errorCount:e,warnCount:t,fixedCount:n,fileCount:o}=r.summary;if(qL(r.fixed,n,r.alsoModified),e===0){console.log(hw(`No errors found in ${o} file(s).`)),gw(r.errors);return}JL(r.errors,e,t),process.exitCode=1}function qL(r,e,t){if(r.length!==0){console.log(hw(`\u2713 Auto-fixed ${e} issue(s):`));for(let n of r)console.log(` ${n.file}:${n.line}:${n.column} - ${n.message}`);if(t.length>0){console.log(Nu(`Note: auto-fix also modified ${t.length} file(s) outside the checked list (added missing 'export'):`));for(let n of t)console.log(` ${n}`)}console.log()}}function JL(r,e,t){let n=r.filter(o=>o.severity==="error");console.error(Lu(`ArkTS check found ${e} error(s):`));for(let o of n){let i=o.rule?` (${o.rule})`:"";console.error(Lu(`${o.file}:${o.line}:${o.column} - ${o.severity}: ${o.message}${i}`))}gw(r,t)}function gw(r,e){let t=r.filter(o=>o.severity!=="error");if(t.length===0)return;let n=e??t.length;console.warn(Nu(`
1406
- Warnings (${n}):`));for(let o of t){let i=o.rule?` (${o.rule})`:"";console.warn(Nu(`${o.file}:${o.line}:${o.column} - ${o.severity}: ${o.message}${i}`))}}import{InvalidArgumentError as YL}from"commander";import*as K from"path";import*as Mu from"os";import{readdirSync as KL,existsSync as pc,readFileSync as XL,unlinkSync as ZL,copyFileSync as Sw,writeFileSync as bw}from"fs";import{execa as QL}from"execa";import{cyan as Se,yellow as Ew}from"colorette";import eN from"ora";var se=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function _u(r){let e=r;return r instanceof se?r.code:e.code??e.name??"UnknownError"}async function vo(r,e,t,n){let o=await $e(process.pid),i=o!==null?te(Number(o)*1024):"unknown",s={event:S.CheckCommand,args:n,mcpMemory:i,lspMemory:"unknown"},a={duration_ms:Date.now()-r,success:e,error_code:t};await I.track(s,a).catch(()=>{})}var tN=["default","csv","json"],yw=["default","json"];function rN(r){return[...r].sort((e,t)=>{let n=vw(e),o=vw(t);return n.apiVersion-o.apiVersion||n.suffix.localeCompare(o.suffix)})}function vw(r){let e=r.match(/\((\d+)\)/),t=e?Number(e[1]):0,n=r.lastIndexOf("_"),o=n>=0?r.slice(n+1):r;return{apiVersion:t,suffix:o}}function Cw(r){let t=KL(r,{withFileTypes:!0}).filter(n=>n.isFile()&&n.name.toLowerCase().endsWith(".json")).map(n=>n.name.slice(0,-5));return rN(t)}async function Pw(r){if(r=r===void 0?"default":r,!yw.includes(r))throw new Error(`--format must be ${yw.join(" or ")}. got "${r}"`);let e=Date.now(),t=["check","compat","versions"];try{let n=await k.new(),{apiChangeDir:o}=n.getApiscanPaths();m(Se(`[compat:versions] apiChangeDir: "${o}"`));let i=Cw(o);if(r==="json")console.log(JSON.stringify({versions:i,count:i.length},null,2));else{if(i.length===0){console.log("No SDK versions available."),await vo(e,!0,null,t);return}console.log(i.join(`
1407
- `))}await vo(e,!0,null,t)}catch(n){let o=_u(n);throw await vo(e,!1,o,t),n}}var ww=new Set([".ets",".c",".cpp"]);function nN(r,e){let t=new Set(r.profile.modules.map(s=>s.name)),n=e.filter(s=>!t.has(s));if(n.length===0)return;let o=r.profile.modules.map(s=>s.name).join(", "),i=n.length>1?"are":"is";throw new se("errorCode",`Module ${n.map(s=>`"${s}"`).join(", ")} ${i} not defined in build-profile.json5. Available modules: ${o}.`)}function oN(r){for(let e of r){let t=K.resolve(e);if(!pc(t))throw new se("errorCode",`File "${e}" does not exist.`);let n=K.extname(t).toLowerCase();if(!ww.has(n)){let o=Array.from(ww).join(", ");throw new se("errorCode",`Unsupported file extension "${n}" for "${e}". Supported: ${o}.`)}}}function iN(r){let e=[],t=[];for(let n of r)K.extname(n).toLowerCase()===".ets"?e.push(n):t.push(n);return{arkTs:e,cpp:t}}function sN(r){let e=[],t=[],n="",o=!1,i=0;for(;i<r.length;){let s=r[i];o?{field:n,inQuotes:o,i}=aN(r,i,s,n,o):s==='"'?(o=!0,i+=1):s===","?(t.push(n),n="",i+=1):s===`
1408
- `?(t.push(n),e.push(t),t=[],n="",i+=1):(s==="\r"||(n+=s),i+=1)}return(n.length>0||t.length>0)&&(t.push(n),e.push(t)),e}function aN(r,e,t,n,o){return t!=='"'?{field:n+t,inQuotes:o,i:e+1}:r[e+1]==='"'?{field:n+'"',inQuotes:o,i:e+2}:{field:n,inQuotes:!1,i:e+1}}function cN(r,e){return e.map(t=>{let n=o=>{let i=r.indexOf(o);return i>=0&&i<t.length?t[i]:""};return{apiDefinition:n("Api Definition"),language:n("Language"),changeId:n("ChangeId"),changedInSdk:n("Changed in SDK"),affectedVersions:n("Affected Versions"),title:n("Title"),codeLocation:n("Code Location"),changeType:n("Change Type")}})}function lN(r){let e=XL(r,"utf8"),t=e.startsWith("\uFEFF")?e.slice(1):e,n=sN(t);if(n.length<2)return[];let[o,...i]=n;return cN(o,i)}function dN(r,e){let t=r.match(/CSV saved to:\s*([^\r\n]+\.csv)/);if(!t)return null;let n=t[1].trim();if(K.isAbsolute(n))return n;let o=K.join(e,n);return E.ensurePathWithinRoot(e,o)}function uN(r,e){let t=new Map;for(let i of r){let s=i.changeType||"(unknown)";t.set(s,(t.get(s)??0)+1)}let n=Array.from(t.entries()).sort((i,s)=>s[1]-i[1]||i[0].localeCompare(s[0])),o=Math.max(5,...n.map(([i])=>i.length));console.log(Se("API change scan summary:")),console.log(` ${"Total".padEnd(o)} ${r.length}`);for(let[i,s]of n)console.log(` ${i.padEnd(o)} ${s}`);e&&console.log(` ${"Report".padEnd(o)} ${e}`)}function pN(r,e){if(console.log(),r.length===0){console.log("No API changes detected.");return}let t=r.slice(0,e),n=r.length-t.length;console.log(Se(`Details (showing ${t.length}${n>0?` of ${r.length}`:""}):`));let o=[["Title","title"],["Language","language"],["ChangeId","changeId"],["Changed in","changedInSdk"],["Affected Versions","affectedVersions"],["Code Location","codeLocation"]],i=Math.max(...o.map(([a])=>a.length)),s=a=>a||"<unknown>";for(let a of t){console.log(` [${s(a.changeType)}] ${s(a.apiDefinition)}`);for(let[c,l]of o)console.log(` ${c.padEnd(i)} ${s(a[l])}`)}n>0&&console.log(Ew(` ... and ${n} more. you can re-run with --output-path <dir> to save the full report.`))}function mN(r,e){let t=r.slice(0,e),n=r.length-t.length;console.log(),console.log(JSON.stringify({records:t,count:r.length},null,2)),n>0&&console.log(Ew(`... and ${n} more. you can re-run with --output-path <dir> to save the full report.`))}function fN(r,e){let t=[];for(let n of e){let o=r.profile.modules.find(i=>i.name===n);if(!o)throw new se("errorCode",`Module "${n}" not found in build-profile.json5.`);t.push(K.resolve(r.rootDir,o.srcPath))}return t}function hN(r,e,t,n){if(!n.sourceVersion||!n.targetVersion)throw new se("errorCode","source-version and target-version are required.");let o=[r,"--startVersion",n.sourceVersion,"--endVersion",n.targetVersion];if(e.length>0){let{arkTs:i,cpp:s}=iN(e),a=d=>K.resolve(process.cwd(),d),c=i.map(a),l=s.map(a);c.length>0&&o.push("--arkTsFiles",c.join(",")),l.length>0&&o.push("--cppFiles",l.join(","))}else if(n.modules&&n.modules.length>0){let i=fN(t,n.modules);o.push("--modulePaths",i.join(","))}else o.push("--projectPath",t.rootDir);return o.push("--outputPath",Mu.tmpdir()),o}async function gN(r,e){let t=K.dirname(e[0]);try{let o=(await QL(r.nodePath,e,{cwd:t,stdin:"ignore",stdout:"pipe",stderr:"inherit"})).stdout;return process.env.DEVECO_CLI_DEBUG&&(console.log(Se("[compat:check] === scan stdout ===")),process.stdout.write(o),o.endsWith(`
1363
+ `));let o=r.filter(a=>{let c=te.relative(e,a);return c.startsWith("..")||te.isAbsolute(c)});if(o.length>0)throw new Error(`File(s) outside the project root ${e}:
1364
+ `+o.map(a=>` ${a}`).join(`
1365
+ `));let s=r.filter(a=>Mr.statSync(a).isFile()&&a.endsWith(".ets")&&!a.endsWith(".d.ets"));if(s.length===0)throw new Error(`No .ets files found in the given file(s):
1366
+ `+r.map(a=>` ${a}`).join(`
1367
+ `));return s}buildArgs(e,t,r,i){let o=[e,"--project",t];return o.push(i?"--fix":"--no-fix"),r.length>0&&o.push("--files",...r),o}buildEnv(){return{...process.env,DEVECO_HOME:this.resolveDevecoHome()}}resolveDevecoHome(){let e=this.toolProvider.toolchainRoot;if(rF.platform()==="darwin"&&!Mr.existsSync(te.join(e,"sdk"))){let t=te.join(e,"Contents");if(Mr.existsSync(te.join(t,"sdk")))return t}return e}parseResult(e,t,r){let i=e.trim();if(!i){let o=t.trim();throw new Error(`arkts-check exited with code ${r} but produced no output`+(o?`: ${o}`:""))}try{let o=JSON.parse(i);return{success:o.success??!1,error:o.error,errors:o.errors??[],fixed:o.fixed??[],alsoModified:o.alsoModified??[],summary:{errorCount:o.summary?.errorCount??0,warnCount:o.summary?.warnCount??0,fixedCount:o.summary?.fixedCount??0,checkerDiagCount:o.summary?.checkerDiagCount,fileCount:o.summary?.fileCount??0}}}catch(o){throw new Error(`Failed to parse arkts-check output: ${i.slice(0,500)}`,{cause:o})}}resolveScriptPath(){let e=nF(import.meta.url),t=te.dirname(e);if(e.includes("dist")){let s=te.dirname(t),a=te.join(s,"src",$E);if(Mr.existsSync(a))return a}let r=te.dirname(t),i=te.dirname(r),o=te.join(i,"src",$E);if(Mr.existsSync(o))return o;throw new Error("arkts-check.cjs not found in deveco-cli package resources. Reinstall deveco-cli.")}};import{red as wf,yellow as vf,green as FE}from"colorette";import{Command as iF}from"commander";function oF(n){let e=n;return e.code??e.name??"UnknownError"}async function yf(n,e,t,r){let i=await lt(process.pid),o=i!==null?ce(Number(i)*1024):"unknown",s={event:v.CheckCommand,args:r,mcpMemory:o,lspMemory:"unknown"},a={duration_ms:Date.now()-n,success:e,error_code:t};await D.track(s,a).catch(()=>{})}function bf(){return new iF("arkts").description("Run ArkTS static checks on .ets source files").arguments("[files...]").option("--fix","Auto-fix high-confidence errors before reporting").option("--project <path>","Project root directory (default: auto-detected from cwd)").action(async(n,e)=>{await sF(n,e)})}async function sF(n,e){let t=Date.now(),r=["check","arkts"];try{let i=await P.new(),o=new ia(i,process.cwd()),s=new mt;process.stderr.isTTY&&s.start("Checking ArkTS...");let a;try{a=await o.check({files:n,fix:e.fix,projectRoot:e.project})}catch(c){throw s.fail("ArkTS check failed"),c}if(a.error&&a.errors.length===0){s.fail("ArkTS check failed"),console.error(wf(a.error)),process.exitCode=1,await yf(t,!1,"CheckFailed",r);return}s.stop(),aF(a),await yf(t,!0,null,r)}catch(i){throw await yf(t,!1,oF(i),r),i}}function aF(n){let{errorCount:e,warnCount:t,fixedCount:r,fileCount:i}=n.summary;if(cF(n.fixed,r,n.alsoModified),e===0){console.log(FE(`No errors found in ${i} file(s).`)),jE(n.errors);return}lF(n.errors,e,t),process.exitCode=1}function cF(n,e,t){if(n.length!==0){console.log(FE(`\u2713 Auto-fixed ${e} issue(s):`));for(let r of n)console.log(` ${r.file}:${r.line}:${r.column} - ${r.message}`);if(t.length>0){console.log(vf(`Note: auto-fix also modified ${t.length} file(s) outside the checked list (added missing 'export'):`));for(let r of t)console.log(` ${r}`)}console.log()}}function lF(n,e,t){let r=n.filter(i=>i.severity==="error");console.error(wf(`ArkTS check found ${e} error(s):`));for(let i of r){let o=i.rule?` (${i.rule})`:"";console.error(wf(`${i.file}:${i.line}:${i.column} - ${i.severity}: ${i.message}${o}`))}jE(n,t)}function jE(n,e){let t=n.filter(i=>i.severity!=="error");if(t.length===0)return;let r=e??t.length;console.warn(vf(`
1368
+ Warnings (${r}):`));for(let i of t){let o=i.rule?` (${i.rule})`:"";console.warn(vf(`${i.file}:${i.line}:${i.column} - ${i.severity}: ${i.message}${o}`))}}import{InvalidArgumentError as dF}from"commander";import*as ne from"path";import*as Sf from"os";import{readdirSync as uF,existsSync as yd,readFileSync as pF,unlinkSync as mF,copyFileSync as WE,writeFileSync as VE}from"fs";import{execa as fF}from"execa";import{cyan as Ie,yellow as GE}from"colorette";import hF from"ora";var me=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function Ef(n){let e=n;return n instanceof me?n.code:e.code??e.name??"UnknownError"}async function So(n,e,t,r){let i=await lt(process.pid),o=i!==null?ce(Number(i)*1024):"unknown",s={event:v.CheckCommand,args:r,mcpMemory:o,lspMemory:"unknown"},a={duration_ms:Date.now()-n,success:e,error_code:t};await D.track(s,a).catch(()=>{})}var gF=["default","csv","json"],HE=["default","json"];function yF(n){return[...n].sort((e,t)=>{let r=UE(e),i=UE(t);return r.apiVersion-i.apiVersion||r.suffix.localeCompare(i.suffix)})}function UE(n){let e=n.match(/\((\d+)\)/),t=e?Number(e[1]):0,r=n.lastIndexOf("_"),i=r>=0?n.slice(r+1):n;return{apiVersion:t,suffix:i}}function qE(n){let t=uF(n,{withFileTypes:!0}).filter(r=>r.isFile()&&r.name.toLowerCase().endsWith(".json")).map(r=>r.name.slice(0,-5));return yF(t)}async function zE(n){if(n=n===void 0?"default":n,!HE.includes(n))throw new Error(`--format must be ${HE.join(" or ")}. got "${n}"`);let e=Date.now(),t=["check","compat","versions"];try{let r=await P.new(),{apiChangeDir:i}=r.getApiscanPaths();m(Ie(`[compat:versions] apiChangeDir: "${i}"`));let o=qE(i);if(n==="json")console.log(JSON.stringify({versions:o,count:o.length},null,2));else{if(o.length===0){console.log("No SDK versions available."),await So(e,!0,null,t);return}console.log(o.join(`
1369
+ `))}await So(e,!0,null,t)}catch(r){let i=Ef(r);throw await So(e,!1,i,t),r}}var BE=new Set([".ets",".c",".cpp"]);function wF(n,e){let t=new Set(n.profile.modules.map(s=>s.name)),r=e.filter(s=>!t.has(s));if(r.length===0)return;let i=n.profile.modules.map(s=>s.name).join(", "),o=r.length>1?"are":"is";throw new me("errorCode",`Module ${r.map(s=>`"${s}"`).join(", ")} ${o} not defined in build-profile.json5. Available modules: ${i}.`)}function vF(n){for(let e of n){let t=ne.resolve(e);if(!yd(t))throw new me("errorCode",`File "${e}" does not exist.`);let r=ne.extname(t).toLowerCase();if(!BE.has(r)){let i=Array.from(BE).join(", ");throw new me("errorCode",`Unsupported file extension "${r}" for "${e}". Supported: ${i}.`)}}}function bF(n){let e=[],t=[];for(let r of n)ne.extname(r).toLowerCase()===".ets"?e.push(r):t.push(r);return{arkTs:e,cpp:t}}function SF(n){let e=[],t=[],r="",i=!1,o=0;for(;o<n.length;){let s=n[o];i?{field:r,inQuotes:i,i:o}=EF(n,o,s,r,i):s==='"'?(i=!0,o+=1):s===","?(t.push(r),r="",o+=1):s===`
1370
+ `?(t.push(r),e.push(t),t=[],r="",o+=1):(s==="\r"||(r+=s),o+=1)}return(r.length>0||t.length>0)&&(t.push(r),e.push(t)),e}function EF(n,e,t,r,i){return t!=='"'?{field:r+t,inQuotes:i,i:e+1}:n[e+1]==='"'?{field:r+'"',inQuotes:i,i:e+2}:{field:r,inQuotes:!1,i:e+1}}function PF(n,e){return e.map(t=>{let r=i=>{let o=n.indexOf(i);return o>=0&&o<t.length?t[o]:""};return{apiDefinition:r("Api Definition"),language:r("Language"),changeId:r("ChangeId"),changedInSdk:r("Changed in SDK"),affectedVersions:r("Affected Versions"),title:r("Title"),codeLocation:r("Code Location"),changeType:r("Change Type")}})}function CF(n){let e=pF(n,"utf8"),t=e.startsWith("\uFEFF")?e.slice(1):e,r=SF(t);if(r.length<2)return[];let[i,...o]=r;return PF(i,o)}function kF(n,e){let t=n.match(/CSV saved to:\s*([^\r\n]+\.csv)/);if(!t)return null;let r=t[1].trim();if(ne.isAbsolute(r))return r;let i=ne.join(e,r);return E.ensurePathWithinRoot(e,i)}function RF(n,e){let t=new Map;for(let o of n){let s=o.changeType||"(unknown)";t.set(s,(t.get(s)??0)+1)}let r=Array.from(t.entries()).sort((o,s)=>s[1]-o[1]||o[0].localeCompare(s[0])),i=Math.max(5,...r.map(([o])=>o.length));console.log(Ie("API change scan summary:")),console.log(` ${"Total".padEnd(i)} ${n.length}`);for(let[o,s]of r)console.log(` ${o.padEnd(i)} ${s}`);e&&console.log(` ${"Report".padEnd(i)} ${e}`)}function DF(n,e){if(console.log(),n.length===0){console.log("No API changes detected.");return}let t=n.slice(0,e),r=n.length-t.length;console.log(Ie(`Details (showing ${t.length}${r>0?` of ${n.length}`:""}):`));let i=[["Title","title"],["Language","language"],["ChangeId","changeId"],["Changed in","changedInSdk"],["Affected Versions","affectedVersions"],["Code Location","codeLocation"]],o=Math.max(...i.map(([a])=>a.length)),s=a=>a||"<unknown>";for(let a of t){console.log(` [${s(a.changeType)}] ${s(a.apiDefinition)}`);for(let[c,l]of i)console.log(` ${c.padEnd(o)} ${s(a[l])}`)}r>0&&console.log(GE(` ... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function xF(n,e){let t=n.slice(0,e),r=n.length-t.length;console.log(),console.log(JSON.stringify({records:t,count:n.length},null,2)),r>0&&console.log(GE(`... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function AF(n,e){let t=[];for(let r of e){let i=n.profile.modules.find(o=>o.name===r);if(!i)throw new me("errorCode",`Module "${r}" not found in build-profile.json5.`);t.push(ne.resolve(n.rootDir,i.srcPath))}return t}function IF(n,e,t,r){if(!r.sourceVersion||!r.targetVersion)throw new me("errorCode","source-version and target-version are required.");let i=[n,"--startVersion",r.sourceVersion,"--endVersion",r.targetVersion];if(e.length>0){let{arkTs:o,cpp:s}=bF(e),a=d=>ne.resolve(process.cwd(),d),c=o.map(a),l=s.map(a);c.length>0&&i.push("--arkTsFiles",c.join(",")),l.length>0&&i.push("--cppFiles",l.join(","))}else if(r.modules&&r.modules.length>0){let o=AF(t,r.modules);i.push("--modulePaths",o.join(","))}else i.push("--projectPath",t.rootDir);return i.push("--outputPath",Sf.tmpdir()),i}async function TF(n,e){let t=ne.dirname(e[0]);try{let i=(await fF(n.nodePath,e,{cwd:t,stdin:"ignore",stdout:"pipe",stderr:"inherit"})).stdout;return process.env.DEVECO_CLI_DEBUG&&(console.log(Ie("[compat:check] === scan stdout ===")),process.stdout.write(i),i.endsWith(`
1409
1371
  `)||process.stdout.write(`
1410
- `),console.log(Se("[compat:check] === end stdout ==="))),o}catch(n){let o=n;process.env.DEVECO_CLI_DEBUG&&o.stdout&&(console.log(Se("[compat:check] === scan stdout (on error) ===")),process.stdout.write(o.stdout),o.stdout.endsWith(`
1372
+ `),console.log(Ie("[compat:check] === end stdout ==="))),i}catch(r){let i=r;process.env.DEVECO_CLI_DEBUG&&i.stdout&&(console.log(Ie("[compat:check] === scan stdout (on error) ===")),process.stdout.write(i.stdout),i.stdout.endsWith(`
1411
1373
  `)||process.stdout.write(`
1412
- `),console.log(Se("[compat:check] === end stdout ===")));let i=new se("errorCode",`Compatibility scan failed: ${o.message}`+(o.stderr?`
1413
- ${o.stderr}`:""));throw o.stdout&&(i.stdout=o.stdout),i}}function yN(r,e){if(!tN.includes(e.format))throw new YL(`--format must be default, csv, or json (console: default|json, file: default|csv|json). got "${e.format}"`);if(r.length>0&&e.modules&&e.modules.length>0)throw new se("errorCode","Cannot use `--modules` together with file arguments. Use either file-level scanning (with files) or module-level scanning (with --modules).");if(!e.sourceVersion)throw new se("errorCode","--source-version is required.");if(!e.targetVersion)throw new se("errorCode","--target-version is required.");if(!e.outputPath&&e.format==="csv")throw new se("errorCode","--format csv requires --output-path. For console output, use --format json or --format default (or omit the flag).")}function vN(r,e){let t=[];if(r.sourceVersion&&!e.includes(r.sourceVersion)&&t.push(`--source-version "${r.sourceVersion}"`),r.targetVersion&&!e.includes(r.targetVersion)&&t.push(`--target-version "${r.targetVersion}"`),t.length>0){let n=t.length>1?"are":"is";throw new se("errorCode",`${t.join(" and ")} ${n} not in the available SDK version list.
1414
- Run \`devecocli compat versions\` to see all available versions.`)}if(r.sourceVersion&&r.targetVersion){let n=e.indexOf(r.sourceVersion),o=e.indexOf(r.targetVersion);if(n>=o)throw new se("errorCode",`--target-version "${r.targetVersion}" must be later than --source-version "${r.sourceVersion}". Run \`devecocli compat versions\` to see the available order.`)}}function wN(r,e,t,n,o){o==="none"&&(t==="json"?mN(r,n):pN(r,n)),uN(r,e)}function SN(r,e){let t=K.dirname(r),n=K.basename(r),o=e.slice(1).map(i=>i.startsWith("--")?i:`"${i}"`).join(" ");m(Se(`[compat:check] command: cd "${t}" && node "${n}" ${o}`))}function bN(r){try{ZL(r),m(Se(`[compat:check] cleaned up tmp report: "${r}"`))}catch(e){m(Se(`[compat:check] failed to clean up tmp report: ${e.message}`))}}var EN=[".csv",".json"];function CN(r){return EN.includes(r.toLowerCase())}function PN(r,e){if(!r)return{kind:"none"};let t=K.extname(r).toLowerCase();if(!CN(t))return{kind:"dir",dirPath:K.resolve(r)};if(t===".csv"&&!(e==="default"||e==="csv")||t===".json"&&e!=="json")throw new se("errorCode",`The --output-path file extension '${t}' does not match --format ${e}. Use --format ${t===".json"?"json":"default"}, or rename the file.`);return{kind:"file",filePath:K.resolve(r),ext:t}}function AN(r){if(r.kind==="file"){if(pc(r.filePath))throw new se("errorCode",`Target file "${r.filePath}" already exists. Remove it first, or choose a different --output-path.`);let e=K.dirname(r.filePath);if(!pc(e))throw new se("errorCode",`Target directory "${e}" does not exist. Create it first, or choose a different --output-path.`)}else if(r.kind==="dir"&&!pc(r.dirPath))throw new se("errorCode",`Target directory "${r.dirPath}" does not exist. Create it first, or choose a different --output-path.`)}function Aw(r){return JSON.stringify({records:r,count:r.length},null,2)+`
1415
- `}function IN(r,e,t,n){n===".csv"?Sw(r,t):bw(t,Aw(e),"utf8"),m(Se(`[compat:check] saved report: "${t}"`))}function kN(r,e,t,n){if(n==="json"){let i=K.basename(r,".csv"),s=K.join(t,`${i}.json`);return bw(s,Aw(e),"utf8"),m(Se(`[compat:check] saved report: "${s}"`)),s}let o=K.join(t,K.basename(r));return Sw(r,o),m(Se(`[compat:check] saved report: "${o}"`)),o}async function DN(r,e){let t=new Ke(r,process.cwd(),!0),n=e.modules&&e.modules.length>0?e.modules[0]:void 0;try{await t.compileNative("default",n)}catch(o){throw new se("errorCode",`hvigorw compileNative failed (module=${n??"<project>"}): `+o.message,{cause:o})}}async function TN(r,e){yN(r,e);let t=V.discover(process.cwd());e.modules&&e.modules.length>0&&nN(t,e.modules),r.length>0&&oN(r);let n=await k.new(),{apiChangeDir:o,scriptPath:i}=n.getApiscanPaths();m(Se(`[compat:check] script: "${i}"`));let s=Cw(o);vN(e,s),e.outputPath&&m(Se(`[compat:check] outputPath: "${e.outputPath}"`));let a=PN(e.outputPath,e.format);return m(Se(`[compat:check] outputTarget: ${a.kind}`)),AN(a),{project:t,scriptPath:i,target:a,toolProvider:n}}function RN(r,e,t,n){if(t.kind==="file")return IN(r,e,t.filePath,t.ext),t.filePath;if(t.kind==="dir")return kN(r,e,t.dirPath,n);if(t.kind==="none")return null;throw new se("errorCode",`Unexpected output target kind: ${t.kind}`)}async function xN(r,e,t,n,o){let i=eN({text:"Running compatibility check...",color:"cyan"}).start();try{await DN(r.toolProvider,t);let s=hN(r.scriptPath,e,r.project,t);SN(r.scriptPath,s);let a=await gN(r.toolProvider,s),c=dN(a,Mu.tmpdir());if(!c)throw new se("errorCode","Scanner output format unexpected: missing report path.");m(Se(`[compat:check] tmp csv: "${c}"`));let l=lN(c),d=RN(c,l,r.target,t.format);bN(c),i.stop(),wN(l,d,t.format,t.limit,r.target.kind),await vo(n,!0,null,o)}catch(s){i.fail("Compatibility check failed");let a=_u(s);throw await vo(n,!1,a,o),s}}async function Iw(r,e){let t=Date.now(),n=["check","compat"];try{let o=await TN(r,e);await xN(o,r,e,t,n)}catch(o){let i=_u(o);throw await vo(t,!1,i,n),o}}function NN(r){let e=Number(r);if(!Number.isInteger(e)||e<=0)throw new LN(`--limit must be a positive integer (got "${r}")`);return e}var Fu=new kw("compat").description("Compatibility checking utilities.");Fu.description("Check source code compatibility against a target SDK version. By default, performs a project-level scan; pass positional `files...` for file-level scanning; pass `--modules` for module-level scanning.").arguments("[files...]").option("--source-version <version>","Current project SDK version (required; use `compat versions` to list available versions). On zsh, quote the value because version strings contain parentheses; run `compat versions` first to copy a real example.").option("--target-version <version>","Target SDK version (required; use `compat versions` to list available versions). On zsh, quote the value because version strings contain parentheses; run `compat versions` first to copy a real example.").option("--modules <modules...>","Modules to check (default: all modules in the project). Mutually exclusive with positional file arguments.").option("--format <format>",'Output format: "json" or "default" (text) for console; "csv", "json", or "default" for file output (--output-path). "csv" requires --output-path.',"default").option("--output-path <path>","Directory to write the detailed report CSV to (default: ./compat-output)").option("--limit <num>","Maximum number of change records to display (default: 100)",NN,100).action(async(r,e)=>{await Iw(r,e)});Fu.command("versions").description("List all available target SDK versions for compatibility checking").option("--format <format>","Output format: default or json").action(async(r,e)=>{let t=e.optsWithGlobals().format;await Pw(t)});var ON=new kw("check").description("Run DevEco project checks").addCommand(Fu).addCommand(Tu()).addCommand(Ou()),Dw=ON;import{Command as EM}from"commander";import{green as sp,red as CM}from"colorette";import ap from"fs";import pS from"path";import mS from"json5";import{readFileSync as lO}from"fs";import{join as MN}from"path";var le={BASE_URL:"https://connect-api.cloud.huawei.com",CERT_LIST_PATH:"/api/cps/harmony-cert-manage/v1/cert/list",CERT_DELETE_PATH:"/api/cps/harmony-cert-manage/v1/cert/delete",CERT_ADD_PATH:"/api/cps/harmony-cert-manage/v1/cert/add",CERT_DOWNLOAD_URL_PATH:"/api/amis/app-manage/v1/objects/url/reapply",DEVICE_ADD_PATH:"/api/cps/device-manage/v1/device/add",DEVICE_LIST_PATH:"/api/cps/device-manage/v1/device/list",PROVISION_ADD_REAL_PATH:"/api/cps/provision-manage/v1/ide/real/provision/add",PROVISION_ADD_TEST_PATH:"/api/cps/provision-manage/v1/ide/test/provision/add",PROVISION_DELETE_PATH:"/api/cps/provision-manage/v1/provision/delete"},qe={CERT_NAME_PREFIX:"auto_debug_",CERT_TYPE_DEBUG:"1",TEAM_ID_INVALID_CHARS:/[\\/.:]/g,CERT_PATTERN:/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/,TARGET_FRIENDLY_NAME:"debugKey",CERTIFICATE_PATTERN_GLOBAL:/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g,BUNDLE_NAME_REGEX:/^[a-zA-Z][a-zA-Z0-9._-]*$/,CERT_BEGIN_HEADER:"-----BEGIN CERTIFICATE-----",CERT_SAVE_DIR:MN(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},be={SUCCESS_MARKER:'"code":0',SQUARE_BRACKETS:"[]",OPENPROXY_BLOCKED_URL:"Openproxy_Blocked_URL_list",CERT_LIMIT_CODE:"205389872",USER_NOT_HARMONY_CODE:"205389904",DEVICE_EXCEEDS_LIMIT_CODE:"205389859",DEVICE_NAME_REPEAT_CODE:"205389857",PROVISION_EXCEEDS_LIMIT_CODE:"205389938",PROVISION_NAME_REPEAT_CODE:"205389830"},bt={FORBIDDEN:403,UNAUTHORIZED:401},C={ERR_FORBIDDEN:"You do not have AppGallery Connect permissions for the current team. Request access from the team administrator or switch to a team where you have permissions.",ERR_UNAUTHORIZED:"Invalid AccessToken. Sign in and try again.",ERR_CERT_LIMIT_REACHED:"The number of certificates has reached the limit. Delete some certificates and try again.",ERR_CERT_NETWORK_ERROR:"Ensure the external network connection is available before downloading the certificate.",ERR_CERT_INVALIDATE:"The downloaded .cer file is invalid. Try again.",ERR_DOWNLOAD_CER:"Failed to download the certificate file. Check the following configurations: Network connection, HTTP Proxy, etc.",ERR_USER_NOT_HARMONY:"The user is not in harmony allow list, please grant the permission",ERR_READ_CSR:"Failed to read the .csr file, please try again later",ERROR_WHILE_ADD_DEVICE:"Failed to add the device, please try again.",DEVICE_LIMIT_REACHED:"The number of devices has reached the limit. Delete some unused devices and try again.",DEVICE_NAME_REPEAT:"Duplicate device name, please try again.",DEVICE_LIST_EMPTY:"No devices available.",ADD_PROFILE_FAIL:"Failed to add the profile, please try again.",NO_AGC_PERMISSION:"You do not have the AppGallery Connect permission with the current team. Apply for the permission form the team administrator, or switch to a team with which you already have the permission.",ERROR_WHILE_DOWNLOAD_PROFILE:"Failed to download the profile, please try again.",PROFILE_NAME_REPEAT:"The profile name already exists in the AGC.",ERROR_WHILE_PARSE_PROFILE:"Failed to parse the profile, please try again.",TEST_PROVISION_EXCEEDS_LIMIT:"Provision number exceeds limit.",CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT:"The certificate application file is inconsistent with the file in profile, please try again.",CERTIFICATE_HAS_EXPIRED:"The signature does not take effect or has expired. It may be the current system time is inaccurate, please calibrate the system time and sign again.",ERROR_SIGN_BUNDLE_NAME_VALIDATE:"The bundle name contains 7 to 128 characters, including only letters, digits, and underscores (_). It must be start with a letter and contain at least three segments separated by periods (.), each of the segments ending with a digit or letter."},pe={TOOLCHAIN_INIT_FAILED:"Auto-sign failed: unable to initialize toolchain",LOGIN_REQUIRED:"Failed to automatically generate signatures.Run devecocli auth login to sign in.",TEAM_INFO_FAILED:"Failed to obtain user team information.Check the network connection, HTTP proxy, and other configurations.",REALNAME_REQUIRED:"Users without real-name verification are not supported.Complete real-name verification in AppGallery Connect.",SESSION_EXPIRED:"User session expired or token invalid. Please login again.",REGION_CHINA_ONLY:"This feature is only available for accounts registered in Chinese mainland.",DEVICE_MISSING:"Unable to create the profile file due to missing devices.Connect a device through IP or USB, or manually add a device in AppGallery Connect first.If you are installing the HAP package on an emulator, you can skip the signing step.",DEVICE_DETECT_FAILED:"Unable to detect devices. Please check hdc status. If installing HAP on an emulator, signature step can be skipped.",PROJECT_DIR_MISSING:"Not in a valid project directory (project-level build-profile.json5 not found).",ATOMIC_SERVICE_UNSUPPORTED:"AtomicService projects are not yet supported. Please configure signing manually."};function mc(r){return{uid:r.uid,teamId:r.teamId,oauth2Token:r.accessToken}}function ju(r){let e=r.replace(qe.TEAM_ID_INVALID_CHARS,"");return`${qe.CERT_NAME_PREFIX}${e}.cer`}function wo(r,e,t){if(r===bt.FORBIDDEN)return e===be.OPENPROXY_BLOCKED_URL?new Error(C.ERR_CERT_NETWORK_ERROR):new Error(C.ERR_FORBIDDEN);if(r===bt.UNAUTHORIZED)return new Error(C.ERR_UNAUTHORIZED);if(t.includes(be.USER_NOT_HARMONY_CODE))return new Error(C.ERR_USER_NOT_HARMONY);if(t.includes(be.CERT_LIMIT_CODE))return new Error(C.ERR_CERT_LIMIT_REACHED);let n=_N(t);return new Error(n??C.ERR_DOWNLOAD_CER)}function _N(r){let e=Tw(r);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let n=typeof t=="string"?Tw(t):t;if(n&&typeof n=="object"){let o=n.msg;if(typeof o=="string"&&o.trim()!=="")return o}return null}function Tw(r){try{return JSON.parse(r)}catch{return null}}function $u(r){return JSON.parse(r)}async function Rw(r){let e=`${le.BASE_URL}${le.CERT_LIST_PATH}`,t=await L.postAllowFailure(e,{headers:mc(r)});if(t.statusCode!==200)throw wo(t.statusCode,t.statusText,t.data);return $u(t.data)?.certList??[]}async function fc(r,e){return(await Rw(r)).find(n=>n.certName===e)??null}async function Hu(r,e){let t=`${le.BASE_URL}${le.CERT_DELETE_PATH}`,n=await L.deleteAllowFailure(t,{headers:mc(r),params:{certIds:[e]}});if(n.statusCode!==200)throw wo(n.statusCode,n.statusText,n.data);return $u(n.data)?.ret?.code===0}async function Bu(r,e,t){let n=`${le.BASE_URL}${le.CERT_ADD_PATH}`,o={csr:e,certName:t,certType:qe.CERT_TYPE_DEBUG},i=await L.postAllowFailure(n,{headers:mc(r),params:o});if(i.statusCode!==200)throw wo(i.statusCode,i.statusText,i.data);if(!i.data.includes(be.SUCCESS_MARKER))throw wo(void 0,i.statusText,i.data)}async function Uu(r,e){let t=`${le.BASE_URL}${le.CERT_DOWNLOAD_URL_PATH}`,n=await L.postAllowFailure(t,{headers:mc(r),params:{sourceUrls:e}});if(n.statusCode!==200)throw wo(n.statusCode,n.statusText,n.data);return $u(n.data)?.urlsInfo?.[0]??null}import{mkdirSync as FN,writeFileSync as jN,existsSync as $N}from"fs";import{dirname as HN}from"path";import{createHash as BN}from"crypto";function UN(r){let e;try{e=new URL(r)}catch{throw new Error(`Invalid download URL: ${JSON.stringify(r)}`)}if(e.protocol!=="https:")throw new Error(`Download URL must use HTTPS: ${e.protocol}`);let t=e.hostname.toLowerCase();if(t==="localhost"||t==="127.0.0.1"||t==="::1"||t.startsWith("169.254.")||t.startsWith("10.")||t.startsWith("192.168.")||/^172\.(1[6-9]|2\d|3[0-1])\./.test(t)||t.endsWith(".internal")||t.endsWith(".local"))throw new Error(`Download URL points to internal/private address: ${t}`)}async function Gi(r,e,t){UN(r);let{statusCode:n,statusText:o,buffer:i}=await L.getBinaryAllowFailure(r,{timeout:qe.DOWNLOAD_CONNECT_TIMEOUT_MS});if(n!==200)throw n===bt.FORBIDDEN&&o===be.OPENPROXY_BLOCKED_URL?new Error(C.ERR_CERT_NETWORK_ERROR):new Error(C.ERR_DOWNLOAD_CER);if(t){let a=BN("sha256").update(i).digest("hex");if(a!==t.toLowerCase())throw new Error(`SHA-256 mismatch for ${e}: expected ${t.toLowerCase()}, got ${a}`)}let s=HN(e);$N(s)||FN(s,{recursive:!0}),jN(e,i)}import sO from"fs/promises";import{readFileSync as aO}from"fs";import hc from"path";import Nw from"crypto";import WN from"os";import zi from"fs/promises";var Ow={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},xw=["ECC","RSA"],Lw=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],VN={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},GN=8,Wu=64,zN=/[\\/:*?"<>|=-]/g,Et={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function qN(r){if(!r.keyAlias.trim())throw new Error("keyAlias cannot be empty");if(!r.keystoreFile.trim())throw new Error("keystoreFile cannot be empty");if(r.keyAlias.length>Wu)throw new Error(`The length of keyAlias cannot exceed ${Wu}`);if(!xw.includes(r.keyAlg))throw new Error(`Invalid key algorithm ${r.keyAlg}, available: ${xw.join(" / ")}`);let e=VN[r.keyAlg];if(!e.includes(r.keySize))throw new Error(`Key algorithm ${r.keyAlg} does not support size ${r.keySize}, available: ${e.join(", ")}`)}function JN(r){if(!r.keyAlias.trim())throw new Error("keyAlias cannot be empty");if(!r.keystoreFile.trim())throw new Error("keystoreFile cannot be empty");if(!r.subject.trim())throw new Error("subject cannot be empty");if(!Lw.includes(r.signAlg))throw new Error(`Invalid sign algorithm ${r.signAlg}, available: ${Lw.join(" / ")}`)}function YN(r){return Nw.createHash("sha256").update(r,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function KN(r){let e=r?.trim()??"";return e&&e.replace(zN,"_").replace(/\.+/g,"_").slice(0,Wu)||Et.productName}async function Mw(){let r=await k.new(),e=r.javaPath;if(!e)throw new Error("Java runtime not found. DevEco Studio JBR is required to run hap-sign-tool.jar.");let t=r.sdkPath;f.info(`\u8BFB\u53D6SDK\u6839\u76EE\u5F55\uFF1A${t}`);let n=hc.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");try{await zi.access(n)}catch(o){throw new Error(`Sign tool jar not found: ${n}`,{cause:o})}return{javaPath:e,jarPath:n}}async function XN(r){let{javaPath:e,jarPath:t}=await Mw(),n=["-jar",t,Ow.GENERATE_KEYPAIR,"-keyAlias",r.keyAlias,"-keyAlg",r.keyAlg,"-keySize",r.keySize,"-keystoreFile",r.keystoreFile,"-keystorePwd",r.keystorePwd];r.keyPwd&&n.push("-keyPwd",r.keyPwd),r.pwdInputMode&&n.push("-pwdInputMode",r.pwdInputMode);let o=n.map((i,s)=>s>0&&["-keyPwd","-keystorePwd"].includes(n[s-1])?"******":i);return f.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),[e,...n]}async function ZN(r){let{javaPath:e,jarPath:t}=await Mw(),n=["-jar",t,Ow.GENERATE_CSR,"-keyAlias",r.keyAlias,"-subject",r.subject,"-signAlg",r.signAlg,"-keystoreFile",r.keystoreFile,"-keystorePwd",r.keystorePwd];r.outFile&&n.push("-outFile",r.outFile),r.keyPwd&&n.push("-keyPwd",r.keyPwd),r.pwdInputMode&&n.push("-pwdInputMode",r.pwdInputMode);let o=n.map((i,s)=>s>0&&["-keyPwd","-keystorePwd"].includes(n[s-1])?"******":i);return f.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),[e,...n]}async function QN(r){f.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),qN(r);let e=await XN(r),t=await Mo(e[0],e.slice(1));if(t.exitCode!==0){let n=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the private key P12, exit code${t.exitCode}\uFF1A${n}`)}return f.info("\u751F\u6210P12\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}async function eO(r){f.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),JN(r);let e=await ZN(r),t=await Mo(e[0],e.slice(1));if(t.exitCode!==0){let n=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the CSR, exit code${t.exitCode}\uFF1A${n}`)}return f.info("\u751F\u6210CSR\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}function tO(r=GN){return Nw.randomBytes(r).toString("base64url").replaceAll(/[-_=]/g,"")}async function rO(){let r=WN.homedir();try{await zi.access(r)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=hc.join(r,".ohos","config");try{await zi.mkdir(e,{recursive:!0,mode:448})}catch(t){throw new Error(`Failed to create directory ${e}`,{cause:t})}return f.info(`\u7B7E\u540D\u914D\u7F6E\u76EE\u5F55\u5C31\u7EEA\uFF1A${e}`),e}async function De(r,e,t){let n=KN(r),o=hc.basename(e),i=YN(e),s=`${n}_${o}_${i}=.${t}`,a=await rO();return hc.join(a,s)}function nO(r){let e;try{e=V.discover(r).rootDir}catch(t){throw new Error(`Current directory ${r} is not a valid project root`,{cause:t})}return e}async function oO(r){try{await zi.access(r)}catch(e){throw new Error(`Project directory ${r} is not accessible, missing read/write permissions`,{cause:e})}}async function iO(r){try{await zi.access(r)}catch(e){throw new Error(`P12 file ${r} does not exist, terminating CSR generation.`,{cause:e})}}async function Vu(r,e,t){let n=process.cwd(),o=nO(n);await oO(o),f.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${o}`);let i=tO(),s=await De(r??"",o,"p12"),a=await De(r??"",o,"csr");return console.log("Start generating p12"),await QN({keyAlias:e?.keyAlias??Et.keyAlias,keyPwd:i,keyAlg:e?.keyAlg??Et.keyAlg,keySize:e?.keySize??Et.keySize,keystoreFile:s,keystorePwd:i}),await iO(s),console.log("Start generating csr"),await eO({subject:t?.subject??Et.csrSubject,outFile:a,keyAlias:t?.keyAlias??Et.keyAlias,keyPwd:i,signAlg:t?.signAlg??Et.signAlg,keystoreFile:s,keystorePwd:i}),{p12FilePath:s,csrFilePath:a,keyPwd:i,keyAlias:e?.keyAlias??Et.keyAlias}}var cO=["p12","cer","csr","p7b"];async function Gu(r,e){for(let t of cO){let n=await De(r,e,t);await sO.rm(n,{force:!0})}}function zu(r){let e;try{e=aO(r,"utf-8")}catch{throw new Error(C.ERR_CERT_INVALIDATE)}if(!qe.CERT_PATTERN.test(e))throw new Error(C.ERR_CERT_INVALIDATE)}async function _w(r,e){return{certPath:await De(r,e,"cer"),csrPath:await De(r,e,"csr"),p12Path:await De(r,e,"p12"),profilePath:await De(r,e,"p7b")}}async function qu(r,e){let t=e??"",n=V.discover(process.cwd()).rootDir;await Gu(t,n);let o=ju(r.teamId),i=await fc(r,o);if(i&&!await Hu(r,i.id))throw new Error(C.ERR_DOWNLOAD_CER);let s=await Vu(e),a;try{a=lO(s.csrFilePath,"utf-8")}catch{throw new Error(C.ERR_READ_CSR)}console.log("Start generating certificate"),await Bu(r,a,o);let c=await fc(r,o);if(!c)throw new Error(C.ERR_DOWNLOAD_CER);let l=await Uu(r,c.certObjectId);if(!l)throw new Error(C.ERR_DOWNLOAD_CER);let d=await De(t,n,"cer");await Gi(l.newUrl,d,l.sha256),zu(d);let g=await De(t,n,"p7b");return{p12FilePath:s.p12FilePath,csrFilePath:s.csrFilePath,cerFilePath:d,profileFilePath:g,certId:c.id,keyAlias:s.keyAlias,keyPwd:s.keyPwd,storePassword:s.keyPwd}}import Ac from"crypto";import Br from"fs";import*as Xw from"path";import xO from"json5";import{execa as Jw}from"execa";import Yw from"node-forge";import{createCipheriv as dO,createDecipheriv as uO,pbkdf2Sync as pO,randomBytes as Xu}from"crypto";import{promises as yn}from"fs";import{dirname as mO,join as Ct}from"path";var gc=3,qi=16,fO=1e4,Fw="material",hO=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Bw="aes-128-gcm",gn=12,yc=16,jr=4;function Ju(r){return new Uint8Array(Xu(r))}function gO(r){return Xu(r).toString("hex")}function yO(...r){if(r.length===0)return new Uint8Array(0);let e=r[0].length,t=new Uint8Array(e);for(let n=0;n<e;n++){let o=0;for(let i of r)o^=i[n];t[n]=o}return t}function jw(r,e,t=fO,n=qi){let o=[...r,hO],i=yO(...o),s=Buffer.from(i).toString("utf8"),a=Buffer.from(s,"utf8"),c=pO(a,e,t,n,"sha256");return new Uint8Array(c)}function $w(r,e){let t=Xu(gn),n=dO(Bw,r,t),o=Buffer.concat([n.update(e),n.final()]),i=n.getAuthTag(),s=Buffer.concat([o,i]),a=s.length,c=Buffer.alloc(jr+gn+s.length);return c.writeUInt32BE(a,0),t.copy(c,jr),s.copy(c,jr+gn),c}function Hw(r,e){if(e.length<jr+gn+yc)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),n=e.subarray(jr,jr+gn),o=e.subarray(jr+gn,jr+gn+t);if(o.length<yc)throw new Error("Ciphertext too short for auth tag");let i=o.subarray(0,o.length-yc),s=o.subarray(o.length-yc),a=uO(Bw,r,n);return a.setAuthTag(s),Buffer.concat([a.update(i),a.final()])}async function vO(r){try{await yn.rm(r,{recursive:!0,force:!0})}catch{}}async function Yu(r){let e=await yn.readdir(r),t=e.filter(n=>n!==".DS_Store");if(t.length!==1)throw new Error(`Expected exactly 1 file in ${r}, but found ${t.length} (filtered from ${e.length})`);return yn.readFile(Ct(r,t[0]))}async function Ku(r,e){let t=gO(qi),n=Ct(r,t);return await yn.writeFile(n,e,{mode:384}),t}var $r=class{static keyChain=Promise.resolve();static async generateMaterial(e){let t=Ct(e,Fw);await vO(t);let n=Ct(t,"ac"),o=Ct(t,"ce");await yn.mkdir(n,{recursive:!0,mode:448}),await yn.mkdir(o,{recursive:!0,mode:448});for(let d=0;d<gc;d++)await yn.mkdir(Ct(t,"fd",String(d)),{recursive:!0,mode:448});let i=Ju(qi),s=[];for(let d=0;d<gc;d++)s.push(Ju(qi));let a=Ju(qi),c=jw(s,i),l=$w(c,a);await Ku(n,i),await Ku(o,l);for(let d=0;d<gc;d++){let g=Ct(t,"fd",String(d));await Ku(g,s[d])}return a}static async readMaterial(e){let t=Ct(e,Fw),n=Ct(t,"ac"),o=new Uint8Array(await Yu(n)),i=[];for(let d=0;d<gc;d++){let g=Ct(t,"fd",String(d)),y=await Yu(g);i.push(new Uint8Array(y))}let s=Ct(t,"ce"),a=await Yu(s),c=jw(i,o),l=Hw(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t,n=this.keyChain;this.keyChain=new Promise(o=>{t=o}),await n;try{let o=mO(e);try{return await this.readMaterial(o)}catch{return await this.generateMaterial(o)}}finally{t()}}static async encryptedPassword(e,t){let n=await this.getStoreKey(t),o=Buffer.from(e,"utf8");return $w(n,o).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let n=await this.getStoreKey(t),o=Buffer.from(e,"hex");return Hw(n,o).toString("utf8")}};import zw from"fs";import Cc from"path";import PO from"json5";import*as vc from"fs";import*as Uw from"path";function wc(r){let e=Uw.resolve(r);if(!vc.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=vc.readFileSync(e,"utf-8")}catch(s){throw new Error(`Failed to read SDK info file: ${e}`,{cause:s})}let n;try{n=JSON.parse(t)}catch(s){throw new Error(`Invalid JSON in SDK info file: ${e}`,{cause:s})}let o=n?.data?.apiVersion;if(o==null||o==="")throw new Error(`Missing data.apiVersion in SDK info file: ${e}`);let i=Number(o);if(!Number.isFinite(i))throw new Error(`Invalid data.apiVersion in SDK info file: ${String(o)}`);return i}import*as bo from"fs";import*as Je from"path";import{debuglog as So}from"util";var Ww={"acl.SYSTEM_FLOAT_WINDOW.instead.name":"PiPWindow","acl.READ_CONTACTS.instead.name":"contact.selectContacts","acl.READ_IMAGEVIDEO.instead.name":"PhotoViewPicker","acl.WRITE_IMAGEVIDEO.instead.name":"SaveButton","acl.READ_AUDIO.instead.name":"AudioViewPicker","acl.WRITE_AUDIO.instead.name":"AudioViewPicker","acl.READ_PASTEBOARD.instead.name":"PasteButton"};function wO(r){return Object.prototype.hasOwnProperty.call(Ww,r)}function Sc(r){if(wO(r))return Ww[r]}var Vw={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as SO}from"url";var Ec=class{permissionName;permissionDisplayName;minSupportApiLevel;permissionInsteadName;permissionHelpUrlKey;constructor(e={}){this.permissionName=e.permissionName??"",this.permissionDisplayName=e.permissionDisplayName??"",this.minSupportApiLevel=e.minSupportApiLevel??"",this.permissionInsteadName=e.permissionInsteadName,this.permissionHelpUrlKey=e.permissionHelpUrlKey}};function bc(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Gw(r){return r==null||r.length===0}function bO(r){return!Gw(r)}function Zu(r,e){let t=r[e];return typeof t=="string"?t:t==null?"":String(t)}function EO(r,e){let t=r[e];if(typeof t=="boolean")return t;if(typeof t=="number")return t!==0;if(typeof t=="string"){let n=t.trim().toLowerCase();return n==="true"||n==="1"}return!1}function CO(r,e){let t=r[e];if(typeof t=="number")return Math.trunc(t);if(typeof t=="string"){let n=Number.parseInt(t,10);return Number.isNaN(n)?0:n}return 0}var Hr=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=Je.join("aclPermission","aclPermissionsInfo.json");static ACL_HAVE_INSTEAD_NAME=new Set(["ohos.permission.SYSTEM_FLOAT_WINDOW","ohos.permission.READ_CONTACTS","ohos.permission.READ_IMAGEVIDEO","ohos.permission.WRITE_IMAGEVIDEO","ohos.permission.READ_AUDIO","ohos.permission.WRITE_AUDIO","ohos.permission.READ_PASTEBOARD"]);static ACL_AVAILABLE_LEVEL_VALUE="system_basic";static ACL_AVAILABLE_TYPE_VALUE="NORMAL";static ACL_AVAILABLE_LEVEL_KEY="availableLevel";static ACL_AVAILABLE_TYPE_KEY="availableType";static ACL_PROVISION_ENABLE_KEY="provisionEnable";static ACL_NAME_KEY="name";static ACL_CONFIG_PREFIX="acl.";static ACL_INSTEAD_NAME_SUFFIX=".instead.name";static ACL_HELP_URL_KEY_SUFFIX=".help.key";static ACL_DEFINE_PERMISSION_KEY="definePermissions";static ACL_SINCE_KEY="since";static PERMISSION_DEFINITIONS_RELATIVE_PATH=Je.join("lib","PermissionDefinitions.json");static INCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.FILE_ACCESS_PERSIST","ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORY","ohos.permission.READ_WRITE_DOCUMENTS_DIRECTORY"]);static EXCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.READ_DOCUMENT","ohos.permission.WRITE_DOCUMENT"]);static handleSpecificAclPermissions(){this.addAclWhiteList(this.INCLUDE_ACL_PERMISSIONS),this.addAclBlackList(this.EXCLUDE_ACL_PERMISSIONS)}static aclPermissionInfoMap=new Map;static aclPermissionNamesMap=new Map;static aclWhiteList=new Set;static aclBlackList=new Set;static builtInConfigTextLoader;static initAclPermission(e,t){let n=e.rootDir,o=this.getOrCreateSet(this.aclPermissionNamesMap,n),i=this.getOrCreateSet(this.aclPermissionInfoMap,n);o.clear(),i.clear();let s=Je.join(t.sdkPath,"default","sdk-pkg.json"),a=wc(s);this.MIN_API_TO_FIND_ACL_IN_SDK-a>0?this.initAclPermissionFromBuiltInConfig(o,i):this.initAclPermissionFromSDK(t,o,i)}static getAclPermissionInfos(e){return this.aclPermissionInfoMap.get(e.rootDir)??new Set}static getAclPermissionNames(e){return this.aclPermissionNamesMap.get(e.rootDir)??new Set}static addAclWhiteList(e){for(let t of e)this.aclWhiteList.add(t)}static addAclBlackList(e){for(let t of e)this.aclBlackList.add(t)}static getOrCreateSet(e,t){let n=e.get(t);return n||(n=new Set,e.set(t,n)),n}static readBuiltInConfigText(){if(this.builtInConfigTextLoader)return this.builtInConfigTextLoader();let e=Je.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(bo.existsSync(e))return bo.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=SO(e);if(t.includes("dist")){let s=Je.dirname(t),a=Je.dirname(s);return Je.join(a,"src","resources")}let n=Je.dirname(t),o=Je.dirname(n),i=Je.dirname(o);return Je.join(i,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let n;try{n=this.readBuiltInConfigText()}catch{So("read builtin acl permission failed.");return}if(n!==void 0)try{let o=JSON.parse(n),s=(Array.isArray(o)?o:bc(o)?Object.values(o):[]).filter(bc).map(a=>new Ec(a));s.forEach(a=>{let c=a.permissionInsteadName;bO(c)&&(a.permissionInsteadName=Sc(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(o){So(`failed to parse aclPermissionsInfo.json: ${o}`)}}static initAclPermissionFromSDK(e,t,n){let o=this.parsePermissionDefinitionFile(e);o&&o.forEach(i=>{if(!bc(i))return;let s=i,a=Zu(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(Gw(a)||(this.generateAclInfos(n,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||Zu(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||Zu(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:EO(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,n){let o=new Ec;o.permissionName=t;let i=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;o.permissionDisplayName=i;let s=CO(n,this.ACL_SINCE_KEY);o.minSupportApiLevel=String(s),this.handleInsteadName(o,i),e.add(o)}static parsePermissionDefinitionFile(e){let t=Je.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!bo.existsSync(t))return;let n;try{n=bo.readFileSync(t,"utf-8")}catch(s){So(`failed to load permissionDefinitions.json: ${s}`);return}let o;try{let s=JSON.parse(n);if(!bc(s)){So("json object is null");return}o=s}catch(s){So(`failed to parse permissionDefinitions.json: ${s}`);return}let i=o[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(i)){So("definePermissions is not an array");return}return i}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=Sc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=Sc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function Pc(r,e){let t=new Set,n=new Set;Hr.handleSpecificAclPermissions(),Hr.initAclPermission(r,e);for(let o of r.profile.modules){let i=qw(o,r,e,n,Cc.join("src","main"));for(let a of i)t.add(a);let s=qw(o,r,e,n,Cc.join("src","ohosTest"));for(let a of s)t.add(a)}return AO(n),t}function AO(r){if(r.size>0)throw new Error(Vw.DUPLICATE_PERMISSION)}function qw(r,e,t,n,o){let i=kO(e.rootDir,r,o);if(i==null)return new Set;let s=[];for(let y of i){if(typeof y!="object"||y===null)continue;let b=IO(y,"name");b&&s.push(b)}let a=new Set(s);a.size!==s.length&&n.add(r.name);let c=Cc.join(t.sdkPath,"default","sdk-pkg.json"),l=wc(c),d=Hr.getAclPermissionInfos(e),g=new Set(Array.from(d).filter(y=>{let b=Number(y.minSupportApiLevel);return Number.isFinite(b)&&b<=l}).map(y=>y.permissionName));for(let y of Array.from(a))g.has(y)||a.delete(y);return a}function IO(r,e){let t=r[e];return typeof t=="string"?t:""}function kO(r,e,t){let n=Cc.join(r,e.srcPath,t,"module.json5"),o=DO(n);if(o==null)return null;let i=TO(o,"module");return i==null?null:RO(i,"requestPermissions")}function DO(r){try{if(!zw.existsSync(r))return null;let e=zw.readFileSync(r,"utf-8");return PO.parse(e)}catch{return null}}function TO(r,e){if(r==null||typeof r!="object")return null;let t=r[e];return t!=null&&typeof t=="object"&&!Array.isArray(t)?t:null}function RO(r,e){if(r==null||typeof r!="object")return null;let t=r[e];return Array.isArray(t)?t:null}var ep=class{verifyStorePassword(e,t){try{let n=Br.readFileSync(e),o=Yw.asn1.fromDer(n.toString("binary"));return Yw.pkcs12.pkcs12FromAsn1(o,t),!0}catch{return!1}}getLocalCerFingerprints(e){let n=Br.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(n&&n.length>0)return n.map(o=>this.formatFp(new Ac.X509Certificate(o).fingerprint256));try{return[this.formatFp(new Ac.X509Certificate(Br.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let o=Br.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let i of o)try{let s=new Ac.X509Certificate(i);if(this.formatFp(s.fingerprint256)===t){let a=new Date(s.validTo);return isNaN(a.getTime())?null:a}}catch{}return null}formatFp(e){let t=e.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}};function LO(r){let e=Br.readFileSync(r,"utf-8"),t=NO(e),n=null;if(t)try{n=JSON.parse(t)}catch{n=null}let o=n?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:Qu(o["bundle-name"]),expiryDate:OO(n?.validity?.["not-after"]),cerFingerprintInProfile:MO(Qu(o["development-certificate"])),deviceUdidsInProfile:_O(n?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:FO(n?.acls?.["allowed-acls"]),teamIdInProfile:Qu(o["developer-id"])}}function NO(r){let e=r.indexOf("{");if(e<0)return null;let t=0,n=-1,o=!1,i=!1;for(let s=e;s<r.length;s++){let a=r[s];if(o){i?i=!1:a==="\\"?i=!0:a==='"'&&(o=!1);continue}if(a==='"')o=!0;else if(a==="{")t++;else if(a==="}"&&(t--,t===0)){n=s;break}}return n<0?null:r.slice(e,n+1)}function OO(r){if(typeof r!="number"||!Number.isFinite(r))return null;let e=new Date(r*1e3);return isNaN(e.getTime())?null:e}function MO(r){if(!r)return null;try{let t=new Ac.X509Certificate(r).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function _O(r){if(!Array.isArray(r))return[];let e=[];for(let t of r)if(typeof t=="string"){let n=t.toUpperCase();e.includes(n)||e.push(n)}return e}function FO(r){if(!Array.isArray(r))return[];let e=[];for(let t of r)typeof t=="string"?e.push(t):t&&typeof t=="object"&&typeof t.name=="string"&&e.push(t.name);return[...new Set(e)].sort()}function Qu(r){return typeof r=="string"?r:null}var Ji=class r{static async shouldRegenerate(e,t){let n=await r.#e(e,t);return r.#t(n)??r.#r(n)??r.#n(n)??r.#o(n)??r.#i(n)??r.#s(n)??r.#a(n)??r.#c(n)??r.#l(n)??r.#d(n)??await r.#u(n)??r.#p()}static async#e(e,t){let n=e.force,o=e.teamId,i=e.productName??"default",s=V.discover(process.cwd()),a=s.rootDir,[c,l]=await Promise.all([jO(i,a),HO(t.hdcPath)]),d=null;if(Kw(c).allExist)try{d=LO(c.profileFile)}catch{}return{force:n,teamId:o,productName:i,projectPath:a,materialPaths:c,bundleName:s.getBundleName(i),deviceUdids:l,storePassword:await $O(a,i,c.storeFile),localAclPermissions:[...Pc(s,t)].sort(),hapSignTool:new ep,profileInfo:d}}static#t(e){return e.force?(m("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:et({force:!0})}):null}static#r(e){let t=Kw(e.materialPaths);return t.allExist?null:(m(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:et({allFilesExist:!1,missingFiles:t.missing})})}static#n(e){return(e.profileInfo?.rawContent??"").trim().length>0?null:(m("[reGenerateSign] profile content is empty"),{shouldRegenerate:!0,reason:"Profile file content is empty",checkDetails:et({allFilesExist:!0,profileContentNotEmpty:!1})})}static#o(e){let t=e.profileInfo?.expiryDate;return!t||t>=new Date?null:(m(`[reGenerateSign] profile expired at ${t.toISOString()}`),{shouldRegenerate:!0,reason:`Profile expired at ${t.toISOString()}`,checkDetails:et({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#i(e){let t=e.profileInfo?.bundleNameInProfile;return t&&t===e.bundleName?null:(m(`[reGenerateSign] bundleName mismatch \u2014 current=${e.bundleName}, profile=${t}`),{shouldRegenerate:!0,reason:`bundleName mismatch: current=${e.bundleName}, in profile=${t}`,checkDetails:et({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!1})})}static#s(e){let t=e.profileInfo?.teamIdInProfile;return t&&t===e.teamId?null:(m(`[reGenerateSign] teamId mismatch \u2014 current=${e.teamId}, profile=${t}`),{shouldRegenerate:!0,reason:`teamId mismatch: current=${e.teamId}, in profile=${t}`,checkDetails:et({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=UO(e.profileInfo?.deviceUdidsInProfile??[],e.deviceUdids);return t.allPresent?null:(m(`[reGenerateSign] missing device UDIDs: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Device UDID(s) not in profile: ${t.missing.join(", ")}`,checkDetails:et({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return WO(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(m("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:et({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!1})})}static#l(e){let t=e.hapSignTool.getLocalCerFingerprints(e.materialPaths.cerFile),n=e.profileInfo?.cerFingerprintInProfile;return n&&t.includes(n)?null:(m("[reGenerateSign] certificate mismatch"),{shouldRegenerate:!0,reason:"Certificate mismatch between profile and local .cer file",checkDetails:et({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!1})})}static#d(e){let t=e.profileInfo?.cerFingerprintInProfile,n=e.hapSignTool.getLocalCerExpiry(e.materialPaths.cerFile,t);return!n||n>=new Date?null:(m(`[reGenerateSign] local certificate expired at ${n.toISOString()}`),{shouldRegenerate:!0,reason:`Local certificate expired at ${n.toISOString()}`,checkDetails:et({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!1})})}static async#u(e){return e.storePassword?e.hapSignTool.verifyStorePassword(e.materialPaths.storeFile,e.storePassword)?null:(m("[reGenerateSign] keystore password verification failed"),{shouldRegenerate:!0,reason:"Keystore password verification failed (storeFile may be corrupted or password changed)",checkDetails:et({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})}):(m("[reGenerateSign] no stored keystore password"),{shouldRegenerate:!0,reason:"No stored keystore password available for verification",checkDetails:et({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})})}static#p(){return m("[reGenerateSign] all checks passed \u2014 skip regeneration"),{shouldRegenerate:!1,reason:"",checkDetails:et({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function jO(r,e){let[t,n,o,i]=await Promise.all([De(r,e,"p12"),De(r,e,"csr"),De(r,e,"cer"),De(r,e,"p7b")]);return{storeFile:t,csrFile:n,cerFile:o,profileFile:i}}async function $O(r,e,t){let n=Xw.join(r,"build-profile.json5");if(!Br.existsSync(n))return;let o;try{o=xO.parse(Br.readFileSync(n,"utf-8"))}catch{return}let a=(o?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await $r.decryptPassword(a,t)}catch{return}}async function HO(r){m(`Executing: ${r} list targets`);let{stdout:e}=await Jw(r,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let o of e.split(`
1416
- `)){let i=o.trim();if(!i||i.startsWith("[Empty]"))continue;let s=i.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let n=[];for(let o of t)try{m(`Executing: ${r} -t ${o} shell bm get -u`);let{stdout:i}=await Jw(r,["-t",o,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),s=BO(i);s&&n.push(s)}catch{m(`[reGenerateSign] Failed to get UDID for ${o}, skipping`)}return n}function BO(r){let e=r.trim();if(!e)return null;let t=e.split(`
1417
- `);for(let o=0;o<t.length-1;o++)if(t[o].includes("udid of current device is")){let s=t[o+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(s)return s[0].toUpperCase()}let n=e.match(/[A-Fa-f0-9]{64}/);return n?n[0].toUpperCase():null}function Kw(r){let e=[r.storeFile,r.csrFile,r.cerFile,r.profileFile],t=[];for(let n of e)Br.existsSync(n)||t.push(n);return{allExist:t.length===0,missing:t}}function UO(r,e){let t=[];for(let n of e)r.includes(n)||t.push(n);return{allPresent:t.length===0,missing:t}}function WO(r,e){let t=[...r].sort(),n=[...e].sort();return t.length!==n.length?!1:t.every((o,i)=>o===n[i])}function et(r){let e={force:!1,allFilesExist:!1,missingFiles:[],profileContentNotEmpty:!1,profileNotExpired:!1,bundleNameMatched:!1,teamIdMatched:!1,allDevicesInProfile:!1,missingDeviceUdids:[],aclMatched:!1,cerMatched:!1,cerNotExpired:!1,storePasswordValid:!1};return r.force?{...e,force:!0}:{...e,...r,force:!1}}import{debuglog as tp}from"util";import{execa as rp}from"execa";async function Qw(r,e){let t=await Ic(r);if(!t)throw new Error(C.DEVICE_LIST_EMPTY);let n=await zO(e);if(t.length===0)for(let s of n)await VO(r,s.udid,s.deviceName);else for(let s of n)await GO(r,t,s.udid,s.deviceName);let i=(await Ic(r)).map(s=>s.id);if(i.length===0)throw new Error(C.DEVICE_LIST_EMPTY);return i}async function VO(r,e,t){await rS(r,e,eS(t))}async function GO(r,e,t,n){for(let o=0;o<e.length;o++){if(t===e[o].udid)return;if(o===e.length-1){await rS(r,t,eS(n));return}}}function eS(r){switch(r){case"liteWearable":return"1";case"wearable":return"2";case"tv":return"3";default:return"4"}}async function Zw(r,e=1,t=100){let n=`${le.BASE_URL}${le.DEVICE_LIST_PATH}?encodeFlag=0&start=${e}&pageSize=${t}`,o=nS(r),i=await L.get(n,{headers:o});if(!i)throw tp("query devices failed: response is null"),new Error(C.ERROR_WHILE_ADD_DEVICE);if(i.statusCode!==200)throw tS(i.statusCode,i.statusText,i.data);let s=JSON.parse(i.data);if(!s||!s.list)throw tp("query devices failed: response list is null"),new Error(s.ret?.msg||C.ERROR_WHILE_ADD_DEVICE);return{deviceList:s.list,total:s.totalCount||0}}function tS(r,e,t){return r===bt.FORBIDDEN?e===be.OPENPROXY_BLOCKED_URL?new Error(C.ERR_CERT_NETWORK_ERROR):new Error(C.ERR_FORBIDDEN):r===bt.UNAUTHORIZED?new Error(C.ERR_UNAUTHORIZED):t.includes(be.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(C.DEVICE_LIMIT_REACHED):new Error(C.ERROR_WHILE_ADD_DEVICE)}async function Ic(r){let t=await Zw(r,1,100);if(!t||!t.deviceList||t.deviceList.length===0)return[];let n=[...t.deviceList],o=t.total,i=Math.floor(o/100)+(o%100===0?0:1);for(let s=2;s<=i;s++){let a=await Zw(r,s,100);if(!a||!a.deviceList||a.deviceList.length===0)break;n.push(...a.deviceList)}return n}async function rS(r,e,t){let n=`${le.BASE_URL}${le.DEVICE_ADD_PATH}`,o=nS(r),s={deviceName:`auto_sign_device_No.${Math.floor(Math.random()*3e3)}${Date.now()}`,udid:e,deviceType:t},a=await L.postAllowFailure(n,{headers:o,params:s});if(!a)throw tp("add device failed: response is null"),new Error(C.ERROR_WHILE_ADD_DEVICE);if(a.statusCode!==200)throw tS(a.statusCode,a.statusText,a.data);let c=a.data,l=JSON.parse(a.data);if(!l||!l.ret||l.ret.code!==0)throw c.includes(be.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(C.DEVICE_LIMIT_REACHED):c.includes(be.DEVICE_NAME_REPEAT_CODE)?new Error(C.DEVICE_NAME_REPEAT):new Error(C.ERROR_WHILE_ADD_DEVICE)}function nS(r){return{uid:r.uid,teamId:r.teamId,oauth2Token:r.accessToken}}async function zO(r){let{stdout:e}=await rp(r,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let o of e.split(`
1418
- `)){let i=o.trim();if(!i||i.startsWith("[Empty]"))continue;let s=i.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let n=[];for(let o of t)try{let i=await qO(o,r),s=await JO(o,r);i.length>0&&n.push({id:"",udid:i,deviceName:s})}catch{m(`Failed to get device info for ${o}, skipping`)}return n}async function qO(r,e){let{stdout:t}=await rp(e,["-t",r,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),n=t.trim();if(!n)return"";let o=n.split(`
1419
- `);for(let s=0;s<o.length-1;s++)if(o[s].includes("udid of current device is")){let c=o[s+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(c)return c[0].toUpperCase()}let i=n.match(/[A-Fa-f0-9]{64}/);return i?i[0].toUpperCase():""}async function JO(r,e){let{stdout:t}=await rp(e,["-c","-t",r,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return YO(t)}function YO(r){let e=r.trim();return!e||e.includes("inaccessible")?"phone":r.includes("liteWearable")?"liteWearable":r.includes("wearable")?"wearable":r.includes("tv")?"tv":"phone"}import vn from"fs";import{createHash as KO}from"crypto";import{debuglog as tr}from"util";import{Buffer as iS}from"buffer";import{createPublicKey as XO,X509Certificate as np}from"crypto";import{readFileSync as ZO}from"fs";import wn from"node-forge";async function sS(r,e){console.log("Start generating profile");let{productName:t,bundleName:n,projectPath:o,aclPermissionList:i,allDeviceIds:s,certIds:a,keyAlias:c,keyPwd:l}=e;if(s==null||s.length===0)throw new Error(C.DEVICE_LIST_EMPTY);let d=`${le.BASE_URL}${le.PROVISION_ADD_TEST_PATH}`,g=QO(t,n),y=await tM(r,d,a||[],n,s,g,i||[]);if(!y||!y.profileInfo||!y.profileInfo.provisionFileUrl)throw tr("add provision failed, the provision file url is null"),new Error(C.ADD_PROFILE_FAIL);let b=y.profileInfo,$=(await iM(r,b.provisionFileUrl)).urlList,me=y.profileInfo.id;if($&&$.length>0){let Te=await _w(t,o),Pt=Te.profilePath;if(!await sM($,Pt))throw await oS(r,me),new Error(C.ERROR_WHILE_DOWNLOAD_PROFILE);if(await oS(r,me),vn.existsSync(Te.certPath)&&vn.existsSync(Pt)&&vn.existsSync(Te.p12Path)){let Nc=vn.readFileSync(Te.certPath,"utf8"),Oc=vn.readFileSync(Pt,"utf8");return aM(Oc,Nc,Te.p12Path,c,l)||oM(Pt),Pt}}throw new Error(C.ADD_PROFILE_FAIL)}function QO(r,e){let t=r?`${r}_`:"";return`${eM(`${t}${e}_${e}`)}`}function eM(r){return KO("sha256").update(r).digest("hex").substring(0,16)}async function tM(r,e,t,n,o,i,s){rM(n);let a=ip(r),c={certList:t,packageName:n,deviceList:o,provisionName:i};s.length&&(c.aclPermissionList=s);let l=await L.postAllowFailure(e,{headers:a,params:c});if(!l)throw tr("add provision failed: response is null"),new Error(C.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw op(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw tr(`add provision fail: ${l.data}`),nM(l.data,i),new Error(d.ret?.msg||C.ADD_PROFILE_FAIL);let g=d.provisionFileUrl;return{profileInfo:{id:d.id,name:i,provisionFileUrl:g}}}function op(r,e,t){return r===bt.FORBIDDEN?e===be.OPENPROXY_BLOCKED_URL?new Error(C.ERR_CERT_NETWORK_ERROR):new Error(C.ERR_FORBIDDEN):r===bt.UNAUTHORIZED?new Error(C.ERR_UNAUTHORIZED):t.includes(be.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(C.TEST_PROVISION_EXCEEDS_LIMIT):new Error(C.ADD_PROFILE_FAIL)}function rM(r){if(!r||r.trim().length===0)throw new Error(C.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!qe.BUNDLE_NAME_REGEX.test(r))throw new Error(C.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function nM(r,e){if(r.includes(be.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(C.TEST_PROVISION_EXCEEDS_LIMIT);if(r.includes(be.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(C.PROFILE_NAME_REPEAT)}async function oS(r,e){if(!e||e.trim().length===0)return;let t=`${le.BASE_URL}${le.PROVISION_DELETE_PATH}?id=${e}`,n=await L.deleteAllowFailure(t,{headers:ip(r)});if(n.statusCode!==200)throw op(n.statusCode,n.statusText,n.data);let o=JSON.parse(n.data);(!o||!o.ret||o.ret.code!==0)&&tr(`delete provision failed: ${n.data}`)}function oM(...r){for(let e of r)try{vn.existsSync(e)&&vn.unlinkSync(e)}catch(t){tr(`delete local sign file error: ${t.message}`)}}async function iM(r,e){let t=`${le.BASE_URL}${le.CERT_DOWNLOAD_URL_PATH}`,n=ip(r),o={sourceUrls:e},i=await L.postAllowFailure(t,{headers:n,params:o});if(!i)throw tr("get download list failed: response is null"),new Error(C.ADD_PROFILE_FAIL);if(i.statusCode!==200)throw op(i.statusCode,i.statusText,i.data);let s=JSON.parse(i.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw tr("download: The application does not exist"),new Error(s.ret?.msg||C.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function sM(r,e){if(!r||r.length===0)return!1;let t=r[0];return await Gi(t.newUrl,e,t.sha256),!0}function aM(r,e,t,n,o){return cM(r,e),n=n||qe.TARGET_FRIENDLY_NAME,o=o||"",lM(e,t,n,o),!0}function cM(r,e){if(e.lastIndexOf(qe.CERT_BEGIN_HEADER)<0)throw new Error(C.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(qe.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!r.includes(t))throw new Error(C.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function lM(r,e,t,n){let o=r.matchAll(qe.CERTIFICATE_PATTERN_GLOBAL),i=[],s=new Date;for(let c of o)try{let l=c[0],d=dM(l),g=new Date(d.validFrom),y=new Date(d.validTo);if(s<g||s>y){let b=`Certificate is not valid, Valid from ${g} to ${y}`;throw console.warn(`checkCertificateInValidityPeriod: ${b}`),new Error(C.CERTIFICATE_HAS_EXPIRED)}i.push(d)}catch(l){throw console.warn(`checkCertificateInValidityPeriod\uFF1A ${l.message}`),new Error(C.CERTIFICATE_HAS_EXPIRED,{cause:l})}if(!i||i.length===0)throw new Error(C.CERTIFICATE_HAS_EXPIRED);if(!pM(e,t,n,i))throw new Error(C.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function dM(r){let e="-----BEGIN CERTIFICATE-----",t=r.trim();try{if(t.startsWith(e))return new np(t);let n=iS.from(t,"base64");return new np(n)}catch(n){throw new Error("decodeBase64ToX509Certificate",{cause:n})}}function uM(r){if(r.cert){let e=wn.pki.publicKeyToPem(r.cert.publicKey);return XO(e).export({type:"spki",format:"der"})}if(r.asn1)try{let e=wn.asn1.toDer(r.asn1).getBytes(),t=iS.from(e,"binary");return new np(t).publicKey.export({type:"spki",format:"der"})}catch(e){return tr(`Failed to parse cert from asn1: ${e}`),null}return null}function pM(r,e,t,n){try{let o=ZO(r),i=wn.asn1.fromDer(wn.util.createBuffer(o)),c=wn.pkcs12.pkcs12FromAsn1(i,t).getBags({bagType:wn.pki.oids.certBag})[wn.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let g=uM(l);if(!g)continue;if(n.some(b=>{let N=b.publicKey.export({type:"spki",format:"der"});return g.equals(N)}))return!0}return!1}catch(o){let i=o instanceof Error?o.message:String(o);return tr(`Failed to process P12 file: ${r}, error: ${i}`),!1}}function ip(r){return{uid:r.uid,teamId:r.teamId,oauth2Token:r.accessToken}}var cS="https://developer.huawei.com",mM={"ohos.permission.SYSTEM_FLOAT_WINDOW":"/consumer/cn/doc/harmonyos-guides/window-pipwindow","ohos.permission.READ_CONTACTS":"/consumer/cn/doc/harmonyos-references/js-apis-contact#contactselectcontacts10","ohos.permission.READ_IMAGEVIDEO":"/consumer/cn/doc/harmonyos-guides/select-user-file#%E9%80%89%E6%8B%A9%E5%9B%BE%E7%89%87%E6%88%96%E8%A7%86%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.WRITE_IMAGEVIDEO":"/consumer/cn/doc/harmonyos-guides/savebutton","ohos.permission.READ_AUDIO":"/consumer/cn/doc/harmonyos-guides/select-user-file#%E9%80%89%E6%8B%A9%E9%9F%B3%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.WRITE_AUDIO":"/consumer/cn/doc/harmonyos-guides/save-user-file#%E4%BF%9D%E5%AD%98%E9%9F%B3%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.READ_PASTEBOARD":"/consumer/cn/doc/harmonyos-guides/pastebutton"},fM="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function hM(r){let e=mM[r];return e?`${cS}${e}`:void 0}function gM(){return`${cS}${fM}`}var yM={"acl.can.apply.text":"Permission Application Scenarios","acl.permissions.warn":"Note: You are applying for restricted ACL permissions: {0} These permissions are subject to review together with your app release. For a faster review process, apply for the following permissions instead, if they are sufficient for your purposes: {1} {2}"};function aS(r,e){return(yM[r]??r).replace(/\{(\d+)\}/g,(n,o)=>String(e[Number(o)]??""))}function vM(r){return Array.from(r).join(", ")}function lS(r,e){if(r.size===0)return;let t=Hr.getAclPermissionInfos(e),n=new Set;for(let g of t)r.has(g.permissionName)&&n.add(g);for(let g of n){let y=hM(g.permissionName);y!=null&&(g.permissionHelpUrlKey=y)}let o=new Set;for(let g of n)o.add(g.permissionDisplayName);let i=new Set;for(let g of n)if(g.permissionHelpUrlKey!=null){let y=g.permissionInsteadName??g.permissionDisplayName;i.add(`${y} (${g.permissionHelpUrlKey})`)}let s=gM(),a=aS("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=i.size>0?Array.from(i).join(", ")+".":"",d=aS("acl.permissions.warn",[vM(o),l,c]);console.log(d)}var kc=class{_project=null;get project(){if(!this._project)throw new Error("Project not initialized. Call checkProjectDir first.");return this._project}checkProjectDir(e){try{return this._project=V.discover(process.cwd()),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Project.discover() failed: ${t.message}`),e(pe.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(n){return m(`[EnvCheck] Product validation failed: ${n.message}`),t(`Product "${e}" not found.Check the product property in the build-profile.json5 file.`)}}checkBundleName(e,t){try{return this._project.getBundleName(),{passed:!0,message:""}}catch(n){return m(`[EnvCheck] BundleName check failed: ${n.message}`),t(`bundleName was not found under product "${e}".Check the bundleName configuration.`)}}checkAtomicService(){return this._project.isAtomicService()?{passed:!1,message:pe.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import wM from"fs";import dS from"path";var Dc=class{constructor(e){this.toolProvider=e}checkJava(e){try{return this.toolProvider.assertJava(),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Java check failed: ${t.message}`),e(`${t.message}`)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,n=dS.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");if(!wM.existsSync(n)){let o=dS.join("sdk","default","openharmony","toolchains","lib","hap_sign_tools.jar");return e(`hap_sign_tools.jar not found.Check whether ${o} exists.`)}return{passed:!0,message:""}}};var Tc=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await Me.getUserInfo()}catch(e){return m(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await Me.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(pe.LOGIN_REQUIRED)}catch(t){return m(`[EnvCheck] Login check failed: ${t.message}`),e(pe.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(pe.TEAM_INFO_FAILED);try{if((await gr()).teamList.length>0)return{passed:!0,message:""}}catch(n){return m(`[EnvCheck] Team API error: ${n.message}`),e(pe.TEAM_INFO_FAILED)}return m("[EnvCheck] No teams found for current user"),e(pe.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(pe.REALNAME_REQUIRED):t.isRealName!==!0?(m("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(pe.REALNAME_REQUIRED)):{passed:!0,message:""}:e(pe.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let n=e??"";try{let o=await gr();if(n=e??(o.teamList.length>0?o.teamList[0].id:t.userId)??"",!o.teamList.some(s=>s.id===n)){let s=`team-id for ${n} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`;return m(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(o){return m(`[EnvCheck] Team ID check failed: ${o.message}`),{passed:!1,message:`team-id for ${n} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`}}}async checkRegion(e){let t=await this.ensureUserInfo();return t?t.countryCode?t.countryCode!=="CN"?e(pe.REGION_CHINA_ONLY):{passed:!0,message:""}:(m("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(pe.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function SM(r){try{let{teamList:e}=await gr();if(e.length>0)return e[0].id}catch(e){m(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return r??""}async function bM(r){let e=await Me.getUserInfo(),t=await Me.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let n=r||await SM(e.userId);if(!n)throw new Error("No team found");let o={uid:e.userId??"",teamId:n,accessToken:t.accessToken};return(await Ic(o)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var Rc=class{constructor(e){this.toolProvider=e}async checkDevice(e,t){try{let n=await bM(t);if(n.length>0)return m(`[EnvCheck] Scenario 4 Device check: ${n.length} device(s) found in AGC cloud, skipping local device check`),{passed:!0,message:""};m("[EnvCheck] Scenario 4 Device check: no cloud devices found, falling back to local hdc");let i=await ue.from(this.toolProvider).listDevices();return i.length===0?(m("[EnvCheck] Scenario 4 Device check: no local devices found"),e(pe.DEVICE_MISSING)):i.some(a=>Rt(a.serial))?{passed:!0,message:""}:(m("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(pe.DEVICE_MISSING))}catch(n){return m(`[EnvCheck] Scenario 4 Device check failed: ${n.message}`),e(pe.DEVICE_DETECT_FAILED)}}};var xc=class{projectChecker=new kc;toolchainChecker=null;authChecker=new Tc;deviceChecker=null;constructor(){}async preflight(e){let t=n=>this.blockingFail(n);return!(!await this.runAuthChain(e,t)||!await this.initToolchain()||!await this.runDeviceCheck(e,t)||!await this.runProjectChecks(e,t)||!await this.runAuxChecks(e))}async runAuthChain(e,t){let n=i=>(i.passed||this.fail(i),!0),o=[()=>this.authChecker.checkLogin(t),()=>this.authChecker.checkRealname(t),()=>this.authChecker.checkTeamInfo(t)];for(let i of o)if(!n(await i()))return!1;return!(e.teamId&&!n(await this.authChecker.checkTeamId(e.teamId)))}async initToolchain(){try{let e=await k.new();return this.toolchainChecker=new Dc(e),this.deviceChecker=new Rc(e),!0}catch(e){throw m(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(pe.TOOLCHAIN_INIT_FAILED,{cause:e})}}async runDeviceCheck(e,t){return(o=>o.passed?!0:(this.fail(o),!1))(await this.deviceChecker.checkDevice(t,e.teamId))}async runProjectChecks(e,t){let n=i=>i.passed?!0:(this.fail(i),!1);if(!n(this.projectChecker.checkProjectDir(t))||!n(this.projectChecker.checkAtomicService()))return!1;let o=[()=>this.projectChecker.checkProduct(e.productName,t),()=>this.projectChecker.checkBundleName(e.productName,t),()=>this.toolchainChecker.checkJava(t),()=>this.toolchainChecker.checkHapSignTools(t)];for(let i of o)if(!n(i()))return!1;return!0}async runAuxChecks(e){let t=n=>n.passed?!0:(this.fail(n),!1);return!e.teamId&&!t(await this.authChecker.checkTeamId(e.teamId))?!1:(await this.authChecker.checkRegion(n=>this.blockingFail(n)),!0)}blockingFail(e){return{passed:!1,message:e}}fail(e){throw m(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};var uS=5*1024*1024;function PM(r){try{let e=ap.statSync(r);if(e.size>uS)throw new Error(`Profile file too large: ${e.size} bytes (max ${uS} bytes): ${r}`);let t=ap.readFileSync(r,"utf-8");return mS.parse(t)}catch(e){if(e.code==="ENOENT")return{app:{signingConfigs:[],products:[]}};throw new Error(`Failed to read profile: ${r}`,{cause:e})}}function AM(r){r.app||(r.app={signingConfigs:[],products:[]}),r.app.signingConfigs||(r.app.signingConfigs=[]),r.app.products||(r.app.products=[])}async function IM(r){if(r.keyPwd===r.storePassword){let n=await $r.encryptedPassword(r.keyPwd,r.p12FilePath);return{keyPassword:n,storePassword:n}}let e=await $r.encryptedPassword(r.keyPwd,r.p12FilePath),t=await $r.encryptedPassword(r.storePassword,r.p12FilePath);return{keyPassword:e,storePassword:t}}async function kM(r,e,t){let n=pS.join(r,"build-profile.json5"),o=PM(n);AM(o);let i=t??"default",{keyPassword:s,storePassword:a}=await IM(e),c={name:i,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:Et.signAlg,storeFile:e.p12FilePath,storePassword:a}},l=o.app?.signingConfigs?.findIndex(g=>g.name===i);l!==void 0&&l>=0?o.app.signingConfigs[l]=c:o.app.signingConfigs.push(c);let d=o.app?.products?.findIndex(g=>g.name===i);d!==void 0&&d>=0?o.app.products[d].signingConfig=i:o.app.products.push({name:i,signingConfig:i}),ap.writeFileSync(n,mS.stringify(o,null,2),"utf-8")}async function DM(r){let e=await Me.getUserInfo(),t=await Me.refreshToken();if(!e||!t)throw new Error("Failed to obtain login credentials. Run `devecocli auth login` again.");return{uid:e.userId??"",teamId:r.teamId??e.userId??"",accessToken:t.accessToken??""}}async function TM(r){let e=r.product||"default";await new xc().preflight({productName:e,teamId:r.teamId}),console.log("Executing signature generate command");let n=await DM(r),o=await k.new(),{shouldRegenerate:i}=await Ji.shouldRegenerate({force:r.force??!1,teamId:n.teamId,productName:r.product},o);if(!i){console.log(sp("Signature generation completed successfully."));return}await RM(r,n,o),console.log(sp("Signature generation completed successfully."))}async function RM(r,e,t){let n=await qu(e,r.product),o=xM(r,e,n,t);o.allDeviceIds=await Qw(e,t.hdcPath),await sS(e,o);let i=V.discover(process.cwd()).rootDir;await kM(i,n,r.product??"default"),console.log(sp(`Signing config written to ${pS.join(i,"build-profile.json5")}`))}function xM(r,e,t,n){let o=process.cwd(),i=V.discover(o),s=Pc(i,n);return lS(s,i),{productName:r.product||"default",bundleName:i.getBundleName(r.product||"default"),projectPath:i.rootDir,teamId:e.teamId,force:r.force||!1,aclPermissionList:[...s],certIds:[t.certId],keyAlias:t.keyAlias,keyPwd:t.keyPwd}}var fS=new EM("signature").description("Generate application signature.");fS.command("generate").description("Automatically generate signing materials and write them to the project configuration.").option("--force","Force overwrite existing local signing materials.").option("--team-id <team-id>","Specify the team ID to use.").option("--product <product>","Specify the product. The default value is default.").action(async r=>{let e={event:S.CommandExecuted,args:["signature","generate",...r.force?["--force"]:[],...r.teamId?["--team-id"]:[],...r.product?["--product"]:[]]},t=Date.now(),n=!0,o=null;try{await TM(r)}catch(i){n=!1,o=q(i),console.error(CM(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:n,error_code:o};await I.track(e,i)}});var hS=fS;if(!At())try{I.init(Lc.join(ct(),"TraceLogData")),I.startScheduler()}catch(r){h.error(`[telemetry] init failed: ${r instanceof Error?r.message:String(r)}`)}(async()=>{if(!At())try{let r=await k.new();I.setSourceType(r.sourceType);let e=await k.getCltVersion();e&&I.setCltVersion(e);let t=await k.getStudioVersion();t&&I.setStudioVersion(t)}catch(r){h.error(`[telemetry] toolchain info failed: ${r instanceof Error?r.message:String(r)}`)}})();de.name("devecocli").description(`HarmonyOS application development command line tool
1374
+ `),console.log(Ie("[compat:check] === end stdout ===")));let o=new me("errorCode",`Compatibility scan failed: ${i.message}`+(i.stderr?`
1375
+ ${i.stderr}`:""));throw i.stdout&&(o.stdout=i.stdout),o}}function OF(n,e){if(!gF.includes(e.format))throw new dF(`--format must be default, csv, or json (console: default|json, file: default|csv|json). got "${e.format}"`);if(n.length>0&&e.modules&&e.modules.length>0)throw new me("errorCode","Cannot use `--modules` together with file arguments. Use either file-level scanning (with files) or module-level scanning (with --modules).");if(!e.sourceVersion)throw new me("errorCode","--source-version is required.");if(!e.targetVersion)throw new me("errorCode","--target-version is required.");if(!e.outputPath&&e.format==="csv")throw new me("errorCode","--format csv requires --output-path. For console output, use --format json or --format default (or omit the flag).")}function MF(n,e){let t=[];if(n.sourceVersion&&!e.includes(n.sourceVersion)&&t.push(`--source-version "${n.sourceVersion}"`),n.targetVersion&&!e.includes(n.targetVersion)&&t.push(`--target-version "${n.targetVersion}"`),t.length>0){let r=t.length>1?"are":"is";throw new me("errorCode",`${t.join(" and ")} ${r} not in the available SDK version list.
1376
+ Run \`devecocli compat versions\` to see all available versions.`)}if(n.sourceVersion&&n.targetVersion){let r=e.indexOf(n.sourceVersion),i=e.indexOf(n.targetVersion);if(r>=i)throw new me("errorCode",`--target-version "${n.targetVersion}" must be later than --source-version "${n.sourceVersion}". Run \`devecocli compat versions\` to see the available order.`)}}function NF(n,e,t,r,i){i==="none"&&(t==="json"?xF(n,r):DF(n,r)),RF(n,e)}function LF(n,e){let t=ne.dirname(n),r=ne.basename(n),i=e.slice(1).map(o=>o.startsWith("--")?o:`"${o}"`).join(" ");m(Ie(`[compat:check] command: cd "${t}" && node "${r}" ${i}`))}function _F(n){try{mF(n),m(Ie(`[compat:check] cleaned up tmp report: "${n}"`))}catch(e){m(Ie(`[compat:check] failed to clean up tmp report: ${e.message}`))}}var $F=[".csv",".json"];function FF(n){return $F.includes(n.toLowerCase())}function jF(n,e){if(!n)return{kind:"none"};let t=ne.extname(n).toLowerCase();if(!FF(t))return{kind:"dir",dirPath:ne.resolve(n)};if(t===".csv"&&!(e==="default"||e==="csv")||t===".json"&&e!=="json")throw new me("errorCode",`The --output-path file extension '${t}' does not match --format ${e}. Use --format ${t===".json"?"json":"default"}, or rename the file.`);return{kind:"file",filePath:ne.resolve(n),ext:t}}function HF(n){if(n.kind==="file"){if(yd(n.filePath))throw new me("errorCode",`Target file "${n.filePath}" already exists. Remove it first, or choose a different --output-path.`);let e=ne.dirname(n.filePath);if(!yd(e))throw new me("errorCode",`Target directory "${e}" does not exist. Create it first, or choose a different --output-path.`)}else if(n.kind==="dir"&&!yd(n.dirPath))throw new me("errorCode",`Target directory "${n.dirPath}" does not exist. Create it first, or choose a different --output-path.`)}function JE(n){return JSON.stringify({records:n,count:n.length},null,2)+`
1377
+ `}function UF(n,e,t,r){r===".csv"?WE(n,t):VE(t,JE(e),"utf8"),m(Ie(`[compat:check] saved report: "${t}"`))}function BF(n,e,t,r){if(r==="json"){let o=ne.basename(n,".csv"),s=ne.join(t,`${o}.json`);return VE(s,JE(e),"utf8"),m(Ie(`[compat:check] saved report: "${s}"`)),s}let i=ne.join(t,ne.basename(n));return WE(n,i),m(Ie(`[compat:check] saved report: "${i}"`)),i}async function WF(n,e){let t=new dt(n,process.cwd(),!0),r=e.modules&&e.modules.length>0?e.modules[0]:void 0;try{await t.compileNative("default",r)}catch(i){throw new me("errorCode",`hvigorw compileNative failed (module=${r??"<project>"}): `+i.message,{cause:i})}}async function VF(n,e){OF(n,e);let t=B.discover(process.cwd());e.modules&&e.modules.length>0&&wF(t,e.modules),n.length>0&&vF(n);let r=await P.new(),{apiChangeDir:i,scriptPath:o}=r.getApiscanPaths();m(Ie(`[compat:check] script: "${o}"`));let s=qE(i);MF(e,s),e.outputPath&&m(Ie(`[compat:check] outputPath: "${e.outputPath}"`));let a=jF(e.outputPath,e.format);return m(Ie(`[compat:check] outputTarget: ${a.kind}`)),HF(a),{project:t,scriptPath:o,target:a,toolProvider:r}}function GF(n,e,t,r){if(t.kind==="file")return UF(n,e,t.filePath,t.ext),t.filePath;if(t.kind==="dir")return BF(n,e,t.dirPath,r);if(t.kind==="none")return null;throw new me("errorCode",`Unexpected output target kind: ${t.kind}`)}async function qF(n,e,t,r,i){let o=hF({text:"Running compatibility check...",color:"cyan"}).start();try{await WF(n.toolProvider,t);let s=IF(n.scriptPath,e,n.project,t);LF(n.scriptPath,s);let a=await TF(n.toolProvider,s),c=kF(a,Sf.tmpdir());if(!c)throw new me("errorCode","Scanner output format unexpected: missing report path.");m(Ie(`[compat:check] tmp csv: "${c}"`));let l=CF(c),d=GF(c,l,n.target,t.format);_F(c),o.stop(),NF(l,d,t.format,t.limit,n.target.kind),await So(r,!0,null,i)}catch(s){o.fail("Compatibility check failed");let a=Ef(s);throw await So(r,!1,a,i),s}}async function YE(n,e){let t=Date.now(),r=["check","compat"];try{let i=await VF(n,e);await qF(i,n,e,t,r)}catch(i){let o=Ef(i);throw await So(t,!1,o,r),i}}function JF(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new zF(`--limit must be a positive integer (got "${n}")`);return e}var Pf=new KE("compat").description("Compatibility checking utilities.");Pf.description("Check source code compatibility against a target SDK version. By default, performs a project-level scan; pass positional `files...` for file-level scanning; pass `--modules` for module-level scanning.").arguments("[files...]").option("--source-version <version>","Current project SDK version (required; use `compat versions` to list available versions). On zsh, quote the value because version strings contain parentheses; run `compat versions` first to copy a real example.").option("--target-version <version>","Target SDK version (required; use `compat versions` to list available versions). On zsh, quote the value because version strings contain parentheses; run `compat versions` first to copy a real example.").option("--modules <modules...>","Modules to check (default: all modules in the project). Mutually exclusive with positional file arguments.").option("--format <format>",'Output format: "json" or "default" (text) for console; "csv", "json", or "default" for file output (--output-path). "csv" requires --output-path.',"default").option("--output-path <path>","Directory to write the detailed report CSV to (default: ./compat-output)").option("--limit <num>","Maximum number of change records to display (default: 100)",JF,100).action(async(n,e)=>{await YE(n,e)});Pf.command("versions").description("List all available target SDK versions for compatibility checking").option("--format <format>","Output format: default or json").action(async(n,e)=>{let t=e.optsWithGlobals().format;await zE(t)});var YF=new KE("check").description("Run DevEco project checks").addCommand(Pf).addCommand(hf()).addCommand(bf()),XE=YF;import{Command as $H}from"commander";import{green as qf,red as FH,yellow as LP}from"colorette";import ui from"fs";import zf from"path";import _P from"json5";import{readFileSync as Cj}from"fs";import{join as KF}from"path";var fe={BASE_URL:"https://connect-api.cloud.huawei.com",CERT_LIST_PATH:"/api/cps/harmony-cert-manage/v1/cert/list",CERT_DELETE_PATH:"/api/cps/harmony-cert-manage/v1/cert/delete",CERT_ADD_PATH:"/api/cps/harmony-cert-manage/v1/cert/add",CERT_DOWNLOAD_URL_PATH:"/api/amis/app-manage/v1/objects/url/reapply",DEVICE_ADD_PATH:"/api/cps/device-manage/v1/device/add",DEVICE_LIST_PATH:"/api/cps/device-manage/v1/device/list",PROVISION_ADD_REAL_PATH:"/api/cps/provision-manage/v1/ide/real/provision/add",PROVISION_ADD_TEST_PATH:"/api/cps/provision-manage/v1/ide/test/provision/add",PROVISION_DELETE_PATH:"/api/cps/provision-manage/v1/provision/delete"},Re={CERT_NAME_PREFIX:"auto_debug_",CERT_NAME_PREFIX_RELEASE:"auto_release_",CERT_TYPE_DEBUG:"1",CERT_TYPE_RELEASE:"2",TEAM_ID_INVALID_CHARS:/[\\/.:]/g,CERT_PATTERN:/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/,TARGET_FRIENDLY_NAME:"debugKey",CERTIFICATE_PATTERN_GLOBAL:/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g,BUNDLE_NAME_REGEX:/^[a-zA-Z][a-zA-Z0-9._-]*$/,CERT_BEGIN_HEADER:"-----BEGIN CERTIFICATE-----",CERT_SAVE_DIR:KF(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},Te={SUCCESS_MARKER:'"code":0',SQUARE_BRACKETS:"[]",OPENPROXY_BLOCKED_URL:"Openproxy_Blocked_URL_list",CERT_LIMIT_CODE:"205389872",USER_NOT_HARMONY_CODE:"205389904",DEVICE_EXCEEDS_LIMIT_CODE:"205389859",DEVICE_NAME_REPEAT_CODE:"205389857",PROVISION_EXCEEDS_LIMIT_CODE:"205389938",PROVISION_NAME_REPEAT_CODE:"205389830"},Ut={FORBIDDEN:403,UNAUTHORIZED:401},k={ERR_FORBIDDEN:"You do not have AppGallery Connect permissions for the current team. Request access from the team administrator or switch to a team where you have permissions.",ERR_UNAUTHORIZED:"Invalid AccessToken. Sign in and try again.",ERR_CERT_LIMIT_REACHED:"The number of certificates has reached the limit. Delete some certificates and try again.",ERR_CERT_NETWORK_ERROR:"Ensure the external network connection is available before downloading the certificate.",ERR_CERT_INVALIDATE:"The downloaded .cer file is invalid. Try again.",ERR_DOWNLOAD_CER:"Failed to download the certificate file. Check the following configurations: Network connection, HTTP Proxy, etc.",ERR_USER_NOT_HARMONY:"The user is not in harmony allow list, please grant the permission",ERR_READ_CSR:"Failed to read the .csr file, please try again later",ERROR_WHILE_ADD_DEVICE:"Failed to add the device, please try again.",DEVICE_LIMIT_REACHED:"The number of devices has reached the limit. Delete some unused devices and try again.",DEVICE_NAME_REPEAT:"Duplicate device name, please try again.",DEVICE_LIST_EMPTY:"No devices available.",ADD_PROFILE_FAIL:"Failed to add the profile, please try again.",NO_AGC_PERMISSION:"You do not have the AppGallery Connect permission with the current team. Apply for the permission form the team administrator, or switch to a team with which you already have the permission.",ERROR_WHILE_DOWNLOAD_PROFILE:"Failed to download the profile, please try again.",PROFILE_NAME_REPEAT:"The profile name already exists in the AGC.",ERROR_WHILE_PARSE_PROFILE:"Failed to parse the profile, please try again.",TEST_PROVISION_EXCEEDS_LIMIT:"Provision number exceeds limit.",CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT:"The certificate application file is inconsistent with the file in profile, please try again.",CERTIFICATE_HAS_EXPIRED:"The signature does not take effect or has expired. It may be the current system time is inaccurate, please calibrate the system time and sign again.",ERROR_SIGN_BUNDLE_NAME_VALIDATE:"The bundle name contains 7 to 128 characters, including only letters, digits, and underscores (_). It must be start with a letter and contain at least three segments separated by periods (.), each of the segments ending with a digit or letter."},ve={TOOLCHAIN_INIT_FAILED:"Auto-sign failed: unable to initialize toolchain",LOGIN_REQUIRED:"Failed to automatically generate signatures.Run devecocli auth login to sign in.",TEAM_INFO_FAILED:"Failed to obtain user team information.Check the network connection, HTTP proxy, and other configurations.",REALNAME_REQUIRED:"Users without real-name verification are not supported.Complete real-name verification in AppGallery Connect.",SESSION_EXPIRED:"User session expired or token invalid. Please login again.",REGION_CHINA_ONLY:"This feature is only available for accounts registered in Chinese mainland.",DEVICE_MISSING:"Unable to create the profile file due to missing devices.Connect a device through IP or USB, or manually add a device in AppGallery Connect first.If you are installing the HAP package on an emulator, you can skip the signing step.",DEVICE_DETECT_FAILED:"Unable to detect devices. Please check hdc status. If installing HAP on an emulator, signature step can be skipped.",PROJECT_DIR_MISSING:"Not in a valid project directory (project-level build-profile.json5 not found).",ATOMIC_SERVICE_UNSUPPORTED:"AtomicService projects are not yet supported. Please configure signing manually."};function wd(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function Cf(n,e=!1){let t=n.replace(Re.TEAM_ID_INVALID_CHARS,"");return`${e?Re.CERT_NAME_PREFIX_RELEASE:Re.CERT_NAME_PREFIX}${t}.cer`}function Eo(n,e,t){if(n===Ut.FORBIDDEN)return e===Te.OPENPROXY_BLOCKED_URL?new Error(k.ERR_CERT_NETWORK_ERROR):new Error(k.ERR_FORBIDDEN);if(n===Ut.UNAUTHORIZED)return new Error(k.ERR_UNAUTHORIZED);if(t.includes(Te.USER_NOT_HARMONY_CODE))return new Error(k.ERR_USER_NOT_HARMONY);if(t.includes(Te.CERT_LIMIT_CODE))return new Error(k.ERR_CERT_LIMIT_REACHED);let r=XF(t);return new Error(r??k.ERR_DOWNLOAD_CER)}function XF(n){let e=ZE(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?ZE(t):t;if(r&&typeof r=="object"){let i=r.msg;if(typeof i=="string"&&i.trim()!=="")return i}return null}function ZE(n){try{return JSON.parse(n)}catch{return null}}function kf(n){return JSON.parse(n)}async function QE(n){let e=`${fe.BASE_URL}${fe.CERT_LIST_PATH}`,t=await $.postAllowFailure(e,{headers:wd(n)});if(t.statusCode!==200)throw Eo(t.statusCode,t.statusText,t.data);return kf(t.data)?.certList??[]}async function vd(n,e){return(await QE(n)).find(r=>r.certName===e)??null}async function Rf(n,e){let t=`${fe.BASE_URL}${fe.CERT_DELETE_PATH}`,r=await $.deleteAllowFailure(t,{headers:wd(n),params:{certIds:[e]}});if(r.statusCode!==200)throw Eo(r.statusCode,r.statusText,r.data);return kf(r.data)?.ret?.code===0}async function Df(n,e,t,r=Re.CERT_TYPE_DEBUG){let i=`${fe.BASE_URL}${fe.CERT_ADD_PATH}`,o={csr:e,certName:t,certType:r},s=await $.postAllowFailure(i,{headers:wd(n),params:o});if(s.statusCode!==200)throw Eo(s.statusCode,s.statusText,s.data);if(!s.data.includes(Te.SUCCESS_MARKER))throw Eo(void 0,s.statusText,s.data)}async function xf(n,e){let t=`${fe.BASE_URL}${fe.CERT_DOWNLOAD_URL_PATH}`,r=await $.postAllowFailure(t,{headers:wd(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw Eo(r.statusCode,r.statusText,r.data);return kf(r.data)?.urlsInfo?.[0]??null}import{mkdirSync as ZF,writeFileSync as QF,existsSync as ej}from"fs";import{dirname as tj}from"path";import{createHash as rj}from"crypto";function nj(n){let e;try{e=new URL(n)}catch{throw new Error(`Invalid download URL: ${JSON.stringify(n)}`)}if(e.protocol!=="https:")throw new Error(`Download URL must use HTTPS: ${e.protocol}`);let t=e.hostname.toLowerCase();if(t==="localhost"||t==="127.0.0.1"||t==="::1"||t.startsWith("169.254.")||t.startsWith("10.")||t.startsWith("192.168.")||/^172\.(1[6-9]|2\d|3[0-1])\./.test(t)||t.endsWith(".internal")||t.endsWith(".local"))throw new Error(`Download URL points to internal/private address: ${t}`)}async function oa(n,e,t){nj(n);let{statusCode:r,statusText:i,buffer:o}=await $.getBinaryAllowFailure(n,{timeout:Re.DOWNLOAD_CONNECT_TIMEOUT_MS});if(r!==200)throw r===Ut.FORBIDDEN&&i===Te.OPENPROXY_BLOCKED_URL?new Error(k.ERR_CERT_NETWORK_ERROR):new Error(k.ERR_DOWNLOAD_CER);if(t){let a=rj("sha256").update(o).digest("hex");if(a!==t.toLowerCase())throw new Error(`SHA-256 mismatch for ${e}: expected ${t.toLowerCase()}, got ${a}`)}let s=tj(e);ej(s)||ZF(s,{recursive:!0}),QF(e,o)}import Sj from"fs/promises";import{readFileSync as Ej}from"fs";import bd from"path";import rP from"crypto";import ij from"os";import sa from"fs/promises";var nP={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},eP=["ECC","RSA"],tP=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],oj={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},sj=8,Af=64,aj=/[\\/:*?"<>|=-]/g,Nr={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function cj(n){if(!n.keyAlias.trim())throw new Error("keyAlias cannot be empty");if(!n.keystoreFile.trim())throw new Error("keystoreFile cannot be empty");if(n.keyAlias.length>Af)throw new Error(`The length of keyAlias cannot exceed ${Af}`);if(!eP.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${eP.join(" / ")}`);let e=oj[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function lj(n){if(!n.keyAlias.trim())throw new Error("keyAlias cannot be empty");if(!n.keystoreFile.trim())throw new Error("keystoreFile cannot be empty");if(!n.subject.trim())throw new Error("subject cannot be empty");if(!tP.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${tP.join(" / ")}`)}function dj(n){return rP.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function uj(n){let e=n?.trim()??"";return e&&e.replace(aj,"_").replace(/\.+/g,"_").slice(0,Af)||Nr.productName}async function iP(){let n=await P.new();n.assertJava();let e=n.javaPath,t=n.sdkPath;f.info(`\u8BFB\u53D6SDK\u6839\u76EE\u5F55\uFF1A${t}`);let r=bd.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");try{await sa.access(r)}catch(i){throw new Error(`Sign tool jar not found: ${r}`,{cause:i})}return{javaPath:e,jarPath:r}}async function pj(n){let{javaPath:e,jarPath:t}=await iP(),r=["-jar",t,nP.GENERATE_KEYPAIR,"-keyAlias",n.keyAlias,"-keyAlg",n.keyAlg,"-keySize",n.keySize,"-keystoreFile",n.keystoreFile,"-keystorePwd",n.keystorePwd];n.keyPwd&&r.push("-keyPwd",n.keyPwd),n.pwdInputMode&&r.push("-pwdInputMode",n.pwdInputMode);let i=r.map((o,s)=>s>0&&["-keyPwd","-keystorePwd"].includes(r[s-1])?"******":o);return f.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),[e,...r]}async function mj(n){let{javaPath:e,jarPath:t}=await iP(),r=["-jar",t,nP.GENERATE_CSR,"-keyAlias",n.keyAlias,"-subject",n.subject,"-signAlg",n.signAlg,"-keystoreFile",n.keystoreFile,"-keystorePwd",n.keystorePwd];n.outFile&&r.push("-outFile",n.outFile),n.keyPwd&&r.push("-keyPwd",n.keyPwd),n.pwdInputMode&&r.push("-pwdInputMode",n.pwdInputMode);let i=r.map((o,s)=>s>0&&["-keyPwd","-keystorePwd"].includes(r[s-1])?"******":o);return f.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),[e,...r]}async function fj(n){f.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),cj(n);let e=await pj(n),t=await jo(e[0],e.slice(1));if(t.exitCode!==0){let r=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the private key P12, exit code${t.exitCode}\uFF1A${r}`)}return f.info("\u751F\u6210P12\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}async function hj(n){f.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),lj(n);let e=await mj(n),t=await jo(e[0],e.slice(1));if(t.exitCode!==0){let r=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the CSR, exit code${t.exitCode}\uFF1A${r}`)}return f.info("\u751F\u6210CSR\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}function gj(n=sj){return rP.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function yj(){let n=ij.homedir();try{await sa.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=bd.join(n,".ohos","config");try{await sa.mkdir(e,{recursive:!0,mode:448})}catch(t){throw new Error(`Failed to create directory ${e}`,{cause:t})}return f.info(`\u7B7E\u540D\u914D\u7F6E\u76EE\u5F55\u5C31\u7EEA\uFF1A${e}`),e}async function Fe(n,e,t,r){let i=uj(n),o=bd.basename(e),s=dj(e),c=`${i}_${o}_${s}${r==="release"?"_release":""}=.${t}`,l=await yj();return bd.join(l,c)}function wj(n){let e;try{e=B.discover(n).rootDir}catch(t){throw new Error(`Current directory ${n} is not a valid project root`,{cause:t})}return e}async function vj(n){try{await sa.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function bj(n){try{await sa.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function If(n,e,t,r){let i=process.cwd(),o=wj(i);await vj(o),f.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${o}`);let s=gj(),a=r==="release",c=a?"releaseKey":Nr.keyAlias,l=a?"CN=ReleaseKey":Nr.csrSubject,d=await Fe(n??"",o,"p12",r),g=await Fe(n??"",o,"csr",r);return console.log("Start generating p12"),await fj({keyAlias:e?.keyAlias??c,keyPwd:s,keyAlg:e?.keyAlg??Nr.keyAlg,keySize:e?.keySize??Nr.keySize,keystoreFile:d,keystorePwd:s}),await bj(d),console.log("Start generating csr"),await hj({subject:t?.subject??l,outFile:g,keyAlias:e?.keyAlias??c,keyPwd:s,signAlg:t?.signAlg??Nr.signAlg,keystoreFile:d,keystorePwd:s}),{p12FilePath:d,csrFilePath:g,keyPwd:s,keyAlias:e?.keyAlias??c}}var Pj=["p12","cer","csr","p7b"];async function Tf(n,e,t){for(let r of Pj){let i=await Fe(n,e,r,t);await Sj.rm(i,{force:!0})}}function Of(n){let e;try{e=Ej(n,"utf-8")}catch{throw new Error(k.ERR_CERT_INVALIDATE)}if(!Re.CERT_PATTERN.test(e))throw new Error(k.ERR_CERT_INVALIDATE)}async function Sd(n,e,t){return{certPath:await Fe(n,e,"cer",t),csrPath:await Fe(n,e,"csr",t),p12Path:await Fe(n,e,"p12",t),profilePath:await Fe(n,e,"p7b",t)}}async function Mf(n,e,t){let r=e??"",i=B.discover(process.cwd()).rootDir;await Tf(r,i,t);let o=Cf(n.teamId,t==="release"),s=await vd(n,o);if(s&&!await Rf(n,s.id))throw new Error(k.ERR_DOWNLOAD_CER);let a=await If(e,void 0,void 0,t),c;try{c=Cj(a.csrFilePath,"utf-8")}catch{throw new Error(k.ERR_READ_CSR)}console.log("Start generating certificate");let l=t==="release"?Re.CERT_TYPE_RELEASE:Re.CERT_TYPE_DEBUG;await Df(n,c,o,l);let d=await vd(n,o);if(!d)throw new Error(k.ERR_DOWNLOAD_CER);let g=await xf(n,d.certObjectId);if(!g)throw new Error(k.ERR_DOWNLOAD_CER);let w=await Fe(r,i,"cer",t);await oa(g.newUrl,w,g.sha256),Of(w);let R=await Fe(r,i,"p7b",t);return{p12FilePath:a.p12FilePath,csrFilePath:a.csrFilePath,cerFilePath:w,profileFilePath:R,certId:d.id,keyAlias:a.keyAlias,keyPwd:a.keyPwd,storePassword:a.keyPwd}}import Td from"crypto";import En from"fs";import*as vP from"path";import qj from"json5";import{execa as gP}from"execa";import yP from"node-forge";import{createCipheriv as kj,createDecipheriv as Rj,pbkdf2Sync as Dj,randomBytes as $f}from"crypto";import{promises as ai}from"fs";import{dirname as xj,join as Bt}from"path";var Ed=3,aa=16,Aj=1e4,oP="material",Ij=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),lP="aes-128-gcm",si=12,Pd=16,vn=4;function Nf(n){return new Uint8Array($f(n))}function Tj(n){return $f(n).toString("hex")}function Oj(...n){if(n.length===0)return new Uint8Array(0);let e=n[0].length,t=new Uint8Array(e);for(let r=0;r<e;r++){let i=0;for(let o of n)i^=o[r];t[r]=i}return t}function sP(n,e,t=Aj,r=aa){let i=[...n,Ij],o=Oj(...i),s=Buffer.from(o).toString("utf8"),a=Buffer.from(s,"utf8"),c=Dj(a,e,t,r,"sha256");return new Uint8Array(c)}function aP(n,e){let t=$f(si),r=kj(lP,n,t),i=Buffer.concat([r.update(e),r.final()]),o=r.getAuthTag(),s=Buffer.concat([i,o]),a=s.length,c=Buffer.alloc(vn+si+s.length);return c.writeUInt32BE(a,0),t.copy(c,vn),s.copy(c,vn+si),c}function cP(n,e){if(e.length<vn+si+Pd)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(vn,vn+si),i=e.subarray(vn+si,vn+si+t);if(i.length<Pd)throw new Error("Ciphertext too short for auth tag");let o=i.subarray(0,i.length-Pd),s=i.subarray(i.length-Pd),a=Rj(lP,n,r);return a.setAuthTag(s),Buffer.concat([a.update(o),a.final()])}async function Mj(n){try{await ai.rm(n,{recursive:!0,force:!0})}catch{}}async function Lf(n){let e=await ai.readdir(n),t=e.filter(r=>r!==".DS_Store");if(t.length!==1)throw new Error(`Expected exactly 1 file in ${n}, but found ${t.length} (filtered from ${e.length})`);return ai.readFile(Bt(n,t[0]))}async function _f(n,e){let t=Tj(aa),r=Bt(n,t);return await ai.writeFile(r,e,{mode:384}),t}var bn=class{static keyChain=Promise.resolve();static async generateMaterial(e){let t=Bt(e,oP);await Mj(t);let r=Bt(t,"ac"),i=Bt(t,"ce");await ai.mkdir(r,{recursive:!0,mode:448}),await ai.mkdir(i,{recursive:!0,mode:448});for(let d=0;d<Ed;d++)await ai.mkdir(Bt(t,"fd",String(d)),{recursive:!0,mode:448});let o=Nf(aa),s=[];for(let d=0;d<Ed;d++)s.push(Nf(aa));let a=Nf(aa),c=sP(s,o),l=aP(c,a);await _f(r,o),await _f(i,l);for(let d=0;d<Ed;d++){let g=Bt(t,"fd",String(d));await _f(g,s[d])}return a}static async readMaterial(e){let t=Bt(e,oP),r=Bt(t,"ac"),i=new Uint8Array(await Lf(r)),o=[];for(let d=0;d<Ed;d++){let g=Bt(t,"fd",String(d)),w=await Lf(g);o.push(new Uint8Array(w))}let s=Bt(t,"ce"),a=await Lf(s),c=sP(o,i),l=cP(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t,r=this.keyChain;this.keyChain=new Promise(i=>{t=i}),await r;try{let i=xj(e);try{return await this.readMaterial(i)}catch{return await this.generateMaterial(i)}}finally{t()}}static async encryptedPassword(e,t){let r=await this.getStoreKey(t),i=Buffer.from(e,"utf8");return aP(r,i).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),i=Buffer.from(e,"hex");return cP(r,i).toString("utf8")}};import fP from"fs";import Ad from"path";import jj from"json5";import*as Cd from"fs";import*as dP from"path";function kd(n){let e=dP.resolve(n);if(!Cd.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=Cd.readFileSync(e,"utf-8")}catch(s){throw new Error(`Failed to read SDK info file: ${e}`,{cause:s})}let r;try{r=JSON.parse(t)}catch(s){throw new Error(`Invalid JSON in SDK info file: ${e}`,{cause:s})}let i=r?.data?.apiVersion;if(i==null||i==="")throw new Error(`Missing data.apiVersion in SDK info file: ${e}`);let o=Number(i);if(!Number.isFinite(o))throw new Error(`Invalid data.apiVersion in SDK info file: ${String(i)}`);return o}import*as Co from"fs";import*as st from"path";import{debuglog as Po}from"util";var uP={"acl.SYSTEM_FLOAT_WINDOW.instead.name":"PiPWindow","acl.READ_CONTACTS.instead.name":"contact.selectContacts","acl.READ_IMAGEVIDEO.instead.name":"PhotoViewPicker","acl.WRITE_IMAGEVIDEO.instead.name":"SaveButton","acl.READ_AUDIO.instead.name":"AudioViewPicker","acl.WRITE_AUDIO.instead.name":"AudioViewPicker","acl.READ_PASTEBOARD.instead.name":"PasteButton"};function Nj(n){return Object.prototype.hasOwnProperty.call(uP,n)}function Rd(n){if(Nj(n))return uP[n]}var pP={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as Lj}from"url";var xd=class{permissionName;permissionDisplayName;minSupportApiLevel;permissionInsteadName;permissionHelpUrlKey;constructor(e={}){this.permissionName=e.permissionName??"",this.permissionDisplayName=e.permissionDisplayName??"",this.minSupportApiLevel=e.minSupportApiLevel??"",this.permissionInsteadName=e.permissionInsteadName,this.permissionHelpUrlKey=e.permissionHelpUrlKey}};function Dd(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function mP(n){return n==null||n.length===0}function _j(n){return!mP(n)}function Ff(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function $j(n,e){let t=n[e];if(typeof t=="boolean")return t;if(typeof t=="number")return t!==0;if(typeof t=="string"){let r=t.trim().toLowerCase();return r==="true"||r==="1"}return!1}function Fj(n,e){let t=n[e];if(typeof t=="number")return Math.trunc(t);if(typeof t=="string"){let r=Number.parseInt(t,10);return Number.isNaN(r)?0:r}return 0}var Sn=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=st.join("aclPermission","aclPermissionsInfo.json");static ACL_HAVE_INSTEAD_NAME=new Set(["ohos.permission.SYSTEM_FLOAT_WINDOW","ohos.permission.READ_CONTACTS","ohos.permission.READ_IMAGEVIDEO","ohos.permission.WRITE_IMAGEVIDEO","ohos.permission.READ_AUDIO","ohos.permission.WRITE_AUDIO","ohos.permission.READ_PASTEBOARD"]);static ACL_AVAILABLE_LEVEL_VALUE="system_basic";static ACL_AVAILABLE_TYPE_VALUE="NORMAL";static ACL_AVAILABLE_LEVEL_KEY="availableLevel";static ACL_AVAILABLE_TYPE_KEY="availableType";static ACL_PROVISION_ENABLE_KEY="provisionEnable";static ACL_NAME_KEY="name";static ACL_CONFIG_PREFIX="acl.";static ACL_INSTEAD_NAME_SUFFIX=".instead.name";static ACL_HELP_URL_KEY_SUFFIX=".help.key";static ACL_DEFINE_PERMISSION_KEY="definePermissions";static ACL_SINCE_KEY="since";static PERMISSION_DEFINITIONS_RELATIVE_PATH=st.join("lib","PermissionDefinitions.json");static INCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.FILE_ACCESS_PERSIST","ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORY","ohos.permission.READ_WRITE_DOCUMENTS_DIRECTORY"]);static EXCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.READ_DOCUMENT","ohos.permission.WRITE_DOCUMENT"]);static handleSpecificAclPermissions(){this.addAclWhiteList(this.INCLUDE_ACL_PERMISSIONS),this.addAclBlackList(this.EXCLUDE_ACL_PERMISSIONS)}static aclPermissionInfoMap=new Map;static aclPermissionNamesMap=new Map;static aclWhiteList=new Set;static aclBlackList=new Set;static builtInConfigTextLoader;static initAclPermission(e,t){let r=e.rootDir,i=this.getOrCreateSet(this.aclPermissionNamesMap,r),o=this.getOrCreateSet(this.aclPermissionInfoMap,r);i.clear(),o.clear();let s=st.join(t.sdkPath,"default","sdk-pkg.json"),a=kd(s);this.MIN_API_TO_FIND_ACL_IN_SDK-a>0?this.initAclPermissionFromBuiltInConfig(i,o):this.initAclPermissionFromSDK(t,i,o)}static getAclPermissionInfos(e){return this.aclPermissionInfoMap.get(e.rootDir)??new Set}static getAclPermissionNames(e){return this.aclPermissionNamesMap.get(e.rootDir)??new Set}static addAclWhiteList(e){for(let t of e)this.aclWhiteList.add(t)}static addAclBlackList(e){for(let t of e)this.aclBlackList.add(t)}static getOrCreateSet(e,t){let r=e.get(t);return r||(r=new Set,e.set(t,r)),r}static readBuiltInConfigText(){if(this.builtInConfigTextLoader)return this.builtInConfigTextLoader();let e=st.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(Co.existsSync(e))return Co.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=Lj(e);if(t.includes("dist")){let s=st.dirname(t),a=st.dirname(s);return st.join(a,"src","resources")}let r=st.dirname(t),i=st.dirname(r),o=st.dirname(i);return st.join(o,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{Po("read builtin acl permission failed.");return}if(r!==void 0)try{let i=JSON.parse(r),s=(Array.isArray(i)?i:Dd(i)?Object.values(i):[]).filter(Dd).map(a=>new xd(a));s.forEach(a=>{let c=a.permissionInsteadName;_j(c)&&(a.permissionInsteadName=Rd(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(i){Po(`failed to parse aclPermissionsInfo.json: ${i}`)}}static initAclPermissionFromSDK(e,t,r){let i=this.parsePermissionDefinitionFile(e);i&&i.forEach(o=>{if(!Dd(o))return;let s=o,a=Ff(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(mP(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||Ff(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||Ff(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:$j(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let i=new xd;i.permissionName=t;let o=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;i.permissionDisplayName=o;let s=Fj(r,this.ACL_SINCE_KEY);i.minSupportApiLevel=String(s),this.handleInsteadName(i,o),e.add(i)}static parsePermissionDefinitionFile(e){let t=st.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!Co.existsSync(t))return;let r;try{r=Co.readFileSync(t,"utf-8")}catch(s){Po(`failed to load permissionDefinitions.json: ${s}`);return}let i;try{let s=JSON.parse(r);if(!Dd(s)){Po("json object is null");return}i=s}catch(s){Po(`failed to parse permissionDefinitions.json: ${s}`);return}let o=i[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(o)){Po("definePermissions is not an array");return}return o}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=Rd(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=Rd(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function Id(n,e){let t=new Set,r=new Set;Sn.handleSpecificAclPermissions(),Sn.initAclPermission(n,e);for(let i of n.profile.modules){let o=hP(i,n,e,r,Ad.join("src","main"));for(let a of o)t.add(a);let s=hP(i,n,e,r,Ad.join("src","ohosTest"));for(let a of s)t.add(a)}return Hj(r),t}function Hj(n){if(n.size>0)throw new Error(pP.DUPLICATE_PERMISSION)}function hP(n,e,t,r,i){let o=Bj(e.rootDir,n,i);if(o==null)return new Set;let s=[];for(let w of o){if(typeof w!="object"||w===null)continue;let R=Uj(w,"name");R&&s.push(R)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=Ad.join(t.sdkPath,"default","sdk-pkg.json"),l=kd(c),d=Sn.getAclPermissionInfos(e),g=new Set(Array.from(d).filter(w=>{let R=Number(w.minSupportApiLevel);return Number.isFinite(R)&&R<=l}).map(w=>w.permissionName));for(let w of Array.from(a))g.has(w)||a.delete(w);return a}function Uj(n,e){let t=n[e];return typeof t=="string"?t:""}function Bj(n,e,t){let r=Ad.join(n,e.srcPath,t,"module.json5"),i=Wj(r);if(i==null)return null;let o=Vj(i,"module");return o==null?null:Gj(o,"requestPermissions")}function Wj(n){try{if(!fP.existsSync(n))return null;let e=fP.readFileSync(n,"utf-8");return jj.parse(e)}catch{return null}}function Vj(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return t!=null&&typeof t=="object"&&!Array.isArray(t)?t:null}function Gj(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var Hf=class{verifyStorePassword(e,t){try{let r=En.readFileSync(e),i=yP.asn1.fromDer(r.toString("binary"));return yP.pkcs12.pkcs12FromAsn1(i,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=En.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(i=>this.formatFp(new Td.X509Certificate(i).fingerprint256));try{return[this.formatFp(new Td.X509Certificate(En.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let i=En.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let o of i)try{let s=new Td.X509Certificate(o);if(this.formatFp(s.fingerprint256)===t){let a=new Date(s.validTo);return isNaN(a.getTime())?null:a}}catch{}return null}formatFp(e){let t=e.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}};function zj(n,e){let t=En.readFileSync(n,"utf-8"),r=Jj(t),i=null;if(r)try{i=JSON.parse(r)}catch{i=null}let o=i?.["bundle-info"]??{},s=e==="release"?"distribution-certificate":"development-certificate";return{rawContent:t,bundleNameInProfile:jf(o["bundle-name"]),expiryDate:Yj(i?.validity?.["not-after"]),cerFingerprintInProfile:Kj(jf(o[s])),deviceUdidsInProfile:Xj(i?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:Zj(i?.acls?.["allowed-acls"]),teamIdInProfile:jf(o["developer-id"])}}function Jj(n){let e=n.indexOf("{");if(e<0)return null;let t=0,r=-1,i=!1,o=!1;for(let s=e;s<n.length;s++){let a=n[s];if(i){o?o=!1:a==="\\"?o=!0:a==='"'&&(i=!1);continue}if(a==='"')i=!0;else if(a==="{")t++;else if(a==="}"&&(t--,t===0)){r=s;break}}return r<0?null:n.slice(e,r+1)}function Yj(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function Kj(n){if(!n)return null;try{let t=new Td.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function Xj(n){if(!Array.isArray(n))return[];let e=[];for(let t of n)if(typeof t=="string"){let r=t.toUpperCase();e.includes(r)||e.push(r)}return e}function Zj(n){if(!Array.isArray(n))return[];let e=[];for(let t of n)typeof t=="string"?e.push(t):t&&typeof t=="object"&&typeof t.name=="string"&&e.push(t.name);return[...new Set(e)].sort()}function jf(n){return typeof n=="string"?n:null}var ca=class n{static async shouldRegenerate(e,t){let r=await n.#e(e,t);return n.#t(r)??n.#r(r)??n.#n(r)??n.#i(r)??n.#o(r)??n.#s(r)??(r.type==="release"?null:n.#a(r))??n.#c(r)??n.#l(r)??n.#d(r)??await n.#u(r)??n.#p()}static async#e(e,t){let r=e.force,i=e.teamId,o=e.productName??"default",s=e.type,a=B.discover(process.cwd()),c=a.rootDir,[l,d]=await Promise.all([Qj(o,c,s),s==="release"?Promise.resolve([]):tH(t.hdcPath)]),g=null;if(wP(l).allExist)try{g=zj(l.profileFile,s)}catch{}return{force:r,teamId:i,productName:o,projectPath:c,type:s,materialPaths:l,bundleName:a.getBundleName(o),deviceUdids:d,storePassword:await eH(c,o,l.storeFile,s),localAclPermissions:[...Id(a,t)].sort(),hapSignTool:new Hf,profileInfo:g}}static#t(e){return e.force?(m("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:ft({force:!0})}):null}static#r(e){let t=wP(e.materialPaths);return t.allExist?null:(m(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:ft({allFilesExist:!1,missingFiles:t.missing})})}static#n(e){return(e.profileInfo?.rawContent??"").trim().length>0?null:(m("[reGenerateSign] profile content is empty"),{shouldRegenerate:!0,reason:"Profile file content is empty",checkDetails:ft({allFilesExist:!0,profileContentNotEmpty:!1})})}static#i(e){let t=e.profileInfo?.expiryDate;return!t||t>=new Date?null:(m(`[reGenerateSign] profile expired at ${t.toISOString()}`),{shouldRegenerate:!0,reason:`Profile expired at ${t.toISOString()}`,checkDetails:ft({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#o(e){let t=e.profileInfo?.bundleNameInProfile;return t&&t===e.bundleName?null:(m(`[reGenerateSign] bundleName mismatch \u2014 current=${e.bundleName}, profile=${t}`),{shouldRegenerate:!0,reason:`bundleName mismatch: current=${e.bundleName}, in profile=${t}`,checkDetails:ft({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!1})})}static#s(e){let t=e.profileInfo?.teamIdInProfile;return t&&t===e.teamId?null:(m(`[reGenerateSign] teamId mismatch \u2014 current=${e.teamId}, profile=${t}`),{shouldRegenerate:!0,reason:`teamId mismatch: current=${e.teamId}, in profile=${t}`,checkDetails:ft({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=nH(e.profileInfo?.deviceUdidsInProfile??[],e.deviceUdids);return t.allPresent?null:(m(`[reGenerateSign] missing device UDIDs: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Device UDID(s) not in profile: ${t.missing.join(", ")}`,checkDetails:ft({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return iH(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(m("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:ft({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!1})})}static#l(e){let t=e.hapSignTool.getLocalCerFingerprints(e.materialPaths.cerFile),r=e.profileInfo?.cerFingerprintInProfile;return r&&t.includes(r)?null:(m("[reGenerateSign] certificate mismatch"),{shouldRegenerate:!0,reason:"Certificate mismatch between profile and local .cer file",checkDetails:ft({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!1})})}static#d(e){let t=e.profileInfo?.cerFingerprintInProfile,r=e.hapSignTool.getLocalCerExpiry(e.materialPaths.cerFile,t);return!r||r>=new Date?null:(m(`[reGenerateSign] local certificate expired at ${r.toISOString()}`),{shouldRegenerate:!0,reason:`Local certificate expired at ${r.toISOString()}`,checkDetails:ft({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!1})})}static async#u(e){return e.storePassword?e.hapSignTool.verifyStorePassword(e.materialPaths.storeFile,e.storePassword)?null:(m("[reGenerateSign] keystore password verification failed"),{shouldRegenerate:!0,reason:"Keystore password verification failed (storeFile may be corrupted or password changed)",checkDetails:ft({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})}):(m("[reGenerateSign] no stored keystore password"),{shouldRegenerate:!0,reason:"No stored keystore password available for verification",checkDetails:ft({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})})}static#p(){return m("[reGenerateSign] all checks passed \u2014 skip regeneration"),{shouldRegenerate:!1,reason:"",checkDetails:ft({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function Qj(n,e,t){let[r,i,o,s]=await Promise.all([Fe(n,e,"p12",t),Fe(n,e,"csr",t),Fe(n,e,"cer",t),Fe(n,e,"p7b",t)]);return{storeFile:r,csrFile:i,cerFile:o,profileFile:s}}async function eH(n,e,t,r){let i=vP.join(n,"build-profile.json5");if(!En.existsSync(i))return;let o;try{o=qj.parse(En.readFileSync(i,"utf-8"))}catch{return}let s=r==="release"?`${e}_release`:e,l=(o?.app?.signingConfigs??[]).find(d=>d.name===s)?.material?.storePassword;if(l)try{return await bn.decryptPassword(l,t)}catch{return}}async function tH(n){m(`Executing: ${n} list targets`);let{stdout:e}=await gP(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
1378
+ `)){let o=i.trim();if(!o||o.startsWith("[Empty]"))continue;let s=o.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let r=[];for(let i of t)try{m(`Executing: ${n} -t ${i} shell bm get -u`);let{stdout:o}=await gP(n,["-t",i,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),s=rH(o);s&&r.push(s)}catch{m(`[reGenerateSign] Failed to get UDID for ${i}, skipping`)}return r}function rH(n){let e=n.trim();if(!e)return null;let t=e.split(`
1379
+ `);for(let i=0;i<t.length-1;i++)if(t[i].includes("udid of current device is")){let s=t[i+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(s)return s[0].toUpperCase()}let r=e.match(/[A-Fa-f0-9]{64}/);return r?r[0].toUpperCase():null}function wP(n){let e=[n.storeFile,n.csrFile,n.cerFile,n.profileFile],t=[];for(let r of e)En.existsSync(r)||t.push(r);return{allExist:t.length===0,missing:t}}function nH(n,e){let t=[];for(let r of e)n.includes(r)||t.push(r);return{allPresent:t.length===0,missing:t}}function iH(n,e){let t=[...n].sort(),r=[...e].sort();return t.length!==r.length?!1:t.every((i,o)=>i===r[o])}function ft(n){let e={force:!1,allFilesExist:!1,missingFiles:[],profileContentNotEmpty:!1,profileNotExpired:!1,bundleNameMatched:!1,teamIdMatched:!1,allDevicesInProfile:!1,missingDeviceUdids:[],aclMatched:!1,cerMatched:!1,cerNotExpired:!1,storePasswordValid:!1};return n.force?{...e,force:!0}:{...e,...n,force:!1}}import{debuglog as Uf}from"util";import{execa as Bf}from"execa";async function SP(n,e){let t=await Od(n);if(!t)throw new Error(k.DEVICE_LIST_EMPTY);let r=await aH(e);if(t.length===0)for(let s of r)await oH(n,s.udid,s.deviceName);else for(let s of r)await sH(n,t,s.udid,s.deviceName);let o=(await Od(n)).map(s=>s.id);if(o.length===0)throw new Error(k.DEVICE_LIST_EMPTY);return o}async function oH(n,e,t){await CP(n,e,EP(t))}async function sH(n,e,t,r){for(let i=0;i<e.length;i++){if(t===e[i].udid)return;if(i===e.length-1){await CP(n,t,EP(r));return}}}function EP(n){switch(n){case"liteWearable":return"1";case"wearable":return"2";case"tv":return"3";default:return"4"}}async function bP(n,e=1,t=100){let r=`${fe.BASE_URL}${fe.DEVICE_LIST_PATH}?encodeFlag=0&start=${e}&pageSize=${t}`,i=kP(n),o=await $.get(r,{headers:i});if(!o)throw Uf("query devices failed: response is null"),new Error(k.ERROR_WHILE_ADD_DEVICE);if(o.statusCode!==200)throw PP(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.list)throw Uf("query devices failed: response list is null"),new Error(s.ret?.msg||k.ERROR_WHILE_ADD_DEVICE);return{deviceList:s.list,total:s.totalCount||0}}function PP(n,e,t){return n===Ut.FORBIDDEN?e===Te.OPENPROXY_BLOCKED_URL?new Error(k.ERR_CERT_NETWORK_ERROR):new Error(k.ERR_FORBIDDEN):n===Ut.UNAUTHORIZED?new Error(k.ERR_UNAUTHORIZED):t.includes(Te.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(k.DEVICE_LIMIT_REACHED):new Error(k.ERROR_WHILE_ADD_DEVICE)}async function Od(n){let t=await bP(n,1,100);if(!t||!t.deviceList||t.deviceList.length===0)return[];let r=[...t.deviceList],i=t.total,o=Math.floor(i/100)+(i%100===0?0:1);for(let s=2;s<=o;s++){let a=await bP(n,s,100);if(!a||!a.deviceList||a.deviceList.length===0)break;r.push(...a.deviceList)}return r}async function CP(n,e,t){let r=`${fe.BASE_URL}${fe.DEVICE_ADD_PATH}`,i=kP(n),s={deviceName:`auto_sign_device_No.${Math.floor(Math.random()*3e3)}${Date.now()}`,udid:e,deviceType:t},a=await $.postAllowFailure(r,{headers:i,params:s});if(!a)throw Uf("add device failed: response is null"),new Error(k.ERROR_WHILE_ADD_DEVICE);if(a.statusCode!==200)throw PP(a.statusCode,a.statusText,a.data);let c=a.data,l=JSON.parse(a.data);if(!l||!l.ret||l.ret.code!==0)throw c.includes(Te.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(k.DEVICE_LIMIT_REACHED):c.includes(Te.DEVICE_NAME_REPEAT_CODE)?new Error(k.DEVICE_NAME_REPEAT):new Error(k.ERROR_WHILE_ADD_DEVICE)}function kP(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}async function aH(n){let{stdout:e}=await Bf(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
1380
+ `)){let o=i.trim();if(!o||o.startsWith("[Empty]"))continue;let s=o.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let r=[];for(let i of t)try{let o=await cH(i,n),s=await lH(i,n);o.length>0&&r.push({id:"",udid:o,deviceName:s})}catch{m(`Failed to get device info for ${i}, skipping`)}return r}async function cH(n,e){let{stdout:t}=await Bf(e,["-t",n,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),r=t.trim();if(!r)return"";let i=r.split(`
1381
+ `);for(let s=0;s<i.length-1;s++)if(i[s].includes("udid of current device is")){let c=i[s+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(c)return c[0].toUpperCase()}let o=r.match(/[A-Fa-f0-9]{64}/);return o?o[0].toUpperCase():""}async function lH(n,e){let{stdout:t}=await Bf(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return dH(t)}function dH(n){let e=n.trim();return!e||e.includes("inaccessible")?"phone":n.includes("liteWearable")?"liteWearable":n.includes("wearable")?"wearable":n.includes("tv")?"tv":"phone"}import ci from"fs";import{createHash as uH}from"crypto";import{debuglog as di}from"util";import{Buffer as DP}from"buffer";import{createPublicKey as pH,X509Certificate as Wf}from"crypto";import{readFileSync as mH}from"fs";import li from"node-forge";async function xP(n,e){console.log("Start generating profile");let{productName:t,bundleName:r,projectPath:i,aclPermissionList:o,allDeviceIds:s,certIds:a,keyAlias:c,keyPwd:l}=e,d=e.type==="release";if(!d&&(s==null||s.length===0))throw new Error(k.DEVICE_LIST_EMPTY);let g=d?fe.PROVISION_ADD_REAL_PATH:fe.PROVISION_ADD_TEST_PATH,w=`${fe.BASE_URL}${g}`,R=fH(t,r),z=await gH(n,w,a||[],r,s??[],R,o||[]);if(!z||!z.profileInfo||!z.profileInfo.provisionFileUrl)throw di("add provision failed, the provision file url is null"),new Error(k.ADD_PROFILE_FAIL);let ie=z.profileInfo,Wt=(await bH(n,ie.provisionFileUrl)).urlList,Cn=z.profileInfo.id;if(Wt&&Wt.length>0){let kn=await Sd(t,i,e.type),Rn=kn.profilePath;if(!await SH(Wt,Rn))throw await RP(n,Cn),new Error(k.ERROR_WHILE_DOWNLOAD_PROFILE);if(await RP(n,Cn),ci.existsSync(kn.certPath)&&ci.existsSync(Rn)&&ci.existsSync(kn.p12Path)){let zP=ci.readFileSync(kn.certPath,"utf8"),JP=ci.readFileSync(Rn,"utf8");return EH(JP,zP,kn.p12Path,c,l)||vH(Rn),Rn}}throw new Error(k.ADD_PROFILE_FAIL)}function fH(n,e){let t=n?`${n}_`:"";return`${hH(`${t}${e}_${e}`)}`}function hH(n){return uH("sha256").update(n).digest("hex").substring(0,16)}async function gH(n,e,t,r,i,o,s){yH(r);let a=Gf(n),c={certList:t,packageName:r,provisionName:o};i.length>0&&(c.deviceList=i),s.length&&(c.aclPermissionList=s);let l=await $.postAllowFailure(e,{headers:a,params:c});if(!l)throw m("[generateProfile] add provision failed: response is null"),new Error(k.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw m(`[generateProfile] add provision HTTP ${l.statusCode}: ${l.data}`),Vf(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw m(`[generateProfile] add provision fail: ${l.data}`),wH(l.data,o),new Error(d.ret?.msg||k.ADD_PROFILE_FAIL);let g=d.provisionFileUrl;return{profileInfo:{id:d.id,name:o,provisionFileUrl:g}}}function Vf(n,e,t){return n===Ut.FORBIDDEN?e===Te.OPENPROXY_BLOCKED_URL?new Error(k.ERR_CERT_NETWORK_ERROR):new Error(k.ERR_FORBIDDEN):n===Ut.UNAUTHORIZED?new Error(k.ERR_UNAUTHORIZED):t.includes(Te.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(k.TEST_PROVISION_EXCEEDS_LIMIT):new Error(k.ADD_PROFILE_FAIL)}function yH(n){if(!n||n.trim().length===0)throw new Error(k.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!Re.BUNDLE_NAME_REGEX.test(n))throw new Error(k.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function wH(n,e){if(n.includes(Te.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(k.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(Te.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(k.PROFILE_NAME_REPEAT)}async function RP(n,e){if(!e||e.trim().length===0)return;let t=`${fe.BASE_URL}${fe.PROVISION_DELETE_PATH}?id=${e}`,r=await $.deleteAllowFailure(t,{headers:Gf(n)});if(r.statusCode!==200)throw Vf(r.statusCode,r.statusText,r.data);let i=JSON.parse(r.data);(!i||!i.ret||i.ret.code!==0)&&di(`delete provision failed: ${r.data}`)}function vH(...n){for(let e of n)try{ci.existsSync(e)&&ci.unlinkSync(e)}catch(t){di(`delete local sign file error: ${t.message}`)}}async function bH(n,e){let t=`${fe.BASE_URL}${fe.CERT_DOWNLOAD_URL_PATH}`,r=Gf(n),i={sourceUrls:e},o=await $.postAllowFailure(t,{headers:r,params:i});if(!o)throw di("get download list failed: response is null"),new Error(k.ADD_PROFILE_FAIL);if(o.statusCode!==200)throw Vf(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw di("download: The application does not exist"),new Error(s.ret?.msg||k.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function SH(n,e){if(!n||n.length===0)return!1;let t=n[0];return await oa(t.newUrl,e,t.sha256),!0}function EH(n,e,t,r,i){return PH(n,e),r=r||Re.TARGET_FRIENDLY_NAME,i=i||"",CH(e,t,r,i),!0}function PH(n,e){if(e.lastIndexOf(Re.CERT_BEGIN_HEADER)<0)throw new Error(k.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(Re.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(k.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function CH(n,e,t,r){let i=n.matchAll(Re.CERTIFICATE_PATTERN_GLOBAL),o=[],s=new Date;for(let c of i)try{let l=c[0],d=kH(l),g=new Date(d.validFrom),w=new Date(d.validTo);if(s<g||s>w){let R=`Certificate is not valid, Valid from ${g} to ${w}`;throw console.warn(`checkCertificateInValidityPeriod: ${R}`),new Error(k.CERTIFICATE_HAS_EXPIRED)}o.push(d)}catch(l){throw console.warn(`checkCertificateInValidityPeriod\uFF1A ${l.message}`),new Error(k.CERTIFICATE_HAS_EXPIRED,{cause:l})}if(!o||o.length===0)throw new Error(k.CERTIFICATE_HAS_EXPIRED);if(!DH(e,t,r,o))throw new Error(k.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function kH(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new Wf(t);let r=DP.from(t,"base64");return new Wf(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function RH(n){if(n.cert){let e=li.pki.publicKeyToPem(n.cert.publicKey);return pH(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=li.asn1.toDer(n.asn1).getBytes(),t=DP.from(e,"binary");return new Wf(t).publicKey.export({type:"spki",format:"der"})}catch(e){return di(`Failed to parse cert from asn1: ${e}`),null}return null}function DH(n,e,t,r){try{let i=mH(n),o=li.asn1.fromDer(li.util.createBuffer(i)),c=li.pkcs12.pkcs12FromAsn1(o,t).getBags({bagType:li.pki.oids.certBag})[li.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let g=RH(l);if(!g)continue;if(r.some(R=>{let z=R.publicKey.export({type:"spki",format:"der"});return g.equals(z)}))return!0}return!1}catch(i){let o=i instanceof Error?i.message:String(i);return di(`Failed to process P12 file: ${n}, error: ${o}`),!1}}function Gf(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var IP="https://developer.huawei.com",xH={"ohos.permission.SYSTEM_FLOAT_WINDOW":"/consumer/cn/doc/harmonyos-guides/window-pipwindow","ohos.permission.READ_CONTACTS":"/consumer/cn/doc/harmonyos-references/js-apis-contact#contactselectcontacts10","ohos.permission.READ_IMAGEVIDEO":"/consumer/cn/doc/harmonyos-guides/select-user-file#%E9%80%89%E6%8B%A9%E5%9B%BE%E7%89%87%E6%88%96%E8%A7%86%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.WRITE_IMAGEVIDEO":"/consumer/cn/doc/harmonyos-guides/savebutton","ohos.permission.READ_AUDIO":"/consumer/cn/doc/harmonyos-guides/select-user-file#%E9%80%89%E6%8B%A9%E9%9F%B3%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.WRITE_AUDIO":"/consumer/cn/doc/harmonyos-guides/save-user-file#%E4%BF%9D%E5%AD%98%E9%9F%B3%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.READ_PASTEBOARD":"/consumer/cn/doc/harmonyos-guides/pastebutton"},AH="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function IH(n){let e=xH[n];return e?`${IP}${e}`:void 0}function TH(){return`${IP}${AH}`}var OH={"acl.can.apply.text":"Permission Application Scenarios","acl.permissions.warn":"Note: You are applying for restricted ACL permissions: {0} These permissions are subject to review together with your app release. For a faster review process, apply for the following permissions instead, if they are sufficient for your purposes: {1} {2}"};function AP(n,e){return(OH[n]??n).replace(/\{(\d+)\}/g,(r,i)=>String(e[Number(i)]??""))}function MH(n){return Array.from(n).join(", ")}function TP(n,e){if(n.size===0)return;let t=Sn.getAclPermissionInfos(e),r=new Set;for(let g of t)n.has(g.permissionName)&&r.add(g);for(let g of r){let w=IH(g.permissionName);w!=null&&(g.permissionHelpUrlKey=w)}let i=new Set;for(let g of r)i.add(g.permissionDisplayName);let o=new Set;for(let g of r)if(g.permissionHelpUrlKey!=null){let w=g.permissionInsteadName??g.permissionDisplayName;o.add(`${w} (${g.permissionHelpUrlKey})`)}let s=TH(),a=AP("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=o.size>0?Array.from(o).join(", ")+".":"",d=AP("acl.permissions.warn",[MH(i),l,c]);console.log(d)}var Md=class{_project=null;get project(){if(!this._project)throw new Error("Project not initialized. Call checkProjectDir first.");return this._project}checkProjectDir(e){try{return this._project=B.discover(process.cwd()),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Project.discover() failed: ${t.message}`),e(ve.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Product validation failed: ${r.message}`),t(`Product "${e}" not found.Check the product property in the build-profile.json5 file.`)}}checkBundleName(e,t){try{return this._project.getBundleName(),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] BundleName check failed: ${r.message}`),t(`bundleName was not found under product "${e}".Check the bundleName configuration.`)}}checkAtomicService(){return this._project.isAtomicService()?{passed:!1,message:ve.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import NH from"fs";import OP from"path";var Nd=class{constructor(e){this.toolProvider=e}checkJava(e){try{return this.toolProvider.assertJava(),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Java check failed: ${t.message}`),e(`${t.message}`)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=OP.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");if(!NH.existsSync(r)){let i=OP.join("sdk","default","openharmony","toolchains","lib","hap_sign_tools.jar");return e(`hap_sign_tools.jar not found.Check whether ${i} exists.`)}return{passed:!0,message:""}}};var Ld=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await qe.getUserInfo()}catch(e){return m(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await qe.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(ve.LOGIN_REQUIRED)}catch(t){return m(`[EnvCheck] Login check failed: ${t.message}`),e(ve.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(ve.TEAM_INFO_FAILED);try{if((await nn()).teamList.length>0)return{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Team API error: ${r.message}`),e(ve.TEAM_INFO_FAILED)}return m("[EnvCheck] No teams found for current user"),e(ve.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(ve.REALNAME_REQUIRED):t.isRealName!==!0?(m("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(ve.REALNAME_REQUIRED)):{passed:!0,message:""}:e(ve.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let i=await nn();if(r=e??(i.teamList.length>0?i.teamList[0].id:t.userId)??"",!i.teamList.some(s=>s.id===r)){let s=`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`;return m(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(i){return m(`[EnvCheck] Team ID check failed: ${i.message}`),{passed:!1,message:`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`}}}async checkRegion(e){let t=await this.ensureUserInfo();return t?t.countryCode?t.countryCode!=="CN"?e(ve.REGION_CHINA_ONLY):{passed:!0,message:""}:(m("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(ve.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function LH(n){try{let{teamList:e}=await nn();if(e.length>0)return e[0].id}catch(e){m(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function _H(n){let e=await qe.getUserInfo(),t=await qe.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await LH(e.userId);if(!r)throw new Error("No team found");let i={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await Od(i)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var _d=class{constructor(e){this.toolProvider=e}async checkDevice(e,t){try{let r=await _H(t);if(r.length>0)return m(`[EnvCheck] Scenario 4 Device check: ${r.length} device(s) found in AGC cloud, skipping local device check`),{passed:!0,message:""};m("[EnvCheck] Scenario 4 Device check: no cloud devices found, falling back to local hdc");let o=await le.from(this.toolProvider).listDevices();return o.length===0?(m("[EnvCheck] Scenario 4 Device check: no local devices found"),e(ve.DEVICE_MISSING)):o.some(a=>Jt(a.serial))?{passed:!0,message:""}:(m("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(ve.DEVICE_MISSING))}catch(r){return m(`[EnvCheck] Scenario 4 Device check failed: ${r.message}`),e(ve.DEVICE_DETECT_FAILED)}}};var $d=class{projectChecker=new Md;toolchainChecker=null;authChecker=new Ld;deviceChecker=null;constructor(){}async preflight(e){let t=r=>this.blockingFail(r);return!(!await this.runAuthChain(e,t)||!await this.initToolchain()||e.type!=="release"&&!await this.runDeviceCheck(e,t)||!await this.runProjectChecks(e,t)||!await this.runAuxChecks(e))}async runAuthChain(e,t){let r=o=>(o.passed||this.fail(o),!0),i=[()=>this.authChecker.checkLogin(t),()=>this.authChecker.checkRealname(t),()=>this.authChecker.checkTeamInfo(t)];for(let o of i)if(!r(await o()))return!1;return!(e.teamId&&!r(await this.authChecker.checkTeamId(e.teamId)))}async initToolchain(){try{let e=await P.new();return this.toolchainChecker=new Nd(e),this.deviceChecker=new _d(e),!0}catch(e){throw m(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(ve.TOOLCHAIN_INIT_FAILED,{cause:e})}}async runDeviceCheck(e,t){return(i=>i.passed?!0:(this.fail(i),!1))(await this.deviceChecker.checkDevice(t,e.teamId))}async runProjectChecks(e,t){let r=o=>o.passed?!0:(this.fail(o),!1);if(!r(this.projectChecker.checkProjectDir(t))||!r(this.projectChecker.checkAtomicService()))return!1;let i=[()=>this.projectChecker.checkProduct(e.productName,t),()=>this.projectChecker.checkBundleName(e.productName,t),()=>this.toolchainChecker.checkJava(t),()=>this.toolchainChecker.checkHapSignTools(t)];for(let o of i)if(!r(o()))return!1;return!0}async runAuxChecks(e){let t=r=>r.passed?!0:(this.fail(r),!1);return!e.teamId&&!t(await this.authChecker.checkTeamId(e.teamId))?!1:(await this.authChecker.checkRegion(r=>this.blockingFail(r)),!0)}blockingFail(e){return{passed:!1,message:e}}fail(e){throw m(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};var MP=5*1024*1024;function jH(n){try{let e=ui.statSync(n);if(e.size>MP)throw new Error(`Profile file too large: ${e.size} bytes (max ${MP} bytes): ${n}`);let t=ui.readFileSync(n,"utf-8");return _P.parse(t)}catch(e){if(e.code==="ENOENT")return{app:{signingConfigs:[],products:[]}};throw new Error(`Failed to read profile: ${n}`,{cause:e})}}function HH(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function UH(n){if(n.keyPwd===n.storePassword){let r=await bn.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await bn.encryptedPassword(n.keyPwd,n.p12FilePath),t=await bn.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function $P(n,e,t,r){let i=zf.join(n,"build-profile.json5"),o=jH(i);HH(o);let s=r==="release"?`${t??"default"}_release`:t??"default",{keyPassword:a,storePassword:c}=await UH(e),l={name:s,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:a,profile:e.profileFilePath,signAlg:Nr.signAlg,storeFile:e.p12FilePath,storePassword:c}},d=o.app?.signingConfigs?.findIndex(w=>w.name===s);d!==void 0&&d>=0?o.app.signingConfigs[d]=l:o.app.signingConfigs.push(l);let g=o.app?.products?.findIndex(w=>w.name===t);g!==void 0&&g>=0?o.app.products[g].signingConfig=s:o.app.products.push({name:t,signingConfig:s}),ui.writeFileSync(i,_P.stringify(o,null,2),"utf-8")}async function BH(n){let e=await qe.getUserInfo(),t=await qe.refreshToken();if(!e||!t)throw new Error("Failed to obtain login credentials. Run `devecocli auth login` again.");return{uid:e.userId??"",teamId:n.teamId??e.userId??"",accessToken:t.accessToken??""}}var NP=["debug","release"];async function WH(n){let e=n.product||"default";if(n.type&&!NP.includes(n.type))throw new Error(`Invalid signing type '${n.type}'. Valid types: ${NP.join(", ")}`);await new $d().preflight({productName:e,teamId:n.teamId,type:n.type}),console.log("Executing signature generate command");let r=await BH(n),i=await P.new(),{shouldRegenerate:o}=await ca.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product,type:n.type},i);if(!o){console.log(qf("Signature generation completed successfully."));return}await VH(n,r,i)||(process.exitCode=1)}async function VH(n,e,t){if(n.type==="release"&&await qH(n))return!1;let r=await Mf(e,n.product,n.type),i=zH(n,e,r,t);n.type!=="release"&&(i.allDeviceIds=await SP(e,t.hdcPath));try{await xP(e,i)}catch(s){if(n.type==="release")return GH(n,r);throw s}let o=B.discover(process.cwd()).rootDir;return await $P(o,r,n.product??"default",n.type),console.log(qf(`Signing config written to ${zf.join(o,"build-profile.json5")}`)),console.log(qf("Signature generation completed successfully.")),!0}async function GH(n,e){let t=n.product||"default",r=B.discover(process.cwd()).rootDir;return await $P(r,e,t,n.type),console.warn(LP(`
1382
+ Release certificate materials generated successfully, but the release Profile (.p7b) cannot be auto-generated.
1383
+ Signing config (with encrypted p12 password) has been written to build-profile.json5.
1384
+ Please go to AGC (https://developer.huawei.com/consumer/cn/doc/doccenter-deveco-studio/ide-publish-app#section1079214271414) to manually apply for a release Profile:
1385
+ 1. Use the generated .csr file to apply for a release certificate
1386
+ 2. Apply for and download the release Profile (.p7b)
1387
+ 3. Set the profile path in the '${t}_release' signing config in build-profile.json5
1388
+ 4. Build with: devecocli build --assemble-type assembleHap --build-mode release --signing-config ${t}_release
1389
+
1390
+ Generated files:
1391
+ p12: ${e.p12FilePath}
1392
+ csr: ${e.csrFilePath}
1393
+ cer: ${e.cerFilePath}
1394
+
1395
+ Signing config '${t}_release' written to ${zf.join(r,"build-profile.json5")}
1396
+ `)),!1}async function qH(n){let e=B.discover(process.cwd()).rootDir,t=n.product||"default",r=await Sd(t,e,n.type),i=ui.existsSync(r.p12Path)&&ui.existsSync(r.csrPath)&&ui.existsSync(r.certPath),o=ui.existsSync(r.profilePath);return!i||o?!1:(console.warn(LP(`
1397
+ Release certificate materials already exist. Profile (.p7b) is still missing.
1398
+ Please go to AGC (https://developer.huawei.com/consumer/cn/doc/doccenter-deveco-studio/ide-publish-app#section1079214271414) to manually apply for a release Profile:
1399
+ 1. Use the generated .csr file to apply for a release certificate
1400
+ 2. Apply for and download the release Profile (.p7b)
1401
+ 3. Set the profile path in the '${t}_release' signing config in build-profile.json5
1402
+ 4. Build with: devecocli build --assemble-type assembleHap --build-mode release --signing-config ${t}_release
1403
+
1404
+ Existing files:
1405
+ p12: ${r.p12Path}
1406
+ csr: ${r.csrPath}
1407
+ cer: ${r.certPath}
1408
+ `)),!0)}function zH(n,e,t,r){let i=process.cwd(),o=B.discover(i),s=Id(o,r);return TP(s,o),{productName:n.product||"default",bundleName:o.getBundleName(n.product||"default"),projectPath:o.rootDir,teamId:e.teamId,force:n.force||!1,aclPermissionList:[...s],certIds:[t.certId],keyAlias:t.keyAlias,keyPwd:t.keyPwd,type:n.type||"debug"}}var FP=new $H("signature").description("Generate application signature.");FP.command("generate").description("Automatically generate signing materials and write them to the project configuration.").option("--force","Force overwrite existing local signing materials.").option("--team-id <team-id>","Specify the team ID to use.").option("--product <product>","Specify the product. The default value is default.").option("--type <type>","Signing type: debug or release (default: debug)").action(async n=>{let e={event:v.CommandExecuted,args:["signature","generate",...n.force?["--force"]:[],...n.teamId?["--team-id"]:[],...n.product?["--product"]:[],...n.type?["--type"]:[]]},t=Date.now(),r=!0,i=null;try{await WH(n)}catch(o){r=!1,i=X(o),console.error(FH(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await D.track(e,o)}});var jP=FP;import{Command as nU}from"commander";import{green as iU,red as rh}from"colorette";import ko from"fs";import Hd from"path";import oU from"ora";import Fd from"fs";import Jf from"path";import{homedir as JH}from"os";function HP(){let n=process.env.DEVECO_CLI_DATA_DIR?W():Jf.join(JH(),be.CONFIG_DIR_NAME,be.APP_NAME);return Jf.join(n,"ui_verification_config.json")}function UP(){let n=HP();if(!Fd.existsSync(n))return{};try{let e=JSON.parse(Fd.readFileSync(n,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Yf(){let n=UP();if(Object.keys(n).length===0)return null;let e;if(pm(n.encryptedApiKey))try{e=um(n.encryptedApiKey)}catch{}return{baseUrl:typeof n.baseUrl=="string"?n.baseUrl:void 0,modelName:typeof n.modelName=="string"?n.modelName:void 0,apiKey:e}}function Kf(n){let e=HP();Fd.mkdirSync(Jf.dirname(e),{recursive:!0,mode:448});let t=UP();return n.baseUrl!==void 0&&(t.baseUrl=n.baseUrl),n.modelName!==void 0&&(t.modelName=n.modelName),n.apiKey!==void 0&&(t.encryptedApiKey=dm(n.apiKey),delete t.apiKey),Fd.writeFileSync(e,JSON.stringify(t,null,2),{encoding:"utf8",mode:384}),e}import jd from"fs";import YH from"os";import BP from"path";var pi=BP.join(YH.tmpdir(),"ui-verification","cache"),KH=15;function Xf(n=pi,e=KH){if(!jd.existsSync(n))return;let t=jd.readdirSync(n,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>{let i=BP.join(n,r.name);return{entryPath:i,mtime:jd.statSync(i).mtimeMs}}).sort((r,i)=>r.mtime-i.mtime);for(let r of t.slice(0,Math.max(0,t.length-e)))jd.rmSync(r.entryPath,{recursive:!0,force:!0})}import{execFile as XH,spawn as ZH}from"child_process";import QH from"fs";import Zf from"path";import{fileURLToPath as eU}from"url";function tU(){let n=Zf.dirname(eU(import.meta.url));for(;;){let e=Zf.join(n,"node_modules","ui-verification-mcp","bin","ui-verification-mcp.cjs");if(QH.existsSync(e))return e;let t=Zf.dirname(n);if(t===n)break;n=t}throw new Error("ui-verification-mcp is not installed. Run `npm install` and try again.")}var la=class n{constructor(e){this.child=e;this.stopped=new Promise(r=>e.once("close",()=>r())),e.stdout?.on("data",r=>{this.buffer+=r.toString();let i=this.buffer.split(`
1409
+ `);this.buffer=i.pop()??"";for(let o of i)if(o.trim())try{this.handleMessage(JSON.parse(o))}catch{}});let t=r=>{this.closedError??=r;for(let i of this.pending.values())i.reject(r);this.pending.clear(),this.progressHandlers.clear()};e.on("error",t),e.on("exit",(r,i)=>{let o=r===null?`signal ${i??"unknown"}`:`code ${r}`;t(new Error(`ui-verification-mcp exited with ${o}`))})}buffer="";nextId=1;pending=new Map;progressHandlers=new Map;closedError;closePromise;stopped;abortCleanup;handleMessage(e){if(!("id"in e)){if(e.method!=="notifications/progress")return;let i=e.params;if(i?.progressToken===void 0||i.progress===void 0)return;this.progressHandlers.get(i.progressToken)?.(i.progress,i.total,i.message);return}let t=e.id;if(typeof t!="number")return;let r=this.pending.get(t);r&&(this.pending.delete(t),r.resolve(e))}sendAndWait(e,t,r,i="MCP request timed out"){return new Promise((o,s)=>{if(this.closedError){s(this.closedError);return}this.registerPending(e,o,s,r,i);try{this.child.stdin?.write(`${JSON.stringify(t)}
1410
+ `)}catch(a){let c=this.pending.get(e);this.pending.delete(e),c?.reject(a instanceof Error?a:new Error(String(a)))}})}registerPending(e,t,r,i,o="MCP request timed out"){let s=!1,a=i===void 0?void 0:setTimeout(()=>{s||(s=!0,this.pending.delete(e),r(new Error(o)))},i),c=()=>{a!==void 0&&clearTimeout(a)};this.pending.set(e,{resolve:l=>{s||(s=!0,c(),t(l))},reject:l=>{s||(s=!0,c(),r(l))}})}static async start(e,t){t?.throwIfAborted();let r=tU();m(`Executing: ${process.execPath} ${r}`);let i=ZH(process.execPath,[r],{env:e,detached:process.platform!=="win32",stdio:["pipe","pipe","ignore"]}),o=new n(i);o.attachCancellation(t);try{return await o.sendAndWait(0,{jsonrpc:"2.0",id:0,method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"devecocli",version:"1.0.0"}}}),o}catch(s){throw await o.close(s instanceof Error?s:new Error(String(s))),s}}async callTool(e,t,r,i){let o=this.nextId++;r&&this.progressHandlers.set(o,r);try{let s=await this.sendAndWait(o,{jsonrpc:"2.0",id:o,method:"tools/call",params:{name:e,arguments:t,...r?{_meta:{progressToken:o}}:{}}},i,`${e} timed out after ${Math.floor((i??0)/6e4)} minutes`);if(s.error){let l=s.error;throw new Error(String(l.message??`${e} failed`))}let a=s.result;if(a?.structuredContent!==void 0)return a.structuredContent;let c=a?.content;return c?.length&&typeof c[0].text=="string"?c[0].text:a}finally{this.progressHandlers.delete(o)}}attachCancellation(e){if(!e)return;let t=()=>{let r=e.reason;this.close(r instanceof Error?r:new Error("Verification cancelled by user"))};e.addEventListener("abort",t,{once:!0}),this.abortCleanup=()=>e.removeEventListener("abort",t),e.aborted&&t()}close(e=new Error("ui-verification-mcp session closed")){if(this.closePromise)return this.closePromise;this.closedError??=e,this.abortCleanup?.(),this.abortCleanup=void 0;for(let t of this.pending.values())t.reject(e);return this.pending.clear(),this.progressHandlers.clear(),this.closePromise=this.terminateProcessTree(),this.closePromise}async terminateProcessTree(){if(!this.child.pid){await this.stopped;return}if(process.platform==="win32"){let t=["/pid",String(this.child.pid),"/t","/f"];m(`Executing: taskkill ${t.join(" ")}`),await new Promise(r=>XH("taskkill",t,()=>r())),await this.stopped;return}this.killProcessGroup("SIGTERM");let e=setTimeout(()=>this.killProcessGroup("SIGKILL"),1e3);try{await this.stopped}finally{clearTimeout(e),this.killProcessGroup("SIGKILL")}}killProcessGroup(e){try{process.kill(-this.child.pid,e)}catch(t){if(t.code!=="ESRCH")throw t}}};import WP from"fs";import th from"path";async function eh(n,e){let t=await new de(n).listTargets();if(t.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");if(e){let r=e.toLowerCase(),i=t.filter(o=>o.id===e||o.name.toLowerCase().includes(r));if(i.length===1)return i[0].id;throw i.length>1?new Error(`Multiple devices match '${e}'. Use a serial instead:
1411
+ ${Qf(i)}`):new Error(`Device '${e}' not found.
1412
+ Available devices:
1413
+ ${Qf(t)}`)}if(t.length===1)return t[0].id;throw new Error(`Multiple devices connected. Use --device <name|serial> to specify one.
1414
+ Available devices:
1415
+ ${Qf(t)}`)}function Qf(n){return n.map(e=>` - ${e.name} (${e.id})`).join(`
1416
+ `)}var Pn=class extends Error{exitCode;constructor(e){super("Verification cancelled by user"),this.exitCode=e==="SIGINT"?130:143}};var rU=600*1e3,da=class{async verifyUi(e,t,r){let i=this.resolveBundleName(e.bundleName),o=await P.new(),s=await eh(o,e.device),a=new AbortController,c=()=>a.abort(new Pn("SIGINT")),l=()=>a.abort(new Pn("SIGTERM"));process.on("SIGINT",c),process.on("SIGTERM",l);let d;try{d=await this.startSession(t,o.hdcPath,a.signal);let g=await d.callTool("verifyUI",{testPlan:e.testPlan,bundleName:i,freshStart:e.freshStart,device:s},r,rU),w=this.parseVerifyResult(g);return await this.cacheArtifacts(d,w.id,a.signal),a.signal.throwIfAborted(),Xf(),w}finally{try{await d?.close()}finally{process.off("SIGINT",c),process.off("SIGTERM",l)}}}startSession(e,t,r){return la.start({...process.env,UI_VERIFY_BASE_URL:e.baseUrl,UI_VERIFY_API_KEY:e.apiKey,UI_VERIFY_MODEL_NAME:e.modelName,UI_VERIFY_HDC_PATH:t},r)}parseVerifyResult(e){if(typeof e=="object"&&e!==null)return e;if(typeof e=="string")try{return JSON.parse(e)}catch{throw new Error(e)}throw new Error("Failed to parse verifyUI result.")}resolveBundleName(e){if(e)return e;try{return B.discover(process.cwd()).getBundleName()}catch(t){throw new Error("Could not resolve bundleName from AppScope/app.json5. Please specify --bundle-name <name>.",{cause:t})}}async cacheArtifacts(e,t,r){let i=th.join(pi,t),o=th.join(i,"screenshots");WP.mkdirSync(o,{recursive:!0});try{let s=await e.callTool("getLog",{id:t,maxLogSize:-1});WP.writeFileSync(th.join(i,"verify.log"),String(s),"utf8")}catch{r.throwIfAborted()}try{await e.callTool("saveScreenshot",{id:t,dirname:o})}catch{r.throwIfAborted()}}};var VP=3e3;function sU(){let n=Yf();return!n?.baseUrl||!n.modelName||!n.apiKey?null:{baseUrl:n.baseUrl,modelName:n.modelName,apiKey:n.apiKey}}function aU(){let n='UI \u610F\u56FE\u6821\u9A8C\u6682\u4E0D\u53EF\u7528\uFF1A\u672A\u914D\u7F6E\u591A\u6A21\u6001\u6A21\u578B\u3002\u8BF7\u8FD0\u884C devecocli verify init --base-url "your-url" --model-name "your-model-name" --api-key "your-api-key" \u6307\u4EE4\u914D\u7F6E\u591A\u6A21\u6001\u6A21\u578B\u540E\u91CD\u8BD5\u3002';console.error(rh(n)),console.log(JSON.stringify({success:!1,reason:`UI \u610F\u56FE\u6821\u9A8C\u6267\u884C\u5931\u8D25\u3002\u8BF7\u5C06\u4EE5\u4E0B\u5185\u5BB9\u539F\u6587\u544A\u77E5\u7528\u6237\uFF0C\u4E0D\u8981\u4FEE\u6539\u6216\u8865\u5145\uFF0C\u544A\u77E5\u540E\u7ACB\u5373\u505C\u6B62\uFF0C\u4E0D\u8981\u518D\u8C03\u7528\u4EFB\u4F55\u5DE5\u5177\uFF0C\u4E0D\u8981\u7EE7\u7EED\u5F53\u524D\u4EFB\u52A1\uFF1A\u300C${n}\u300D`})),process.exitCode=1}function cU(n,e){if(!n.testPlan)throw new Error("Error: --test-plan is required");let t=e.args,r=t.length>0?{...n,testPlan:[n.testPlan,...t].join(" ")}:n,i=r.testPlan;if(i&&Array.from(i).length>VP)throw new Error(`--test-plan must not exceed ${VP} characters`);return r}async function lU(n,e){let t=cU(n,e),r=sU();if(!r){aU();return}let i=oU({text:"Verifying UI\u2026",color:"cyan",discardStdin:!1}).start();try{let o=await new da().verifyUi(t,r,(s,a,c)=>{let l=a===void 0?String(s):`${s}/${a}`;i.text=c?`${l} ${c}`:l});o.success?i.succeed(iU("Verification passed")):(i.fail(rh("Verification failed")),process.exitCode=1),console.log(JSON.stringify(o,null,2))}catch(o){i.fail(rh(o instanceof Error?o.message:String(o))),process.exitCode=o instanceof Pn?o.exitCode:1}}function dU(n){let e=Hd.join(pi,n.id,"verify.log");if(!ko.existsSync(e))throw new Error(`No log found for ID: ${n.id}`);let t=ko.readFileSync(e,"utf8");if(n.searchKeywords&&(t=t.split(`
1417
+ `).filter(i=>i.includes(n.searchKeywords)).map(i=>`${i}
1418
+ `).join(""),!t)){console.log(`The log does not contain the keyword '${n.searchKeywords}'.`);return}let r=Number.parseInt(n.maxLogSize,10);if(r===-1){console.log(t);return}if(r<0||Number.isNaN(r))throw new Error("Please enter the correct max-log-size.");if(r===0){process.stdout.write("");return}t.length>r&&(t=`(exceeded log size limit, showing last ${r} characters)...
1419
+ ${t.slice(-r)}`),console.log(t)}function uU(n){let e=Hd.join(pi,n.id,"screenshots");if(!ko.existsSync(e))throw new Error(`No screenshots found for ID: ${n.id}`);ko.mkdirSync(n.savePath,{recursive:!0});let t=ko.readdirSync(e).map(r=>{let i=Hd.join(n.savePath,r);return ko.copyFileSync(Hd.join(e,r),i),i});console.log(JSON.stringify({filenames:t,message:"Screenshots saved successfully"},null,2))}var Ud=new nU("verify").description("Run UI verification on a connected device").option("--test-plan <plan>","Natural-language test plan describing steps and expected results").option("--bundle-name <name>","Bundle name of the app to be tested").option("--no-fresh-start","Skip relaunching the app before verification").option("--device <name|serial>","Target device name or serial").allowExcessArguments(!0).action(lU);Ud.command("init").description("Configure the vision model for UI verification").option("--base-url <url>","Base URL of the vision model").option("--model-name <name>","Vision model name").option("--api-key <key>","API key for the vision model").action(n=>{if(!n.baseUrl&&!n.modelName&&!n.apiKey)throw new Error("Error: at least one of --base-url, --model-name, --api-key is required");let e=Kf(n);console.log(`UI verification config saved to ${e}`)});Ud.command("log").description("Get verification log by ID").requiredOption("--id <id>","Verification task ID").option("--search-keywords <keywords>","Filter log by keywords").option("--max-log-size <n>","Max characters to show (-1 for unlimited)","5000").action(dU);Ud.command("screenshot").description("Save verification screenshots by ID").requiredOption("--id <id>","Verification task ID").requiredOption("--save-path <path>","Absolute path to save screenshots").action(uU);var GP=Ud;if(!Ye())try{D.init(Bd.join(W(),"TraceLogData")),D.startScheduler()}catch(n){h.error(`[telemetry] init failed: ${n instanceof Error?n.message:String(n)}`)}(async()=>{if(!Ye())try{let n=await P.new();D.setSourceType(n.sourceType);let e=n.readVersion();e&&(n.sourceType==="clt"?D.setCltVersion(e):D.setStudioVersion(e))}catch(n){h.error(`[telemetry] toolchain info failed: ${n instanceof Error?n.message:String(n)}`)}})();se.name("devecocli").description(`HarmonyOS application development command line tool
1420
1420
 
1421
- Privacy: ${Co.PRIVACY_URL}`).version("0.1.7");var gS=de.options.find(r=>r.long==="--version");gS&&(gS.flags="-V, -v, --version");de.addCommand(vm);de.addCommand(vf);de.addCommand(kf);de.addCommand(qf);de.addCommand(wh);de.addCommand(Uh);de.addCommand(hg);de.addCommand(vg);de.addCommand(Tg);de.addCommand(jg);de.addCommand(dy);de.addCommand(Ov);de.addCommand(zv);de.addCommand(Dw);de.addCommand(hS);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 cp=process.argv.slice(2);cp.length>=2&&cp[cp.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);function NM(r){let e=r;for(;e.parent&&e.parent!==de;)e=e.parent;return e}var OM=new Set(["update","auth","serve"]);de.hook("preAction",async(r,e)=>{let t=NM(e),n=Nn();if(t.name()==="update")return;let o=new pr(Lc.join(ct(),"update")),i=ur();if(n==="off"&&o.getBlockedVersions().includes(i))throw new Error(`devecocli ${i} has been disabled, run \`devecocli update\` to upgrade`);process.env.DEVECO_CLI_SKIP_VERSION_CHECK||OM.has(t.name())||await k.checkVersion()});de.hook("postAction",async(r,e)=>{if(process.exitCode||Nn()!=="off")return;await new Jo(e).checkAndNotify()});de.parseAsync(process.argv).finally(()=>{I.stopScheduler();try{Jc(Lc.join(ct(),"TraceLogData"))}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(LM(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&r instanceof Error&&r.stack&&console.error(r.stack),process.exit(1)});
1421
+ Privacy: ${Do.PRIVACY_URL}`).version("1.3.6-Test.1");var qP=se.options.find(n=>n.long==="--version");qP&&(qP.flags="-V, -v, --version");se.addCommand(kg);se.addCommand(pw);se.addCommand(Sw);se.addCommand(uv);se.addCommand($v);se.addCommand(mb);se.addCommand(Fb);se.addCommand(Ub);se.addCommand(Qb);se.addCommand(cS);se.addCommand(jS);se.addCommand(GS);se.addCommand(hE);se.addCommand(XE);se.addCommand(jP);se.addCommand(GP);for(let n=2;n<process.argv.length;n++){let e=process.argv[n];if(e==="-v"){process.argv[n]="-V";break}if(!e.startsWith("-"))break}var nh=process.argv.slice(2);nh.length>=2&&nh[nh.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);function mU(n){let e=n;for(;e.parent&&e.parent!==se;)e=e.parent;return e}var fU=new Set(["update","auth","serve"]);se.hook("preAction",async(n,e)=>{await Tb().catch(()=>{});let t=mU(e),r=Ni();if(t.name()==="update"||t.name()==="docs"&&e.name()==="update")return;let i=new qr(Bd.join(W(),"update")),o=Zt();if(r==="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||fU.has(t.name())||await P.checkVersion()});function hU(n){if(n.name()!=="status"||n.opts().format!=="json")return!1;let t=n.parent;for(;t&&t!==se;){if(t.name()==="screenrecord")return!0;t=t.parent}return!1}se.hook("postAction",async(n,e)=>{if(process.exitCode||Ni()!=="off"||hU(e))return;await new ns(e).checkAndNotify()});se.parseAsync(process.argv).finally(()=>{D.stopScheduler();try{nu(Bd.join(W(),"TraceLogData"))}catch(n){h.error(`[telemetry] background upload spawn check failed: ${n instanceof Error?n.message:String(n)}`)}}).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(pU(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});