@deveco/deveco-cli-common 1.3.7 → 1.3.9

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,112 +1,112 @@
1
1
  #!/usr/bin/env node
2
- var xC=Object.defineProperty;var IC=(n,e)=>{for(var t in e)xC(n,t,{get:e[t],enumerable:!0})};import*as pu from"path";import{program as se}from"commander";import{red as e1}from"colorette";var Vo={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},Ia={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"},jn={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},Go={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"},qo={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:Vo.LOGIN_TIMEOUT_MS,countryCode:"CN"};import{Command as $R}from"commander";import{green as kc,red as $y,yellow as Dc}from"colorette";import Ly from"json5";import*as ds from"fs";import*as Fy from"path";import Y from"fs";import*as j from"path";import Zt from"json5";import*as mu 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(`
2
+ var xC=Object.defineProperty;var AC=(n,e)=>{for(var t in e)xC(n,t,{get:e[t],enumerable:!0})};import*as mu from"path";import{program as oe}from"commander";import{red as e1}from"colorette";var Go={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},Ta={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"},ie={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"},Un={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},qo={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"},zo={baseUrl:ie.LOGIN_URL,authUrl:ie.AUTH_APPLY_PATH,tempTokenCheckUrl:ie.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:ie.JWT_TOKEN_CHECK_PATH,successRedirectUrl:ie.LOGIN_SUCCESS_PATH,failedRedirectUrl:ie.LOGIN_FAILED_PATH,logoutUrl:ie.LOGOUT_PATH,agcTeamListUrl:ie.AGC_TEAM_LIST_URL,appId:be.APP_ID,timeout:Go.LOGIN_TIMEOUT_MS,countryCode:"CN"};import{Command as jR}from"commander";import{green as Rc,red as jy,yellow as xc}from"colorette";import $y from"json5";import*as ps from"fs";import*as Hy from"path";import K from"fs";import*as j from"path";import Qt from"json5";import*as fu 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
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 h=n.extractTimestampFromLogLine(d,i);h&&(l=n.isWithinBounds(h,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",h=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),w=new Date(i,o,s,a,c,l,h);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=mu.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=mu.realpathSync(o)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${o}`}}return n.isPathContained(s,i)}};import fg from"crypto";import ae from"fs";import Ba from"os";import ut from"path";import TC from"https";var $h={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var Aa=class n{static ENDPOINT=$h.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=TC.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",h=>d.push(h)),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 Fh={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()},fu=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??Fh.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}},jh=new fu({namingStrategy:Fh.snakeCase,fieldNames:{}});import zo from"crypto";import Ta from"fs";import OC from"path";var Oa="aes-256-gcm",NC=12,MC="deveco-cli-trace-file",LC="trace-file-secret",Uh=32;function Hh(n){try{let e=Ta.readFileSync(n,"utf8").trim();return e&&Buffer.from(e,"base64").length===Uh?e:null}catch{return null}}function Bh(n){let e=OC.join(n,LC),t=Hh(e);if(t)return hu(t);let r=zo.randomBytes(Uh).toString("base64");try{Ta.mkdirSync(n,{recursive:!0});try{Ta.writeFileSync(e,r,{flag:"wx"})}catch{let i=Hh(e);if(i)return hu(i);Ta.writeFileSync(e,r)}}catch{}return hu(r)}function hu(n){return zo.createHash("sha256").update(MC).update(n).digest()}function Wh(n,e){let t=zo.randomBytes(NC),r=zo.createCipheriv(Oa,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o={version:1,algorithm:Oa,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:r.getAuthTag().toString("base64")};return JSON.stringify(o)}function Vh(n,e){let t;try{t=JSON.parse(n)}catch{return null}if(!_C(t))return n;try{let r=zo.createDecipheriv(Oa,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 _C(n){if(!n||typeof n!="object")return!1;let e=n;return e.version===1&&e.algorithm===Oa&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as J from"fs";import*as ja from"path";import re from"fs";import{spawn as $C}from"child_process";import*as Na from"os";import*as U from"path";import FC from"json5";var gu="Huawei";var Yh=3;function Ma(n){if(!re.existsSync(n)||!re.statSync(n).isDirectory())return!1;let e=re.existsSync(U.join(n,"build-profile.json5")),t=re.existsSync(U.join(n,"hvigorfile.js"))||re.existsSync(U.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=re.readFileSync(U.join(n,"build-profile.json5"),"utf-8");return FC.parse(r).app!==void 0}catch{return!1}}function yu(n,e,t){if(e>=t)return null;let r=jC(n),i=HC(r);if(i)return i;for(let o of r){let s=yu(o,e+1,t);if(s)return s}return null}function jC(n){try{let e=re.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(U.join(n,r.name));return t}catch{return[]}}function HC(n){for(let e of n)if(Ma(e))return e;return null}function br(n){if(!n||n.trim()==="")return null;let e=U.resolve(n),t;try{t=re.realpathSync(e)}catch{t=e}if(!re.existsSync(t))return null;if(Ma(t))return t;let r=t;for(let i=1;i<=3;i++){let o=U.dirname(r);if(o===r)break;if(Ma(o))return o;r=o}if(re.statSync(t).isDirectory()){let i=yu(t,0,Yh);if(i)return i}return null}function La(n){if(!n||n.trim()==="")return null;let e=U.resolve(n),t;try{t=re.realpathSync(e)}catch{t=e}return!re.existsSync(t)||!re.statSync(t).isDirectory()?null:Ma(t)?t:yu(t,0,Yh)}var Gh="DevEco Studio";function Kh(){if(process.platform==="win32"){let n=[U.join("C:\\Program Files",gu,Gh),U.join("C:\\Program Files (x86)",gu,Gh)];return qh(n)}if(process.platform==="darwin"){let n=["/Applications/DevEco Studio.app",U.join(process.env.HOME??"","Applications","DevEco Studio.app")];return qh(n)}return null}function qh(n){for(let e of n)if(re.existsSync(e))return e;return null}function Ri(n,e){let t=e?U.join("standardIndex","index.js"):"index.js";return re.existsSync(U.join(n,"ace-server"))?U.join(n,"ace-server","out",t):U.join(n,"out",t)}function _a(n){return re.existsSync(Ri(n,!0))}var UC=5e3,BC=64*1024,zh=new Map;function Xh(n,e){let t=WC(n),r=zh.get(t);if(r)return r;let i=VC(n,e).catch(()=>!1);return zh.set(t,i),i}function WC(n){let e=U.resolve(n).replace(/\\/g,"/");return process.platform==="win32"?e.toLowerCase():e}function Jh(n){try{let e=JSON.parse(n.trim());return Array.isArray(e.protocols)?e.protocols.includes("--socket"):null}catch{return null}}function VC(n,e){let t=Ri(n,!0);if(!re.existsSync(t))return Promise.resolve(!1);let r=e||process.execPath||"node",i=[t,"--list-protocols"];return g.debug(`Executing: ${r} ${i.join(" ")}`),new Promise(o=>{let s=$C(r,i,{stdio:["ignore","pipe","ignore"],windowsHide:!0}),a="",c=!1,l=h=>{c||(c=!0,clearTimeout(d),s.exitCode===null&&s.signalCode===null&&s.kill(),o(h))},d=setTimeout(()=>l(!1),UC);s.stdout?.on("data",h=>{a=(a+h.toString("utf8")).slice(-BC);let w=Jh(a);w!==null&&l(w)}),s.on("error",()=>l(!1)),s.on("close",()=>l(Jh(a)??!1))})}var GC=[".idea",".deveco","cxx","compile_commands.json"];function Hn(n){return U.join(n,...GC)}function Zh(n){return new Promise(e=>setTimeout(e,n))}var qC=new Set(["c","cc","cpp","cxx","h","hh","hpp","hxx"]);function Un(n){let e=U.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&qC.has(e)}function $a(n){return U.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function xe(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function zC(n){return xe(n)}function Ot(n){let e=zC(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function Jr(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??U.join(Na.homedir(),"AppData","Local");return U.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?U.join(Na.homedir(),"Library","Logs","devecocli-mcp-server"):U.join(Na.homedir(),".local","share","devecocli-mcp-server","logs")}function Qh(n,e){let t=JC(e),r=YC(t,n);if(r!==null)return r;let i=Date.now(),s=`${n.replace(/:/g,"\\:")}=${i}`,a=KC(t,n,s);return XC(e,a),i}function JC(n){let e;try{e=re.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function YC(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 KC(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 XC(n,e){try{re.mkdirSync(U.dirname(n),{recursive:!0})}catch{}try{re.writeFileSync(n,e.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",h=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),w=new Date(i,o,s,a,c,l,h);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=fu.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=fu.realpathSync(o)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${o}`}}return n.isPathContained(s,i)}};import fg from"crypto";import se from"fs";import Va from"os";import ut from"path";import TC from"https";var $h={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var Oa=class n{static ENDPOINT=$h.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=TC.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",h=>d.push(h)),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 Fh={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()},hu=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??Fh.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}},jh=new hu({namingStrategy:Fh.snakeCase,fieldNames:{}});import Jo from"crypto";import Na from"fs";import OC from"path";var Ma="aes-256-gcm",NC=12,MC="deveco-cli-trace-file",LC="trace-file-secret",Uh=32;function Hh(n){try{let e=Na.readFileSync(n,"utf8").trim();return e&&Buffer.from(e,"base64").length===Uh?e:null}catch{return null}}function Bh(n){let e=OC.join(n,LC),t=Hh(e);if(t)return gu(t);let r=Jo.randomBytes(Uh).toString("base64");try{Na.mkdirSync(n,{recursive:!0});try{Na.writeFileSync(e,r,{flag:"wx"})}catch{let i=Hh(e);if(i)return gu(i);Na.writeFileSync(e,r)}}catch{}return gu(r)}function gu(n){return Jo.createHash("sha256").update(MC).update(n).digest()}function Wh(n,e){let t=Jo.randomBytes(NC),r=Jo.createCipheriv(Ma,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o={version:1,algorithm:Ma,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:r.getAuthTag().toString("base64")};return JSON.stringify(o)}function Vh(n,e){let t;try{t=JSON.parse(n)}catch{return null}if(!_C(t))return n;try{let r=Jo.createDecipheriv(Ma,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 _C(n){if(!n||typeof n!="object")return!1;let e=n;return e.version===1&&e.algorithm===Ma&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as Y from"fs";import*as Ua from"path";import re from"fs";import{spawn as $C}from"child_process";import*as La from"os";import*as U from"path";import FC from"json5";var yu="Huawei";var Yh=3;function _a(n){if(!re.existsSync(n)||!re.statSync(n).isDirectory())return!1;let e=re.existsSync(U.join(n,"build-profile.json5")),t=re.existsSync(U.join(n,"hvigorfile.js"))||re.existsSync(U.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=re.readFileSync(U.join(n,"build-profile.json5"),"utf-8");return FC.parse(r).app!==void 0}catch{return!1}}function wu(n,e,t){if(e>=t)return null;let r=jC(n),i=HC(r);if(i)return i;for(let o of r){let s=wu(o,e+1,t);if(s)return s}return null}function jC(n){try{let e=re.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(U.join(n,r.name));return t}catch{return[]}}function HC(n){for(let e of n)if(_a(e))return e;return null}function Sr(n){if(!n||n.trim()==="")return null;let e=U.resolve(n),t;try{t=re.realpathSync(e)}catch{t=e}if(!re.existsSync(t))return null;if(_a(t))return t;let r=t;for(let i=1;i<=3;i++){let o=U.dirname(r);if(o===r)break;if(_a(o))return o;r=o}if(re.statSync(t).isDirectory()){let i=wu(t,0,Yh);if(i)return i}return null}function $a(n){if(!n||n.trim()==="")return null;let e=U.resolve(n),t;try{t=re.realpathSync(e)}catch{t=e}return!re.existsSync(t)||!re.statSync(t).isDirectory()?null:_a(t)?t:wu(t,0,Yh)}var Gh="DevEco Studio";function Kh(){if(process.platform==="win32"){let n=[U.join("C:\\Program Files",yu,Gh),U.join("C:\\Program Files (x86)",yu,Gh)];return qh(n)}if(process.platform==="darwin"){let n=["/Applications/DevEco Studio.app",U.join(process.env.HOME??"","Applications","DevEco Studio.app")];return qh(n)}return null}function qh(n){for(let e of n)if(re.existsSync(e))return e;return null}function xi(n,e){let t=e?U.join("standardIndex","index.js"):"index.js";return re.existsSync(U.join(n,"ace-server"))?U.join(n,"ace-server","out",t):U.join(n,"out",t)}function Fa(n){return re.existsSync(xi(n,!0))}var UC=5e3,BC=64*1024,zh=new Map;function Xh(n,e){let t=WC(n),r=zh.get(t);if(r)return r;let i=VC(n,e).catch(()=>!1);return zh.set(t,i),i}function WC(n){let e=U.resolve(n).replace(/\\/g,"/");return process.platform==="win32"?e.toLowerCase():e}function Jh(n){try{let e=JSON.parse(n.trim());return Array.isArray(e.protocols)?e.protocols.includes("--socket"):null}catch{return null}}function VC(n,e){let t=xi(n,!0);if(!re.existsSync(t))return Promise.resolve(!1);let r=e||process.execPath||"node",i=[t,"--list-protocols"];return g.debug(`Executing: ${r} ${i.join(" ")}`),new Promise(o=>{let s=$C(r,i,{stdio:["ignore","pipe","ignore"],windowsHide:!0}),a="",c=!1,l=h=>{c||(c=!0,clearTimeout(d),s.exitCode===null&&s.signalCode===null&&s.kill(),o(h))},d=setTimeout(()=>l(!1),UC);s.stdout?.on("data",h=>{a=(a+h.toString("utf8")).slice(-BC);let w=Jh(a);w!==null&&l(w)}),s.on("error",()=>l(!1)),s.on("close",()=>l(Jh(a)??!1))})}var GC=[".idea",".deveco","cxx","compile_commands.json"];function Bn(n){return U.join(n,...GC)}function Zh(n){return new Promise(e=>setTimeout(e,n))}var qC=new Set(["c","cc","cpp","cxx","h","hh","hpp","hxx"]);function Wn(n){let e=U.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&qC.has(e)}function ja(n){return U.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function xe(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function zC(n){return xe(n)}function Ot(n){let e=zC(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function Kr(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??U.join(La.homedir(),"AppData","Local");return U.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?U.join(La.homedir(),"Library","Logs","devecocli-mcp-server"):U.join(La.homedir(),".local","share","devecocli-mcp-server","logs")}function Qh(n,e){let t=JC(e),r=YC(t,n);if(r!==null)return r;let i=Date.now(),s=`${n.replace(/:/g,"\\:")}=${i}`,a=KC(t,n,s);return XC(e,a),i}function JC(n){let e;try{e=re.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function YC(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 KC(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 XC(n,e){try{re.mkdirSync(U.dirname(n),{recursive:!0})}catch{}try{re.writeFileSync(n,e.join(`
5
5
  `)+`
6
- `,"utf8")}catch{}}function wu(n,e,t="[Cleanup]"){try{let r=U.dirname(n);if(!re.existsSync(r))return;let i=Date.now();for(let o of re.readdirSync(r,{withFileTypes:!0}))o.isDirectory()&&ZC(U.join(r,o.name),i,e,t)}catch{}}function ZC(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 eg="mcp-server.log",QC="mcp-server",ek={maxSize:10*1024*1024,maxFiles:4},vu=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={...ek,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Jr(),this.currentLogFile=ja.join(this.logDir,eg),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 ja.join(this.logDir,`${QC}-${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===eg||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=ja.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}},bt=null;function Bn(n=!1){bt&&bt.dispose(),bt=new vu(n)}function tg(){bt&&(bt.dispose(),bt=null)}function rg(){bt&&bt.flush()}function ng(){return bt?.getLogFilePath()??null}function ig(){return bt?.getLogDirectory()??null}function Fa(){return bt||Bn(!1),bt}var g={debug:(n,...e)=>Fa().debug(n,...e),info:(n,...e)=>Fa().info(n,...e),warn:(n,...e)=>Fa().warn(n,...e),error:(n,...e)=>Fa().error(n,...e)};import Jo from"fs";import bu from"path";var Yo=300*1e3,Ko=3600*1e3,Su=10080*60*1e3,xi=8*1024*1024,Eu=3600*1e3,og=".pending",tk=/\.reclaim-\d+-\d+$/;function Xe(){let n=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return n==="1"||n==="true"}var rk="upload-state.json";function ag(n){return bu.join(n,rk)}function nk(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function Ha(n){try{let e=Jo.readFileSync(ag(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 nk()}}function Pu(n,e){try{Jo.writeFileSync(ag(n),JSON.stringify(e),"utf8")}catch{}}function cg(n){let e=Ha(n);e.firstEventAt===null&&(e.firstEventAt=Date.now(),Pu(n,e))}function lg(n){let e=Ha(n);e.lastUploadAt=Date.now(),e.firstEventAt=null,Pu(n,e)}function dg(n){let e=Ha(n);e.lastRetryAt=Date.now(),Pu(n,e)}function Cu(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 ku(n){if(!n.startsWith("telemetry-"))return null;let e=tk.exec(n),t=e?n.slice(0,e.index):n;if(!t.endsWith(og))return null;let r=t.slice(0,-og.length);return r.endsWith(".txt")?r:null}function Du(n){return ku(n)!==null}function ik(n,e=Date.now()){try{return e-Jo.statSync(n).mtimeMs>=Eu}catch{return!1}}function sg(n,e=Date.now()){let t;try{t=Jo.readdirSync(n)}catch{return!1}return t.some(r=>Du(r)&&ik(bu.join(n,r),e))}function ok(n,e=Date.now()){if(sg(n,e))return!0;let t=bu.join(n,"failed");if(sg(t,e))return!0;let r;try{r=Jo.readdirSync(t)}catch{return!1}for(let i of r){if(!i.startsWith("telemetry-")||!i.endsWith(".txt"))continue;let o=Cu(i);if(o!==null&&e-o<=Su)return!0}return!1}function ug(n,e=Date.now()){let t=Ha(n);return!!(t.firstEventAt!==null&&e-t.firstEventAt>=Yo||ok(n,e)&&(t.lastRetryAt===null||e-t.lastRetryAt>=Ko))}import sk from"crypto";import Ua from"fs";import ak from"path";var ck="install-id";function lk(n){return ak.join(n,ck)}function pg(n){try{let e=Ua.readFileSync(n,"utf8").trim();return dk(e)?e:null}catch{return null}}function dk(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 mg(n){let e=lk(n),t=pg(e);if(t)return t;let r=sk.randomUUID();try{Ua.mkdirSync(n,{recursive:!0});try{Ua.writeFileSync(e,r,{flag:"wx"})}catch{let i=pg(e);if(i)return i;Ua.writeFileSync(e,r)}}catch{}return r}var Xo=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 Aa;storageDir="";failedDir="";installId="";disabled=Xe();traceFileKey=Buffer.alloc(0);sessionId=fg.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){g.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=ut.join(e,"failed"),this.cliVersion="1.3.7",this.nodeVersion=process.version,this.installId=mg(e).replace(/-/g,""),this.traceFileKey=Bh(e),ae.mkdirSync(e,{recursive:!0}),ae.mkdirSync(this.failedDir,{recursive:!0}),g.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,g.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,g.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,g.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=Wh(JSON.stringify(o),this.traceFileKey);await ae.promises.appendFile(this.currentFile(),s+`
8
- `,"utf8"),cg(this.storageDir)}catch{}}buildTraceEvent(e,t,r,i){let o=`${n.EVENT_PREFIX}${e.event}`,s=jh.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:fg.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=Ba.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=Ba.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 Ba.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(Ba.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 ut.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){g.debug("[telemetry] scheduler not started (telemetry disabled)");return}g.debug(`[telemetry] scheduler started (flush every ${Yo/1e3}s, retry failed every ${Ko/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},Yo)},Yo),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},Ko)},Ko)}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),g.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 lg(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=>ut.join(this.failedDir,o)),i=!0;for(let o of r){let s=ut.basename(o),a=Cu(s);if(a!==null){if(e-a>Su){try{await ae.promises.unlink(o)}catch{}continue}await this.flushFile(o)||(i=!1)}}return i||g.warn("[telemetry] retry failed"),dg(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)Du(i)&&await this.reclaimOrphan(ut.join(t,i),e)}}async reclaimOrphan(e,t){let r;try{let l=await ae.promises.stat(e);if(t-l.mtimeMs<Eu)return;r=l.size}catch{return}let i=ut.dirname(e),o=ku(ut.basename(e));if(o===null)return;let s=await this.claimOrphan(e,i,o);if(s===null)return;let a=ut.join(i,o),c=xi-await this.fileSize(a);if(r>c){try{await ae.promises.unlink(s)}catch{}g.warn(`[telemetry] dropped stale orphan pending: ${s} (${r} bytes > budget ${c})`);return}if(await this.mergeOrphanInto(s,a)){g.warn(`[telemetry] reclaimed orphan pending: ${s} (${r} bytes)`);return}g.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${r} bytes)`)}async claimOrphan(e,t,r){let i=ut.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 g.warn(`[telemetry] merge orphan pending failed: ${e} -> ${t}: ${r instanceof Error?r.message:String(r)}`),!1}try{await ae.promises.unlink(e)}catch(r){g.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=>ut.join(this.storageDir,t)).sort()}async flushFile(e){let t=await this.fileSize(e);if(t>xi){g.warn(`[telemetry] ${ut.basename(e)} is ${t} bytes (> ${xi}), 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=Vh(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){g.warn("[telemetry] upload failed");let d=t.slice(i).join(`
6
+ `,"utf8")}catch{}}function vu(n,e,t="[Cleanup]"){try{let r=U.dirname(n);if(!re.existsSync(r))return;let i=Date.now();for(let o of re.readdirSync(r,{withFileTypes:!0}))o.isDirectory()&&ZC(U.join(r,o.name),i,e,t)}catch{}}function ZC(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 eg="mcp-server.log",QC="mcp-server",ek={maxSize:10*1024*1024,maxFiles:4},bu=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={...ek,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Kr(),this.currentLogFile=Ua.join(this.logDir,eg),Y.existsSync(this.logDir)||Y.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 Ua.join(this.logDir,`${QC}-${e}.log.${t}`)}fileExists(e){try{return Y.accessSync(e,Y.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=Y.readdirSync(this.logDir),t=[];for(let i of e)if(i===eg||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=Ua.join(this.logDir,i),s=Y.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{Y.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)&&Y.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)&&Y.renameSync(o,s)}let r=this.getRotatedFileName(e,1);Y.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=Y.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=Y.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{Y.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);Y.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{Y.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},bt=null;function Vn(n=!1){bt&&bt.dispose(),bt=new bu(n)}function tg(){bt&&(bt.dispose(),bt=null)}function rg(){bt&&bt.flush()}function ng(){return bt?.getLogFilePath()??null}function ig(){return bt?.getLogDirectory()??null}function Ha(){return bt||Vn(!1),bt}var g={debug:(n,...e)=>Ha().debug(n,...e),info:(n,...e)=>Ha().info(n,...e),warn:(n,...e)=>Ha().warn(n,...e),error:(n,...e)=>Ha().error(n,...e)};import Yo from"fs";import Su from"path";var Ko=300*1e3,Xo=3600*1e3,Eu=10080*60*1e3,Ai=8*1024*1024,Pu=3600*1e3,og=".pending",tk=/\.reclaim-\d+-\d+$/;function Xe(){let n=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return n==="1"||n==="true"}var rk="upload-state.json";function ag(n){return Su.join(n,rk)}function nk(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function Ba(n){try{let e=Yo.readFileSync(ag(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 nk()}}function Cu(n,e){try{Yo.writeFileSync(ag(n),JSON.stringify(e),"utf8")}catch{}}function cg(n){let e=Ba(n);e.firstEventAt===null&&(e.firstEventAt=Date.now(),Cu(n,e))}function lg(n){let e=Ba(n);e.lastUploadAt=Date.now(),e.firstEventAt=null,Cu(n,e)}function dg(n){let e=Ba(n);e.lastRetryAt=Date.now(),Cu(n,e)}function ku(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 Du(n){if(!n.startsWith("telemetry-"))return null;let e=tk.exec(n),t=e?n.slice(0,e.index):n;if(!t.endsWith(og))return null;let r=t.slice(0,-og.length);return r.endsWith(".txt")?r:null}function Ru(n){return Du(n)!==null}function ik(n,e=Date.now()){try{return e-Yo.statSync(n).mtimeMs>=Pu}catch{return!1}}function sg(n,e=Date.now()){let t;try{t=Yo.readdirSync(n)}catch{return!1}return t.some(r=>Ru(r)&&ik(Su.join(n,r),e))}function ok(n,e=Date.now()){if(sg(n,e))return!0;let t=Su.join(n,"failed");if(sg(t,e))return!0;let r;try{r=Yo.readdirSync(t)}catch{return!1}for(let i of r){if(!i.startsWith("telemetry-")||!i.endsWith(".txt"))continue;let o=ku(i);if(o!==null&&e-o<=Eu)return!0}return!1}function ug(n,e=Date.now()){let t=Ba(n);return!!(t.firstEventAt!==null&&e-t.firstEventAt>=Ko||ok(n,e)&&(t.lastRetryAt===null||e-t.lastRetryAt>=Xo))}import sk from"crypto";import Wa from"fs";import ak from"path";var ck="install-id";function lk(n){return ak.join(n,ck)}function pg(n){try{let e=Wa.readFileSync(n,"utf8").trim();return dk(e)?e:null}catch{return null}}function dk(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 mg(n){let e=lk(n),t=pg(e);if(t)return t;let r=sk.randomUUID();try{Wa.mkdirSync(n,{recursive:!0});try{Wa.writeFileSync(e,r,{flag:"wx"})}catch{let i=pg(e);if(i)return i;Wa.writeFileSync(e,r)}}catch{}return r}var Zo=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 Oa;storageDir="";failedDir="";installId="";disabled=Xe();traceFileKey=Buffer.alloc(0);sessionId=fg.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){g.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=ut.join(e,"failed"),this.cliVersion="1.3.9",this.nodeVersion=process.version,this.installId=mg(e).replace(/-/g,""),this.traceFileKey=Bh(e),se.mkdirSync(e,{recursive:!0}),se.mkdirSync(this.failedDir,{recursive:!0}),g.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,g.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,g.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,g.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=Wh(JSON.stringify(o),this.traceFileKey);await se.promises.appendFile(this.currentFile(),s+`
8
+ `,"utf8"),cg(this.storageDir)}catch{}}buildTraceEvent(e,t,r,i){let o=`${n.EVENT_PREFIX}${e.event}`,s=jh.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:fg.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=Va.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=Va.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 Va.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(Va.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 ut.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){g.debug("[telemetry] scheduler not started (telemetry disabled)");return}g.debug(`[telemetry] scheduler started (flush every ${Ko/1e3}s, retry failed every ${Xo/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(()=>{})},Xo)},Xo)}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),g.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 lg(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 se.promises.readdir(this.failedDir)}catch{return!0}let r=t.filter(o=>o.startsWith("telemetry-")&&o.endsWith(".txt")).map(o=>ut.join(this.failedDir,o)),i=!0;for(let o of r){let s=ut.basename(o),a=ku(s);if(a!==null){if(e-a>Eu){try{await se.promises.unlink(o)}catch{}continue}await this.flushFile(o)||(i=!1)}}return i||g.warn("[telemetry] retry failed"),dg(this.storageDir),i}async reclaimStalePending(){let e=Date.now();for(let t of[this.storageDir,this.failedDir]){let r;try{r=await se.promises.readdir(t)}catch{continue}for(let i of r)Ru(i)&&await this.reclaimOrphan(ut.join(t,i),e)}}async reclaimOrphan(e,t){let r;try{let l=await se.promises.stat(e);if(t-l.mtimeMs<Pu)return;r=l.size}catch{return}let i=ut.dirname(e),o=Du(ut.basename(e));if(o===null)return;let s=await this.claimOrphan(e,i,o);if(s===null)return;let a=ut.join(i,o),c=Ai-await this.fileSize(a);if(r>c){try{await se.promises.unlink(s)}catch{}g.warn(`[telemetry] dropped stale orphan pending: ${s} (${r} bytes > budget ${c})`);return}if(await this.mergeOrphanInto(s,a)){g.warn(`[telemetry] reclaimed orphan pending: ${s} (${r} bytes)`);return}g.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${r} bytes)`)}async claimOrphan(e,t,r){let i=ut.join(t,`${r}.pending.reclaim-${process.pid}-${Date.now()}`);try{await se.promises.rename(e,i)}catch{return null}return await this.touch(i),i}async mergeOrphanInto(e,t){try{await se.promises.appendFile(t,await se.promises.readFile(e))}catch(r){return g.warn(`[telemetry] merge orphan pending failed: ${e} -> ${t}: ${r instanceof Error?r.message:String(r)}`),!1}try{await se.promises.unlink(e)}catch(r){g.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 se.promises.stat(e)).size}catch{return 0}}async touch(e){let t=new Date;try{await se.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 se.promises.readdir(this.storageDir)}catch{return[]}return e.filter(t=>t.startsWith("telemetry-")&&t.endsWith(".txt")).map(t=>ut.join(this.storageDir,t)).sort()}async flushFile(e){let t=await this.fileSize(e);if(t>Ai){g.warn(`[telemetry] ${ut.basename(e)} is ${t} bytes (> ${Ai}), dropped without uploading`);try{await se.promises.unlink(e)}catch{}return!0}let r=e+".pending";try{await se.promises.rename(e,r)}catch{return!1}await this.touch(r);let i;try{i=await se.promises.readFile(r,"utf8")}catch{return!1}let o=i.split(`
9
+ `).map(s=>s.trim()).filter(Boolean);if(o.length===0){try{await se.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=Vh(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){g.warn("[telemetry] upload failed");let d=t.slice(i).join(`
10
10
  `)+`
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=ut.basename(e,".pending"),i=ut.join(this.failedDir,r),o=t.split(`
12
- `).filter(Boolean),s=xi-await this.fileSize(i),a=this.takeNewestWithinBudget(o,s);a.length<o.length&&g.warn(`[telemetry] failed file capped at ${xi} bytes, dropped ${o.length-a.length} older events`);try{a.length>0&&await ae.promises.appendFile(i,a.join(`
11
+ `;return await this.moveToFailed(e,d),!1}}try{await se.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=ut.basename(e,".pending"),i=ut.join(this.failedDir,r),o=t.split(`
12
+ `).filter(Boolean),s=Ai-await this.fileSize(i),a=this.takeNewestWithinBudget(o,s);a.length<o.length&&g.warn(`[telemetry] failed file capped at ${Ai} bytes, dropped ${o.length-a.length} older events`);try{a.length>0&&await se.promises.appendFile(i,a.join(`
13
13
  `)+`
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 R=new Xo;import{spawn as uk}from"child_process";import{existsSync as pk}from"fs";import{dirname as mk,join as fk}from"path";import{fileURLToPath as hk}from"url";function gk(){let n=mk(hk(import.meta.url)),e=fk(n,"internal","telemetry-upload-background.js");return pk(e)?e:null}function Ru(n){if(Xe()||!ug(n))return;let e=gk();if(!e){g.warn("[telemetry] background upload script not found, skipping spawn");return}try{uk(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){g.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=j.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=j.join(e,"build-profile.json5");if(!Y.existsSync(t))return null;try{let r=Y.readFileSync(t,"utf-8"),i=Zt.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=j.join(r,"src","main","module.json5");if(!Y.existsSync(i))return"entry";try{let o=Y.readFileSync(i,"utf-8");return Zt.parse(o)?.module?.type||"entry"}catch(o){return console.warn(`Warning: Failed to parse ${i}:`,o),"entry"}}findOwningModule(e){let t=j.normalize(e);for(let r of this.profile.modules){let i=j.normalize(j.join(this.rootDir,r.srcPath)),o=i+j.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=j.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 Zt.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=j.join(this.rootDir,"AppScope","app.json5");if(Y.existsSync(t))try{let r=Y.readFileSync(t,"utf-8"),i=Zt.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=j.join(this.rootDir,"AppScope","app.json5");if(!Y.existsSync(e))return!1;try{let t=Y.readFileSync(e,"utf-8");return Zt.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=j.join(i,"src","main","module.json5");if(!Y.existsSync(o))return"EntryAbility";try{let s=Y.readFileSync(o,"utf-8"),c=Zt.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=j.join(this.rootDir,Pe.LOCK_JSON5_PATH);if(!Y.existsSync(t))return null;let r;try{r=Zt.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 h=s[d];!h||typeof h!="object"||this.collectLocalDeps(h,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=j.resolve(this.rootDir,t),i;try{i=E.ensurePathWithinRoot(this.rootDir,r)}catch{return null}let o=this.profile.modules.find(s=>j.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=j.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=Zt.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=j.join(this.rootDir,Pe.OH_PACKAGE_JSON5);if(!Y.existsSync(e))return null;try{let t=Zt.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=j.join(t.srcPath,r),o=E.resolvePathWithinRoot(this.rootDir,i),s=this.profile.modules.find(a=>j.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 D=this.getSignedHapName(c,o.srcPath,i,t);D&&(d=D)}let h=s?"-signed.hsp":"-signed.hap";if(!r&&!d.endsWith(h))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=j.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(j.join(l,d))}return r}listProjectAppArtifacts(e){let t=E.ensurePathWithinRoot(this.rootDir,j.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=j.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=j.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=Zt.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=j.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 Xu from"fs/promises";import Xr from"path";function St(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}import Ou from"fs";import Wn from"path";import{homedir as yg}from"os";import He from"fs/promises";import pt from"path";import{randomUUID as hg}from"crypto";async function Ne(n){try{return await He.lstat(n)}catch(e){if(e.code==="ENOENT")return;throw e}}async function Ce(n){let e=pt.resolve(n),t=pt.dirname(e);try{return pt.join(await He.realpath(t),pt.basename(e))}catch(r){if(r.code!=="ENOENT"||t===e)throw r;return pt.join(await Ce(t),pt.basename(e))}}async function xu(n,e){let t=`${e}.backup-${hg()}`,r=await Ne(e);r&&await He.rename(e,t);try{await He.rename(n,e)}catch(i){throw r&&await He.rename(t,e),i}r&&await He.rm(t,{recursive:!0,force:!0})}function he(n,e){let t=r=>pt.resolve(r).replace(/^\\\\\?\\/,"").replace(/[\\/]+$/,"");return process.platform==="win32"?t(n).toLowerCase()===t(e).toLowerCase():t(n)===t(e)}function Ii(n,e){let t=(r,i)=>{let o=pt.relative(r,i);return o===""||!o.startsWith(`..${pt.sep}`)&&o!==".."&&!pt.isAbsolute(o)};return t(n,e)||t(e,n)}async function Wa(n,e,t=!1){let r=await He.realpath(n);if(!(await He.stat(r)).isDirectory())throw new Error(`Skill source is not a directory: ${n}`);let i=await Ce(e),o=await Ne(i);if(he(r,i))return Qt(i,"same-source");let s=o?await He.realpath(i).catch(()=>i):i;if(o?.isSymbolicLink()&&he(r,s))return Qt(i,"correct-link");let a=await Iu(i,t);if(a)return a;if(Ii(r,i)||o&&Ii(r,s))throw new Error(`Skill source and destination overlap: ${n}, ${e}`);await He.mkdir(pt.dirname(i),{recursive:!0});let c=`${i}.install-${hg()}`;try{let l=await yk(r,c);return await xu(c,i),{success:!0,path:i,...l}}finally{await He.rm(c,{recursive:!0,force:!0})}}function Qt(n,e){return{success:!0,skipped:!0,path:n,reason:e}}async function Iu(n,e){if(!e&&await Ne(n))return Qt(n,"already-exists")}async function yk(n,e){try{let t=process.platform==="win32"?n:pt.relative(pt.dirname(e),n);return await He.symlink(t,e,process.platform==="win32"?"junction":"dir"),{mode:"symlink"}}catch(t){return await He.rm(e,{recursive:!0,force:!0}),await He.cp(n,e,{recursive:!0,dereference:!0,errorOnExist:!0,force:!1}),{mode:"copy",fallbackReason:t.code??String(t)}}}async function Va(n){let e=await Ce(n),t=await Ne(e);return t?(await He.rm(e,{recursive:!t.isSymbolicLink(),force:!0}),{success:!0,path:e}):Qt(e,"not-installed")}var gg={amp:{displayName:"Amp",skillsDir:".agents/skills",globalSkillsDir:"~/.config/agents/skills"},antigravity:{displayName:"Antigravity",skillsDir:".agents/skills",globalSkillsDir:"~/.gemini/antigravity/skills"},"antigravity-cli":{displayName:"Antigravity CLI",skillsDir:".agents/skills",globalSkillsDir:"~/.gemini/antigravity-cli/skills"},astrbot:{displayName:"AstrBot",skillsDir:"data/skills",globalSkillsDir:"~/.astrbot/data/skills"},atomcode:{displayName:"atomcode",skillsDir:".atomcode/skills",globalSkillsDir:"~/.atomcode/skills",detect:["~/.atomcode"]},augment:{displayName:"Augment",skillsDir:".augment/skills",globalSkillsDir:"~/.augment/skills"},bob:{displayName:"IBM Bob",skillsDir:".bob/skills",globalSkillsDir:"~/.bob/skills"},"claude-code":{displayName:"Claude Code",skillsDir:".claude/skills",globalSkillsDir:"~/.claude/skills",detect:["~/.claude"]},cline:{displayName:"Cline",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills"},"codearts-agent":{displayName:"CodeArts Agent",skillsDir:".codeartsdoer/skills",globalSkillsDir:"~/.codeartsdoer/skills"},codebuddy:{displayName:"CodeBuddy",skillsDir:".codebuddy/skills",globalSkillsDir:"~/.codebuddy/skills",detect:["~/.codebuddy"]},codex:{displayName:"Codex",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills",detect:["~/.codex"],legacySkillsDirs:[".codex/skills"],legacyGlobalSkillsDirs:["~/.codex/skills"]},continue:{displayName:"Continue",skillsDir:".continue/skills",globalSkillsDir:"~/.continue/skills"},crush:{displayName:"Crush",skillsDir:".crush/skills",globalSkillsDir:"~/.config/crush/skills"},cursor:{displayName:"Cursor",skillsDir:".agents/skills",globalSkillsDir:"~/.cursor/skills",detect:["~/.cursor"],legacySkillsDirs:[".cursor/skills"]},deepagents:{displayName:"Deep Agents",skillsDir:".agents/skills",globalSkillsDir:"~/.deepagents/agent/skills"},deveco:{displayName:"deveco",skillsDir:".deveco/skills",globalSkillsDir:"~/.config/deveco/skills",detect:["~/.config/deveco"]},devin:{displayName:"Devin for Terminal",skillsDir:".devin/skills",globalSkillsDir:"~/.config/devin/skills"},droid:{displayName:"Droid",skillsDir:".agents/skills",globalSkillsDir:"~/.factory/skills"},dsh:{displayName:"deepseek harness",skillsDir:".dsh/skills",globalSkillsDir:"~/.dsh/skills",detect:["~/.dsh"]},"gemini-cli":{displayName:"Gemini CLI",skillsDir:".agents/skills",globalSkillsDir:"~/.gemini/skills"},"github-copilot":{displayName:"GitHub Copilot",skillsDir:".agents/skills",globalSkillsDir:"~/.copilot/skills"},goose:{displayName:"Goose",skillsDir:".goose/skills",globalSkillsDir:"~/.config/goose/skills"},grok:{displayName:"Grok Build",skillsDir:".grok/skills",globalSkillsDir:"~/.grok/skills"},"hermes-agent":{displayName:"Hermes Agent",skillsDir:".hermes/skills",globalSkillsDir:"~/.hermes/skills"},"iflow-cli":{displayName:"iFlow CLI",skillsDir:".iflow/skills",globalSkillsDir:"~/.iflow/skills"},junie:{displayName:"Junie",skillsDir:".junie/skills",globalSkillsDir:"~/.junie/skills"},kilo:{displayName:"Kilo Code",skillsDir:".agents/skills",globalSkillsDir:"~/.kilo/skills"},"kimi-code-cli":{displayName:"Kimi Code CLI",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills"},"kiro-cli":{displayName:"Kiro CLI",skillsDir:".kiro/skills",globalSkillsDir:"~/.kiro/skills"},kode:{displayName:"Kode",skillsDir:".kode/skills",globalSkillsDir:"~/.kode/skills"},lingma:{displayName:"Lingma",skillsDir:".lingma/skills",globalSkillsDir:"~/.lingma/skills"},"minimax-code":{displayName:"MiniMax Code",skillsDir:".minimax/skills",globalSkillsDir:"~/.minimax/skills"},"mistral-vibe":{displayName:"Mistral Vibe",skillsDir:".vibe/skills",globalSkillsDir:"~/.vibe/skills"},neovate:{displayName:"Neovate",skillsDir:".neovate/skills",globalSkillsDir:"~/.neovate/skills"},ona:{displayName:"Ona",skillsDir:".ona/skills",globalSkillsDir:"~/.ona/skills"},openclaw:{displayName:"OpenClaw",skillsDir:"skills",globalSkillsDir:"~/.openclaw/skills"},opencode:{displayName:"OpenCode",skillsDir:".agents/skills",globalSkillsDir:"~/.config/opencode/skills",detect:["~/.config/opencode"],legacySkillsDirs:[".opencode/skills"]},openhands:{displayName:"OpenHands",skillsDir:".openhands/skills",globalSkillsDir:"~/.openhands/skills"},pi:{displayName:"Pi",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills",detect:["~/.pi/agent"],legacySkillsDirs:[".pi/skills"],legacyGlobalSkillsDirs:["~/.pi/agent/skills"]},qoder:{displayName:"Qoder",skillsDir:".qoder/skills",globalSkillsDir:"~/.qoder/skills",detect:["~/.qoder"]},"qoder-cn":{displayName:"Qoder CN",skillsDir:".qoder/skills",globalSkillsDir:"~/.qoder-cn/skills"},"qwen-code":{displayName:"Qwen Code",skillsDir:".qwen/skills",globalSkillsDir:"~/.qwen/skills"},reasonix:{displayName:"Reasonix",skillsDir:".reasonix/skills",globalSkillsDir:"~/.reasonix/skills"},replit:{displayName:"Replit",skillsDir:".agents/skills",globalSkillsDir:"~/.config/agents/skills"},trae:{displayName:"Trae",skillsDir:".trae/skills",globalSkillsDir:"~/.trae/skills"},"trae-cn":{displayName:"Trae CN",skillsDir:".trae/skills",globalSkillsDir:"~/.trae-cn/skills",detect:["~/.trae-cn"],legacySkillsDirs:[".trae-cn/skills"]},universal:{displayName:"Universal",skillsDir:".agents/skills",globalSkillsDir:"~/.config/agents/skills"},warp:{displayName:"Warp",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills"},windsurf:{displayName:"Windsurf",skillsDir:".windsurf/skills",globalSkillsDir:"~/.codeium/windsurf/skills"},zcode:{displayName:"ZCode",skillsDir:".zcode/skills",globalSkillsDir:"~/.zcode/skills"},zed:{displayName:"Zed",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills"}};var Au="https://matrix.openharmony.cn",Et={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"},Tu=".agents/skills",Zo=gg;function Mu(n){return Wn.resolve(n==="~"||n.startsWith("~/")?Wn.join(yg(),n.slice(1)):n)}function Ze(){return Object.keys(Zo)}function Ga(n){return[...new Set((n??"").split(",").map(e=>e.trim()).filter(Boolean))]}function Nt(n){let e=Object.prototype.hasOwnProperty.call(Zo,n)?Zo[n]:void 0;if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Ze().join(", ")}`);return e}function Nu(n){return Mu(Nt(n).globalSkillsDir)}function Lu(n,e){return Wn.join(n,Nt(e).skillsDir)}function er(n){return Wn.join(n??yg(),Tu)}function Yr(n,e){return e?Lu(e,n):Nu(n)}function qa(n,e){let t=Yr(n,e);return he(t,er(e))}function wg(n,e){let t=Nt(n),r=e?(t.legacySkillsDirs??[]).map(o=>Wn.join(e,o)):(t.legacyGlobalSkillsDirs??[]).map(Mu),i=[Yr(n,e)];return r.filter(o=>i.some(s=>he(s,o))?!1:(i.push(o),!0))}function _u(n,e){let t=Nt(e).skillsDir.split("/")[0];return t.startsWith(".")&&Ou.existsSync(Wn.join(n,t))}function Vn(n,e){let t=Nt(n);if(t.detect)return t.detect.some(o=>Ou.existsSync(Mu(o)));let r=Nu(n);return![er(),Nu("universal")].some(o=>he(o,r))&&Ou.existsSync(Wn.dirname(r))?!0:!!(e&&t.skillsDir!==Tu&&_u(e,n))}import za from"path";function vg(n){let e=[];n.agents.length&&e.push({agents:[...new Set(n.agents)]});let t=new Map;for(let{project:r,agent:i}of n.projectAgents){let o=t.get(r)??[];o.push(i),t.set(r,o)}for(let[r,i]of t)e.push({project:r,agents:[...new Set(i)]});return e}async function vk(n,e,t,r){let i=[];for(let o of wg(n,e.project)){let s=await Ce(za.join(o,t));!r.some(a=>he(a,s))&&await Ne(s)&&i.push(s)}return i}async function Ja(n,e,t=!0){let r=await Ce(za.join(er(n.project),e)),i=[];for(let o of n.agents){let s=Yr(o,n.project),a=await Ce(za.join(s,e)),c=await vk(o,n,e,[r,a]),l=!!(n.project&&!t&&!qa(o,n.project)&&c.length===0&&!_u(n.project,o)),d=i.find(h=>he(h.path,a));d?(d.legacy.push(...c.filter(h=>!d.legacy.some(w=>he(w,h)))),d.skipped&&=l):i.push({path:a,legacy:c,skipped:l})}return i}async function bg(n,e,t=!0){let r=await Ja(n,e,t);if(r.every(o=>o.skipped))return r;let i=await Ce(za.join(er(n.project),e));return r.some(o=>he(o.path,i))||r.unshift({path:i,legacy:[],skipped:!1}),r}import Ai from"fs/promises";import Lt from"path";import{randomUUID as qk}from"crypto";import{lock as zk}from"proper-lockfile";import*as Qo from"fs";import*as Cg from"path";import{homedir as bk}from"os";import*as Sg from"fs";import*as Qe from"path";function $u(n,e){let t=Qe.relative(e,n);return t===""||!Qe.isAbsolute(t)&&!t.startsWith(`..${Qe.sep}`)&&t!==".."}function Kr(n){let e=Qe.resolve(n),t=[],r=e;for(;;)try{let i=Sg.realpathSync(r);return t.length===0?i:Qe.join(i,...t.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=Qe.dirname(r);if(o===r)return e;t.push(Qe.basename(r)),r=o}}function Eg(n,e){let t=Kr(e),r=Kr(n);return $u(r,t)?r:null}function Fu(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function Ya(n){let e=Fu(n);if(!e)throw new Error("Path must not be empty.");return Kr(e)}var Sk="deveco-cli",Pg,ju=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function Ek(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":Fu(n))||Cg.join(bk(),".local","share",Sk);try{return Ya(t)}catch(r){throw new ju(r instanceof Error?r.message:String(r))}}function F(){if(Pg!==void 0)return Pg;let n=Ek();try{if(Qo.existsSync(n))return Qo.realpathSync(n)}catch{}return n}import Hk from"adm-zip";import Uk from"crypto";import{timingSafeEqual as Bk}from"crypto";import Vu from"fs";import Mt from"path";import{fileURLToPath as Wk}from"url";import{homedir as tr}from"os";import et from"path";var rr="deveco-mcp",Ka={"trae-cn":".trae-cn",opencode:".config/opencode",pi:".pi/agent",deveco:".config/deveco",cursor:".cursor",codebuddy:".codebuddy",qoder:".qoder","claude-code":".claude",codex:".codex",atomcode:".atomcode",dsh:".dsh"};var Sr={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:et.join(tr(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},pi:{name:"pi",displayName:"Pi Coding Agent",supportsGlobal:!0,globalConfigPath:et.join(tr(),".pi","agent","mcp.json"),projectConfigPath:".pi/mcp.json",mcpServersKey:"mcpServers",format:"standard"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:et.join(process.platform==="win32"?et.join(process.env.APPDATA??et.join(tr(),"AppData","Roaming"),"Trae CN","User"):et.join(tr(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:et.join(tr(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:et.join(tr(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"codebuddy"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:et.join(process.platform==="win32"?et.join(process.env.APPDATA??et.join(tr(),"AppData","Roaming"),"Qoder","SharedClientCache"):et.join(tr(),"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:et.join(tr(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:et.join(tr(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function Dg(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function kg(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Pk(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."}}}function Rg(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function Xa(n,e){return n.format==="opencode"?Dg(e):n.format==="claude-code"||n.format==="codex"?kg(e):n.format==="codebuddy"?Pk(e):Rg(e)}var Hu="https://developer.huawei.com/consumer/cn/download/";import Mk from"axios";var Ck={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function kk(n){try{return new URL(n)}catch{return null}}function xg(n){var e=(typeof n=="string"?kk(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)||Ck[t]||0,!Dk(r,i)))return"";var o=Uu(t+"_proxy")||Uu("all_proxy");return o&&o.indexOf("://")===-1&&(o=t+"://"+o),o}function Dk(n,e){var t=Uu("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 Uu(n){return process.env[n.toLowerCase()]||process.env[n.toUpperCase()]||""}import{spawn as Tg}from"child_process";import*as Gn from"fs";import*as Og from"os";import*as Za from"path";var Ng=6e4;async function Rk(){if(process.platform!=="win32")return null;let n="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",e=await Ig(n,"ProxyServer");if(!e)return null;let t=await Ig(n,"ProxyEnable");return t!=="1"&&t!=="0x1"?null:e.trim()}function Ig(n,e){return new Promise(t=>{let r=Tg("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 xk(){let n=process.env.HTTPS_PROXY??process.env.HTTP_PROXY??"";if(!n)return null;try{return new URL(n).host}catch{return n}}function Ik(){return`${process.env.SystemRoot??"C:\\Windows"}\\System32\\curl.exe`}function Ag(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 Ak(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??Ng)/1e3)))];return n.method&&n.method!=="GET"&&i.push("-X",n.method),n.data!==void 0&&i.push("--data-binary",n.data),i.push(...Tk(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 Tk(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 Ok(n,e,t){if(t){let l=Gn.readFileSync(e,"utf8"),d=Gn.readFileSync(t),h=Ag(l);return{statusCode:h.statusCode,statusText:h.statusText,body:d.toString("base64"),headers:h.headers,bodyBuffer:d}}let r=n.lastIndexOf("HTTP/");if(r===-1)return null;let i=n.slice(r),o=i.indexOf(`\r
14
+ `,"utf8")}catch{return}try{await se.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 Zo;import{spawn as uk}from"child_process";import{existsSync as pk}from"fs";import{dirname as mk,join as fk}from"path";import{fileURLToPath as hk}from"url";function gk(){let n=mk(hk(import.meta.url)),e=fk(n,"internal","telemetry-upload-background.js");return pk(e)?e:null}function xu(n){if(Xe()||!ug(n))return;let e=gk();if(!e){g.warn("[telemetry] background upload script not found, skipping spawn");return}try{uk(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){g.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=j.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=j.join(e,"build-profile.json5");if(!K.existsSync(t))return null;try{let r=K.readFileSync(t,"utf-8"),i=Qt.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=j.join(r,"src","main","module.json5");if(!K.existsSync(i))return"entry";try{let o=K.readFileSync(i,"utf-8");return Qt.parse(o)?.module?.type||"entry"}catch(o){return console.warn(`Warning: Failed to parse ${i}:`,o),"entry"}}findOwningModule(e){let t=j.normalize(e);for(let r of this.profile.modules){let i=j.normalize(j.join(this.rootDir,r.srcPath)),o=i+j.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=j.join(r,"build-profile.json5");if(!K.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=K.readFileSync(i,"utf-8");return Qt.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=j.join(this.rootDir,"AppScope","app.json5");if(K.existsSync(t))try{let r=K.readFileSync(t,"utf-8"),i=Qt.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=j.join(this.rootDir,"AppScope","app.json5");if(!K.existsSync(e))return!1;try{let t=K.readFileSync(e,"utf-8");return Qt.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=j.join(i,"src","main","module.json5");if(!K.existsSync(o))return"EntryAbility";try{let s=K.readFileSync(o,"utf-8"),c=Qt.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=j.join(this.rootDir,Pe.LOCK_JSON5_PATH);if(!K.existsSync(t))return null;let r;try{r=Qt.parse(K.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 h=s[d];!h||typeof h!="object"||this.collectLocalDeps(h,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=j.resolve(this.rootDir,t),i;try{i=E.ensurePathWithinRoot(this.rootDir,r)}catch{return null}let o=this.profile.modules.find(s=>j.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=j.join(E.resolvePathWithinRoot(this.rootDir,e.srcPath),Pe.OH_PACKAGE_JSON5);if(!K.existsSync(t))return[];let r=this.readRootOverrideMap(),i=[],o=new Set;try{let s=Qt.parse(K.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=j.join(this.rootDir,Pe.OH_PACKAGE_JSON5);if(!K.existsSync(e))return null;try{let t=Qt.parse(K.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=j.join(t.srcPath,r),o=E.resolvePathWithinRoot(this.rootDir,i),s=this.profile.modules.find(a=>j.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(!K.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 h=s?"-signed.hsp":"-signed.hap";if(!r&&!d.endsWith(h))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(!K.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=j.isAbsolute(c)?c:this.buildOutputPath(i.srcPath,r,["outputs",t,c]);if(!K.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(K.existsSync(l))for(let d of K.readdirSync(l))(d.endsWith(".hap")||d.endsWith(".hsp")||d.endsWith(".har"))&&r.push(j.join(l,d))}return r}listProjectAppArtifacts(e){let t=E.ensurePathWithinRoot(this.rootDir,j.resolve(this.rootDir,"build","outputs",e));if(!K.existsSync(t))return[];let r=[],i=o=>{for(let s of K.readdirSync(o,{withFileTypes:!0})){let a=j.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 K.existsSync(s)?o:null}buildOutputPath(e,t,r){let i=E.resolvePathWithinRoot(this.rootDir,e),o=j.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=K.readFileSync(e,"utf-8");r=Qt.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=j.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 Zu from"fs/promises";import Qr from"path";function St(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}import Nu from"fs";import Gn from"path";import{homedir as yg}from"os";import He from"fs/promises";import pt from"path";import{randomUUID as hg}from"crypto";async function Ne(n){try{return await He.lstat(n)}catch(e){if(e.code==="ENOENT")return;throw e}}async function Ce(n){let e=pt.resolve(n),t=pt.dirname(e);try{return pt.join(await He.realpath(t),pt.basename(e))}catch(r){if(r.code!=="ENOENT"||t===e)throw r;return pt.join(await Ce(t),pt.basename(e))}}async function Au(n,e){let t=`${e}.backup-${hg()}`,r=await Ne(e);r&&await He.rename(e,t);try{await He.rename(n,e)}catch(i){throw r&&await He.rename(t,e),i}r&&await He.rm(t,{recursive:!0,force:!0})}function fe(n,e){let t=r=>pt.resolve(r).replace(/^\\\\\?\\/,"").replace(/[\\/]+$/,"");return process.platform==="win32"?t(n).toLowerCase()===t(e).toLowerCase():t(n)===t(e)}function Ii(n,e){let t=(r,i)=>{let o=pt.relative(r,i);return o===""||!o.startsWith(`..${pt.sep}`)&&o!==".."&&!pt.isAbsolute(o)};return t(n,e)||t(e,n)}async function Ga(n,e,t=!1){let r=await He.realpath(n);if(!(await He.stat(r)).isDirectory())throw new Error(`Skill source is not a directory: ${n}`);let i=await Ce(e),o=await Ne(i);if(fe(r,i))return er(i,"same-source");let s=o?await He.realpath(i).catch(()=>i):i;if(o?.isSymbolicLink()&&fe(r,s))return er(i,"correct-link");let a=await Iu(i,t);if(a)return a;if(Ii(r,i)||o&&Ii(r,s))throw new Error(`Skill source and destination overlap: ${n}, ${e}`);await He.mkdir(pt.dirname(i),{recursive:!0});let c=`${i}.install-${hg()}`;try{let l=await yk(r,c);return await Au(c,i),{success:!0,path:i,...l}}finally{await He.rm(c,{recursive:!0,force:!0})}}function er(n,e){return{success:!0,skipped:!0,path:n,reason:e}}async function Iu(n,e){if(!e&&await Ne(n))return er(n,"already-exists")}async function yk(n,e){try{let t=process.platform==="win32"?n:pt.relative(pt.dirname(e),n);return await He.symlink(t,e,process.platform==="win32"?"junction":"dir"),{mode:"symlink"}}catch(t){return await He.rm(e,{recursive:!0,force:!0}),await He.cp(n,e,{recursive:!0,dereference:!0,errorOnExist:!0,force:!1}),{mode:"copy",fallbackReason:t.code??String(t)}}}async function qa(n){let e=await Ce(n),t=await Ne(e);return t?(await He.rm(e,{recursive:!t.isSymbolicLink(),force:!0}),{success:!0,path:e}):er(e,"not-installed")}var gg={amp:{displayName:"Amp",skillsDir:".agents/skills",globalSkillsDir:"~/.config/agents/skills"},antigravity:{displayName:"Antigravity",skillsDir:".agents/skills",globalSkillsDir:"~/.gemini/antigravity/skills"},"antigravity-cli":{displayName:"Antigravity CLI",skillsDir:".agents/skills",globalSkillsDir:"~/.gemini/antigravity-cli/skills"},astrbot:{displayName:"AstrBot",skillsDir:"data/skills",globalSkillsDir:"~/.astrbot/data/skills"},atomcode:{displayName:"atomcode",skillsDir:".atomcode/skills",globalSkillsDir:"~/.atomcode/skills",detect:["~/.atomcode"]},augment:{displayName:"Augment",skillsDir:".augment/skills",globalSkillsDir:"~/.augment/skills"},bob:{displayName:"IBM Bob",skillsDir:".bob/skills",globalSkillsDir:"~/.bob/skills"},"claude-code":{displayName:"Claude Code",skillsDir:".claude/skills",globalSkillsDir:"~/.claude/skills",detect:["~/.claude"]},cline:{displayName:"Cline",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills"},"codearts-agent":{displayName:"CodeArts Agent",skillsDir:".codeartsdoer/skills",globalSkillsDir:"~/.codeartsdoer/skills"},codebuddy:{displayName:"CodeBuddy",skillsDir:".codebuddy/skills",globalSkillsDir:"~/.codebuddy/skills",detect:["~/.codebuddy"]},codex:{displayName:"Codex",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills",detect:["~/.codex"],legacySkillsDirs:[".codex/skills"],legacyGlobalSkillsDirs:["~/.codex/skills"]},continue:{displayName:"Continue",skillsDir:".continue/skills",globalSkillsDir:"~/.continue/skills"},crush:{displayName:"Crush",skillsDir:".crush/skills",globalSkillsDir:"~/.config/crush/skills"},cursor:{displayName:"Cursor",skillsDir:".agents/skills",globalSkillsDir:"~/.cursor/skills",detect:["~/.cursor"],legacySkillsDirs:[".cursor/skills"]},deepagents:{displayName:"Deep Agents",skillsDir:".agents/skills",globalSkillsDir:"~/.deepagents/agent/skills"},deveco:{displayName:"deveco",skillsDir:".deveco/skills",globalSkillsDir:"~/.config/deveco/skills",detect:["~/.config/deveco"]},devin:{displayName:"Devin for Terminal",skillsDir:".devin/skills",globalSkillsDir:"~/.config/devin/skills"},droid:{displayName:"Droid",skillsDir:".agents/skills",globalSkillsDir:"~/.factory/skills"},dsh:{displayName:"deepseek harness",skillsDir:".dsh/skills",globalSkillsDir:"~/.dsh/skills",detect:["~/.dsh"]},"gemini-cli":{displayName:"Gemini CLI",skillsDir:".agents/skills",globalSkillsDir:"~/.gemini/skills"},"github-copilot":{displayName:"GitHub Copilot",skillsDir:".agents/skills",globalSkillsDir:"~/.copilot/skills"},goose:{displayName:"Goose",skillsDir:".goose/skills",globalSkillsDir:"~/.config/goose/skills"},grok:{displayName:"Grok Build",skillsDir:".grok/skills",globalSkillsDir:"~/.grok/skills"},"hermes-agent":{displayName:"Hermes Agent",skillsDir:".hermes/skills",globalSkillsDir:"~/.hermes/skills"},"iflow-cli":{displayName:"iFlow CLI",skillsDir:".iflow/skills",globalSkillsDir:"~/.iflow/skills"},junie:{displayName:"Junie",skillsDir:".junie/skills",globalSkillsDir:"~/.junie/skills"},kilo:{displayName:"Kilo Code",skillsDir:".agents/skills",globalSkillsDir:"~/.kilo/skills"},"kimi-code-cli":{displayName:"Kimi Code CLI",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills"},"kiro-cli":{displayName:"Kiro CLI",skillsDir:".kiro/skills",globalSkillsDir:"~/.kiro/skills"},kode:{displayName:"Kode",skillsDir:".kode/skills",globalSkillsDir:"~/.kode/skills"},lingma:{displayName:"Lingma",skillsDir:".lingma/skills",globalSkillsDir:"~/.lingma/skills"},"minimax-code":{displayName:"MiniMax Code",skillsDir:".minimax/skills",globalSkillsDir:"~/.minimax/skills"},"mistral-vibe":{displayName:"Mistral Vibe",skillsDir:".vibe/skills",globalSkillsDir:"~/.vibe/skills"},neovate:{displayName:"Neovate",skillsDir:".neovate/skills",globalSkillsDir:"~/.neovate/skills"},ona:{displayName:"Ona",skillsDir:".ona/skills",globalSkillsDir:"~/.ona/skills"},openclaw:{displayName:"OpenClaw",skillsDir:"skills",globalSkillsDir:"~/.openclaw/skills"},opencode:{displayName:"OpenCode",skillsDir:".agents/skills",globalSkillsDir:"~/.config/opencode/skills",detect:["~/.config/opencode"],legacySkillsDirs:[".opencode/skills"]},openhands:{displayName:"OpenHands",skillsDir:".openhands/skills",globalSkillsDir:"~/.openhands/skills"},pi:{displayName:"Pi",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills",detect:["~/.pi/agent"],legacySkillsDirs:[".pi/skills"],legacyGlobalSkillsDirs:["~/.pi/agent/skills"]},qoder:{displayName:"Qoder",skillsDir:".qoder/skills",globalSkillsDir:"~/.qoder/skills",detect:["~/.qoder"]},"qoder-cn":{displayName:"Qoder CN",skillsDir:".qoder/skills",globalSkillsDir:"~/.qoder-cn/skills"},"qwen-code":{displayName:"Qwen Code",skillsDir:".qwen/skills",globalSkillsDir:"~/.qwen/skills"},reasonix:{displayName:"Reasonix",skillsDir:".reasonix/skills",globalSkillsDir:"~/.reasonix/skills"},replit:{displayName:"Replit",skillsDir:".agents/skills",globalSkillsDir:"~/.config/agents/skills"},trae:{displayName:"Trae",skillsDir:".trae/skills",globalSkillsDir:"~/.trae/skills"},"trae-cn":{displayName:"Trae CN",skillsDir:".trae/skills",globalSkillsDir:"~/.trae-cn/skills",detect:["~/.trae-cn"],legacySkillsDirs:[".trae-cn/skills"]},universal:{displayName:"Universal",skillsDir:".agents/skills",globalSkillsDir:"~/.config/agents/skills"},warp:{displayName:"Warp",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills"},windsurf:{displayName:"Windsurf",skillsDir:".windsurf/skills",globalSkillsDir:"~/.codeium/windsurf/skills"},zcode:{displayName:"ZCode",skillsDir:".zcode/skills",globalSkillsDir:"~/.zcode/skills"},zed:{displayName:"Zed",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills"}};var Tu="https://matrix.openharmony.cn",Et={TAGS_API_URL:`${Tu}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${Tu}/api/registry/skill/skills`,SKILL_API_BASE:`${Tu}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,DEFAULT_MAX_PAGES:100,SUCCESS_CODE:"20000"},Ou=".agents/skills",Qo=gg;function Lu(n){return Gn.resolve(n==="~"||n.startsWith("~/")?Gn.join(yg(),n.slice(1)):n)}function Ze(){return Object.keys(Qo)}function za(n){return[...new Set((n??"").split(",").map(e=>e.trim()).filter(Boolean))]}function Nt(n){let e=Object.prototype.hasOwnProperty.call(Qo,n)?Qo[n]:void 0;if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Ze().join(", ")}`);return e}function Mu(n){return Lu(Nt(n).globalSkillsDir)}function _u(n,e){return Gn.join(n,Nt(e).skillsDir)}function tr(n){return Gn.join(n??yg(),Ou)}function Xr(n,e){return e?_u(e,n):Mu(n)}function Ja(n,e){let t=Xr(n,e);return fe(t,tr(e))}function wg(n,e){let t=Nt(n),r=e?(t.legacySkillsDirs??[]).map(o=>Gn.join(e,o)):(t.legacyGlobalSkillsDirs??[]).map(Lu),i=[Xr(n,e)];return r.filter(o=>i.some(s=>fe(s,o))?!1:(i.push(o),!0))}function $u(n,e){let t=Nt(e).skillsDir.split("/")[0];return t.startsWith(".")&&Nu.existsSync(Gn.join(n,t))}function qn(n,e){let t=Nt(n);if(t.detect)return t.detect.some(o=>Nu.existsSync(Lu(o)));let r=Mu(n);return![tr(),Mu("universal")].some(o=>fe(o,r))&&Nu.existsSync(Gn.dirname(r))?!0:!!(e&&t.skillsDir!==Ou&&$u(e,n))}import Ya from"path";function vg(n){let e=[];n.agents.length&&e.push({agents:[...new Set(n.agents)]});let t=new Map;for(let{project:r,agent:i}of n.projectAgents){let o=t.get(r)??[];o.push(i),t.set(r,o)}for(let[r,i]of t)e.push({project:r,agents:[...new Set(i)]});return e}async function vk(n,e,t,r){let i=[];for(let o of wg(n,e.project)){let s=await Ce(Ya.join(o,t));!r.some(a=>fe(a,s))&&await Ne(s)&&i.push(s)}return i}async function Ka(n,e,t=!0){let r=await Ce(Ya.join(tr(n.project),e)),i=[];for(let o of n.agents){let s=Xr(o,n.project),a=await Ce(Ya.join(s,e)),c=await vk(o,n,e,[r,a]),l=!!(n.project&&!t&&!Ja(o,n.project)&&c.length===0&&!$u(n.project,o)),d=i.find(h=>fe(h.path,a));d?(d.legacy.push(...c.filter(h=>!d.legacy.some(w=>fe(w,h)))),d.skipped&&=l):i.push({path:a,legacy:c,skipped:l})}return i}async function bg(n,e,t=!0){let r=await Ka(n,e,t);if(r.every(o=>o.skipped))return r;let i=await Ce(Ya.join(tr(n.project),e));return r.some(o=>fe(o.path,i))||r.unshift({path:i,legacy:[],skipped:!1}),r}import Ti from"fs/promises";import Lt from"path";import{randomUUID as qk}from"crypto";import{lock as zk}from"proper-lockfile";import*as es from"fs";import*as Cg from"path";import{homedir as bk}from"os";import*as Sg from"fs";import*as Qe from"path";function Fu(n,e){let t=Qe.relative(e,n);return t===""||!Qe.isAbsolute(t)&&!t.startsWith(`..${Qe.sep}`)&&t!==".."}function Zr(n){let e=Qe.resolve(n),t=[],r=e;for(;;)try{let i=Sg.realpathSync(r);return t.length===0?i:Qe.join(i,...t.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=Qe.dirname(r);if(o===r)return e;t.push(Qe.basename(r)),r=o}}function Eg(n,e){let t=Zr(e),r=Zr(n);return Fu(r,t)?r:null}function ju(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=ju(n);if(!e)throw new Error("Path must not be empty.");return Zr(e)}var Sk="deveco-cli",Pg,Hu=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function Ek(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":ju(n))||Cg.join(bk(),".local","share",Sk);try{return Xa(t)}catch(r){throw new Hu(r instanceof Error?r.message:String(r))}}function F(){if(Pg!==void 0)return Pg;let n=Ek();try{if(es.existsSync(n))return es.realpathSync(n)}catch{}return n}import Hk from"adm-zip";import Uk from"crypto";import{timingSafeEqual as Bk}from"crypto";import Gu from"fs";import Mt from"path";import{fileURLToPath as Wk}from"url";import{homedir as rr}from"os";import et from"path";var nr="deveco-mcp",Za={"trae-cn":".trae-cn",opencode:".config/opencode",pi:".pi/agent",deveco:".config/deveco",cursor:".cursor",codebuddy:".codebuddy",qoder:".qoder","claude-code":".claude",codex:".codex",atomcode:".atomcode",dsh:".dsh"};var Er={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:et.join(rr(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},pi:{name:"pi",displayName:"Pi Coding Agent",supportsGlobal:!0,globalConfigPath:et.join(rr(),".pi","agent","mcp.json"),projectConfigPath:".pi/mcp.json",mcpServersKey:"mcpServers",format:"standard"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:et.join(process.platform==="win32"?et.join(process.env.APPDATA??et.join(rr(),"AppData","Roaming"),"Trae CN","User"):et.join(rr(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:et.join(rr(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:et.join(rr(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"codebuddy"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:et.join(process.platform==="win32"?et.join(process.env.APPDATA??et.join(rr(),"AppData","Roaming"),"Qoder","SharedClientCache"):et.join(rr(),"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:et.join(rr(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:et.join(rr(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function Dg(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function kg(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Pk(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."}}}function Rg(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function Qa(n,e){return n.format==="opencode"?Dg(e):n.format==="claude-code"||n.format==="codex"?kg(e):n.format==="codebuddy"?Pk(e):Rg(e)}var Uu="https://developer.huawei.com/consumer/cn/download/";import Mk from"axios";var Ck={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function kk(n){try{return new URL(n)}catch{return null}}function xg(n){var e=(typeof n=="string"?kk(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)||Ck[t]||0,!Dk(r,i)))return"";var o=Bu(t+"_proxy")||Bu("all_proxy");return o&&o.indexOf("://")===-1&&(o=t+"://"+o),o}function Dk(n,e){var t=Bu("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 Bu(n){return process.env[n.toLowerCase()]||process.env[n.toUpperCase()]||""}import{spawn as Tg}from"child_process";import*as zn from"fs";import*as Og from"os";import*as ec from"path";var Ng=6e4;async function Rk(){if(process.platform!=="win32")return null;let n="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",e=await Ag(n,"ProxyServer");if(!e)return null;let t=await Ag(n,"ProxyEnable");return t!=="1"&&t!=="0x1"?null:e.trim()}function Ag(n,e){return new Promise(t=>{let r=Tg("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 xk(){let n=process.env.HTTPS_PROXY??process.env.HTTP_PROXY??"";if(!n)return null;try{return new URL(n).host}catch{return n}}function Ak(){return`${process.env.SystemRoot??"C:\\Windows"}\\System32\\curl.exe`}function Ig(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 Ik(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??Ng)/1e3)))];return n.method&&n.method!=="GET"&&i.push("-X",n.method),n.data!==void 0&&i.push("--data-binary",n.data),i.push(...Tk(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 Tk(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 Ok(n,e,t){if(t){let l=zn.readFileSync(e,"utf8"),d=zn.readFileSync(t),h=Ig(l);return{statusCode:h.statusCode,statusText:h.statusText,body:d.toString("base64"),headers:h.headers,bodyBuffer:d}}let r=n.lastIndexOf("HTTP/");if(r===-1)return null;let i=n.slice(r),o=i.indexOf(`\r
15
15
  \r
16
- `);if(o===-1)return null;let s=i.slice(0,o),a=i.slice(o+4),c=Ag(s);return{statusCode:c.statusCode,statusText:c.statusText,body:a,headers:c.headers}}async function Mg(n){if(process.platform!=="win32")return null;let e=xk()??await Rk();if(!e)return null;let t;n.binary&&(t=Gn.mkdtempSync(Za.join(Og.tmpdir(),"curl-")));let r=t?Za.join(t,"header.tmp"):void 0,i=t?Za.join(t,"body.tmp"):void 0;try{let o=Ak(n,e,r,i),s=await Nk(o,n.timeoutMs);return!s||s.code!==0?null:Ok(s.stdout,r,i)}catch{return null}finally{t&&Gn.rmSync(t,{recursive:!0,force:!0})}}function Nk(n,e){let t=Ik();return new Promise(r=>{let i=Tg(t,n,{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),o="",s=!1,a=setTimeout(()=>{s||(s=!0,i.kill())},e??Ng);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 Lk(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 Bu=class{client;constructor(){let e={timeout:Vo.HTTP_TIMEOUT_MS,headers:{"User-Agent":Ia.USER_AGENT,"accept-language":Ia.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=Mk.create(e),this.client.interceptors.request.use(t=>{let r=xg(t.url??"");return t.proxy=r?Lk(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}
17
- ${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)||!_k(e))return null;let s,a=t;return r==="GET"?i?.params&&(a=$k(t,i.params)):i?.params!==void 0&&i.params!==null&&(s=typeof i.params=="string"?i.params:JSON.stringify(i.params)),Mg({url:a,method:r,data:s,headers:i?.headers,timeoutMs:i?.timeout,binary:o})}},$=new Bu;function _k(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 $k(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}`}import*as Lg from"fs";import*as _g from"path";var $g=["DevEco"];async function es(){let n=await $.get(Et.TAGS_API_URL),t=tc(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 Fk(n){let e=[],t=Et.DEFAULT_PAGE_SIZE,r=Et.DEFAULT_MAX_PAGES,i=1;for(;i<=r;){let o=await $.post(Et.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:i,pageSize:t,tagIds:[n]}}),s=tc(o,"Skills API");if(e.push(...s.data.list),s.data.list.length<t)break;i++}return e}async function Qa(n){let e=new Map,t=n.map(i=>Fk(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=>!$g.includes(o.name)))}async function jk(n,e){let t=await $.post(Et.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:Et.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return tc(t,"Skills API").data.list}async function ec(n,e){let t=new Map,r=e.map(o=>jk(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=>!$g.includes(s.name)))}function Wu(n){St(n);let e=[];for(let t of Ze()){let r=Yr(t);if(!Vn(t))continue;let i=_g.join(r,n);Lg.existsSync(i)&&e.push(Nt(t).displayName)}return e.sort()}function tc(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=$.parseJson(n);if(t.code!==Et.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Fg(n){St(n);let e=`${Et.SKILL_API_BASE}/${n}/checksum`,t=await $.get(e);return tc(t,"Checksum API").data}var jg=Vu.promises;function Hg(n,e){let t=Mt.resolve(e),r=Mt.resolve(n),i=Mt.relative(r,t);if(i.startsWith("..")||Mt.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function Gu(n){return Mt.isAbsolute(n)?n:Mt.resolve(process.cwd(),n)}function Vk(n){return Uk.createHash("sha256").update(n).digest("hex")}async function Gk(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=Vk(n),i=e.sha256.toLowerCase(),o=Buffer.from(r,"hex"),s=Buffer.from(i,"hex");if(o.length!==s.length||!Bk(o,s))throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function qu(n){St(n);let e=`${Et.SKILL_API_BASE}/${n}/install?format=zip`,t=await $.getBinary(e),r=await Fg(n);return await Gk(t,r),t}async function Ug(n,e,t){St(t);let r=new Hk(n),i=r.getEntries();try{await jg.stat(e)}catch{await jg.mkdir(e,{recursive:!0})}let o=Mt.join(e,t);Hg(e,o);for(let s of i){let a=Mt.join(o,s.entryName);Hg(o,a)}r.extractAllTo(o,!0)}function qn(){let e=Mt.dirname(Wk(import.meta.url));for(;;){let t=Mt.join(e,"skills","deveco-cli");if(Vu.existsSync(t)&&Vu.statSync(t).isDirectory())return t;let r=Mt.dirname(e);if(r===e)break;e=r}throw new Error("skills/deveco-cli directory not found in deveco-cli package. Reinstall deveco-cli.")}function Bg(n){return n?Lt.join(n,".deveco-cli","skills"):Lt.join(F(),"skills")}function Jk(n,e){return St(n),Lt.join(Bg(e),"store",n)}async function Wg(n,e){let t=e??F(),r=await Ai.realpath(t).catch(s=>{if(s.code==="ENOENT")return Ce(t);throw s}),i=Lt.join(r,Lt.relative(t,n)),o=await Ce(i);if(!he(i,o))throw new Error(`Skill storage parent redirects outside its managed location: ${i}`);return o}async function zu(n,e){return Wg(Jk(n,e),e)}async function ts(n,e,t){St(n);let r=e.customPath??Bg(e.project),i=e.customPath?await Ce(Lt.join(r,`.${n}.lock`)):await Wg(Lt.join(r,"locks",`${n}.lock`),e.project);await Ai.mkdir(Lt.dirname(i),{recursive:!0});let o=await zk(r,{realpath:!1,lockfilePath:i,stale:3e4,update:1e4,retries:{retries:100,minTimeout:50,maxTimeout:200}});try{return await t()}finally{await o()}}async function Vg(n){let e=await Ai.lstat(n);if(!e.isDirectory()||e.isSymbolicLink()||!(await Ai.stat(Lt.join(n,"SKILL.md"))).isFile())throw new Error(`Invalid Skill store: ${n}`)}async function Gg(n,e,t,r,i){let o=await zu(n,t),s=await Ne(o);if(!i&&!s&&(await Promise.all(r.map(c=>Ne(c.path)))).every(Boolean))return{results:r.map(c=>Qt(c.path,"already-exists"))};for(let a of r)for(let c of[a.path,...a.legacy])if(Ii(o,c))throw new Error(`Skill store and destination overlap: ${o}, ${c}`);if(!i&&s){try{await Vg(o)}catch(a){throw new Error(`Cannot reuse Skill store ${o}; use --force to replace: ${a.message}`,{cause:a})}return{source:o,results:[]}}return{source:o,results:[await zg(n,e,o)]}}async function qg(n,e,t,r){let i=await Ce(t);return await Iu(i,r)??zg(n,e,i)}async function zg(n,e,t){await Ai.mkdir(Lt.dirname(t),{recursive:!0});let r=`${t}.extract-${qk()}`;try{await Ug(e,r,n);let i=Lt.join(r,n);return await Vg(i),await xu(i,t),{success:!0,path:t,reason:"shared-entity-updated"}}finally{await Ai.rm(r,{recursive:!0,force:!0})}}function rs(n,e){return{success:!1,path:n,error:e instanceof Error?e.message:String(e)}}async function Ju(n,e,t){let r=[];for(let i of vg(e))try{r.push(...await ts(n,i,()=>t(i)))}catch(o){r.push(rs(Xr.join(er(i.project),n),o))}return r}async function Ku(n){return Xu.realpath(n).catch(e=>{if(e.code==="ENOENT"||e.code==="ELOOP")return n;throw e})}async function Yk(n,e){let t=await Xu.realpath(e);for(let r of n.legacy){let i=await Ne(r);if(i&&!i.isSymbolicLink()&&Ii(t,r))throw new Error(`Skill source and legacy destination overlap: ${e}, ${r}`);await Va(r)}}async function Kk(n,e,t,r){let i=[];for(let o of Ze()){let s=Yr(o,e.project);if(e.agents.includes(o)||qa(o,e.project)&&!Vn(o,e.project))continue;let a=await Ce(Xr.join(s,n)),c=await Ne(a);c&&(he(a,t)&&Vn(o,e.project)||r&&c.isSymbolicLink()&&he(await Ku(a),r))&&i.push(Nt(o).displayName)}return[...new Set(i)]}function Xk(n,e){let t=`still used by ${e.join(", ")}`;return console.log(`Skill ${Xr.basename(n)} in ${Xr.dirname(n)} is kept: ${t}.`),Qt(n,t)}async function Yu(n,e,t,r){try{if(!await Ne(n))return;let i=await Kk(e,t,n,r);return i.length?Xk(n,i):await Va(n)}catch(i){return rs(n,i)}}var nr=class{async installBundledSkill(e,t,r=!1){return await Xu.access(Xr.join(e,"SKILL.md")),t.customPath?this.installCustom("deveco-cli",e,t.customPath,r):Ju("deveco-cli",t,i=>this.installScope("deveco-cli",e,i,t.explicitAgents,r))}async installArchiveSkill(e,t,r,i=!1){return St(e),r.customPath?this.installCustom(e,t,r.customPath,i):Ju(e,r,o=>this.installScope(e,t,o,r.explicitAgents,i))}async installCustom(e,t,r,i){let o=Xr.join(r,e);try{return await ts(e,{customPath:r},async()=>[typeof t=="string"?await Wa(t,o,i):await qg(e,t,o,i)])}catch(s){return[rs(o,s)]}}async installScope(e,t,r,i=!0,o=!1){let s=await bg(r,e,i),a=s.filter(l=>!l.skipped),c=s.filter(l=>l.skipped).map(l=>Qt(l.path,"agent-project-root-missing"));if(!a.length)return c;try{let l=typeof t=="string"?{source:t,results:[]}:await Gg(e,t,r.project,a,o);return[...c,...l.results,...l.source?await this.installSkillEntries(l.source,a,o):[]]}catch(l){return[...c,...a.map(d=>rs(d.path,l))]}}async installSkillEntries(e,t,r){let i=[];for(let o of t)try{i.push(await Wa(e,o.path,r)),r&&await Yk(o,e)}catch(s){i.push(rs(o.path,s))}return i}async migrateBundledSkill(e,t){await ts("deveco-cli",t,()=>this.migrateBundledScope(e,t))}async migrateBundledScope(e,t){let r,i=[];for(let o of t.agents)try{for(let s of await Ja({...t,agents:[o]},"deveco-cli"))await this.migrateBundledDestination(e,s,i)}catch(s){r=s,console.error(`Skill migration failed for ${o}: ${s.message}`)}if(r)throw r}async migrateBundledDestination(e,t,r){let i=await Ne(t.path);(!i||!i.isDirectory()&&!i.isSymbolicLink())&&!t.legacy.length||r.some(o=>he(o,t.path))||((await Wa(e,t.path)).reason==="already-exists"&&console.warn(`Skill migration skipped: ${t.path} (already exists; run devecocli init --force to replace).`),r.push(t.path))}async removeSkill(e,t){if(St(e),t.customPath){let r=Xr.join(t.customPath,e);return ts(e,t,async()=>[await Va(r)])}return Ju(e,t,r=>this.removeScope(e,r,t.explicitAgents))}async removeScope(e,t,r=!0){let i=await Ce(Xr.join(er(t.project),e)),o=await this.removeAgentEntries(e,t,i,r);if(o.every(s=>s.success)){let s=await Yu(i,e,t,await Ku(i));s&&o.push(s)}if(o.every(s=>s.success)){let s=await zu(e,t.project),a=await Yu(s,e,{...t,agents:[]},await Ku(s));a&&o.push(a)}return o.length||(console.log(`Skill ${e} not found for the selected agents.`),o.push(Qt(i,"not-installed"))),o}async removeAgentEntries(e,t,r,i){let o=new Set;for(let a of await Ja(t,e,i))if(!a.skipped)for(let c of[a.path,...a.legacy])he(c,r)||o.add(c);let s=[];for(let a of o){let c=await Yu(a,e,t);c&&s.push(c)}return s}};import rc from"fs/promises";import Jg from"path";function Zk(n){return`'${process.platform==="win32"?n.replace(/'/g,"''"):n.replace(/'/g,"'\\''")}'`}async function Qk(n,e){try{if(!(await Ne(n))?.isSymbolicLink())return;let r=await rc.realpath(n);return he(r,e)?void 0:{path:n,reason:`points to ${r}`,repair:!0}}catch(t){let r=t.code,i=r==="ENOENT"||r==="ELOOP"||r==="ENOTDIR";return{path:n,reason:i?"broken link":`cannot check: ${t.message}`,repair:i}}}var Zu=class{checked=new Set;async warnInvalidBundledLinks(e){try{let t=await rc.realpath(e),r=process.platform==="win32"?t.toLowerCase():t;if(this.checked.has(r))return;this.checked.add(r);let i=await rc.realpath(qn());if(!(await rc.stat(Jg.join(i,"SKILL.md"))).isFile())throw new Error(`Skill source has no SKILL.md: ${i}`);let o=await this.checkKnownEntries(t,i);this.reportIssues(t,o)}catch(t){console.warn(`Cannot check project Skill links for ${e}: ${t.message}`)}}async checkKnownEntries(e,t){let r=new Set([er(e),...Ze().map(s=>Lu(e,s))]),i=[],o=[];for(let s of r){let a=Jg.join(s,"deveco-cli");try{let c=await Ce(a);if(i.some(d=>he(d,c)))continue;i.push(c);let l=await Qk(c,t);l&&o.push(l)}catch(c){o.push({path:a,reason:`cannot check: ${c.message}`,repair:!1})}}return o}reportIssues(e,t){for(let r of t)console.warn(`Project Skill link: ${r.path} (${r.reason}).`);t.some(r=>r.repair)&&(console.warn(`Run: devecocli init --project ${Zk(e)} -f`),console.warn("Existing copies and local edits in the selected installation scope will be replaced."))}},tt=new Zu;import rp from"fs";import Qg from"path";import{cyan as mD}from"colorette";import{spawn as cD}from"child_process";import*as Zg from"fs";import*as ic from"path";import{yellow as lD,cyan as dD}from"colorette";import uD from"proper-lockfile";import{compare as eD}from"semver";function Zr(n,e){return eD(n,e)}function Ti(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 Oi(){return process.env.DEVECO_CLI_WRAPPER_NAME?process.env.DEVECO_CLI_WRAPPER_NAME:"@deveco/deveco-cli-common"}function ir(){return process.env.DEVECO_CLI_WRAPPER_VERSION?process.env.DEVECO_CLI_WRAPPER_VERSION:"1.3.7"}function Qr(){return"latest"}function _t(){return Number.isFinite(1),1}var Er="@deveco/deveco-cli-knowledgebase";function Ni(){let n=process.env.DEVECO_CLI_DISABLE_UPDATE;return n==="check"||n==="all"?n:"off"}import*as ns from"fs";import*as is from"path";var tD={lastCheckedTimestamp:null,latestVersion:null,blockedVersions:[],checkError:null,latestDocsVersion:null,latestDocsApiVersion:null,latestCompatibleDocsVersion:null,checkedAgainstDocsApi:null},Qu=new Map,en=class n{static CHECK_WINDOW_HOUR=21;static ONE_DAY_MS=1440*60*1e3;cacheFilePath;lockFilePath;constructor(e){this.cacheFilePath=is.join(e,"cache.json"),this.lockFilePath=is.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=ns.readFileSync(this.cacheFilePath,"utf-8"),r=JSON.parse(t);return Qu.set(this.cacheFilePath,r),r}catch{return{...tD}}}async write(e){m(()=>`Writing update cache: lastChecked=${e.lastCheckedTimestamp}, latest=${e.latestVersion}, blocked=[${e.blockedVersions.join(",")}], error=${e.checkError}`),await ns.promises.mkdir(is.dirname(this.cacheFilePath),{recursive:!0}),await ns.promises.writeFile(this.cacheFilePath,JSON.stringify(e,null,2),"utf-8"),Qu.set(this.cacheFilePath,e)}};import{createRequire as rD}from"module";import{dirname as nD,join as Mi}from"path";import{pathToFileURL as iD}from"url";import{readFile as Yg,access as ep}from"fs/promises";import*as Kg from"semver";var oD=rD(import.meta.url);async function sD(){try{let n=oD.resolve("@deveco/deveco-cli-knowledgebase/package.json"),e=JSON.parse(await Yg(n,"utf8"));return{version:e.version,apiVersion:e.apiVersion??0,dir:nD(n)}}catch{return null}}async function Xg(){let n=F(),e=Mi(n,"doc-data","current.json"),t;try{t=JSON.parse(await Yg(e,"utf8"))}catch{return null}let r=Mi(n,"doc-data",t.version);try{return await ep(Mi(r,"dist","engine","index.js")),await ep(Mi(r,"docs.zip")),await ep(Mi(r,"index.zip")),{version:t.version,apiVersion:t.apiVersion,dir:r}}catch{return null}}async function aD(){return[await Xg(),await sD()].filter(e=>e!==null).sort((e,t)=>Kg.rcompare(e.version,t.version))}async function Li(){let n=_t(),e=await Xg();return e&&e.apiVersion<=n?e.version:null}async function nc(){let n=_t(),e=await aD(),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=Mi(r.dir,"dist","engine","index.js");return await import(iD(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 os=class{constructor(e){this.actionCommand=e}cache=new en(ic.join(F(),"update"));async checkAndNotify(){if(!this.shouldSkip())try{let e=ir(),t=Qr(),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&&Zr(c,e)>0&&a.push(lD(`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=_t(),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 Li();return i&&Zr(r,i)<=0?{message:null,stale:!1}:{message:dD(`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 pD(this.cache.getLockPath(),()=>{let e=[process.argv[1],"update","_check"];m(`Executing: ${process.execPath} ${e.join(" ")}`),cD(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 pD(n,e){await Zg.promises.mkdir(ic.dirname(n),{recursive:!0});let t=await uD.lock(n,{stale:6e4,retries:0,realpath:!1});try{await e()}finally{await t()}}var tp=rp.promises;async function fD(n){let e=Ga(n);for(let t of e)Nt(t);return e}async function hD(n){return Ze().filter(e=>Vn(e,n))}async function gD(){let n=qn();await new nr().migrateBundledSkill(n,{agents:Ze()})}async function ey(){try{let n=Qg.join(F(),"skills","migration-version"),e=await tp.readFile(n,"utf8").catch(r=>{if(r.code==="ENOENT")return"";throw r}),t=ir();if(e.trim()===t)return;await gD(),await tp.mkdir(Qg.dirname(n),{recursive:!0}),await tp.writeFile(n,t,"utf8")}catch{}}function _i(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(mD("Finished:"));for(let i of n){if(!i.path)continue;let o=i.reason==="already-exists"?"already exists; use --force to replace":i.reason,s=i.fallbackReason?" (link failed: "+i.fallbackReason+")":o??i.error?" ("+(o??i.error)+")":"",a=i.success?i.skipped?"skipped":i.mode??(i.reason==="shared-entity-updated"?"updated":"removed"):"failed";console.log(" "+a+": "+i.path+s)}console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function Pr(n,e,t){if(!rp.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!rp.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function $i(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?Gu(n):void 0,resolvedProject:e?Gu(e):void 0}}async function Fi(n,e,t){if(e)return{agents:[],projectAgents:[],customPath:e};let r=n.agent?await fD(n.agent):await hD(t);if(!r.length)throw new Error("No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location.");return t?{agents:[],explicitAgents:!!n.agent,projectAgents:r.map(i=>({project:t,agent:i}))}:{agents:r,projectAgents:[],explicitAgents:!!n.agent}}import yD from"fs";import oc from"path";import{cyan as wD}from"colorette";import*as sc from"smol-toml";var ji=yD.promises;async function vD(n){try{let e=await ji.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 bD(n){try{let e=await ji.readFile(n,"utf8");return e.trim()===""?{}:sc.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 SD(n,e){let t=oc.dirname(n);await ji.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await ji.writeFile(n,r,"utf8")}async function ED(n,e){let t=oc.dirname(n);await ji.mkdir(t,{recursive:!0});let r=sc.stringify(e);await ji.writeFile(n,r,"utf8")}function ty(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function ry(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 ny(n,e){return n.format==="codex"?bD(e):vD(e)}async function iy(n,e,t){return n.format==="codex"?ED(e,t):SD(e,t)}async function np(n,e,t=!1){let r=Sr[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Sr).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 ny(r,r.globalConfigPath);if(ty(i,r.mcpServersKey,rr)&&!t)return console.log(`MCP server ${rr} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let o=Xa(r,void 0);return ry(i,r.mcpServersKey,rr,o,t),await iy(r,r.globalConfigPath,i),console.log(`MCP server ${rr} 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 ac(n,e,t=!1){let r=Sr[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Sr).join(", ")}`};let i=oc.isAbsolute(r.projectConfigPath)?r.projectConfigPath:oc.join(e,r.projectConfigPath);try{let o=await ny(r,i);if(ty(o,r.mcpServersKey,rr)&&!t)return console.log(`MCP server ${rr} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:n,installType:"project"};let s=Xa(r,e);return ry(o,r.mcpServersKey,rr,s,t),await iy(r,i,o),console.log(`MCP server ${rr} 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 ip(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(wD("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)}import PD from"fs";import CD from"path";import{homedir as kD}from"os";async function op(n,e){let t=[],r=n.agent?Ga(n.agent):Object.keys(Ka);for(let i of r){if(!Object.prototype.hasOwnProperty.call(Ka,i))throw new Error(`Invalid MCP agent: ${i}`);(n.agent||PD.existsSync(CD.join(kD(),Ka[i])))&&t.push(i)}if(!t.length)throw new Error("No agents supporting MCP configuration found; use --skill");return e?{agents:[],projectAgents:t.map(i=>({project:e,agent:i}))}:{agents:t,projectAgents:[]}}import{spawnSync as dy}from"child_process";import Me from"fs";import*as rt from"os";import*as I from"path";import lc from"fs";import*as dc from"os";import*as ss from"path";import xD from"regedit";import{execFileSync as DD}from"child_process";import oy from"fs";import*as sy from"os";import*as sp from"path";function cc(n,e){let t=sp.join(n,"Contents","Info.plist");if(!oy.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=DD(r,i,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(o&&!o.includes("Does Not Exist"))return o}catch{}}function RD(n){let e=cc(n,"CFBundleShortVersionString");if(!e)return cc(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[cc(n,"CFBundleVersion"),cc(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 tn(n){if(sy.platform()==="darwin")return RD(n);let e=sp.join(n,"product-info.json");try{let t=JSON.parse(oy.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}var ID="DevEco Studio",AD=["Contents","Resources","product-info.json"],TD="name";function OD(n){return n.filter(e=>{try{return lc.statSync(e).isDirectory()}catch{return!1}})}function ND(n){let e=ss.join(n,...AD);if(lc.existsSync(e))try{let r=JSON.parse(lc.readFileSync(e,"utf8"))[TD];return typeof r=="string"&&r.trim()?r.trim():void 0}catch{return}}function MD(n){return ND(n)===ID}function LD(){let n=[];for(let e of[ss.join(dc.homedir(),"Applications"),"/Applications"])try{n.push(...lc.readdirSync(e).filter(t=>t.endsWith(".app")).map(t=>ss.join(e,t)).filter(MD))}catch{}return n}function ay(n){return new Promise((e,t)=>xD.list(n,(r,i)=>r?t(r):e(i)))}async function cy(n,e,t){let i=((await ay([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(i.length===0)return[];let o=await ay(i);return i.flatMap(s=>{let a=o[s]?.values?.[t]?.value;return a?[a]:[]})}async function _D(){let n=[ss.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 cy(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 cy(e,()=>!0,""))}catch{}return n}async function ly(){let n=dc.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"?LD():await _D(),t=OD(e).flatMap(r=>{let i=tn(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)=>Ti(i.version,r.version)>0?i:r)}var $D=/^#\s*Version:\s*(\S+)/,FD="26.0.0.810";function jD(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 HD(n){let e=I.join(n,"default","openharmony");return[I.join(n,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>I.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 Ti(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):tn(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(tn(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(Ti(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:
18
- ${Hu}`)}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
+ `);if(o===-1)return null;let s=i.slice(0,o),a=i.slice(o+4),c=Ig(s);return{statusCode:c.statusCode,statusText:c.statusText,body:a,headers:c.headers}}async function Mg(n){if(process.platform!=="win32")return null;let e=xk()??await Rk();if(!e)return null;let t;n.binary&&(t=zn.mkdtempSync(ec.join(Og.tmpdir(),"curl-")));let r=t?ec.join(t,"header.tmp"):void 0,i=t?ec.join(t,"body.tmp"):void 0;try{let o=Ik(n,e,r,i),s=await Nk(o,n.timeoutMs);return!s||s.code!==0?null:Ok(s.stdout,r,i)}catch{return null}finally{t&&zn.rmSync(t,{recursive:!0,force:!0})}}function Nk(n,e){let t=Ak();return new Promise(r=>{let i=Tg(t,n,{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),o="",s=!1,a=setTimeout(()=>{s||(s=!0,i.kill())},e??Ng);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 Lk(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 Wu=class{client;constructor(){let e={timeout:Go.HTTP_TIMEOUT_MS,headers:{"User-Agent":Ta.USER_AGENT,"accept-language":Ta.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=Mk.create(e),this.client.interceptors.request.use(t=>{let r=xg(t.url??"");return t.proxy=r?Lk(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}
17
+ ${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)||!_k(e))return null;let s,a=t;return r==="GET"?i?.params&&(a=$k(t,i.params)):i?.params!==void 0&&i.params!==null&&(s=typeof i.params=="string"?i.params:JSON.stringify(i.params)),Mg({url:a,method:r,data:s,headers:i?.headers,timeoutMs:i?.timeout,binary:o})}},$=new Wu;function _k(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 $k(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}`}import*as Lg from"fs";import*as _g from"path";var $g=["DevEco"];async function ts(){let n=await $.get(Et.TAGS_API_URL),t=nc(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 Fk(n){let e=[],t=Et.DEFAULT_PAGE_SIZE,r=Et.DEFAULT_MAX_PAGES,i=1;for(;i<=r;){let o=await $.post(Et.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:i,pageSize:t,tagIds:[n]}}),s=nc(o,"Skills API");if(e.push(...s.data.list),s.data.list.length<t)break;i++}return e}async function tc(n){let e=new Map,t=n.map(i=>Fk(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=>!$g.includes(o.name)))}async function jk(n,e){let t=await $.post(Et.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:Et.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return nc(t,"Skills API").data.list}async function rc(n,e){let t=new Map,r=e.map(o=>jk(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=>!$g.includes(s.name)))}function Vu(n){St(n);let e=[];for(let t of Ze()){let r=Xr(t);if(!qn(t))continue;let i=_g.join(r,n);Lg.existsSync(i)&&e.push(Nt(t).displayName)}return e.sort()}function nc(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=$.parseJson(n);if(t.code!==Et.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Fg(n){St(n);let e=`${Et.SKILL_API_BASE}/${n}/checksum`,t=await $.get(e);return nc(t,"Checksum API").data}var jg=Gu.promises;function Hg(n,e){let t=Mt.resolve(e),r=Mt.resolve(n),i=Mt.relative(r,t);if(i.startsWith("..")||Mt.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function qu(n){return Mt.isAbsolute(n)?n:Mt.resolve(process.cwd(),n)}function Vk(n){return Uk.createHash("sha256").update(n).digest("hex")}async function Gk(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=Vk(n),i=e.sha256.toLowerCase(),o=Buffer.from(r,"hex"),s=Buffer.from(i,"hex");if(o.length!==s.length||!Bk(o,s))throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function zu(n){St(n);let e=`${Et.SKILL_API_BASE}/${n}/install?format=zip`,t=await $.getBinary(e),r=await Fg(n);return await Gk(t,r),t}async function Ug(n,e,t){St(t);let r=new Hk(n),i=r.getEntries();try{await jg.stat(e)}catch{await jg.mkdir(e,{recursive:!0})}let o=Mt.join(e,t);Hg(e,o);for(let s of i){let a=Mt.join(o,s.entryName);Hg(o,a)}r.extractAllTo(o,!0)}function Jn(){let e=Mt.dirname(Wk(import.meta.url));for(;;){let t=Mt.join(e,"skills","deveco-cli");if(Gu.existsSync(t)&&Gu.statSync(t).isDirectory())return t;let r=Mt.dirname(e);if(r===e)break;e=r}throw new Error("skills/deveco-cli directory not found in deveco-cli package. Reinstall deveco-cli.")}function Bg(n){return n?Lt.join(n,".deveco-cli","skills"):Lt.join(F(),"skills")}function Jk(n,e){return St(n),Lt.join(Bg(e),"store",n)}async function Wg(n,e){let t=e??F(),r=await Ti.realpath(t).catch(s=>{if(s.code==="ENOENT")return Ce(t);throw s}),i=Lt.join(r,Lt.relative(t,n)),o=await Ce(i);if(!fe(i,o))throw new Error(`Skill storage parent redirects outside its managed location: ${i}`);return o}async function Ju(n,e){return Wg(Jk(n,e),e)}async function rs(n,e,t){St(n);let r=e.customPath??Bg(e.project),i=e.customPath?await Ce(Lt.join(r,`.${n}.lock`)):await Wg(Lt.join(r,"locks",`${n}.lock`),e.project);await Ti.mkdir(Lt.dirname(i),{recursive:!0});let o=await zk(r,{realpath:!1,lockfilePath:i,stale:3e4,update:1e4,retries:{retries:100,minTimeout:50,maxTimeout:200}});try{return await t()}finally{await o()}}async function Vg(n){let e=await Ti.lstat(n);if(!e.isDirectory()||e.isSymbolicLink()||!(await Ti.stat(Lt.join(n,"SKILL.md"))).isFile())throw new Error(`Invalid Skill store: ${n}`)}async function Gg(n,e,t,r,i){let o=await Ju(n,t),s=await Ne(o);if(!i&&!s&&(await Promise.all(r.map(c=>Ne(c.path)))).every(Boolean))return{results:r.map(c=>er(c.path,"already-exists"))};for(let a of r)for(let c of[a.path,...a.legacy])if(Ii(o,c))throw new Error(`Skill store and destination overlap: ${o}, ${c}`);if(!i&&s){try{await Vg(o)}catch(a){throw new Error(`Cannot reuse Skill store ${o}; use --force to replace: ${a.message}`,{cause:a})}return{source:o,results:[]}}return{source:o,results:[await zg(n,e,o)]}}async function qg(n,e,t,r){let i=await Ce(t);return await Iu(i,r)??zg(n,e,i)}async function zg(n,e,t){await Ti.mkdir(Lt.dirname(t),{recursive:!0});let r=`${t}.extract-${qk()}`;try{await Ug(e,r,n);let i=Lt.join(r,n);return await Vg(i),await Au(i,t),{success:!0,path:t,reason:"shared-entity-updated"}}finally{await Ti.rm(r,{recursive:!0,force:!0})}}function ns(n,e){return{success:!1,path:n,error:e instanceof Error?e.message:String(e)}}async function Yu(n,e,t){let r=[];for(let i of vg(e))try{r.push(...await rs(n,i,()=>t(i)))}catch(o){r.push(ns(Qr.join(tr(i.project),n),o))}return r}async function Xu(n){return Zu.realpath(n).catch(e=>{if(e.code==="ENOENT"||e.code==="ELOOP")return n;throw e})}async function Yk(n,e){let t=await Zu.realpath(e);for(let r of n.legacy){let i=await Ne(r);if(i&&!i.isSymbolicLink()&&Ii(t,r))throw new Error(`Skill source and legacy destination overlap: ${e}, ${r}`);await qa(r)}}async function Kk(n,e,t,r){let i=[];for(let o of Ze()){let s=Xr(o,e.project);if(e.agents.includes(o)||Ja(o,e.project)&&!qn(o,e.project))continue;let a=await Ce(Qr.join(s,n)),c=await Ne(a);c&&(fe(a,t)&&qn(o,e.project)||r&&c.isSymbolicLink()&&fe(await Xu(a),r))&&i.push(Nt(o).displayName)}return[...new Set(i)]}function Xk(n,e){let t=`still used by ${e.join(", ")}`;return console.log(`Skill ${Qr.basename(n)} in ${Qr.dirname(n)} is kept: ${t}.`),er(n,t)}async function Ku(n,e,t,r){try{if(!await Ne(n))return;let i=await Kk(e,t,n,r);return i.length?Xk(n,i):await qa(n)}catch(i){return ns(n,i)}}var ir=class{async installBundledSkill(e,t,r=!1){return await Zu.access(Qr.join(e,"SKILL.md")),t.customPath?this.installCustom("deveco-cli",e,t.customPath,r):Yu("deveco-cli",t,i=>this.installScope("deveco-cli",e,i,t.explicitAgents,r))}async installArchiveSkill(e,t,r,i=!1){return St(e),r.customPath?this.installCustom(e,t,r.customPath,i):Yu(e,r,o=>this.installScope(e,t,o,r.explicitAgents,i))}async installCustom(e,t,r,i){let o=Qr.join(r,e);try{return await rs(e,{customPath:r},async()=>[typeof t=="string"?await Ga(t,o,i):await qg(e,t,o,i)])}catch(s){return[ns(o,s)]}}async installScope(e,t,r,i=!0,o=!1){let s=await bg(r,e,i),a=s.filter(l=>!l.skipped),c=s.filter(l=>l.skipped).map(l=>er(l.path,"agent-project-root-missing"));if(!a.length)return c;try{let l=typeof t=="string"?{source:t,results:[]}:await Gg(e,t,r.project,a,o);return[...c,...l.results,...l.source?await this.installSkillEntries(l.source,a,o):[]]}catch(l){return[...c,...a.map(d=>ns(d.path,l))]}}async installSkillEntries(e,t,r){let i=[];for(let o of t)try{i.push(await Ga(e,o.path,r)),r&&await Yk(o,e)}catch(s){i.push(ns(o.path,s))}return i}async migrateBundledSkill(e,t){await rs("deveco-cli",t,()=>this.migrateBundledScope(e,t))}async migrateBundledScope(e,t){let r,i=[];for(let o of t.agents)try{for(let s of await Ka({...t,agents:[o]},"deveco-cli"))await this.migrateBundledDestination(e,s,i)}catch(s){r=s,console.error(`Skill migration failed for ${o}: ${s.message}`)}if(r)throw r}async migrateBundledDestination(e,t,r){let i=await Ne(t.path);(!i||!i.isDirectory()&&!i.isSymbolicLink())&&!t.legacy.length||r.some(o=>fe(o,t.path))||((await Ga(e,t.path)).reason==="already-exists"&&console.warn(`Skill migration skipped: ${t.path} (already exists; run devecocli init --force to replace).`),r.push(t.path))}async removeSkill(e,t){if(St(e),t.customPath){let r=Qr.join(t.customPath,e);return rs(e,t,async()=>[await qa(r)])}return Yu(e,t,r=>this.removeScope(e,r,t.explicitAgents))}async removeScope(e,t,r=!0){let i=await Ce(Qr.join(tr(t.project),e)),o=await this.removeAgentEntries(e,t,i,r);if(o.every(s=>s.success)){let s=await Ku(i,e,t,await Xu(i));s&&o.push(s)}if(o.every(s=>s.success)){let s=await Ju(e,t.project),a=await Ku(s,e,{...t,agents:[]},await Xu(s));a&&o.push(a)}return o.length||(console.log(`Skill ${e} not found for the selected agents.`),o.push(er(i,"not-installed"))),o}async removeAgentEntries(e,t,r,i){let o=new Set;for(let a of await Ka(t,e,i))if(!a.skipped)for(let c of[a.path,...a.legacy])fe(c,r)||o.add(c);let s=[];for(let a of o){let c=await Ku(a,e,t);c&&s.push(c)}return s}};import ic from"fs/promises";import Jg from"path";function Zk(n){return`'${process.platform==="win32"?n.replace(/'/g,"''"):n.replace(/'/g,"'\\''")}'`}async function Qk(n,e){try{if(!(await Ne(n))?.isSymbolicLink())return;let r=await ic.realpath(n);return fe(r,e)?void 0:{path:n,reason:`points to ${r}`,repair:!0}}catch(t){let r=t.code,i=r==="ENOENT"||r==="ELOOP"||r==="ENOTDIR";return{path:n,reason:i?"broken link":`cannot check: ${t.message}`,repair:i}}}var Qu=class{checked=new Set;async warnInvalidBundledLinks(e){try{let t=await ic.realpath(e),r=process.platform==="win32"?t.toLowerCase():t;if(this.checked.has(r))return;this.checked.add(r);let i=await ic.realpath(Jn());if(!(await ic.stat(Jg.join(i,"SKILL.md"))).isFile())throw new Error(`Skill source has no SKILL.md: ${i}`);let o=await this.checkKnownEntries(t,i);this.reportIssues(t,o)}catch(t){console.warn(`Cannot check project Skill links for ${e}: ${t.message}`)}}async checkKnownEntries(e,t){let r=new Set([tr(e),...Ze().map(s=>_u(e,s))]),i=[],o=[];for(let s of r){let a=Jg.join(s,"deveco-cli");try{let c=await Ce(a);if(i.some(d=>fe(d,c)))continue;i.push(c);let l=await Qk(c,t);l&&o.push(l)}catch(c){o.push({path:a,reason:`cannot check: ${c.message}`,repair:!1})}}return o}reportIssues(e,t){for(let r of t)console.warn(`Project Skill link: ${r.path} (${r.reason}).`);t.some(r=>r.repair)&&(console.warn(`Run: devecocli init --project ${Zk(e)} -f`),console.warn("Existing copies and local edits in the selected installation scope will be replaced."))}},tt=new Qu;import np from"fs";import Qg from"path";import{cyan as mD}from"colorette";import{spawn as cD}from"child_process";import*as Zg from"fs";import*as sc from"path";import{yellow as lD,cyan as dD}from"colorette";import uD from"proper-lockfile";import{compare as eD}from"semver";function en(n,e){return eD(n,e)}function Oi(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 Ni(){return process.env.DEVECO_CLI_WRAPPER_NAME?process.env.DEVECO_CLI_WRAPPER_NAME:"@deveco/deveco-cli-common"}function or(){return process.env.DEVECO_CLI_WRAPPER_VERSION?process.env.DEVECO_CLI_WRAPPER_VERSION:"1.3.9"}function tn(){return"latest"}function _t(){return Number.isFinite(1),1}var Pr="@deveco/deveco-cli-knowledgebase";function Mi(){let n=process.env.DEVECO_CLI_DISABLE_UPDATE;return n==="check"||n==="all"?n:"off"}import*as is from"fs";import*as os from"path";var tD={lastCheckedTimestamp:null,latestVersion:null,blockedVersions:[],checkError:null,latestDocsVersion:null,latestDocsApiVersion:null,latestCompatibleDocsVersion:null,checkedAgainstDocsApi:null},ep=new Map,rn=class n{static CHECK_WINDOW_HOUR=21;static ONE_DAY_MS=1440*60*1e3;cacheFilePath;lockFilePath;constructor(e){this.cacheFilePath=os.join(e,"cache.json"),this.lockFilePath=os.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=ep.get(this.cacheFilePath);if(e)return e;try{let t=is.readFileSync(this.cacheFilePath,"utf-8"),r=JSON.parse(t);return ep.set(this.cacheFilePath,r),r}catch{return{...tD}}}async write(e){m(()=>`Writing update cache: lastChecked=${e.lastCheckedTimestamp}, latest=${e.latestVersion}, blocked=[${e.blockedVersions.join(",")}], error=${e.checkError}`),await is.promises.mkdir(os.dirname(this.cacheFilePath),{recursive:!0}),await is.promises.writeFile(this.cacheFilePath,JSON.stringify(e,null,2),"utf-8"),ep.set(this.cacheFilePath,e)}};import{createRequire as rD}from"module";import{dirname as nD,join as Li}from"path";import{pathToFileURL as iD}from"url";import{readFile as Yg,access as tp}from"fs/promises";import*as Kg from"semver";var oD=rD(import.meta.url);async function sD(){try{let n=oD.resolve("@deveco/deveco-cli-knowledgebase/package.json"),e=JSON.parse(await Yg(n,"utf8"));return{version:e.version,apiVersion:e.apiVersion??0,dir:nD(n)}}catch{return null}}async function Xg(){let n=F(),e=Li(n,"doc-data","current.json"),t;try{t=JSON.parse(await Yg(e,"utf8"))}catch{return null}let r=Li(n,"doc-data",t.version);try{return await tp(Li(r,"dist","engine","index.js")),await tp(Li(r,"docs.zip")),await tp(Li(r,"index.zip")),{version:t.version,apiVersion:t.apiVersion,dir:r}}catch{return null}}async function aD(){return[await Xg(),await sD()].filter(e=>e!==null).sort((e,t)=>Kg.rcompare(e.version,t.version))}async function _i(){let n=_t(),e=await Xg();return e&&e.apiVersion<=n?e.version:null}async function oc(){let n=_t(),e=await aD(),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(iD(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 ss=class{constructor(e){this.actionCommand=e}cache=new rn(sc.join(F(),"update"));async checkAndNotify(){if(!this.shouldSkip())try{let e=or(),t=tn(),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&&en(c,e)>0&&a.push(lD(`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=_t(),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&&en(r,i)<=0?{message:null,stale:!1}:{message:dD(`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 pD(this.cache.getLockPath(),()=>{let e=[process.argv[1],"update","_check"];m(`Executing: ${process.execPath} ${e.join(" ")}`),cD(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 pD(n,e){await Zg.promises.mkdir(sc.dirname(n),{recursive:!0});let t=await uD.lock(n,{stale:6e4,retries:0,realpath:!1});try{await e()}finally{await t()}}var rp=np.promises;async function fD(n){let e=za(n);for(let t of e)Nt(t);return e}async function hD(n){return Ze().filter(e=>qn(e,n))}async function gD(){let n=Jn();await new ir().migrateBundledSkill(n,{agents:Ze()})}async function ey(){try{let n=Qg.join(F(),"skills","migration-version"),e=await rp.readFile(n,"utf8").catch(r=>{if(r.code==="ENOENT")return"";throw r}),t=or();if(e.trim()===t)return;await gD(),await rp.mkdir(Qg.dirname(n),{recursive:!0}),await rp.writeFile(n,t,"utf8")}catch{}}function $i(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(mD("Finished:"));for(let i of n){if(!i.path)continue;let o=i.reason==="already-exists"?"already exists; use --force to replace":i.reason,s=i.fallbackReason?" (link failed: "+i.fallbackReason+")":o??i.error?" ("+(o??i.error)+")":"",a=i.success?i.skipped?"skipped":i.mode??(i.reason==="shared-entity-updated"?"updated":"removed"):"failed";console.log(" "+a+": "+i.path+s)}console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function Cr(n,e,t){if(!np.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!np.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function Fi(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?qu(n):void 0,resolvedProject:e?qu(e):void 0}}async function ji(n,e,t){if(e)return{agents:[],projectAgents:[],customPath:e};let r=n.agent?await fD(n.agent):await hD(t);if(!r.length)throw new Error("No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location.");return t?{agents:[],explicitAgents:!!n.agent,projectAgents:r.map(i=>({project:t,agent:i}))}:{agents:r,projectAgents:[],explicitAgents:!!n.agent}}import yD from"fs";import ac from"path";import{cyan as wD}from"colorette";import*as cc from"smol-toml";var Hi=yD.promises;async function vD(n){try{let e=await Hi.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 bD(n){try{let e=await Hi.readFile(n,"utf8");return e.trim()===""?{}:cc.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 SD(n,e){let t=ac.dirname(n);await Hi.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await Hi.writeFile(n,r,"utf8")}async function ED(n,e){let t=ac.dirname(n);await Hi.mkdir(t,{recursive:!0});let r=cc.stringify(e);await Hi.writeFile(n,r,"utf8")}function ty(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function ry(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 ny(n,e){return n.format==="codex"?bD(e):vD(e)}async function iy(n,e,t){return n.format==="codex"?ED(e,t):SD(e,t)}async function ip(n,e,t=!1){let r=Er[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Er).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 ny(r,r.globalConfigPath);if(ty(i,r.mcpServersKey,nr)&&!t)return console.log(`MCP server ${nr} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let o=Qa(r,void 0);return ry(i,r.mcpServersKey,nr,o,t),await iy(r,r.globalConfigPath,i),console.log(`MCP server ${nr} 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 lc(n,e,t=!1){let r=Er[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Er).join(", ")}`};let i=ac.isAbsolute(r.projectConfigPath)?r.projectConfigPath:ac.join(e,r.projectConfigPath);try{let o=await ny(r,i);if(ty(o,r.mcpServersKey,nr)&&!t)return console.log(`MCP server ${nr} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:n,installType:"project"};let s=Qa(r,e);return ry(o,r.mcpServersKey,nr,s,t),await iy(r,i,o),console.log(`MCP server ${nr} 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 op(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(wD("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)}import PD from"fs";import CD from"path";import{homedir as kD}from"os";async function sp(n,e){let t=[],r=n.agent?za(n.agent):Object.keys(Za);for(let i of r){if(!Object.prototype.hasOwnProperty.call(Za,i))throw new Error(`Invalid MCP agent: ${i}`);(n.agent||PD.existsSync(CD.join(kD(),Za[i])))&&t.push(i)}if(!t.length)throw new Error("No agents supporting MCP configuration found; use --skill");return e?{agents:[],projectAgents:t.map(i=>({project:e,agent:i}))}:{agents:t,projectAgents:[]}}import{spawnSync as dy}from"child_process";import Me from"fs";import*as rt from"os";import*as A from"path";import uc from"fs";import*as pc from"os";import*as as from"path";import xD from"regedit";import{execFileSync as DD}from"child_process";import oy from"fs";import*as sy from"os";import*as ap from"path";function dc(n,e){let t=ap.join(n,"Contents","Info.plist");if(!oy.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=DD(r,i,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(o&&!o.includes("Does Not Exist"))return o}catch{}}function RD(n){let e=dc(n,"CFBundleShortVersionString");if(!e)return dc(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[dc(n,"CFBundleVersion"),dc(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 nn(n){if(sy.platform()==="darwin")return RD(n);let e=ap.join(n,"product-info.json");try{let t=JSON.parse(oy.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}var AD="DevEco Studio",ID=["Contents","Resources","product-info.json"],TD="name";function OD(n){return n.filter(e=>{try{return uc.statSync(e).isDirectory()}catch{return!1}})}function ND(n){let e=as.join(n,...ID);if(uc.existsSync(e))try{let r=JSON.parse(uc.readFileSync(e,"utf8"))[TD];return typeof r=="string"&&r.trim()?r.trim():void 0}catch{return}}function MD(n){return ND(n)===AD}function LD(){let n=[];for(let e of[as.join(pc.homedir(),"Applications"),"/Applications"])try{n.push(...uc.readdirSync(e).filter(t=>t.endsWith(".app")).map(t=>as.join(e,t)).filter(MD))}catch{}return n}function ay(n){return new Promise((e,t)=>xD.list(n,(r,i)=>r?t(r):e(i)))}async function cy(n,e,t){let i=((await ay([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(i.length===0)return[];let o=await ay(i);return i.flatMap(s=>{let a=o[s]?.values?.[t]?.value;return a?[a]:[]})}async function _D(){let n=[as.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 cy(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 cy(e,()=>!0,""))}catch{}return n}async function ly(){let n=pc.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"?LD():await _D(),t=OD(e).flatMap(r=>{let i=nn(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)=>Oi(i.version,r.version)>0?i:r)}var $D=/^#\s*Version:\s*(\S+)/,FD="26.0.0.810";function jD(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 HD(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 Oi(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):nn(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(nn(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(Oi(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:
18
+ ${Uu}`)}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}
19
19
  Searched paths:
20
20
  ${r.join(`
21
- `)}`,a)}let o=Kr(e),s=Kr(i);return n.assertInsideRoot(s,o,"codelinter"),s}static isValidRoot(e,t){if(!n.isDirectory(e))return!1;if(t==="clt")return Me.existsSync(I.join(e,"version.txt"));let r=rt.platform()==="darwin"?I.join(e,"Contents"):e,i=rt.platform()==="darwin"?I.join(r,"Info.plist"):I.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=rt.platform()==="win32",r=t?".exe":"",i=I.join(e,"sdk");return{nodePath:t?I.join(e,"tool","node","node.exe"):I.join(e,"tool","node","bin","node"),ohpmJsPath:I.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:I.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:i,hdcPath:I.join(i,"default","openharmony","toolchains",`hdc${r}`),emulatorPath:I.join(e,"emulator",t?"Emulator.exe":"Emulator"),clangdPath:n.clangdPathFor(i),arktsLangServerCandidates:[{root:I.join(e,"arkts-lsp","lib"),marker:I.join(e,"arkts-lsp","lib","out","index.js")}],codelinterCandidates:n.codelinterCandidatesFor(e,"clt")}}static buildStudioToolPaths(e){let t=rt.platform()==="darwin",r=rt.platform()==="win32",i=t?I.join(e,"Contents"):e,o=I.join(i,"tools"),s=I.join(i,"sdk"),a=r?".exe":"";return{nodePath:r?I.join(o,"node","node.exe"):I.join(o,"node","bin","node"),ohpmJsPath:I.join(o,"ohpm","bin","pm-cli.js"),hvigorJsPath:I.join(o,"hvigor","bin","hvigorw.js"),javaPath:r?I.join(e,"jbr","bin","java.exe"):t?I.join(i,"jbr","Contents","Home","bin","java"):I.join(i,"jbr","bin","java"),sdkPath:s,hdcPath:I.join(s,"default","openharmony","toolchains",`hdc${a}`),emulatorPath:I.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[I.join(e,"codelinter","index.js"),I.join(e,"codelinter","run","index.js"),I.join(e,"tool","codelinter","bin","codelinter.js"),I.join(e,"tool","codelinter","codelinter.js")];let r=rt.platform()==="darwin"?["Contents"]:[];return[I.join(e,...r,"plugins","codelinter","run","index.js"),I.join(e,...r,"plugins","codelinter","index.js"),I.join(e,...r,"tools","codelinter","bin","codelinter.js"),I.join(e,...r,"tools","codelinter","codelinter.js")]}static studioArktsLangServerCandidates(e){if(rt.platform()==="linux")return[];let t=rt.platform()==="darwin"?["Contents"]:[],r=I.join(e,...t,"plugins","openharmony");return[{root:r,marker:I.join(r,"ace-server","out","index.js")}]}static clangdPathFor(e){return I.join(e,"default","openharmony","native","llvm","bin",rt.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 ly();return m(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,r){let i;try{i=Ya(e)}catch(o){throw new Error(`Invalid ${r}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}return t==="studio"&&rt.platform()==="darwin"&&(i=n.normalizeMacStudioRoot(i)),n.isValidRoot(i,t)?i:n.throwInvalidSource(i,t,r,e)}static assertBuiltPathsInsideRoot(e,t,r){let i=Kr(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(Eg(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=`${I.sep}Contents`,r=I.normalize(e);return r.endsWith(t)?r.slice(0,-t.length):r}static readCltVersion(e){try{return Me.readFileSync(I.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match($D)?.[1]?.trim()).find(Boolean)}catch{return}}static resolveCltJava(e){let t=process.env.JAVA_HOME?.trim(),i=[t&&(n.javaIn(I.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=rt.platform()==="win32",t=e?"where.exe":"which",r=e?["java"]:["-a","java"];m(`Executing: ${t} ${r.join(" ")}`);let i=dy(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(rt.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(r=>I.join(e,r)).find(Me.existsSync)}static isUsableJava(e){let t=["-version"];m(`Executing: ${e} ${t.join(" ")}`);let r=dy(e,t,{encoding:"utf8",stdio:"pipe",timeout:2e3,windowsHide:!0});return!r.error&&r.status===0}getMaxApiLevel(){for(let e of HD(this.sdkPath)){let t=jD(e);if(t!==void 0)return t}return 23}getSdkPlatformVersion(){let e=I.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=rt.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=I.join(this._devecoStudioPath,t,"plugins","harmony","arkanalyzer-apiscan"),i=I.join(r,"resources","apiChange"),o=I.join(r,"api-change-scan.js");if(!Me.existsSync(i)||!Me.existsSync(o)){let s=tn(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${FD}. Upgrade before using 'check compat' at ${Hu}`)}return this._apiscanPaths={apiChangeDir:i,scriptPath:o},this._apiscanPaths}};import{execa as eR}from"execa";import*as yy from"net";import*as rn from"path";import*as mc from"fs";import*as fc from"os";import{execFile as lp,spawn as uy}from"child_process";import{existsSync as UD,readdirSync as BD,readFileSync as WD}from"fs";var pc="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",ap,cp="---MEMORY-SAMPLE-DELIMITER---";function my(){return ap===void 0&&(ap=UD(pc)),ap}function mt(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(" ")}`),lp(r,i,{timeout:5e3,windowsHide:!0},(o,s)=>{if(o){e(null);return}e(t?QD(s):ZD(s))})})}async function VD(){return process.platform==="linux"?uc():process.platform==="darwin"?GD():process.platform==="win32"?qD():[]}function uc(){let n=[],e;try{e=BD("/proc")}catch{return n}for(let t of e){if(!/^\d+$/.test(t))continue;let r=Number(t);try{let i=WD(`/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 GD(){return new Promise(n=>{lp("ps",["-ax","-o","pid=,ppid=,rss="],{timeout:5e3,windowsHide:!0},(e,t)=>{if(e){n([]);return}n(fy(t))})})}function fy(n){let e=[];for(let t of n.trim().split(`
22
- `)){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 qD(){return new Promise(n=>{if(!my()){n([]);return}lp(pc,["-NoProfile","-Command",'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId),$($_.ParentProcessId),$($_.WorkingSetSize)" }'],{timeout:5e3,windowsHide:!0},(t,r)=>{if(t){n([]);return}n(hy(r))})})}function hy(n){let e=[];for(let t of n.trim().split(`
23
- `)){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 gy(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 zD(n){let e=await VD();return gy(e,n)}function JD(n){if(process.platform==="darwin"){let e=(n/1e3).toFixed(1),t=`while true; do ps -ax -o pid=,ppid=,rss=; echo '${cp}'; sleep ${e}; done`;return m(`Executing: sh -c ${t}`),uy("sh",["-c",t],{stdio:["ignore","pipe","ignore"],windowsHide:!0})}if(process.platform==="win32"&&my()){let e=`while ($true) { Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId),$($_.ParentProcessId),$($_.WorkingSetSize)" }; Write-Output '${cp}'; Start-Sleep -Milliseconds ${n} }`;return m(`Executing: ${pc} -NoProfile -Command ${e}`),uy(pc,["-NoProfile","-Command",e],{stdio:["ignore","pipe","ignore"],windowsHide:!0})}return null}function ce(n){return`${(n/1024/1024).toFixed(2)}MB`}async function py(n,e){if(!n)return process.memoryUsage().rss;if(e)return zD(n);let t=await mt(n);return t?Number(t)*1024:0}function Hi(n,e=2e3,t=!1){let r=0,i=!1,o=a=>{if(i||!n)return;let c=t?gy(a,n):a.find(l=>l.pid===n)?.rssBytes??0;c>r&&(r=c)};if(!n)return KD(e);if(process.platform==="linux")return XD(e,o,()=>r);let s=JD(e);return s?(YD(s,o),{stop:async()=>{i=!0;try{s.kill()}catch{}let a=await py(n,t);return Math.max(r,a)}}):{stop:async()=>{i=!0;let a=await py(n,t);return Math.max(r,a)}}}function YD(n,e){let t=process.platform==="darwin"?fy:hy,r="";n.stdout?.on("data",i=>{r+=i.toString();let o=r.split(cp);r=o.pop()??"";for(let s of o)e(t(s))}),n.on("error",()=>{})}function KD(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 XD(n,e,t){e(uc());let r=setInterval(()=>e(uc()),n);return{stop:async()=>(clearInterval(r),e(uc()),t())}}function ZD(n){let e=n.trim().match(/^(\d+)$/);return e?e[1]:null}function QD(n){let e=n.match(/"([^"]+?)\s*K"/i);return e&&e[1].replace(/\D/g,"")||null}var hc="module",ft=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let i=rn.dirname(e.javaPath),o=`${i}${rn.delimiter}${process.env.PATH||""}`,s={...process.env,PATH:o,DEVECO_SDK_HOME:e.sdkPath},a=fc.platform()==="darwin"&&e.javaPath==="/usr/bin/java";e.sourceType==="clt"&&e.javaPath&&!a&&(s.JAVA_HOME=rn.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??hc];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 yy.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(!mc.existsSync(t))return null;try{let r=mc.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||rn.join(fc.homedir(),".hvigor");return rn.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=eR(t,r,{cwd:this.projectRoot,env:this.env,stdout:i,stderr:i}),s=Xe()?void 0:Hi(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 tR}from"execa";var Ui=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=tR(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"}),i=Xe()?void 0:Hi(r.pid,2e3,!1);try{await r}finally{if(i){let o=await i.stop();o>0&&(this.peakMemoryMb=ce(o))}}}};import{mkdir as rR}from"fs/promises";import{dirname as nR,resolve as iR}from"path";import{execa as oR}from"execa";import{lock as dp,check as jG}from"proper-lockfile";function up(n){return iR(n,".hvigor",".build-lock")}function sR(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function wy(n){let e=nR(up(n));if(await rR(e,{recursive:!0}),process.platform==="win32")try{await oR("attrib",["+h",e])}catch{}}async function aR(n,e){let t=new AbortController,r=sR(e);await wy(n);let i={lockfilePath:up(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await dp(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 dp(n,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function zn(n,e,t){let{release:r,signal:i}=await aR(n,t);try{return await e(i)}finally{await r()}}async function gc(n,e){let t=new AbortController;await wy(n);let r={lockfilePath:up(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await dp(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 Cr from"fs";import*as or from"path";import cR from"json5";var lR=1e3;function Bi(n,e,t){let r=dR(n,e,t);return r.required?(m(`[ProjectCheck] ${t} check: ${r.reason}`),r):null}function yc(n){m(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=or.join(n,Pe.SYNC_OUTPUT_PATH);if(!Cr.existsSync(e)){let a={required:!0,reason:`sync baseline file not found: ${e}`};return m(`[ProjectCheck] ${a.reason}`),a}let t=Cr.statSync(e).mtimeMs,r=or.join(n,Pe.LOCK_JSON5_PATH);if(!Cr.existsSync(r)){let a={required:!0,reason:`oh_modules lock not found: ${r}`};return m(`[ProjectCheck] ${a.reason}`),a}let i=uR(n);if(i===null)return{required:!0,reason:"failed to parse build-profile.json5"};let o=Bi(or.join(n,Pe.OH_PACKAGE_JSON5),t,"root");if(o||(o=Bi(or.join(n,Pe.BUILD_PROFILE_JSON5),t,"build-profile"),o)||(o=Bi(or.join(n,Pe.HVIGOR_CONFIG),t,"hvigor-config"),o)||(o=Bi(or.join(n,Pe.HVIGOR_CONFIG),t,"hvigor-config"),o))return o;for(let a of i)if(o=Bi(or.join(n,a.srcPath,Pe.OH_PACKAGE_JSON5),t,a.name),o||(o=Bi(or.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 dR(n,e,t){if(!Cr.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=Cr.statSync(n).mtimeMs;return r-e>lR?{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 uR(n){let e=or.join(n,Pe.BUILD_PROFILE_JSON5);try{let t=Cr.readFileSync(e,"utf-8");if(!t.trim())return null;let r=cR.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 vy from"util";var pp="";function vc(n){if(!n||n==="auto"||n==="stdout"||n==="none"){pp="";return}pp=n}function by(){return pp||(ig()??"")}function wc(n,...e){if(e.length===0)return n;try{return vy.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var f={info(n,...e){g.info(`[lsp] ${wc(n,...e)}`)},warn(n,...e){g.warn(`[lsp] ${wc(n,...e)}`)},error(n,...e){g.error(`[lsp] ${wc(n,...e)}`)},debug(n,...e){g.debug(`[lsp] ${wc(n,...e)}`)}};import*as as from"fs";import*as cs from"os";import*as Vi from"path";import pR 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",Wi={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate"};var Sy=8192,mp=100,Ey=.03,Py=.7,nt=900*1e3;function ht(n){if(!as.existsSync(n))return null;try{let e=as.readFileSync(n,"utf-8");return e.trim()?pR.parse(e):null}catch{return null}}function bc(n,e){let t=Math.floor(cs.totalmem()/1048576),r=Math.floor(t*Py),i,o;e!==void 0&&Number.isFinite(e)&&e>0?(i=e,o=`override(${e})`):(i=Sy,n>mp&&(i+=(n-mp)*Ey*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 $t(n){if(n.startsWith("file:"))return n;try{let e=Vi.resolve(n),t=new URL(`file://${e}`).toString();if(cs.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 Gi(n){return n&&n.replace(/\\/g,"/")}function ge(n){let e=Vi.normalize(n).replace(/\\/g,"/");if(cs.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function Jn(n){return n||process.execPath||"node"}function ls(n){let e=ge(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=${ge(n.projectPath)}`),n.sdkPath&&t.push(`--sdkPath=${ge(n.sdkPath)}`),t}function Cy(n){return Vi.join(n,"build-profile.json5")}var kr=class{constructor(e){this.projectRoot=e}getAllModuleInfo(){let e=Cy(this.projectRoot);try{let t=ht(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 mR}from"child_process";import*as Ec from"fs";var fR=600*1e3;function hR(n,e,t){let r=t.split(/\s+/).filter(i=>i.length>0);return[n,[e,...r]]}function gR(n,e){let t=[],r=[],i="",o="";return n.stdout?.on("data",s=>{let a=s.toString();t.push(a),i=ky(i+a,e)}),n.stderr?.on("data",s=>{let a=s.toString();r.push(a),o=ky(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 ky(n,e){let t=n.split(/\r?\n/),r=t.pop()??"";for(let i of t)i&&e?.(i);return r}function Sc(n){return n.join("")}function yR(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
21
+ `)}`,a)}let o=Zr(e),s=Zr(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=rt.platform()==="darwin"?A.join(e,"Contents"):e,i=rt.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=rt.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=rt.platform()==="darwin",r=rt.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=rt.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(rt.platform()==="linux")return[];let t=rt.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",rt.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 ly();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"&&rt.platform()==="darwin"&&(i=n.normalizeMacStudioRoot(i)),n.isValidRoot(i,t)?i:n.throwInvalidSource(i,t,r,e)}static assertBuiltPathsInsideRoot(e,t,r){let i=Zr(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(Eg(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($D)?.[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=rt.platform()==="win32",t=e?"where.exe":"which",r=e?["java"]:["-a","java"];m(`Executing: ${t} ${r.join(" ")}`);let i=dy(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(rt.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=dy(e,t,{encoding:"utf8",stdio:"pipe",timeout:2e3,windowsHide:!0});return!r.error&&r.status===0}getMaxApiLevel(){for(let e of HD(this.sdkPath)){let t=jD(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=rt.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=nn(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${FD}. Upgrade before using 'check compat' at ${Uu}`)}return this._apiscanPaths={apiChangeDir:i,scriptPath:o},this._apiscanPaths}};import{execa as eR}from"execa";import*as yy from"net";import*as on from"path";import*as hc from"fs";import*as gc from"os";import{execFile as dp,spawn as uy}from"child_process";import{existsSync as UD,readdirSync as BD,readFileSync as WD}from"fs";var fc="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",cp,lp="---MEMORY-SAMPLE-DELIMITER---";function my(){return cp===void 0&&(cp=UD(fc)),cp}function mt(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(" ")}`),dp(r,i,{timeout:5e3,windowsHide:!0},(o,s)=>{if(o){e(null);return}e(t?QD(s):ZD(s))})})}async function VD(){return process.platform==="linux"?mc():process.platform==="darwin"?GD():process.platform==="win32"?qD():[]}function mc(){let n=[],e;try{e=BD("/proc")}catch{return n}for(let t of e){if(!/^\d+$/.test(t))continue;let r=Number(t);try{let i=WD(`/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 GD(){return new Promise(n=>{dp("ps",["-ax","-o","pid=,ppid=,rss="],{timeout:5e3,windowsHide:!0},(e,t)=>{if(e){n([]);return}n(fy(t))})})}function fy(n){let e=[];for(let t of n.trim().split(`
22
+ `)){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 qD(){return new Promise(n=>{if(!my()){n([]);return}dp(fc,["-NoProfile","-Command",'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId),$($_.ParentProcessId),$($_.WorkingSetSize)" }'],{timeout:5e3,windowsHide:!0},(t,r)=>{if(t){n([]);return}n(hy(r))})})}function hy(n){let e=[];for(let t of n.trim().split(`
23
+ `)){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 gy(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 zD(n){let e=await VD();return gy(e,n)}function JD(n){if(process.platform==="darwin"){let e=(n/1e3).toFixed(1),t=`while true; do ps -ax -o pid=,ppid=,rss=; echo '${lp}'; sleep ${e}; done`;return m(`Executing: sh -c ${t}`),uy("sh",["-c",t],{stdio:["ignore","pipe","ignore"],windowsHide:!0})}if(process.platform==="win32"&&my()){let e=`while ($true) { Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId),$($_.ParentProcessId),$($_.WorkingSetSize)" }; Write-Output '${lp}'; Start-Sleep -Milliseconds ${n} }`;return m(`Executing: ${fc} -NoProfile -Command ${e}`),uy(fc,["-NoProfile","-Command",e],{stdio:["ignore","pipe","ignore"],windowsHide:!0})}return null}function ae(n){return`${(n/1024/1024).toFixed(2)}MB`}async function py(n,e){if(!n)return process.memoryUsage().rss;if(e)return zD(n);let t=await mt(n);return t?Number(t)*1024:0}function Ui(n,e=2e3,t=!1){let r=0,i=!1,o=a=>{if(i||!n)return;let c=t?gy(a,n):a.find(l=>l.pid===n)?.rssBytes??0;c>r&&(r=c)};if(!n)return KD(e);if(process.platform==="linux")return XD(e,o,()=>r);let s=JD(e);return s?(YD(s,o),{stop:async()=>{i=!0;try{s.kill()}catch{}let a=await py(n,t);return Math.max(r,a)}}):{stop:async()=>{i=!0;let a=await py(n,t);return Math.max(r,a)}}}function YD(n,e){let t=process.platform==="darwin"?fy:hy,r="";n.stdout?.on("data",i=>{r+=i.toString();let o=r.split(lp);r=o.pop()??"";for(let s of o)e(t(s))}),n.on("error",()=>{})}function KD(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 XD(n,e,t){e(mc());let r=setInterval(()=>e(mc()),n);return{stop:async()=>(clearInterval(r),e(mc()),t())}}function ZD(n){let e=n.trim().match(/^(\d+)$/);return e?e[1]:null}function QD(n){let e=n.match(/"([^"]+?)\s*K"/i);return e&&e[1].replace(/\D/g,"")||null}var yc="module",ft=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let i=on.dirname(e.javaPath),o=`${i}${on.delimiter}${process.env.PATH||""}`,s={...process.env,PATH:o,DEVECO_SDK_HOME:e.sdkPath},a=gc.platform()==="darwin"&&e.javaPath==="/usr/bin/java";e.sourceType==="clt"&&e.javaPath&&!a&&(s.JAVA_HOME=on.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??yc];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 yy.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(!hc.existsSync(t))return null;try{let r=hc.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||on.join(gc.homedir(),".hvigor");return on.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=eR(t,r,{cwd:this.projectRoot,env:this.env,stdout:i,stderr:i}),s=Xe()?void 0:Ui(o.pid,2e3,!0),a="";try{await o}finally{if(s){let c=await s.stop();c>0&&(a=ae(c),m(`Hvigor peak memory: ${a}`))}}return a}};import{execa as tR}from"execa";var Bi=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=tR(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"}),i=Xe()?void 0:Ui(r.pid,2e3,!1);try{await r}finally{if(i){let o=await i.stop();o>0&&(this.peakMemoryMb=ae(o))}}}};import{mkdir as rR}from"fs/promises";import{dirname as nR,resolve as iR}from"path";import{execa as oR}from"execa";import{lock as up,check as jG}from"proper-lockfile";function pp(n){return iR(n,".hvigor",".build-lock")}function sR(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function wy(n){let e=nR(pp(n));if(await rR(e,{recursive:!0}),process.platform==="win32")try{await oR("attrib",["+h",e])}catch{}}async function aR(n,e){let t=new AbortController,r=sR(e);await wy(n);let i={lockfilePath:pp(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await up(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 up(n,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function kr(n,e,t){let{release:r,signal:i}=await aR(n,t);try{return await e(i)}finally{await r()}}async function wc(n,e){let t=new AbortController;await wy(n);let r={lockfilePath:pp(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await up(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 cs from"fs";import*as G from"path";import vy from"fs";import*as by from"path";import cR from"json5";function lR(n,e){try{let r=cR.parse(vy.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 $t(n,e){let t=by.join(n,"build-profile.json5");return vy.existsSync(t)?lR(t,e)??e:e}var sr=class n{static generate(e,t,r,i){let o=$t(e,t),s=G.join(e,o),a=G.join(s,"build","config"),c=n.buildConfig(e,s,r,i);cs.mkdirSync(a,{recursive:!0}),cs.writeFileSync(G.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[BuildConfigManager] buildConfig.json written to ${a}`);let l=G.join(s,"build",r,"intermediates","loader_out",r,"ets");cs.mkdirSync(l,{recursive:!0})}static remove(e,t){let r=$t(e,t),i=G.join(e,r,"build","config","buildConfig.json");cs.existsSync(i)&&(cs.unlinkSync(i),m(`[BuildConfigManager] buildConfig.json removed: ${i}`))}static removeAll(e){for(let t of e.profile.modules)n.remove(e.rootDir,t.name)}static async withBuildConfig(e,t,r,i,o){for(let s of t)n.generate(e,s,r,i);try{return await o()}finally{for(let s of t)n.remove(e,s)}}static buildConfig(e,t,r,i){let o=G.dirname(i.nodePath)+G.sep,s=G.join(t,"build",r),a=G.join(s,"intermediates"),c=G.join(a,"loader_out",r),l=G.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:G.join(e,"build-profile.json5"),localPropertiesPath:G.join(e,"local.properties"),appResource:G.join(l,"ResourceTable.txt"),cachePath:G.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:G.join(a,"loader",r,"loader.json"),aceModuleJsonPath:G.join(l,"module.json"),aceSoPath:G.join(c,"nativeDependencies.txt"),aceModuleRoot:G.join(t,"src","main","ets"),aceModuleBuild:G.join(c,"ets"),aceProfilePath:G.join(l,"resources","base","profile"),aceSuperVisualPath:G.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"false",mode:"hotReload",oldMapFilePath:G.join(c,"ets"),changedFileList:G.join(a,"patch",r,"changedFileList.json"),patchAbcPath:G.join(a,"patch",r,"ets"),removeChangedFileListInSdk:"true"}}}};import*as Dr from"fs";import*as ar from"path";import dR from"json5";var uR=1e3;function Wi(n,e,t){let r=pR(n,e,t);return r.required?(m(`[ProjectCheck] ${t} check: ${r.reason}`),r):null}function vc(n){m(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=ar.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=ar.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=mR(n);if(i===null)return{required:!0,reason:"failed to parse build-profile.json5"};let o=Wi(ar.join(n,Pe.OH_PACKAGE_JSON5),t,"root");if(o||(o=Wi(ar.join(n,Pe.BUILD_PROFILE_JSON5),t,"build-profile"),o)||(o=Wi(ar.join(n,Pe.HVIGOR_CONFIG),t,"hvigor-config"),o)||(o=Wi(ar.join(n,Pe.HVIGOR_CONFIG),t,"hvigor-config"),o))return o;for(let a of i)if(o=Wi(ar.join(n,a.srcPath,Pe.OH_PACKAGE_JSON5),t,a.name),o||(o=Wi(ar.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 pR(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>uR?{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 mR(n){let e=ar.join(n,Pe.BUILD_PROFILE_JSON5);try{let t=Dr.readFileSync(e,"utf-8");if(!t.trim())return null;let r=dR.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 q from"path";import*as Sy from"util";var mp="";function Sc(n){if(!n||n==="auto"||n==="stdout"||n==="none"){mp="";return}mp=n}function Ey(){return mp||(ig()??"")}function bc(n,...e){if(e.length===0)return n;try{return Sy.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var f={info(n,...e){g.info(`[lsp] ${bc(n,...e)}`)},warn(n,...e){g.warn(`[lsp] ${bc(n,...e)}`)},error(n,...e){g.error(`[lsp] ${bc(n,...e)}`)},debug(n,...e){g.debug(`[lsp] ${bc(n,...e)}`)}};import*as ls from"fs";import*as ds from"os";import*as Gi from"path";import fR 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 Py=8192,fp=100,Cy=.03,ky=.7,nt=900*1e3;function ht(n){if(!ls.existsSync(n))return null;try{let e=ls.readFileSync(n,"utf-8");return e.trim()?fR.parse(e):null}catch{return null}}function Ec(n,e){let t=Math.floor(ds.totalmem()/1048576),r=Math.floor(t*ky),i,o;e!==void 0&&Number.isFinite(e)&&e>0?(i=e,o=`override(${e})`):(i=Py,n>fp&&(i+=(n-fp)*Cy*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 Ft(n){if(n.startsWith("file:"))return n;try{let e=Gi.resolve(n),t=new URL(`file://${e}`).toString();if(ds.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 qi(n){return n&&n.replace(/\\/g,"/")}function he(n){let e=Gi.normalize(n).replace(/\\/g,"/");if(ds.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function Yn(n){return n||process.execPath||"node"}function us(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 Dy(n){return Gi.join(n,"build-profile.json5")}var Rr=class{constructor(e){this.projectRoot=e}getAllModuleInfo(){let e=Dy(this.projectRoot);try{let t=ht(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 hR}from"child_process";import*as Cc from"fs";var gR=600*1e3;function yR(n,e,t){let r=t.split(/\s+/).filter(i=>i.length>0);return[n,[e,...r]]}function wR(n,e){let t=[],r=[],i="",o="";return n.stdout?.on("data",s=>{let a=s.toString();t.push(a),i=Ry(i+a,e)}),n.stderr?.on("data",s=>{let a=s.toString();r.push(a),o=Ry(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 Ry(n,e){let t=n.split(/\r?\n/),r=t.pop()??"";for(let i of t)i&&e?.(i);return r}function Pc(n){return n.join("")}function vR(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
24
24
  Output so far:
25
- `+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function wR(n,e,t,r){return new Promise(i=>{let o=mR(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:s,stderr:a,flush:c}=gR(o,r),l=setTimeout(()=>{o.kill(),c();let d=[Sc(s),Sc(a)].filter(Boolean).join(`
25
+ `+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function bR(n,e,t,r){return new Promise(i=>{let o=hR(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:s,stderr:a,flush:c}=wR(o,r),l=setTimeout(()=>{o.kill(),c();let d=[Pc(s),Pc(a)].filter(Boolean).join(`
26
26
  `).trim();i({success:!1,output:`Build process timeout after 10 minutes.
27
27
  Output so far:
28
- `+d,exitCode:-1})},fR);o.on("close",(d,h)=>{clearTimeout(l),c();let w=[Sc(s),Sc(a)].filter(Boolean).join(`
29
- `).trim()||"";i(yR(d,h,w))}),o.on("error",d=>{clearTimeout(l),i({success:!1,output:`Build execution exception: ${d.message}`,exitCode:-1})})})}async function fp(n,e,t,r,i,o){let s={...process.env,DEVECO_SDK_HOME:r},a=hR(e,t,i);return await wR(a,n,s,o)}function vR(n,e,t){return{node_path:e,hvigor_path:t,sdk_path:n}}function bR(n){return!n.node_path||!Ec.existsSync(n.node_path)?`Node path not found or invalid: ${n.node_path}`:!n.hvigor_path||!Ec.existsSync(n.hvigor_path)?`Hvigor path not found or invalid: ${n.hvigor_path}`:!n.sdk_path||!Ec.existsSync(n.sdk_path)?`SDK path not found or invalid: ${n.sdk_path}`:null}var SR="--sync -p product=default";async function Dy(n,e,t,r,i){try{let o=vR(e,t,r),s=bR(o);if(s!=null)return f.info(`Config validation failed: ${s}`),!1;let a=await fp(n,o.node_path,o.hvigor_path,e,SR,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 ER(n){let e=G.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh"].includes(e)}function PR(n,e){let t=G.join(n,e.name);return e.isDirectory()?e.name===".cxx"||xy(t):ER(t)}function xy(n){if(!Z.existsSync(n))return!1;try{return Z.readdirSync(n,{withFileTypes:!0}).some(t=>PR(n,t))}catch{}return!1}function nn(n){try{let t=new kr(n).getAllModuleInfo(),r=[];for(let i of t){let o=G.resolve(n,i.srcPath);xy(o)&&r.push(i)}return r}catch(e){throw g.error(`[CppCompile] findCppModules threw: ${e instanceof Error?e.message:String(e)}`),e}}function CR(n){let e=[],r=new kr(n).getAllModuleInfo();for(let i of r){let o=G.resolve(n,i.srcPath),s=G.join(o,".cxx");Z.existsSync(s)&&Iy(s,e)}return e}function Iy(n,e){try{let t=Z.readdirSync(n,{withFileTypes:!0});for(let r of t){let i=G.join(n,r.name);r.isDirectory()?Iy(i,e):r.name==="compile_commands.json"&&e.push(i)}}catch{}}function kR(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 DR(n,e){let t=G.join(n,...RR.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 hp(n){let e=CR(n);if(e.length>0){let t=kR(e);DR(n,t),g.info(`[CppCompile] compile_commands.json generated, ${t.length} compile commands`)}else g.warn("[CppCompile] No compile_commands.json files found")}var RR=[".idea",".deveco","cxx","compile_commands.json"];async function xR(n,e,t,r,i){if(!r){g.warn(`[CppCompile] hvigorw.js path not injected (sdk '${e}')`);return}g.info(`[CppCompile] sdkPath: ${e}, hvigorPath: ${r}`);for(let o of i){let s=o.name;try{E.assertModuleName(s)}catch{g.warn(`[CppCompile] Skipping module with invalid name: ${s}`);continue}let a=["--mode","module","-p",`module=${o.name}`,"-p","product=default","compileNative"].join(" ");g.info(`[CppCompile] Running compileNative for module: ${o.name}`);let c=await fp(n,t,r,e,a);c.success?g.info(`[CppCompile] compileNative ${o.name} succeeded`):g.warn(`[CppCompile] compileNative ${o.name} failed: ${c.output}`)}}async function Ay(n,e,t,r){let i=nn(n);if(i.length===0){g.info("[CppCompile] No C++ modules found, skipping initialization");return}g.info(`[CppCompile] Found ${i.length} C++ module(s): ${i.map(o=>o.name).join(", ")}`),await xR(n,e,t,r,i),hp(n),LR(n,i)}function Pc(n,e){let t=n?.trim()??"";if(!t)return null;let r=t;if(/\{workspace\}/i.test(r)){if(!e)return g.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 g.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 g.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 g.warn(`[CppCompile] Custom compile_commands.json is not a JSON array: ${i}, falling back to default sync`),null}catch(o){return g.warn(`[CppCompile] Failed to read custom compile_commands.json (${i}): ${o}, falling back to default sync`),null}return G.dirname(i)}var IR=1e3,AR=["src","main","cpp","CMakeLists.txt"],TR=new Set([".cxx","build","node_modules",".preview",".hvigor",".idea"]),OR=new Set(["c","cpp","cxx","cc"]),NR="cpp-source-manifest.json";function MR(n){let e=G.extname(n).replace(/^\./,"").toLowerCase();return OR.has(e)}function Ry(n,e){return Z.existsSync(n)?Z.statSync(n).mtimeMs-e>IR:!1}function Ty(n){return G.join(G.dirname(Hn(n)),NR)}function Oy(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(TR.has(i.name))continue;Oy(o,e,t)}else MR(i.name)&&t.push(G.relative(e,o).replace(/\\/g,"/"))}}function Ny(n,e){let t=[];for(let r of e){let i=G.resolve(n,r.srcPath);Oy(i,n,t)}return t.sort()}function LR(n,e){let t=Ny(n,e),r={files:t,updatedAt:Date.now()},i=Ty(n);try{Z.mkdirSync(G.dirname(i),{recursive:!0}),Z.writeFileSync(i,JSON.stringify(r,null,2),"utf8"),g.info(`[CppCompile] C++ source manifest written, ${t.length} files`)}catch(o){g.warn(`[CppCompile] Failed to write C++ source manifest: ${o}`)}}function _R(n,e){let t=Ty(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=Ny(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 My(n){let e=Hn(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=nn(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(Ry(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,...AR);if(Ry(a,t))return{required:!0,reason:`module '${o.name}': CMakeLists.txt newer than baseline`}}let i=_R(n,r);return i||{required:!1,reason:`C++ project up-to-date (baseline: ${new Date(t).toISOString()})`}}var _y=["assembleHap","assembleApp","assembleHsp","assembleHar"];function FR(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&&!_y.includes(e.assembleType))throw new Error(`Invalid assemble type '${e.assembleType}'. Valid types: ${_y.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 jy(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 jR(n,e){let t;if(e.modules&&e.modules.length>0)t=e.modules,jy(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 gp(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(Dc(`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 Cc(n,e){let t=e,r=`${n} failed`;console.error($y(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 HR(n,e,t,r,i){if(!yc(i).required)return console.log(`
28
+ `+d,exitCode:-1})},gR);o.on("close",(d,h)=>{clearTimeout(l),c();let w=[Pc(s),Pc(a)].filter(Boolean).join(`
29
+ `).trim()||"";i(vR(d,h,w))}),o.on("error",d=>{clearTimeout(l),i({success:!1,output:`Build execution exception: ${d.message}`,exitCode:-1})})})}async function hp(n,e,t,r,i,o){let s={...process.env,DEVECO_SDK_HOME:r},a=yR(e,t,i);return await bR(a,n,s,o)}function SR(n,e,t){return{node_path:e,hvigor_path:t,sdk_path:n}}function ER(n){return!n.node_path||!Cc.existsSync(n.node_path)?`Node path not found or invalid: ${n.node_path}`:!n.hvigor_path||!Cc.existsSync(n.hvigor_path)?`Hvigor path not found or invalid: ${n.hvigor_path}`:!n.sdk_path||!Cc.existsSync(n.sdk_path)?`SDK path not found or invalid: ${n.sdk_path}`:null}var PR="--sync -p product=default";async function xy(n,e,t,r,i){try{let o=SR(e,t,r),s=ER(o);if(s!=null)return f.info(`Config validation failed: ${s}`),!1;let a=await hp(n,o.node_path,o.hvigor_path,e,PR,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 CR(n){let e=q.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh"].includes(e)}function kR(n,e){let t=q.join(n,e.name);return e.isDirectory()?e.name===".cxx"||Iy(t):CR(t)}function Iy(n){if(!Z.existsSync(n))return!1;try{return Z.readdirSync(n,{withFileTypes:!0}).some(t=>kR(n,t))}catch{}return!1}function sn(n){try{let t=new Rr(n).getAllModuleInfo(),r=[];for(let i of t){let o=q.resolve(n,i.srcPath);Iy(o)&&r.push(i)}return r}catch(e){throw g.error(`[CppCompile] findCppModules threw: ${e instanceof Error?e.message:String(e)}`),e}}function DR(n){let e=[],r=new Rr(n).getAllModuleInfo();for(let i of r){let o=q.resolve(n,i.srcPath),s=q.join(o,".cxx");Z.existsSync(s)&&Ty(s,e)}return e}function Ty(n,e){try{let t=Z.readdirSync(n,{withFileTypes:!0});for(let r of t){let i=q.join(n,r.name);r.isDirectory()?Ty(i,e):r.name==="compile_commands.json"&&e.push(i)}}catch{}}function RR(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 xR(n,e){let t=q.join(n,...AR.slice(0,-1));Z.mkdirSync(t,{recursive:!0});let r=q.join(t,"compile_commands.json");Z.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function gp(n){let e=DR(n);if(e.length>0){let t=RR(e);xR(n,t),g.info(`[CppCompile] compile_commands.json generated, ${t.length} compile commands`)}else g.warn("[CppCompile] No compile_commands.json files found")}var AR=[".idea",".deveco","cxx","compile_commands.json"];async function IR(n,e,t,r,i){if(!r){g.warn(`[CppCompile] hvigorw.js path not injected (sdk '${e}')`);return}g.info(`[CppCompile] sdkPath: ${e}, hvigorPath: ${r}`);for(let o of i){let s=o.name;try{E.assertModuleName(s)}catch{g.warn(`[CppCompile] Skipping module with invalid name: ${s}`);continue}let a=["--mode","module","-p",`module=${o.name}`,"-p","product=default","compileNative"].join(" ");g.info(`[CppCompile] Running compileNative for module: ${o.name}`);let c=await hp(n,t,r,e,a);c.success?g.info(`[CppCompile] compileNative ${o.name} succeeded`):g.warn(`[CppCompile] compileNative ${o.name} failed: ${c.output}`)}}async function Oy(n,e,t,r){let i=sn(n);if(i.length===0){g.info("[CppCompile] No C++ modules found, skipping initialization");return}g.info(`[CppCompile] Found ${i.length} C++ module(s): ${i.map(o=>o.name).join(", ")}`),await IR(n,e,t,r,i),gp(n),$R(n,i)}function kc(n,e){let t=n?.trim()??"";if(!t)return null;let r=t;if(/\{workspace\}/i.test(r)){if(!e)return g.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(!q.isAbsolute(r)){if(!e)return g.warn(`[CppCompile] Relative compile_commands path '${r}' requires a project root, falling back to default sync`),null;r=q.join(e,r)}let i=q.resolve(r);try{if(!Z.existsSync(i)||!Z.statSync(i).isFile())return g.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 g.warn(`[CppCompile] Custom compile_commands.json is not a JSON array: ${i}, falling back to default sync`),null}catch(o){return g.warn(`[CppCompile] Failed to read custom compile_commands.json (${i}): ${o}, falling back to default sync`),null}return q.dirname(i)}var TR=1e3,OR=["src","main","cpp","CMakeLists.txt"],NR=new Set([".cxx","build","node_modules",".preview",".hvigor",".idea"]),MR=new Set(["c","cpp","cxx","cc"]),LR="cpp-source-manifest.json";function _R(n){let e=q.extname(n).replace(/^\./,"").toLowerCase();return MR.has(e)}function Ay(n,e){return Z.existsSync(n)?Z.statSync(n).mtimeMs-e>TR:!1}function Ny(n){return q.join(q.dirname(Bn(n)),LR)}function My(n,e,t){let r;try{r=Z.readdirSync(n,{withFileTypes:!0})}catch{return}for(let i of r){let o=q.join(n,i.name);if(i.isDirectory()){if(NR.has(i.name))continue;My(o,e,t)}else _R(i.name)&&t.push(q.relative(e,o).replace(/\\/g,"/"))}}function Ly(n,e){let t=[];for(let r of e){let i=q.resolve(n,r.srcPath);My(i,n,t)}return t.sort()}function $R(n,e){let t=Ly(n,e),r={files:t,updatedAt:Date.now()},i=Ny(n);try{Z.mkdirSync(q.dirname(i),{recursive:!0}),Z.writeFileSync(i,JSON.stringify(r,null,2),"utf8"),g.info(`[CppCompile] C++ source manifest written, ${t.length} files`)}catch(o){g.warn(`[CppCompile] Failed to write C++ source manifest: ${o}`)}}function FR(n,e){let t=Ny(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=Ly(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 _y(n){let e=Bn(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=sn(n);if(r.length===0)return{required:!1,reason:"no C++ modules, skip compileNative"};for(let o of r){let s=q.resolve(n,o.srcPath);if(Ay(q.join(s,"build-profile.json5"),t))return{required:!0,reason:`module '${o.name}': build-profile.json5 newer than baseline`};let a=q.join(s,...OR);if(Ay(a,t))return{required:!0,reason:`module '${o.name}': CMakeLists.txt newer than baseline`}}let i=FR(n,r);return i||{required:!1,reason:`C++ project up-to-date (baseline: ${new Date(t).toISOString()})`}}var Fy=["assembleHap","assembleApp","assembleHsp","assembleHar"];function HR(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&&!Fy.includes(e.assembleType))throw new Error(`Invalid assemble type '${e.assembleType}'. Valid types: ${Fy.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 Uy(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 UR(n,e){let t;if(e.modules&&e.modules.length>0)t=e.modules,Uy(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 yp(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(xc(`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 Dc(n,e){let t=e,r=`${n} failed`;console.error(jy(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 BR(n,e,t,r,i){if(!vc(i).required)return console.log(`
30
30
  [ohpm install] Skipped (configurations unchanged)`),console.log(`
31
31
  [hvigor sync] Skipped (configurations unchanged)`),"";console.log(`
32
- [ohpm install] Running...`);try{await n.install()}catch(s){Cc("ohpm install",s)}console.log(`
33
- [hvigor sync] Running...`);try{return await e.sync(t,r)}catch(s){Cc("hvigor sync",s)}return""}async function yp(n,e,t,r,i,o){let s=await HR(n,e,t,r,o);console.log(`
34
- [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){Cc("hvigor build",c)}return UR(o),{ohpmMemoryMb:n.peakMemoryMb,syncMemoryMb:s,buildMemoryMb:a}}function UR(n){try{if(nn(n).length===0)return;hp(n),console.log(kc(`
35
- Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(Dc(`
36
- Failed to merge compile_commands.json: ${e.message}`))}}async function Hy(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=X(o),console.error($y(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await R.track(n,o)}}function BR(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 WR(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 VR(n){let e=B.discover(process.cwd());await tt.warnInvalidBundledLinks(e.rootDir),console.warn(Dc("Ensure the project source is trustworthy before proceeding."));let t=await P.new();t.assertJava(),FR(e,n);let r=n.product||"default",i=n.buildMode||"debug",o=GR(e,n),s=new Ui(t,e.rootDir),a=new ft(t,e.rootDir),c=n.signingConfig?qR(e.rootDir,r,n.signingConfig):void 0;try{let l=await zn(e.rootDir,async()=>yp(s,a,r,i,o,e.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")});return console.log(`
37
- `+kc("Build completed successfully")),zR(e,o,r),{bundleName:e.getBundleName(),...l}}finally{c?.()}}function GR(n,e){if(e.assembleType==="assembleApp"||e.product&&!e.modules&&!e.assembleType)return{type:"product"};let t=jR(n,e),r=gp(n,t,e.assembleType);return{type:"modules",modulesToBuild:t,moduleTasks:r}}function qR(n,e,t){let r=Fy.join(n,"build-profile.json5"),i=ds.readFileSync(r,"utf-8"),o=Ly.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}'`),ds.writeFileSync(r,Ly.stringify(o,null,2),"utf-8"),()=>{ds.writeFileSync(r,i,"utf-8"),m("[build] restored original build-profile.json5")}}function zR(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(kc("Build artifacts:"));for(let o of i)console.log(` ${o}`)}}async function JR(n){let e=process.cwd(),t=B.discover(e);await tt.warnInvalidBundledLinks(t.rootDir),console.warn(Dc("Ensure the project source is trusted before proceeding."));let r=await P.new();r.assertJava();let i;n.modules&&n.modules.length>0&&(jy(t,n.modules),i=n.modules.map(s=>s.split("@",1)[0]));let o=new ft(r,t.rootDir);return await zn(t.rootDir,async()=>{let s=i&&i.length>0?`mode=${n.mode??hc}, modules=${i.join(",")}`:`mode=${n.mode??hc}`;console.log(`
38
- Running hvigor clean (${s})...`);try{await o.clean(n.mode,i)}catch(a){Cc("hvigor clean",a)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
39
- `+kc("Clean completed successfully.")),t.getBundleName()}var Uy=new $R("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=BR(n);await Hy(e,async()=>{let t=await VR(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)})});Uy.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=WR(r);await Hy(i,async()=>{i.bundle_name=await JR(r)})});var By=Uy;import{Command as vA}from"commander";import{green as Cs,red as bA,yellow as nl}from"colorette";import*as ks from"path";import{randomUUID as cx}from"crypto";import{execa as Ky}from"execa";import{execa as ax}from"execa";import{execFile as YR,spawn as KR}from"child_process";import{promisify as XR}from"util";var ZR=XR(YR);function Wy(n,e,t){let i=n.replace(/\r\n/g,`
32
+ [ohpm install] Running...`);try{await n.install()}catch(s){Dc("ohpm install",s)}console.log(`
33
+ [hvigor sync] Running...`);try{return await e.sync(t,r)}catch(s){Dc("hvigor sync",s)}return""}async function wp(n,e,t,r,i,o){let s=await BR(n,e,t,r,o);console.log(`
34
+ [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){Dc("hvigor build",c)}return WR(o),{ohpmMemoryMb:n.peakMemoryMb,syncMemoryMb:s,buildMemoryMb:a}}function WR(n){try{if(sn(n).length===0)return;gp(n),console.log(Rc(`
35
+ Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(xc(`
36
+ Failed to merge compile_commands.json: ${e.message}`))}}async function By(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=X(o),console.error(jy(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await D.track(n,o)}}function VR(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 GR(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 qR(n){let e=B.discover(process.cwd());await tt.warnInvalidBundledLinks(e.rootDir),console.warn(xc("Ensure the project source is trustworthy before proceeding."));let t=await P.new();t.assertJava(),HR(e,n);let r=n.product||"default",i=n.buildMode||"debug",o=zR(e,n),s=new Bi(t,e.rootDir),a=new ft(t,e.rootDir),c=n.signingConfig?JR(e.rootDir,r,n.signingConfig):void 0;try{let l=await kr(e.rootDir,async()=>(sr.removeAll(e),wp(s,a,r,i,o,e.rootDir)),()=>console.log("Another build is already running for this project. Waiting for completion..."));return console.log(`
37
+ `+Rc("Build completed successfully")),YR(e,o,r),{bundleName:e.getBundleName(),...l}}finally{c?.()}}function zR(n,e){if(e.assembleType==="assembleApp"||e.product&&!e.modules&&!e.assembleType)return{type:"product"};let t=UR(n,e),r=yp(n,t,e.assembleType);return{type:"modules",modulesToBuild:t,moduleTasks:r}}function JR(n,e,t){let r=Hy.join(n,"build-profile.json5"),i=ps.readFileSync(r,"utf-8"),o=$y.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}'`),ps.writeFileSync(r,$y.stringify(o,null,2),"utf-8"),()=>{ps.writeFileSync(r,i,"utf-8"),m("[build] restored original build-profile.json5")}}function YR(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(Rc("Build artifacts:"));for(let o of i)console.log(` ${o}`)}}async function KR(n){let e=process.cwd(),t=B.discover(e);await tt.warnInvalidBundledLinks(t.rootDir),console.warn(xc("Ensure the project source is trusted before proceeding."));let r=await P.new();r.assertJava();let i;n.modules&&n.modules.length>0&&(Uy(t,n.modules),i=n.modules.map(s=>s.split("@",1)[0]));let o=new ft(r,t.rootDir);return await kr(t.rootDir,async()=>{let s=i&&i.length>0?`mode=${n.mode??yc}, modules=${i.join(",")}`:`mode=${n.mode??yc}`;console.log(`
38
+ Running hvigor clean (${s})...`);try{await o.clean(n.mode,i)}catch(a){Dc("hvigor clean",a)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
39
+ `+Rc("Clean completed successfully.")),t.getBundleName()}var Wy=new jR("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=VR(n);await By(e,async()=>{let t=await qR(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)})});Wy.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=GR(r);await By(i,async()=>{i.bundle_name=await KR(r)})});var Vy=Wy;import{Command as vI}from"commander";import{green as Ds,red as bI,yellow as il}from"colorette";import*as Rs from"path";import{randomUUID as dx}from"crypto";import{execa as Zy}from"execa";import{execa as lx}from"execa";import{execFile as XR,spawn as ZR}from"child_process";import{promisify as QR}from"util";var ex=QR(XR);function Gy(n,e,t){let i=n.replace(/\r\n/g,`
40
40
  `).split(`
41
- `),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 Vy(n,e,t){let r=n.endsWith("\r")?n.slice(0,-1):n;r.length>0&&t.onData([r],e)}function QR(n,e){return{stdout:n.stdoutChunks.join(""),stderr:n.stderrChunks.join(""),exitCode:e??-1}}function ex(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function tx(n,e,t,r,i){n.stdout?.on("data",o=>{let s=o.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=Wy(e.stdoutLineBuffer+s,"stdout",t)}),n.stderr?.on("data",o=>{let s=o.toString();e.stderrChunks.push(s),e.stderrLineBuffer=Wy(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,Vy(e.stdoutLineBuffer,"stdout",t),Vy(e.stderrLineBuffer,"stderr",t),t.onClose(o);let s=QR(e,o);r(s)})}async function us(n,e=[],t={}){try{let{stdout:r,stderr:i}=await ZR(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 Gy(n,e,t){return await new Promise((r,i)=>{let o=KR(n,e,{stdio:["inherit","pipe","pipe"]}),s=ex();tx(o,s,t,r,i)})}function qy(n){let e=n.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var rx=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],nx=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function Ft(n){return n?rx.some(e=>e.test(n))?"transient":nx.some(e=>e.test(n))?"fatal":"ok":"ok"}var ix=/(?:^|\s)(\d{2,})(?:\s|$)/;function zy(n){let e=n.stdout.trim(),t=n.stderr.trim();return Ft(e)!=="ok"||Ft(t)!=="ok"?"query-failed":n.exitCode===0?e&&ix.test(e)?"alive":"dead":n.exitCode===1&&!e&&!t?"dead":"query-failed"}var wp=[800,1500,2500];function ox(n){return new Promise(e=>setTimeout(e,n))}async function C(n,e){let t=1+wp.length,r={stdout:"",stderr:"",exitCode:-1};for(let i=0;i<t;i++){if(r=await us(n,e),r.exitCode===0||Ft(r.stderr)!=="transient"||i>=t-1)return r;m(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${wp[i]}ms`),await ox(wp[i])}return r}var Jy=/^[\w.-]+$/;async function Rc(n,e,t){if(!Jy.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||Ft(o)!=="ok"))return qy(o)}var vp="__DEVECO_PARAM_DELIM__";function sx(n,e){let t=new Map,r=n.split(vp);for(let i=0;i<e.length;i++){let o=(r[i]??"").trim();if(!o||Ft(o)!=="ok")continue;let s=qy(o);s&&t.set(e[i],s)}return t}async function qi(n,e,t){let r=t.filter(a=>Jy.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 Rc(n,e,r[0]);return c&&a.set(r[0],c),a}let i=r.map(a=>`param get ${a}`).join(`; echo ${vp}; `)+`; echo ${vp}`,o=await C(n,["-t",e,"shell",i]);if(o.exitCode===0){let a=sx(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 Rc(n,e,a);c&&s.set(a,c)}return s}function sr(n){return n.startsWith("127.0.0.1:")}var Yy=["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(" ")}`),ax(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let r of e.split(`
42
- `)){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 qi(this.hdcPath,e,[...Yy]);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:
41
+ `),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 qy(n,e,t){let r=n.endsWith("\r")?n.slice(0,-1):n;r.length>0&&t.onData([r],e)}function tx(n,e){return{stdout:n.stdoutChunks.join(""),stderr:n.stderrChunks.join(""),exitCode:e??-1}}function rx(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function nx(n,e,t,r,i){n.stdout?.on("data",o=>{let s=o.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=Gy(e.stdoutLineBuffer+s,"stdout",t)}),n.stderr?.on("data",o=>{let s=o.toString();e.stderrChunks.push(s),e.stderrLineBuffer=Gy(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,qy(e.stdoutLineBuffer,"stdout",t),qy(e.stderrLineBuffer,"stderr",t),t.onClose(o);let s=tx(e,o);r(s)})}async function ms(n,e=[],t={}){try{let{stdout:r,stderr:i}=await ex(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 zy(n,e,t){return await new Promise((r,i)=>{let o=ZR(n,e,{stdio:["inherit","pipe","pipe"]}),s=rx();nx(o,s,t,r,i)})}function Jy(n){let e=n.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var ix=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],ox=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function jt(n){return n?ix.some(e=>e.test(n))?"transient":ox.some(e=>e.test(n))?"fatal":"ok":"ok"}var sx=/(?:^|\s)(\d{2,})(?:\s|$)/;function Yy(n){let e=n.stdout.trim(),t=n.stderr.trim();return jt(e)!=="ok"||jt(t)!=="ok"?"query-failed":n.exitCode===0?e&&sx.test(e)?"alive":"dead":n.exitCode===1&&!e&&!t?"dead":"query-failed"}var vp=[800,1500,2500];function ax(n){return new Promise(e=>setTimeout(e,n))}async function C(n,e){let t=1+vp.length,r={stdout:"",stderr:"",exitCode:-1};for(let i=0;i<t;i++){if(r=await ms(n,e),r.exitCode===0||jt(r.stderr)!=="transient"||i>=t-1)return r;m(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${vp[i]}ms`),await ax(vp[i])}return r}var Ky=/^[\w.-]+$/;async function Ac(n,e,t){if(!Ky.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||jt(o)!=="ok"))return Jy(o)}var bp="__DEVECO_PARAM_DELIM__";function cx(n,e){let t=new Map,r=n.split(bp);for(let i=0;i<e.length;i++){let o=(r[i]??"").trim();if(!o||jt(o)!=="ok")continue;let s=Jy(o);s&&t.set(e[i],s)}return t}async function zi(n,e,t){let r=t.filter(a=>Ky.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 Ac(n,e,r[0]);return c&&a.set(r[0],c),a}let i=r.map(a=>`param get ${a}`).join(`; echo ${bp}; `)+`; echo ${bp}`,o=await C(n,["-t",e,"shell",i]);if(o.exitCode===0){let a=cx(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 Ac(n,e,a);c&&s.set(a,c)}return s}function cr(n){return n.startsWith("127.0.0.1:")}var Xy=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],ce=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(" ")}`),lx(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let r of e.split(`
42
+ `)){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 zi(this.hdcPath,e,[...Xy]);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:
43
43
  `+o.map(s=>` - ${s.name} (${s.device.serial})`).join(`
44
- `),"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 qi(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=sr(e),r,i;try{let o=await qi(this.hdcPath,e,[...Yy]);r=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:i}}};function lx(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 Ky(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=cx(),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=lx(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=zy(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 Ky(this.toolProvider.hdcPath,i,{stdio:"inherit",env:{...process.env}})}};import bp from"fs";import*as Yn from"path";function ps(n,e){if(!bp.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=bp.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=Yn.resolve(e),o=new Set,s=[];for(let a of r){let c=Yn.resolve(i,a),l=Yn.isAbsolute(a)?Yn.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(!bp.existsSync(c))throw new Error(`File not found: ${a}`);let h=d.reason?`; ${d.reason}`:"";throw new Error(`File path is outside the project directory: ${a}${h}`)}o.has(c)||(o.add(c),s.push(c))}return s}import Sp from"fs";import ms from"path";import{execa as px}from"execa";import Xy from"fs";import*as Zy from"path";import dx from"json5";function ux(n,e){try{let r=dx.parse(Xy.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 ar(n,e){let t=Zy.join(n,"build-profile.json5");return Xy.existsSync(t)?ux(t,e)??e:e}async function Qy(n,e,t,r){let i=ms.dirname(n.javaPath),o={...process.env,PATH:`${i}${ms.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 px(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=>fx(e,l,r))}function ew(n,e,t){let r=ar(n,e);return ms.join(n,r,"build",t,"outputs")}function mx(n,e,t){return ms.join(ew(n,e,t),`${e}-${t}-signed.hqf`)}function fx(n,e,t){let r=ew(n,e,t),i=mx(n,e,t);if(Sp.existsSync(i))return i;let o=Ep(r,"-signed.hqf")??Ep(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 Ep(n,e){if(!Sp.existsSync(n))return null;for(let t of Sp.readdirSync(n,{withFileTypes:!0})){let r=ms.join(n,t.name);if(t.isDirectory()){let i=Ep(r,e);if(i)return i}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import ue from"fs";import*as H from"path";import Pp from"json5";var tw="default",zi=class n{static writeChangedFileLists(e,t,r,i){let o=t||tw,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),h=n.collectChanges(r,e,a,l,d);return{writtenModules:n.flushCollectors(e,o,c,d,i),skippedFiles:h}}static initEmptyChangedFileLists(e,t,r){let i=t||tw,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=H.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 h=n.resolveTargetModules(d,t,r,i);if(h.length===0){s.push(c);continue}n.dispatchToCollectors(h,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=H.join(e,r,"build",t,"intermediates","patch","default"),s=H.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=H.join(e,r,"build",t,"intermediates","hotReload"),c=H.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=H.join(e,"build-profile.json5");if(!ue.existsSync(t))return null;try{let r=ue.readFileSync(t,"utf-8");return Pp.parse(r)}catch{return null}}static classifyFile(e,t,r){let i=H.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=H.normalize(e);for(let o of r){let s=H.normalize(H.join(t,o.srcPath)),a=s+H.sep;if(i.startsWith(a)||i===s)return o}return null}static getModuleType(e,t){let r=H.join(e,t,"src","main","module.json5");if(!ue.existsSync(r))return"entry";try{let i=ue.readFileSync(r,"utf-8");return Pp.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=H.join(e,t,"oh-package.json5");if(!ue.existsSync(r))return[];try{let i=ue.readFileSync(r,"utf-8"),o=Pp.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=H.resolve(e,t,o);return i.find(l=>H.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(h=>h.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=H.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=H.join(e,o,"build",r,"intermediates","hotReload","changedFileList.json"),a=n.readExistingApply(s),c=n.mergeApplyEntries(a,i),l=H.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=H.join(e,a,"build",r,"intermediates","patch","default","changedFileList.json"),l=n.readExistingPatch(c),d=H.join(e,a,"src","main","ets"),h=i.map(dt=>n.resolveRelativePathForPatch(dt,d)),w=n.mergeStrings(l.modifiedFiles,h),D=n.mergePatchResources(l.rawFile,o),z=n.mergePatchResources(l.resFile,s),ie=H.dirname(c);ue.existsSync(ie)||ue.mkdirSync(ie,{recursive:!0}),ue.writeFileSync(c,JSON.stringify({resources:{resFile:z,rawFile:D},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 H.relative(H.normalize(t),H.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 hx from"fs";import{randomUUID as gx}from"crypto";import{execa as yx}from"execa";var Ji=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!hx.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/${gx()}`,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 yx(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}};var wx="6.1.1",xc=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}async execute(e){await zn(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(wx);let t=ps(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=zi.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 Qy(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 Ji(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 Cp from"fs";import*as K from"path";var Ic=class n{static generate(e,t,r,i){let o=ar(e,t),s=K.join(e,o),a=K.join(s,"build","config"),c=n.buildConfig(e,s,r,i);Cp.mkdirSync(a,{recursive:!0}),Cp.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");Cp.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 rw from"fs";import*as Q from"path";var Ac=class n{static generate(e,t,r,i){let o=ar(e,t),s=Q.join(e,o),a=Q.join(s,"build","config"),c=n.buildConfig(e,s,r,i);rw.mkdirSync(a,{recursive:!0}),rw.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 nw from"crypto";import Pt from"fs";import Ct from"path";import iw from"os";import{io as vx}from"socket.io-client";var bx=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Yi=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;Pt.mkdirSync(Ct.dirname(i),{recursive:!0}),Pt.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(`
44
+ `),"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 zi(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=cr(e),r,i;try{let o=await zi(this.hdcPath,e,[...Xy]);r=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:i}}};function ux(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 le=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=ce.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;m(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await Zy(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=dx(),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=ux(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=Yy(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 Zy(this.toolProvider.hdcPath,i,{stdio:"inherit",env:{...process.env}})}};import Sp from"fs";import*as Kn from"path";function fs(n,e){if(!Sp.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=Sp.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=Kn.resolve(e),o=new Set,s=[];for(let a of r){let c=Kn.resolve(i,a),l=Kn.isAbsolute(a)?Kn.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(!Sp.existsSync(c))throw new Error(`File not found: ${a}`);let h=d.reason?`; ${d.reason}`:"";throw new Error(`File path is outside the project directory: ${a}${h}`)}o.has(c)||(o.add(c),s.push(c))}return s}import Ep from"fs";import hs from"path";import{execa as px}from"execa";async function Qy(n,e,t,r){let i=hs.dirname(n.javaPath),o={...process.env,PATH:`${i}${hs.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 px(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=>fx(e,l,r))}function ew(n,e,t){let r=$t(n,e);return hs.join(n,r,"build",t,"outputs")}function mx(n,e,t){return hs.join(ew(n,e,t),`${e}-${t}-signed.hqf`)}function fx(n,e,t){let r=ew(n,e,t),i=mx(n,e,t);if(Ep.existsSync(i))return i;let o=Pp(r,"-signed.hqf")??Pp(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 Pp(n,e){if(!Ep.existsSync(n))return null;for(let t of Ep.readdirSync(n,{withFileTypes:!0})){let r=hs.join(n,t.name);if(t.isDirectory()){let i=Pp(r,e);if(i)return i}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import de from"fs";import*as H from"path";import Cp from"json5";var tw="default",Ji=class n{static writeChangedFileLists(e,t,r,i){let o=t||tw,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),h=n.collectChanges(r,e,a,l,d);return{writtenModules:n.flushCollectors(e,o,c,d,i),skippedFiles:h}}static initEmptyChangedFileLists(e,t,r){let i=t||tw,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=H.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 h=n.resolveTargetModules(d,t,r,i);if(h.length===0){s.push(c);continue}n.dispatchToCollectors(h,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=H.join(e,r,"build",t,"intermediates","patch","default"),s=H.join(o,"changedFileList.json");if(de.existsSync(s)||(de.mkdirSync(o,{recursive:!0}),de.writeFileSync(s,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!i)return;let a=H.join(e,r,"build",t,"intermediates","hotReload"),c=H.join(a,"changedFileList.json");de.existsSync(c)||(de.mkdirSync(a,{recursive:!0}),de.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=H.join(e,"build-profile.json5");if(!de.existsSync(t))return null;try{let r=de.readFileSync(t,"utf-8");return Cp.parse(r)}catch{return null}}static classifyFile(e,t,r){let i=H.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=H.normalize(e);for(let o of r){let s=H.normalize(H.join(t,o.srcPath)),a=s+H.sep;if(i.startsWith(a)||i===s)return o}return null}static getModuleType(e,t){let r=H.join(e,t,"src","main","module.json5");if(!de.existsSync(r))return"entry";try{let i=de.readFileSync(r,"utf-8");return Cp.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=H.join(e,t,"oh-package.json5");if(!de.existsSync(r))return[];try{let i=de.readFileSync(r,"utf-8"),o=Cp.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=H.resolve(e,t,o);return i.find(l=>H.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(h=>h.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=H.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=H.join(e,o,"build",r,"intermediates","hotReload","changedFileList.json"),a=n.readExistingApply(s),c=n.mergeApplyEntries(a,i),l=H.dirname(s);de.existsSync(l)||de.mkdirSync(l,{recursive:!0}),de.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),m(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!de.existsSync(e))return[];try{let t=de.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,r,i,o,s){let a=t.replace(/^\.\//,""),c=H.join(e,a,"build",r,"intermediates","patch","default","changedFileList.json"),l=n.readExistingPatch(c),d=H.join(e,a,"src","main","ets"),h=i.map(dt=>n.resolveRelativePathForPatch(dt,d)),w=n.mergeStrings(l.modifiedFiles,h),R=n.mergePatchResources(l.rawFile,o),J=n.mergePatchResources(l.resFile,s),ye=H.dirname(c);de.existsSync(ye)||de.mkdirSync(ye,{recursive:!0}),de.writeFileSync(c,JSON.stringify({resources:{resFile:J,rawFile:R},modifiedFiles:w}),"utf-8"),m(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!de.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=de.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 H.relative(H.normalize(t),H.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 hx from"fs";import{randomUUID as gx}from"crypto";import{execa as yx}from"execa";var Yi=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!hx.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/${gx()}`,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 yx(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}};var wx="6.1.1",Ic=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}async execute(e){await kr(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(wx);let t=fs(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=Ji.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 sr.withBuildConfig(this.projectRoot,t,e.productName,this.toolProvider,()=>Qy(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 Yi(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 le(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 le(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 rw from"fs";import*as Q from"path";var Tc=class n{static generate(e,t,r,i){let o=$t(e,t),s=Q.join(e,o),a=Q.join(s,"build","config"),c=n.buildConfig(e,s,r,i);rw.mkdirSync(a,{recursive:!0}),rw.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 nw from"crypto";import Pt from"fs";import Ct from"path";import iw from"os";import{io as vx}from"socket.io-client";var bx=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;Pt.mkdirSync(Ct.dirname(i),{recursive:!0}),Pt.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(`
45
45
  `)?a:a+`
46
46
  `),r.length>100&&r.shift())},onWatchResult:s=>{let a=n.extractText(s);if(!a.trim())return;let c=`[WatchResult] ${a}`;console.log(c),Pt.writeFileSync(e,[...r,c+`
47
47
  `].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 Ct.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=vx(`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),h(),this.invalidateSocket(),i(new Error(`Socket disconnected: ${w}`)))},s=this.createOutputHandler(),{onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d}=this.getDataHandler(),h=()=>{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:h}}getDataHandler(){let e=n.extractText;return{onWatchLog:s=>{let a=e(s);a.trim()&&process.stdout.write(a+(a.endsWith(`
48
48
  `)?"":`
49
- `))},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(!Pt.existsSync(e))return null;try{let t=Pt.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=Ct.join(t,"fd"),i=Ct.join(t,"ac"),o=Ct.join(t,"ce"),s=this.readComponents(r),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(bx)]),c=this.readSingleFile(i),l=nw.pbkdf2Sync(Buffer.from(a).toString(),c,1e4,16,"sha256"),d=this.readSingleFile(o),h=this.aesGcmDecrypt(l,d),w=Buffer.from(e,"hex");return this.aesGcmDecrypt(h,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=nw.createDecipheriv("aes-128-gcm",e,o);return l.setAuthTag(c),Buffer.concat([l.update(a),l.final()])}readComponents(e){let t=Pt.readdirSync(e).map(r=>Ct.join(e,r)).filter(r=>Pt.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=Pt.readdirSync(r);if(i.length===0)throw new Error(`No file in ${r}`);return Pt.readFileSync(Ct.join(r,i[0]))})}readSingleFile(e){let t=Pt.readdirSync(e).map(r=>Ct.join(e,r)).filter(r=>Pt.statSync(r).isFile());if(t.length===0)throw new Error(`No file in ${e}`);return Pt.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||Ct.join(iw.homedir(),".hvigor");return Ct.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||Ct.join(iw.homedir(),".hvigor");return Ct.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import aw from"fs";import*as Dr from"path";import{green as Mc,yellow as kp}from"colorette";import Kn from"fs";import*as Xn from"path";import Sx from"json5";var Ex=2e6,Px=1e6,Cx="hotreload",Tc=class n{static generateOrUpdate(e,t,r){let i=n.readAppConfig(e),o=Xn.resolve(e,t),s=Xn.join(o,"patch.json"),a;return Kn.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:Ex,versionCode:i.versionCode},module:{name:r,type:Cx}}),n.writePatchJson(s,a),a}static readAppConfig(e){let t=Xn.join(e,"AppScope","app.json5");if(!Kn.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let r=Kn.readFileSync(t,"utf-8"),i=Sx.parse(r),o=i?.app?.bundleName;if(!o)throw new Error("bundleName is missing in AppScope/app.json5");let s=i?.app?.versionCode??Px;return{bundleName:o,versionCode:s}}static readExistingPatch(e){let t=Kn.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=Xn.dirname(e);Kn.existsSync(r)||Kn.mkdirSync(r,{recursive:!0});let i=JSON.stringify(t,null,2);Kn.writeFileSync(e,i,"utf-8"),m(`[PatchManager] patch.json written to ${e}`),m(`[PatchManager] Content: ${i}`)}};import Ie from"fs";import*as ee from"path";import ow from"crypto";import kx from"json5";import{execa as sw}from"execa";var Oc=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=ow.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=ow.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=Ie.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(Ie.statSync(e).isDirectory()){let i=Ie.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(Ie.readFileSync(ee.join(e,i[0])))}return new Int8Array(Ie.readFileSync(e))}},Nc=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(Ie.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(!Ie.existsSync(e))return null;let t=Ie.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=ar(this.projectRoot,e),i=ee.join(this.projectRoot,r,"build",t,"outputs","default");return Ie.existsSync(i)||Ie.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 sw(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):Ie.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 sw(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}`):Ie.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=Oc.decryptPwd(r,t.storePassword,"storePassword"),o=Oc.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 Ie.existsSync(r)?t:null}readSigningConfig(e){let t=ee.join(this.projectRoot,"build-profile.json5");if(!Ie.existsSync(t))return null;try{let r=Ie.readFileSync(t,"utf-8"),i=kx.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(Ie.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(Ie.existsSync(r))return r;return null}};async function cw(n){let e=Date.now(),t=ar(n.projectPath,n.moduleName),r=Dx(n);console.log(kp("[HotReload] Ensure the project source is trusted before proceeding."));let i=Rx(n),o=ps(r,n.projectPath);console.log(`[HotReload] Parsed ${o.length} changed file(s) from ${n.applyFileName}`),xx(n,o),Ix(n,t),await Ax(n,i);let s=Dr.join(n.projectPath,t,"patch.json"),a=await Ox(n,t,s);return await Nx(n,a),console.log(Mc("[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 Dx(n){if(Dr.basename(n.applyFileName)!==n.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n.applyFileName}`);return Dr.join(n.projectPath,".hvigor",n.applyFileName)}function Rx(n){let{projectPath:e,toolProvider:t}=n,r=new Yi(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 xx(n,e){let t=zi.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(Mc(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn(kp(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function Ix(n,e){let t=Tc.generateOrUpdate(n.projectPath,e,n.moduleName);console.log(Mc(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function Ax(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=Tx(r);throw new Error(`Daemon hot compile exited with code ${i}`+(o?`
49
+ `))},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(!Pt.existsSync(e))return null;try{let t=Pt.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=Ct.join(t,"fd"),i=Ct.join(t,"ac"),o=Ct.join(t,"ce"),s=this.readComponents(r),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(bx)]),c=this.readSingleFile(i),l=nw.pbkdf2Sync(Buffer.from(a).toString(),c,1e4,16,"sha256"),d=this.readSingleFile(o),h=this.aesGcmDecrypt(l,d),w=Buffer.from(e,"hex");return this.aesGcmDecrypt(h,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=nw.createDecipheriv("aes-128-gcm",e,o);return l.setAuthTag(c),Buffer.concat([l.update(a),l.final()])}readComponents(e){let t=Pt.readdirSync(e).map(r=>Ct.join(e,r)).filter(r=>Pt.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=Pt.readdirSync(r);if(i.length===0)throw new Error(`No file in ${r}`);return Pt.readFileSync(Ct.join(r,i[0]))})}readSingleFile(e){let t=Pt.readdirSync(e).map(r=>Ct.join(e,r)).filter(r=>Pt.statSync(r).isFile());if(t.length===0)throw new Error(`No file in ${e}`);return Pt.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||Ct.join(iw.homedir(),".hvigor");return Ct.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||Ct.join(iw.homedir(),".hvigor");return Ct.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import aw from"fs";import*as xr from"path";import{green as Lc,yellow as kp}from"colorette";import Xn from"fs";import*as Zn from"path";import Sx from"json5";var Ex=2e6,Px=1e6,Cx="hotreload",Oc=class n{static generateOrUpdate(e,t,r){let i=n.readAppConfig(e),o=Zn.resolve(e,t),s=Zn.join(o,"patch.json"),a;return Xn.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:Ex,versionCode:i.versionCode},module:{name:r,type:Cx}}),n.writePatchJson(s,a),a}static readAppConfig(e){let t=Zn.join(e,"AppScope","app.json5");if(!Xn.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let r=Xn.readFileSync(t,"utf-8"),i=Sx.parse(r),o=i?.app?.bundleName;if(!o)throw new Error("bundleName is missing in AppScope/app.json5");let s=i?.app?.versionCode??Px;return{bundleName:o,versionCode:s}}static readExistingPatch(e){let t=Xn.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=Zn.dirname(e);Xn.existsSync(r)||Xn.mkdirSync(r,{recursive:!0});let i=JSON.stringify(t,null,2);Xn.writeFileSync(e,i,"utf-8"),m(`[PatchManager] patch.json written to ${e}`),m(`[PatchManager] Content: ${i}`)}};import Ae from"fs";import*as ee from"path";import ow from"crypto";import kx from"json5";import{execa as sw}from"execa";var Nc=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=ow.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=ow.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=Ae.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(Ae.statSync(e).isDirectory()){let i=Ae.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(Ae.readFileSync(ee.join(e,i[0])))}return new Int8Array(Ae.readFileSync(e))}},Mc=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(Ae.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(!Ae.existsSync(e))return null;let t=Ae.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=$t(this.projectRoot,e),i=ee.join(this.projectRoot,r,"build",t,"outputs","default");return Ae.existsSync(i)||Ae.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 sw(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):Ae.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 sw(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}`):Ae.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=Nc.decryptPwd(r,t.storePassword,"storePassword"),o=Nc.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 Ae.existsSync(r)?t:null}readSigningConfig(e){let t=ee.join(this.projectRoot,"build-profile.json5");if(!Ae.existsSync(t))return null;try{let r=Ae.readFileSync(t,"utf-8"),i=kx.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(Ae.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(Ae.existsSync(r))return r;return null}};async function cw(n){let e=Date.now(),t=$t(n.projectPath,n.moduleName),r=Dx(n);console.log(kp("[HotReload] Ensure the project source is trusted before proceeding."));let i=Rx(n),o=fs(r,n.projectPath);console.log(`[HotReload] Parsed ${o.length} changed file(s) from ${n.applyFileName}`),xx(n,o),Ax(n,t),await Ix(n,i);let s=xr.join(n.projectPath,t,"patch.json"),a=await Ox(n,t,s);return await Nx(n,a),console.log(Lc("[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 Dx(n){if(xr.basename(n.applyFileName)!==n.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n.applyFileName}`);return xr.join(n.projectPath,".hvigor",n.applyFileName)}function Rx(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 xx(n,e){let t=Ji.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(Lc(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn(kp(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function Ax(n,e){let t=Oc.generateOrUpdate(n.projectPath,e,n.moduleName);console.log(Lc(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function Ix(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=Tx(r);throw new Error(`Daemon hot compile exited with code ${i}`+(o?`
50
50
  --- compile output (from watch session) ---
51
51
  ${o}`:""))}}finally{e.disconnect()}console.log(`[Timing] daemon hot compile: ${Date.now()-t}ms`)}function Tx(n){try{return aw.existsSync(n)?aw.readFileSync(n,"utf8").split(/\r?\n/).filter(t=>t.trim()).slice(-40).join(`
52
- `):""}catch{return""}}async function Ox(n,e,t){let r=Dr.join(n.projectPath,e,"build",n.productName,"intermediates"),i=[Dr.join(r,"hotReload","patchAbcPath"),Dr.join(r,"patch","default")],o=Date.now(),s=new Nc(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 Nx(n,e){let t=Date.now(),i=await new Ji(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 Dp(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 lw(n,e,t){let r=Dr.join(n.rootDir,".hvigor",t),i;try{i=ps(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(kp(`[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 dw(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 uw(n,e){await new ft(n,e.rootDir).stopDaemon(),console.log(Mc("Hvigor daemon stopped."))}var Lc=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(`
53
- `)}toTraceError(e,t){return new y(this.formatFailure(e,t),e.status)}};import Qc from"fs";import yA from"path";import{yellow as Ps}from"colorette";import{cyan as _c}from"colorette";function Zn(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=Ft(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 Rp=[800,1500,2500];function Lx(n){return new Promise(e=>setTimeout(e,n))}var on=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(`
54
- `)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let i=t[0];return m(_c(`Using device serial: ${i}`)),i}if(e&&t.includes(e))return m(_c(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let i=this.findDeviceByArg(r,e);if(i)return m(_c(`Using device: ${i.name} (${i.serial})`)),i.serial;let o=this.formatConnectedDeviceList(r);throw new y(`Device '${e}' not found.
52
+ `):""}catch{return""}}async function Ox(n,e,t){let r=xr.join(n.projectPath,e,"build",n.productName,"intermediates"),i=[xr.join(r,"hotReload","patchAbcPath"),xr.join(r,"patch","default")],o=Date.now(),s=new Mc(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 Nx(n,e){let t=Date.now(),i=await new Yi(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 Dp(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 lw(n,e,t){let r=xr.join(n.rootDir,".hvigor",t),i;try{i=fs(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(kp(`[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 dw(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 uw(n,e){let t=new ft(n,e.rootDir);try{await t.stopDaemon()}finally{await kr(e.rootDir,async()=>{sr.removeAll(e)},()=>console.log("Another build is already running for this project. Waiting for completion..."))}console.log(Lc("Hvigor daemon stopped."))}var _c=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(`
53
+ `)}toTraceError(e,t){return new y(this.formatFailure(e,t),e.status)}};import el from"fs";import yI from"path";import{yellow as ks}from"colorette";import{cyan as $c}from"colorette";function Qn(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=jt(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 Rp=[800,1500,2500];function Lx(n){return new Promise(e=>setTimeout(e,n))}var an=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=ce.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(`
54
+ `)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let i=t[0];return m($c(`Using device serial: ${i}`)),i}if(e&&t.includes(e))return m($c(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let i=this.findDeviceByArg(r,e);if(i)return m($c(`Using device: ${i.name} (${i.serial})`)),i.serial;let o=this.formatConnectedDeviceList(r);throw new y(`Device '${e}' not found.
55
55
  Available devices:
56
- ${o}`,"Device not found.")}if(r.length===1){let i=r[0];return m(_c(`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=Zn(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=Zn(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 Gy(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+Rp.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||Ft(a.stderr)!=="transient"||c>=s-1)return a;m(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${Rp[c]}ms`),await Lx(Rp[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=Zn(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=Zn(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=Zn(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=Zn(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:
56
+ ${o}`,"Device not found.")}if(r.length===1){let i=r[0];return m($c(`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=Qn(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=Qn(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 zy(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+Rp.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||jt(a.stderr)!=="transient"||c>=s-1)return a;m(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${Rp[c]}ms`),await Lx(Rp[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=Qn(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=Qn(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=Qn(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=Qn(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:
57
57
  ${o.stdout}`),this.parseCrashLogFilenames(o.stdout,r)}parseCrashLogFilenames(e,t){return e.split(`
58
- `).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=Zn(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 $x,unlinkSync as Fx}from"fs";import{tmpdir as jx}from"os";import{join as Hx}from"path";var Rr=class{constructor(e,t){this.hdcPath=e;this.serial=t}async listWindows(e){let t=await this.fetchDump(),r=_x(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 _x(n){let e=n.split(`
59
- `),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]),h=Number(c[2]),w=Number(c[3]),D=Number(c[4]);Number.isFinite(w)&&Number.isFinite(d)&&Number.isFinite(h)&&r.push({id:w,name:l,pid:h,displayId:d,type:D})}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 pw(n){if(!(!n||n==="HitTestMode.Default"))return n.startsWith("HitTestMode.")?n.slice(12):n}function fs(n){if(!(n==null||n==="")){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1}}function $c(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 mw(n){return n.originalText||void 0}function Ki(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 fw(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 h=l?s+1:s;for(let w=i.children.length-1;w>=0;w--)r.push({current:i.children[w],parent:d,depth:h})}return t}function Ux(n){let e=$x(n,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function Bx(n){return n.attributes??{}}function Fc(n,e,t){let r=Bx(n),i={id:r.id||void 0,type:r.type||void 0,text:mw(r),bounds:$c(r.bounds),clickable:fs(r.clickable)||void 0,longClickable:fs(r.longClickable)||void 0,scrollable:fs(r.scrollable)||void 0,checkable:fs(r.checkable)||void 0,hitTestBehavior:pw(r.hitTestBehavior),children:[]};return e>0&&t+1>=e||n.children&&(i.children=n.children.map(o=>Fc(o,e,t+1))),i}function Wx(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 xr=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=Hx(jx(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,r),Ux(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}`),Fx(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 Rr(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=Wx(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=>Fc(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:Fc(s,t,0)})}return i}async dumpCollapsedTree(e,t,r,i){return(await this.dumpRawNodes(e,r,i)).flatMap(s=>fw(Fc(s,0,0),t))}async dumpRawTree(e,t){return(await this.dumpRawNodes(e,t,!1))[0]}};var Ue=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}},Vx=["*=","^=","$=","/="],Gx=/[A-Za-z_]/,qx=/[A-Za-z0-9_]/,Ip=/\s/,zx=/^(.*)\/([gimsuy]+)$/,Ap=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 Ir(n){for(;!n.eof()&&Ip.test(n.peek());)n.next()}function Jx(n){let e=n.pos;if(!Gx.test(n.peek()))throw new Ue("expected attribute key",n.pos,n.input);for(;!n.eof()&&qx.test(n.peek());)n.next();return n.input.slice(e,n.pos)}function Yx(n,e){for(let t of Vx)if(n.startsWith(t))return n.pos+=t.length,t;if(n.peek()==="=")return n.next(),"=";throw new Ue(`expected operator (=, *=, ^=, $=, /=) after key "${e}"`,n.pos,n.input)}function hw(n){let e=n.match(zx);return e?{value:e[1],flags:e[2]}:{value:n}}function Kx(n,e){n.next();let t="";for(;!n.eof();){let r=n.next();if(r==="\\"){if(n.eof())throw new Ue("dangling escape in quoted value",n.pos,n.input);t+=n.next();continue}if(r===e)return t;t+=r}throw new Ue("unterminated quoted value",n.pos,n.input)}function xp(n){return n==='"'||n==="'"}function Xx(n,e){let t=n.peek();if(xp(t)){let i=Kx(n,t);return e==="/="?hw(i):{value:i}}let r="";for(;!n.eof();){let i=n.peek();if(i===","||i==="["||xp(i))break;if(Ip.test(i)){let o=n.pos+1;for(;o<n.input.length&&Ip.test(n.input[o]);)o++;let s=o<n.input.length?n.input[o]:"";if(s===""||s===","||s==="["||xp(s))break;r+=n.next();continue}if(i==="\\"){if(n.next(),n.eof())throw new Ue("dangling escape in value",n.pos,n.input);r+=n.next();continue}r+=n.next()}return e==="/="?hw(r):{value:r}}function gw(n){Ir(n);let e=Jx(n);Ir(n);let t=Yx(n,e);if(Ir(n),n.eof()||n.peek()===","||n.peek()==="[")throw new Ue(`missing value for key "${e}"`,n.pos,n.input);let{value:r,flags:i}=Xx(n,t);if(t==="/=")try{new RegExp(r,i)}catch(s){throw new Ue(`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 Zx(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 Ue(`invalid index "${e}" (expected N, -N, or "last")`,n.pos,n.input)}function hs(n){if(typeof n!="string")throw new Ue("input must be a string",0,String(n));let e=new Ap(n),t=[];if(Ir(e),e.eof())throw new Ue("empty selector",e.pos,n);for(t.push(gw(e));Ir(e),e.peek()===",";){if(e.next(),Ir(e),e.eof()||e.peek()===",")throw new Ue("expected clause after comma",e.pos,n);t.push(gw(e))}let r;if(Ir(e),e.peek()==="["){if(e.next(),r=Zx(e),Ir(e),e.peek()!=="]")throw new Ue("expected ']' after index",e.pos,n);e.next(),Ir(e)}if(!e.eof())throw new Ue(`unexpected trailing input "${e.input.slice(e.pos)}"`,e.pos,n);return{clauses:t,index:r,raw:n}}function Qx(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 eI(n,e){let t=Qx(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 jc(n,e){let t=[],r=[n];for(;r.length>0;){let i=r.pop(),o=i.attributes??null;e.clauses.every(a=>eI(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 Xi(n,e){return e===void 0?n[0]:e>=0?n[e]:n[n.length+e]}import{DOMParser as tI}from"@xmldom/xmldom";import{select as rI}from"xpath";var nI=["id","key","originalText","description","enabled","focused","checked","selected","visible","clickable","longClickable","scrollable","checkable","accessibilityLevel","hitTestBehavior","bounds"];function iI(n){if(!n)return"node";let e=n.replace(/[^A-Za-z0-9_-]/g,"_");return/^[0-9]/.test(e)&&(e="_"+e),e||"node"}var oI=/&/g,sI=/</g,aI=/>/g,cI=/"/g,lI=/'/g;function Hc(n){return n.replace(oI,"&amp;").replace(sI,"&lt;").replace(aI,"&gt;").replace(cI,"&quot;").replace(lI,"&apos;")}function dI(n){let e=[],t=typeof n.type=="string"?n.type:"";t&&e.push(` type="${Hc(t)}"`);let r=n.originalText??n.text;r!=null&&r!==""&&e.push(` text="${Hc(String(r))}"`);for(let o of nI){let s=n[o];s==null||s===""||e.push(` ${o}="${Hc(String(s))}"`)}let i=n.description;return i!=null&&i!==""&&e.push(` desc="${Hc(String(i))}"`),e.join("")}function yw(n){let e=n.attributes??{},t=iI(typeof e.type=="string"?e.type:void 0),r=dI(e),i=n.children??[];return i.length===0?`<${t}${r}/>`:`<${t}${r}>${i.map(yw).join("")}</${t}>`}function uI(n){return`<?xml version="1.0" encoding="UTF-8"?>${yw(n)}`}function pI(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 mI(n){return typeof n!="object"||n===null?!1:n.nodeType===1}function fI(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:pI(e("bounds")),attributes:t}}function Tp(n,e){if(typeof e!="string"||e.trim()==="")throw new Error("xpath expression must be a non-empty string");let t=uI(n),r=new tI().parseFromString(t,"text/xml"),i=rI(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)mI(s)&&o.push(fI(s));return o}function Uc(n){return typeof n=="string"&&n.trimStart().startsWith("xpath=")}function Bc(n){return n.trimStart().slice(6)}function Wc(n){return new Promise(e=>setTimeout(e,n))}function Op(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:$c(t.bounds),attributes:t}}function ww(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 Vc(n){return n.startsWith("base64=")?Buffer.from(n.slice(7).trim(),"base64").toString("utf8"):n}var hI=new Set(["text","desc","description"]),gs=[];function bw(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)bw(t,e)}function Sw(n,e){let t=new Set;bw(n,t);let r=[];for(let i of e)hI.has(i.key)||t.has(i.key)||r.push(i.key);return r}function vw(n,e){let t=Sw(n,e);for(let r of t)gs.push(`WARNING: attribute "${r}" not found in any node of the layout tree. No matches will be returned for this key.`)}function Np(){return gs.splice(0)}var Zi=class{dumper;constructor(e){this.dumper=new xr(e)}async find(e,t,r){gs.splice(0);let i=Vc(t);if(Uc(i))return this.runXpathFind(e,Bc(i),r);let o=hs(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 h=await this.dumper.dumpRawTree(e,r?.window);if(l||(vw(h,t.clauses),l=!0),a=jc(h,t),c=r?.all?a.length>0:Xi(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 Wc(o)}if(r?.all)return a.map((h,w)=>Op(h,w));let d=Xi(a,t.index);if(!d){let h=a.length,w=t.index===void 0?0:t.index;throw new Error(`Index ${w} out of range (matched ${h} element(s)) for selector: ${t.raw}`)}return[Op(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=Tp(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 Wc(o)}return r?.all?a.map((l,d)=>ww(l,d)):[ww(a[0],0)]}async waitForAppearance(e,t,r,i){gs.splice(0);let o=Vc(t);if(Uc(o))return(await this.runXpathFind(e,Bc(o),{timeoutMs:r,window:i}))[0];let s=hs(o);return await this.runWaitFor(e,s,r,i,!0)}async waitForDisappear(e,t,r,i){gs.splice(0);let o=Vc(t);if(Uc(o))return this.runXpathWaitFor(e,Bc(o),r,i,!1);let s=hs(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||(vw(l,t.clauses),c=!0);let d=jc(l,t),h=Xi(d,t.index)!==void 0;if(o&&h){let w=Xi(d,t.index);return Op(w,t.index??0)}if(!o&&!h)return;if(Date.now()-a>=r)throw new Error(`Timed out (${r}ms) waiting for selector to ${o?"appear":"disappear"}: ${t.raw}`);await Wc(300)}}async runXpathWaitFor(e,t,r,i,o){let a=Date.now();for(;;){let c=await this.dumper.dumpRawTree(e,i),d=Tp(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 Wc(300)}}};import it from"fs";import Le from"path";import{randomUUID as gI}from"crypto";function Ew(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 Pw(n,e){return[n,e].filter(Boolean).join(`
60
- `).trim()}function Cw(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 kw(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 Dw(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 yI(){return String(Date.now())}function Mp(n){let e;try{e=it.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{it.accessSync(n,it.constants.W_OK|it.constants.X_OK)}catch(t){throw new Error(`Screenshot directory is not writable: ${n}`,{cause:t})}}function Lp(n,e){try{throw it.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 Rw(n){if(!it.existsSync(n))throw new Error(`Screenshot file was not created: ${n}`);let e=it.statSync(n);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${n}`);let t=it.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 xw(n){try{return Rw(n),!0}catch{return!1}}function Iw(n){let e=[];for(let t of it.readdirSync(n,{withFileTypes:!0})){let r=Le.join(n,t.name);if(t.isDirectory()){e.push(...Iw(r));continue}t.isFile()&&xw(r)&&e.push(r)}return e}function wI(n,e){let t=Le.join(n,Le.basename(e));if(xw(t))return t;let r=Iw(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}function vI(n,e){try{it.copyFileSync(n,e,it.constants.COPYFILE_EXCL)}catch(t){throw t.code==="EEXIST"?new Error(`Screenshot file already exists: ${e}`,{cause:t}):t}Rw(e)}var Qn=class{constructor(e){this.toolProvider=e}resolveDestinationPath(e){if(!e?.trim())throw new Error("--path is required.");let t=e.trim(),r=Le.resolve(t);try{if(it.statSync(r).isDirectory()){Mp(r);let o=Le.join(r,`screenshot-${yI()}.png`);return Lp(o,r),o}}catch(o){if(o.code!=="ENOENT")throw o}if(Le.extname(r).toLowerCase()!==".png")throw new Error(`Screenshot path must be an existing directory or a PNG file: ${r}`);let i=Le.dirname(r);return Mp(i),Lp(r,i),r}async captureToPath(e,t,r){let i=Le.dirname(Le.resolve(t));Mp(i),Lp(Le.resolve(t),i);let o=`/data/local/tmp/devecocli-${gI()}.png`;await this.capture({hdcPath:this.toolProvider.hdcPath,serial:e,localPath:Le.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?Dw(r.stdout):void 0}async tryCreateRemoteScreenshot(e,t){let r=Ew(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:Cw(Pw(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&&kw(i.output))throw new Error(`Screenshot was not created on device: ${e.remotePath}.
58
+ `).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=Qn(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 $x,unlinkSync as Fx}from"fs";import{tmpdir as jx}from"os";import{join as Hx}from"path";var Ar=class{constructor(e,t){this.hdcPath=e;this.serial=t}async listWindows(e){let t=await this.fetchDump(),r=_x(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 _x(n){let e=n.split(`
59
+ `),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]),h=Number(c[2]),w=Number(c[3]),R=Number(c[4]);Number.isFinite(w)&&Number.isFinite(d)&&Number.isFinite(h)&&r.push({id:w,name:l,pid:h,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 pw(n){if(!(!n||n==="HitTestMode.Default"))return n.startsWith("HitTestMode.")?n.slice(12):n}function gs(n){if(!(n==null||n==="")){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1}}function Fc(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 mw(n){return n.originalText||void 0}function Xi(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 fw(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 h=l?s+1:s;for(let w=i.children.length-1;w>=0;w--)r.push({current:i.children[w],parent:d,depth:h})}return t}function Ux(n){let e=$x(n,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function Bx(n){return n.attributes??{}}function jc(n,e,t){let r=Bx(n),i={id:r.id||void 0,type:r.type||void 0,text:mw(r),bounds:Fc(r.bounds),clickable:gs(r.clickable)||void 0,longClickable:gs(r.longClickable)||void 0,scrollable:gs(r.scrollable)||void 0,checkable:gs(r.checkable)||void 0,hitTestBehavior:pw(r.hitTestBehavior),children:[]};return e>0&&t+1>=e||n.children&&(i.children=n.children.map(o=>jc(o,e,t+1))),i}function Wx(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 Ir=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=Hx(jx(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,r),Ux(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}`),Fx(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 Ar(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=Wx(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=>jc(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:jc(s,t,0)})}return i}async dumpCollapsedTree(e,t,r,i){return(await this.dumpRawNodes(e,r,i)).flatMap(s=>fw(jc(s,0,0),t))}async dumpRawTree(e,t){return(await this.dumpRawNodes(e,t,!1))[0]}};var Ue=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}},Vx=["*=","^=","$=","/="],Gx=/[A-Za-z_]/,qx=/[A-Za-z0-9_]/,Ap=/\s/,zx=/^(.*)\/([gimsuy]+)$/,Ip=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 Tr(n){for(;!n.eof()&&Ap.test(n.peek());)n.next()}function Jx(n){let e=n.pos;if(!Gx.test(n.peek()))throw new Ue("expected attribute key",n.pos,n.input);for(;!n.eof()&&qx.test(n.peek());)n.next();return n.input.slice(e,n.pos)}function Yx(n,e){for(let t of Vx)if(n.startsWith(t))return n.pos+=t.length,t;if(n.peek()==="=")return n.next(),"=";throw new Ue(`expected operator (=, *=, ^=, $=, /=) after key "${e}"`,n.pos,n.input)}function hw(n){let e=n.match(zx);return e?{value:e[1],flags:e[2]}:{value:n}}function Kx(n,e){n.next();let t="";for(;!n.eof();){let r=n.next();if(r==="\\"){if(n.eof())throw new Ue("dangling escape in quoted value",n.pos,n.input);t+=n.next();continue}if(r===e)return t;t+=r}throw new Ue("unterminated quoted value",n.pos,n.input)}function xp(n){return n==='"'||n==="'"}function Xx(n,e){let t=n.peek();if(xp(t)){let i=Kx(n,t);return e==="/="?hw(i):{value:i}}let r="";for(;!n.eof();){let i=n.peek();if(i===","||i==="["||xp(i))break;if(Ap.test(i)){let o=n.pos+1;for(;o<n.input.length&&Ap.test(n.input[o]);)o++;let s=o<n.input.length?n.input[o]:"";if(s===""||s===","||s==="["||xp(s))break;r+=n.next();continue}if(i==="\\"){if(n.next(),n.eof())throw new Ue("dangling escape in value",n.pos,n.input);r+=n.next();continue}r+=n.next()}return e==="/="?hw(r):{value:r}}function gw(n){Tr(n);let e=Jx(n);Tr(n);let t=Yx(n,e);if(Tr(n),n.eof()||n.peek()===","||n.peek()==="[")throw new Ue(`missing value for key "${e}"`,n.pos,n.input);let{value:r,flags:i}=Xx(n,t);if(t==="/=")try{new RegExp(r,i)}catch(s){throw new Ue(`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 Zx(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 Ue(`invalid index "${e}" (expected N, -N, or "last")`,n.pos,n.input)}function ys(n){if(typeof n!="string")throw new Ue("input must be a string",0,String(n));let e=new Ip(n),t=[];if(Tr(e),e.eof())throw new Ue("empty selector",e.pos,n);for(t.push(gw(e));Tr(e),e.peek()===",";){if(e.next(),Tr(e),e.eof()||e.peek()===",")throw new Ue("expected clause after comma",e.pos,n);t.push(gw(e))}let r;if(Tr(e),e.peek()==="["){if(e.next(),r=Zx(e),Tr(e),e.peek()!=="]")throw new Ue("expected ']' after index",e.pos,n);e.next(),Tr(e)}if(!e.eof())throw new Ue(`unexpected trailing input "${e.input.slice(e.pos)}"`,e.pos,n);return{clauses:t,index:r,raw:n}}function Qx(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 eA(n,e){let t=Qx(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 Hc(n,e){let t=[],r=[n];for(;r.length>0;){let i=r.pop(),o=i.attributes??null;e.clauses.every(a=>eA(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 Zi(n,e){return e===void 0?n[0]:e>=0?n[e]:n[n.length+e]}import{DOMParser as tA}from"@xmldom/xmldom";import{select as rA}from"xpath";var nA=["id","key","originalText","description","enabled","focused","checked","selected","visible","clickable","longClickable","scrollable","checkable","accessibilityLevel","hitTestBehavior","bounds"];function iA(n){if(!n)return"node";let e=n.replace(/[^A-Za-z0-9_-]/g,"_");return/^[0-9]/.test(e)&&(e="_"+e),e||"node"}var oA=/&/g,sA=/</g,aA=/>/g,cA=/"/g,lA=/'/g;function Uc(n){return n.replace(oA,"&amp;").replace(sA,"&lt;").replace(aA,"&gt;").replace(cA,"&quot;").replace(lA,"&apos;")}function dA(n){let e=[],t=typeof n.type=="string"?n.type:"";t&&e.push(` type="${Uc(t)}"`);let r=n.originalText??n.text;r!=null&&r!==""&&e.push(` text="${Uc(String(r))}"`);for(let o of nA){let s=n[o];s==null||s===""||e.push(` ${o}="${Uc(String(s))}"`)}let i=n.description;return i!=null&&i!==""&&e.push(` desc="${Uc(String(i))}"`),e.join("")}function yw(n){let e=n.attributes??{},t=iA(typeof e.type=="string"?e.type:void 0),r=dA(e),i=n.children??[];return i.length===0?`<${t}${r}/>`:`<${t}${r}>${i.map(yw).join("")}</${t}>`}function uA(n){return`<?xml version="1.0" encoding="UTF-8"?>${yw(n)}`}function pA(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 mA(n){return typeof n!="object"||n===null?!1:n.nodeType===1}function fA(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:pA(e("bounds")),attributes:t}}function Tp(n,e){if(typeof e!="string"||e.trim()==="")throw new Error("xpath expression must be a non-empty string");let t=uA(n),r=new tA().parseFromString(t,"text/xml"),i=rA(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)mA(s)&&o.push(fA(s));return o}function Bc(n){return typeof n=="string"&&n.trimStart().startsWith("xpath=")}function Wc(n){return n.trimStart().slice(6)}function Vc(n){return new Promise(e=>setTimeout(e,n))}function Op(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:Fc(t.bounds),attributes:t}}function ww(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 Gc(n){return n.startsWith("base64=")?Buffer.from(n.slice(7).trim(),"base64").toString("utf8"):n}var hA=new Set(["text","desc","description"]),ws=[];function bw(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)bw(t,e)}function Sw(n,e){let t=new Set;bw(n,t);let r=[];for(let i of e)hA.has(i.key)||t.has(i.key)||r.push(i.key);return r}function vw(n,e){let t=Sw(n,e);for(let r of t)ws.push(`WARNING: attribute "${r}" not found in any node of the layout tree. No matches will be returned for this key.`)}function Np(){return ws.splice(0)}var Qi=class{dumper;constructor(e){this.dumper=new Ir(e)}async find(e,t,r){ws.splice(0);let i=Gc(t);if(Bc(i))return this.runXpathFind(e,Wc(i),r);let o=ys(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 h=await this.dumper.dumpRawTree(e,r?.window);if(l||(vw(h,t.clauses),l=!0),a=Hc(h,t),c=r?.all?a.length>0:Zi(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 Vc(o)}if(r?.all)return a.map((h,w)=>Op(h,w));let d=Zi(a,t.index);if(!d){let h=a.length,w=t.index===void 0?0:t.index;throw new Error(`Index ${w} out of range (matched ${h} element(s)) for selector: ${t.raw}`)}return[Op(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=Tp(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 Vc(o)}return r?.all?a.map((l,d)=>ww(l,d)):[ww(a[0],0)]}async waitForAppearance(e,t,r,i){ws.splice(0);let o=Gc(t);if(Bc(o))return(await this.runXpathFind(e,Wc(o),{timeoutMs:r,window:i}))[0];let s=ys(o);return await this.runWaitFor(e,s,r,i,!0)}async waitForDisappear(e,t,r,i){ws.splice(0);let o=Gc(t);if(Bc(o))return this.runXpathWaitFor(e,Wc(o),r,i,!1);let s=ys(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||(vw(l,t.clauses),c=!0);let d=Hc(l,t),h=Zi(d,t.index)!==void 0;if(o&&h){let w=Zi(d,t.index);return Op(w,t.index??0)}if(!o&&!h)return;if(Date.now()-a>=r)throw new Error(`Timed out (${r}ms) waiting for selector to ${o?"appear":"disappear"}: ${t.raw}`);await Vc(300)}}async runXpathWaitFor(e,t,r,i,o){let a=Date.now();for(;;){let c=await this.dumper.dumpRawTree(e,i),d=Tp(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 Vc(300)}}};import it from"fs";import Le from"path";import{randomUUID as gA}from"crypto";function Ew(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 Pw(n,e){return[n,e].filter(Boolean).join(`
60
+ `).trim()}function Cw(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 kw(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 Dw(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 yA(){return String(Date.now())}function Mp(n){let e;try{e=it.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{it.accessSync(n,it.constants.W_OK|it.constants.X_OK)}catch(t){throw new Error(`Screenshot directory is not writable: ${n}`,{cause:t})}}function Lp(n,e){try{throw it.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 Rw(n){if(!it.existsSync(n))throw new Error(`Screenshot file was not created: ${n}`);let e=it.statSync(n);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${n}`);let t=it.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 xw(n){try{return Rw(n),!0}catch{return!1}}function Aw(n){let e=[];for(let t of it.readdirSync(n,{withFileTypes:!0})){let r=Le.join(n,t.name);if(t.isDirectory()){e.push(...Aw(r));continue}t.isFile()&&xw(r)&&e.push(r)}return e}function wA(n,e){let t=Le.join(n,Le.basename(e));if(xw(t))return t;let r=Aw(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}function vA(n,e){try{it.copyFileSync(n,e,it.constants.COPYFILE_EXCL)}catch(t){throw t.code==="EEXIST"?new Error(`Screenshot file already exists: ${e}`,{cause:t}):t}Rw(e)}var ei=class{constructor(e){this.toolProvider=e}resolveDestinationPath(e){if(!e?.trim())throw new Error("--path is required.");let t=e.trim(),r=Le.resolve(t);try{if(it.statSync(r).isDirectory()){Mp(r);let o=Le.join(r,`screenshot-${yA()}.png`);return Lp(o,r),o}}catch(o){if(o.code!=="ENOENT")throw o}if(Le.extname(r).toLowerCase()!==".png")throw new Error(`Screenshot path must be an existing directory or a PNG file: ${r}`);let i=Le.dirname(r);return Mp(i),Lp(r,i),r}async captureToPath(e,t,r){let i=Le.dirname(Le.resolve(t));Mp(i),Lp(Le.resolve(t),i);let o=`/data/local/tmp/devecocli-${gA()}.png`;await this.capture({hdcPath:this.toolProvider.hdcPath,serial:e,localPath:Le.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?Dw(r.stdout):void 0}async tryCreateRemoteScreenshot(e,t){let r=Ew(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:Cw(Pw(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&&kw(i.output))throw new Error(`Screenshot was not created on device: ${e.remotePath}.
61
61
  snapshot_display output:
62
62
  ${i.output}`);i.output&&(t=i.output)}throw new Error(t?`Screenshot was not created on device: ${e.remotePath}.
63
63
  snapshot_display output:
64
- ${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}`}`),wI(t,e.remotePath)}async receiveScreenshotFile(e){let t=it.mkdtempSync(Le.join(Le.dirname(e.localPath),".devecocli-screenshot-"));try{let r=await this.tryReceiveScreenshot(e,t,Le.join(t,Le.basename(e.remotePath)))??await this.tryReceiveScreenshot(e,t,t)??await this.tryReceiveScreenshot(e,t,Le.join(t,"screenshot.png"));if(!r)throw new Error(`Screenshot file was not created in ${t}.`);vI(r,e.localPath)}finally{it.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 av from"path";import{randomBytes as ZI}from"crypto";async function T(n,e){let r=await new on(n).selectDevice(e);if(!r)throw new Error("No device selected. Use `devecocli device list` to see targets.");return r}var ys="com.huawei.hmos.screenrecorder",ei="com.huawei.hmos.screenrecorder.ServiceExtAbility",Aw="/data/local/tmp",S=class extends Error{constructor(t,r=t,i){super(r,i);this.code=t;this.name="ScreenRecordError"}};var _p=/^\s*uri \[([^\]]*)\]\s*$/,bI=/^\s*uri \[/,SI=/AbilityRecord ID\s*[:#]\s*(\d+)/,EI=/start time \[(\d+)\]/,PI=/bundle name \[([^\]]*)\]/,CI=/main name \[([^\]]*)\]/,kI=/\[(?:Fail|E\d{5,})\]|^\s*(?:error|Error)(?::|\s)/m,DI=ei.slice(ei.lastIndexOf(".")+1);function RI(n){let e=[],t;for(let r of n.split(/\r?\n/))_p.test(r)?(t=[r],e.push(t)):t&&t.push(r);return e}function xI(n){let e={};for(let t of n){let r=_p.exec(t);if(r){e.uri=r[1].trim();continue}let i=SI.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=EI.exec(t);if(o){e.startedAtMs=Number(o[1]);continue}let s=PI.exec(t);if(s){e.bundleName=s[1].trim();continue}let a=CI.exec(t);a&&(e.mainName=a[1].trim())}return e}function Tw(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 II(n){let{bundleName:e,abilityName:t}=Tw(n);return e!==ys||!t?!1:t===ei||t===DI}function AI(n){if(kI.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(bI.test(t)&&!_p.test(t))throw new S("DUMP_PARSE_FAILED","aa dump output has an unterminated uri line; output may be truncated");let e=RI(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 Ow(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 AI(n)){let r=xI(t);if(!II(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}=Tw(r);e.set(r.id,{abilityRecordId:r.id,bundleName:i??ys,abilityName:o??ei,startedAtMs:r.startedAtMs})}return[...e.values()]}function $p(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 ti(n,e){return!n||!e?n===e:n.fileName===e.fileName&&n.abilityRecordId===e.abilityRecordId&&n.startTime===e.startTime&&n.localPath===e.localPath}function Nw(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 Mw(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 Lw(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 _w(n,e,t){return ti(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 $w(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 Fw(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 jw(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 Hw(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 Uw(n){return n.status==="idle"&&n.session?{status:"idle",note:"interrupted session found; retrievable via ui screenrecord stop"}:{status:n.status}}function Bw(n,e){return!ti(n.session,e)||n.status!=="recording"}function Fp(n,e){return n.startTime+e}function Ww(n,e,t){return t+Math.max(0,e-n)}import sn from"fs";import Yw from"path";import{randomBytes as MI}from"crypto";import{lock as LI}from"proper-lockfile";import ws from"path";var TI=/^[A-Za-z0-9][A-Za-z0-9.-]*\.mp4$/;function Qi(n){return Buffer.from(n,"utf8").toString("hex")}function ri(n,e){return String(n).padStart(e,"0")}function Vw(n){return`${ri(n.getFullYear(),4)}${ri(n.getMonth()+1,2)}${ri(n.getDate(),2)}-${ri(n.getHours(),2)}${ri(n.getMinutes(),2)}${ri(n.getSeconds(),2)}${ri(n.getMilliseconds(),3)}`}function OI(n){return n.replace(/[<>:"/\\|?*\u0000-\u001f]/g,"-").replace(/\s+/g," ").trim().replace(/[. ]+$/,"").replace(/^[. ]+/,"")||"device"}function Gw(n,e){if(!/^[a-z0-9]{4}$/.test(e))throw new S("INVALID_RECORDING_PATH",`Internal: bad random suffix ${JSON.stringify(e)}`);return`devecocli-${Vw(n)}-${e}.mp4`}function qw(n,e,t){return`${OI(n)}-${Vw(e)}-${t}.mp4`}function zw(n,e){if(!TI.test(n))throw new S("INVALID_RECORDING_PATH",`Unsafe device file name: ${JSON.stringify(n)}`);return`${Aw}/devecocli-${e}-${n}`}var NI=20;function Jw(n){let e=ws.dirname(n),t=ws.extname(n),r=ws.basename(n,t),i=[n];i.push(ws.join(e,`${r}-recovered${t}`));for(let o=2;o<NI;o++)i.push(ws.join(e,`${r}-recovered-${o}${t}`));return i}var _I=5*6e4,$I=5*6e4,FI=1e4,jI=6e4,jp=200;function HI(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 Kw(n){return new Promise(e=>setTimeout(e,n))}function UI(){return MI(8).toString("hex")}async function Xw(n){let e;try{e=await sn.promises.readFile(n,"utf8")}catch{return}try{let t=JSON.parse(e);return typeof t.token=="string"?t.token:void 0}catch{return}}var Gc=class{constructor(e,t={}){this.recordDir=e;this.releaseGuardWaitMs=t.releaseGuardWaitMs??FI}releaseGuardWaitMs;lockPath(e){return Yw.join(this.recordDir,`${Qi(e)}.lock`)}guardPath(e){return Yw.join(this.recordDir,`${Qi(e)}.guard`)}async withDeviceLock(e,t,r=jI){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 LI(this.guardPath(e),{realpath:!1,stale:_I,update:1e3,retries:0})}catch(s){if(s.code!=="ELOCKED"||Date.now()>=i)throw s;await Kw(Math.min(jp,i-Date.now()));continue}try{return await t()}finally{await o()}}}async acquire(e,t){await sn.promises.mkdir(this.recordDir,{recursive:!0});let r=UI(),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()+jp>o)throw new S("LOCK_BUSY",`Timed out waiting ${t}ms for the device lock (${e})`);await Kw(jp)}}async tryCreateOrReclaim(e,t){let r;try{r=await sn.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 sn.promises.readFile(e,"utf8"),r=await sn.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){HI(i.pid)==="dead"&&await sn.promises.unlink(e);return}Date.now()-r.mtimeMs>$I&&await sn.promises.unlink(e)}buildLease(e,t){let r=new AbortController;return{token:t,signal:r.signal,assertOwned:async()=>{if(await Xw(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 Xw(r)===t.token&&await sn.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 BI}from"execa";var Hp=15e3,Zw=10*6e4,WI=3,Qw=400;function VI(n){return new Promise(e=>setTimeout(e,n))}function GI(n){return async(e,t)=>{m(`Executing: ${n} ${e.join(" ")}`);let r=await BI(n,e,{reject:!1,timeout:t.timeoutMs??Hp,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 qc=class n{runner;constructor(e){this.runner=GI(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<WI;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}
65
- ${r.stderr}`;if(r.exitCode===0||Ft(a)!=="transient")return r;if(i!==void 0&&Date.now()+Qw>i)break;await VI(Qw)}return r}static assertUsable(e,t){let r=`${e.stdout}
66
- ${e.stderr}`.trim();if(e.exitCode!==0||Ft(r)!=="ok")throw new S(t,`hdc command failed (exit ${e.exitCode}): ${r.split(`
64
+ ${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}`}`),wA(t,e.remotePath)}async receiveScreenshotFile(e){let t=it.mkdtempSync(Le.join(Le.dirname(e.localPath),".devecocli-screenshot-"));try{let r=await this.tryReceiveScreenshot(e,t,Le.join(t,Le.basename(e.remotePath)))??await this.tryReceiveScreenshot(e,t,t)??await this.tryReceiveScreenshot(e,t,Le.join(t,"screenshot.png"));if(!r)throw new Error(`Screenshot file was not created in ${t}.`);vA(r,e.localPath)}finally{it.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 av from"path";import{randomBytes as ZA}from"crypto";async function T(n,e){let r=await new an(n).selectDevice(e);if(!r)throw new Error("No device selected. Use `devecocli device list` to see targets.");return r}var vs="com.huawei.hmos.screenrecorder",ti="com.huawei.hmos.screenrecorder.ServiceExtAbility",Iw="/data/local/tmp",S=class extends Error{constructor(t,r=t,i){super(r,i);this.code=t;this.name="ScreenRecordError"}};var _p=/^\s*uri \[([^\]]*)\]\s*$/,bA=/^\s*uri \[/,SA=/AbilityRecord ID\s*[:#]\s*(\d+)/,EA=/start time \[(\d+)\]/,PA=/bundle name \[([^\]]*)\]/,CA=/main name \[([^\]]*)\]/,kA=/\[(?:Fail|E\d{5,})\]|^\s*(?:error|Error)(?::|\s)/m,DA=ti.slice(ti.lastIndexOf(".")+1);function RA(n){let e=[],t;for(let r of n.split(/\r?\n/))_p.test(r)?(t=[r],e.push(t)):t&&t.push(r);return e}function xA(n){let e={};for(let t of n){let r=_p.exec(t);if(r){e.uri=r[1].trim();continue}let i=SA.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=EA.exec(t);if(o){e.startedAtMs=Number(o[1]);continue}let s=PA.exec(t);if(s){e.bundleName=s[1].trim();continue}let a=CA.exec(t);a&&(e.mainName=a[1].trim())}return e}function Tw(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 AA(n){let{bundleName:e,abilityName:t}=Tw(n);return e!==vs||!t?!1:t===ti||t===DA}function IA(n){if(kA.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(bA.test(t)&&!_p.test(t))throw new S("DUMP_PARSE_FAILED","aa dump output has an unterminated uri line; output may be truncated");let e=RA(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 Ow(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 IA(n)){let r=xA(t);if(!AA(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}=Tw(r);e.set(r.id,{abilityRecordId:r.id,bundleName:i??vs,abilityName:o??ti,startedAtMs:r.startedAtMs})}return[...e.values()]}function $p(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 ri(n,e){return!n||!e?n===e:n.fileName===e.fileName&&n.abilityRecordId===e.abilityRecordId&&n.startTime===e.startTime&&n.localPath===e.localPath}function Nw(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 Mw(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 Lw(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 _w(n,e,t){return ri(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 $w(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 Fw(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 jw(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 Hw(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 Uw(n){return n.status==="idle"&&n.session?{status:"idle",note:"interrupted session found; retrievable via ui screenrecord stop"}:{status:n.status}}function Bw(n,e){return!ri(n.session,e)||n.status!=="recording"}function Fp(n,e){return n.startTime+e}function Ww(n,e,t){return t+Math.max(0,e-n)}import cn from"fs";import Yw from"path";import{randomBytes as MA}from"crypto";import{lock as LA}from"proper-lockfile";import bs from"path";var TA=/^[A-Za-z0-9][A-Za-z0-9.-]*\.mp4$/;function eo(n){return Buffer.from(n,"utf8").toString("hex")}function ni(n,e){return String(n).padStart(e,"0")}function Vw(n){return`${ni(n.getFullYear(),4)}${ni(n.getMonth()+1,2)}${ni(n.getDate(),2)}-${ni(n.getHours(),2)}${ni(n.getMinutes(),2)}${ni(n.getSeconds(),2)}${ni(n.getMilliseconds(),3)}`}function OA(n){return n.replace(/[<>:"/\\|?*\u0000-\u001f]/g,"-").replace(/\s+/g," ").trim().replace(/[. ]+$/,"").replace(/^[. ]+/,"")||"device"}function Gw(n,e){if(!/^[a-z0-9]{4}$/.test(e))throw new S("INVALID_RECORDING_PATH",`Internal: bad random suffix ${JSON.stringify(e)}`);return`devecocli-${Vw(n)}-${e}.mp4`}function qw(n,e,t){return`${OA(n)}-${Vw(e)}-${t}.mp4`}function zw(n,e){if(!TA.test(n))throw new S("INVALID_RECORDING_PATH",`Unsafe device file name: ${JSON.stringify(n)}`);return`${Iw}/devecocli-${e}-${n}`}var NA=20;function Jw(n){let e=bs.dirname(n),t=bs.extname(n),r=bs.basename(n,t),i=[n];i.push(bs.join(e,`${r}-recovered${t}`));for(let o=2;o<NA;o++)i.push(bs.join(e,`${r}-recovered-${o}${t}`));return i}var _A=5*6e4,$A=5*6e4,FA=1e4,jA=6e4,jp=200;function HA(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 Kw(n){return new Promise(e=>setTimeout(e,n))}function UA(){return MA(8).toString("hex")}async function Xw(n){let e;try{e=await cn.promises.readFile(n,"utf8")}catch{return}try{let t=JSON.parse(e);return typeof t.token=="string"?t.token:void 0}catch{return}}var qc=class{constructor(e,t={}){this.recordDir=e;this.releaseGuardWaitMs=t.releaseGuardWaitMs??FA}releaseGuardWaitMs;lockPath(e){return Yw.join(this.recordDir,`${eo(e)}.lock`)}guardPath(e){return Yw.join(this.recordDir,`${eo(e)}.guard`)}async withDeviceLock(e,t,r=jA){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 LA(this.guardPath(e),{realpath:!1,stale:_A,update:1e3,retries:0})}catch(s){if(s.code!=="ELOCKED"||Date.now()>=i)throw s;await Kw(Math.min(jp,i-Date.now()));continue}try{return await t()}finally{await o()}}}async acquire(e,t){await cn.promises.mkdir(this.recordDir,{recursive:!0});let r=UA(),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()+jp>o)throw new S("LOCK_BUSY",`Timed out waiting ${t}ms for the device lock (${e})`);await Kw(jp)}}async tryCreateOrReclaim(e,t){let r;try{r=await cn.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 cn.promises.readFile(e,"utf8"),r=await cn.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){HA(i.pid)==="dead"&&await cn.promises.unlink(e);return}Date.now()-r.mtimeMs>$A&&await cn.promises.unlink(e)}buildLease(e,t){let r=new AbortController;return{token:t,signal:r.signal,assertOwned:async()=>{if(await Xw(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 Xw(r)===t.token&&await cn.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 BA}from"execa";var Hp=15e3,Zw=10*6e4,WA=3,Qw=400;function VA(n){return new Promise(e=>setTimeout(e,n))}function GA(n){return async(e,t)=>{m(`Executing: ${n} ${e.join(" ")}`);let r=await BA(n,e,{reject:!1,timeout:t.timeoutMs??Hp,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 zc=class n{runner;constructor(e){this.runner=GA(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<WA;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}
65
+ ${r.stderr}`;if(r.exitCode===0||jt(a)!=="transient")return r;if(i!==void 0&&Date.now()+Qw>i)break;await VA(Qw)}return r}static assertUsable(e,t){let r=`${e.stdout}
66
+ ${e.stderr}`.trim();if(e.exitCode!==0||jt(r)!=="ok")throw new S(t,`hdc command failed (exit ${e.exitCode}): ${r.split(`
67
67
  `)[0]??""}`)}async observeOnce(e,t){let r=await this.runReadOnly(["-t",e,"shell","aa","dump","-e"],t);return n.assertUsable(r,"DUMP_PARSE_FAILED"),Ow(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(`
68
- `)[0]??""}`);return Math.round(i*1e3)}async toggleOnce(e,t,r,i){await r.assertOwned();let o=["-t",e,"shell","aa","start","-b",ys,"-a",ei];t!==void 0&&o.push("--ps","CustomizedFileName",t);try{let s=await this.runner(o,{timeoutMs:i??Hp,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(`
68
+ `)[0]??""}`);return Math.round(i*1e3)}async toggleOnce(e,t,r,i){await r.assertOwned();let o=["-t",e,"shell","aa","start","-b",vs,"-a",ti];t!==void 0&&o.push("--ps","CustomizedFileName",t);try{let s=await this.runner(o,{timeoutMs:i??Hp,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(`
69
69
  `)[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:Zw});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(`
70
70
  `)[0]??""}`)}async receiveFile(e,t,r,i){let o=await this.runner(["-t",e,"file","recv",t,r],{timeoutMs:Zw,signal:i});if(o.exitCode!==0)throw new S("SAVE_FAILED",`hdc file recv failed (exit ${o.exitCode}): ${(o.stderr||o.stdout).split(`
71
- `)[0]??""}`)}async removeStaging(e,t){return(await this.runReadOnly(["-t",e,"shell","rm","-f",t],Hp)).exitCode===0}};import Ar from"fs";import cr from"path";import{createFile as qI}from"mp4box";var tv=".devecocli-record-";function eo(n,e){return new S("INVALID_RECORDING_PATH",e instanceof Error?`${n}: ${e.message}`:n,e instanceof Error?{cause:e}:void 0)}async function Up(n){try{return{stat:await Ar.promises.stat(n)}}catch(e){let t=e.code;return t==="ENOENT"?null:{code:t??"UNKNOWN"}}}async function ev(n){let e=await Up(n);if(!e)throw eo(`Directory does not exist: ${n}`);if("code"in e)throw eo(`Directory is not accessible: ${n}`);if(!e.stat.isDirectory())throw eo(`Path is not a directory: ${n}`);try{await Ar.promises.access(n,Ar.constants.W_OK)}catch(t){throw eo(`Directory is not writable: ${n}`,t)}}async function Bp(n){if(await Up(n))throw new S("DESTINATION_EXISTS",`Destination already exists: ${n}`)}async function Wp(n,e,t,r){if(!n?.trim())throw eo("--path is required.");let i=cr.resolve(n.trim()),o=await Up(i);if(o&&"stat"in o&&o.stat.isDirectory()){await ev(i);let a=cr.join(i,qw(e,t,r));return await Bp(a),a}if(o)throw new S("DESTINATION_EXISTS",`Destination already exists: ${i}`);if(cr.extname(i).toLowerCase()!==".mp4")throw eo(`Destination must be an existing directory or a new .mp4 file: ${i}`);let s=cr.dirname(i);return await ev(s),i}async function rv(n){return Ar.promises.mkdtemp(cr.join(cr.dirname(n),tv))}var zI=4*1024*1024;async function JI(n){let e=await Ar.promises.open(n,"r");try{let{size:t}=await e.stat(),r=qI(),i=0;for(let s=0;s<t;){let a=Math.min(zI,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 nv(n){let e;try{e=await JI(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 YI(n){let e=await Ar.promises.open(n,"r+");try{await e.sync()}finally{await e.close()}}async function KI(n){try{let e=await Ar.promises.open(cr.dirname(n),"r");try{await e.sync()}finally{await e.close()}}catch{}}async function iv(n,e){await YI(n);for(let t of Jw(e))try{return await Ar.promises.link(n,t),await KI(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 ov(n,e){let t=cr.dirname(e),r=cr.basename(n);cr.dirname(n)!==t||!r.startsWith(tv)||await Ar.promises.rm(n,{recursive:!0,force:!0}).catch(()=>{})}import Tr from"fs";import zc from"path";import{randomBytes as XI}from"crypto";function sv(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!==zc.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||!zc.isAbsolute(t.localPath))throw r("localPath");return{fileName:t.fileName,abilityRecordId:t.abilityRecordId,startTime:t.startTime,localPath:t.localPath}}var Jc=class{constructor(e){this.recordDir=e}sessionPath(e){return zc.join(this.recordDir,`${Qi(e)}.json`)}async read(e){let t=this.sessionPath(e),r;try{r=await Tr.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 sv(i,t)}async createAtomic(e,t,r){await Tr.promises.mkdir(this.recordDir,{recursive:!0});let i=this.sessionPath(e),o=zc.join(this.recordDir,`${Qi(e)}.${XI(6).toString("hex")}.tmp`),s=JSON.stringify(sv(t,"input")),a;try{a=await Tr.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 Tr.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 Tr.promises.link(o,i),await this.syncDir()}finally{await Tr.promises.unlink(o).catch(()=>{})}}async deleteIfSame(e,t,r){await r.assertOwned();let i=await this.read(e);if(i){if(!ti(i,t))throw new S("SESSION_CHANGED","The recording session changed hands; leaving the new record untouched");await Tr.promises.unlink(this.sessionPath(e)),await this.syncDir()}}async exists(e){try{return await Tr.promises.lstat(e),!0}catch{return!1}}async syncDir(){try{let e=await Tr.promises.open(this.recordDir,"r");try{await e.sync()}finally{await e.close()}}catch{}}};var QI={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},cv=4e3;function vs(n){return new Promise(e=>setTimeout(e,n))}function Yc(){return ZI(2).toString("hex")}var lv=["SIGINT","SIGTERM","SIGHUP"];function eA(n,e){let t=()=>{n.requested||(n.requested=!0,e?.(),n.wake())};for(let r of lv)process.on(r,t);return()=>{for(let r of lv)process.off(r,t)}}var an=class{constructor(e,t={}){this.toolProvider=e;let r=av.join(F(),"record");this.deps={store:t.store??new Jc(r),lock:t.lock??new Gc(r),device:t.device??new qc(e.hdcPath),timing:{...QI,...t.timing}}}deps;async startDetached(e,t){let r=await this.resolveTarget(e),i=await Wp(t,r.name,new Date,Yc());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=eA(o,r.onStopRequested);try{let a=await this.resolveTarget(e),c=await Wp(t,a.name,new Date,Yc()),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(Bw(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=Lw(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(!ti(i,s))continue;let a=$p(o,s);return Uw(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 $p(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=Nw(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=Mw(s);if(a.plan==="error")throw a.error}return this.toggleAndRegister(e,t,r)}async toggleAndRegister(e,t,r){await Bp(t);let i=Gw(new Date,Yc()),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=jw(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 vs(Math.min(this.deps.timing.observeIntervalMs,r))}}async observeActiveId(e,t,r){let i=await this.deps.device.observeOnce(e,r),o=Fw(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 vs(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 vs(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=Fp(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=_w(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=$w(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=Fp(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=Hw(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=Ww(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 rv(t.localPath);try{let a=await this.receiveUntilValid(e,o,t,s,r,i);await r.assertOwned();let c=await iv(a,t.localPath);return await this.deleteSessionAfterSave(e,t,r,c),{kind:"saved",localPath:c,warnings:i}}finally{await ov(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)]??cv,cv,o);i+=1,await vs(a)}}async receiveUntilValid(e,t,r,i,o,s){for(let a=0;a<this.deps.timing.mediaRecvAttempts;a++){await o.assertOwned();let c=zw(r.fileName,Yc()),l=await this.receiveOnce(e,t,c,i,r.fileName,o,s);try{return await nv(l),l}catch(d){if(d.code!=="MEDIA_NOT_READY")throw d;m(`Received file incomplete (attempt ${a+1}); retrying export`),await vs(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=av.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 Kc={left:"0",right:"1",up:"2",down:"3"};function Be(n,e){let t=Number(n);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function Vp(n,e){n!==void 0&&Be(n,e)}function dv(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function Xc(n,e){if(n!==void 0&&n.length===0)throw new Error(`${e} must not be empty`)}function bs(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 uv(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function pv(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 to(n,e,t,r,i=!0){dv(n,e),Xc(t,"--id"),Vp(n,"x"),Vp(e,"y"),uv(r),pv(n!==void 0,!!t,!!r,i)}async function lr(n){let e=await P.new(),t=await T(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function ro(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 Rr(n,e).listWindows({all:!0}),c=new xr(n);return tA(c,e,a,i,o)}async function tA(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 nA(s,r)}return rA(n,e,t,r)}async function rA(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 Ki([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 mv(s[0].node,r)}function nA(n,e){let t=Ki(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 mv(t[0],e)}function mv(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 kt(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 iA,inflateSync as oA}from"zlib";import sA from"fs";var fv=8,hv=32,aA=.06,cA=.04,Gp=10,Zc=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<=Gp}}analyzeFile(e){let t;try{t=sA.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
71
+ `)[0]??""}`)}async removeStaging(e,t){return(await this.runReadOnly(["-t",e,"shell","rm","-f",t],Hp)).exitCode===0}};import Or from"fs";import lr from"path";import{createFile as qA}from"mp4box";var tv=".devecocli-record-";function to(n,e){return new S("INVALID_RECORDING_PATH",e instanceof Error?`${n}: ${e.message}`:n,e instanceof Error?{cause:e}:void 0)}async function Up(n){try{return{stat:await Or.promises.stat(n)}}catch(e){let t=e.code;return t==="ENOENT"?null:{code:t??"UNKNOWN"}}}async function ev(n){let e=await Up(n);if(!e)throw to(`Directory does not exist: ${n}`);if("code"in e)throw to(`Directory is not accessible: ${n}`);if(!e.stat.isDirectory())throw to(`Path is not a directory: ${n}`);try{await Or.promises.access(n,Or.constants.W_OK)}catch(t){throw to(`Directory is not writable: ${n}`,t)}}async function Bp(n){if(await Up(n))throw new S("DESTINATION_EXISTS",`Destination already exists: ${n}`)}async function Wp(n,e,t,r){if(!n?.trim())throw to("--path is required.");let i=lr.resolve(n.trim()),o=await Up(i);if(o&&"stat"in o&&o.stat.isDirectory()){await ev(i);let a=lr.join(i,qw(e,t,r));return await Bp(a),a}if(o)throw new S("DESTINATION_EXISTS",`Destination already exists: ${i}`);if(lr.extname(i).toLowerCase()!==".mp4")throw to(`Destination must be an existing directory or a new .mp4 file: ${i}`);let s=lr.dirname(i);return await ev(s),i}async function rv(n){return Or.promises.mkdtemp(lr.join(lr.dirname(n),tv))}var zA=4*1024*1024;async function JA(n){let e=await Or.promises.open(n,"r");try{let{size:t}=await e.stat(),r=qA(),i=0;for(let s=0;s<t;){let a=Math.min(zA,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 nv(n){let e;try{e=await JA(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 YA(n){let e=await Or.promises.open(n,"r+");try{await e.sync()}finally{await e.close()}}async function KA(n){try{let e=await Or.promises.open(lr.dirname(n),"r");try{await e.sync()}finally{await e.close()}}catch{}}async function iv(n,e){await YA(n);for(let t of Jw(e))try{return await Or.promises.link(n,t),await KA(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 ov(n,e){let t=lr.dirname(e),r=lr.basename(n);lr.dirname(n)!==t||!r.startsWith(tv)||await Or.promises.rm(n,{recursive:!0,force:!0}).catch(()=>{})}import Nr from"fs";import Jc from"path";import{randomBytes as XA}from"crypto";function sv(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!==Jc.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||!Jc.isAbsolute(t.localPath))throw r("localPath");return{fileName:t.fileName,abilityRecordId:t.abilityRecordId,startTime:t.startTime,localPath:t.localPath}}var Yc=class{constructor(e){this.recordDir=e}sessionPath(e){return Jc.join(this.recordDir,`${eo(e)}.json`)}async read(e){let t=this.sessionPath(e),r;try{r=await Nr.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 sv(i,t)}async createAtomic(e,t,r){await Nr.promises.mkdir(this.recordDir,{recursive:!0});let i=this.sessionPath(e),o=Jc.join(this.recordDir,`${eo(e)}.${XA(6).toString("hex")}.tmp`),s=JSON.stringify(sv(t,"input")),a;try{a=await Nr.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 Nr.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 Nr.promises.link(o,i),await this.syncDir()}finally{await Nr.promises.unlink(o).catch(()=>{})}}async deleteIfSame(e,t,r){await r.assertOwned();let i=await this.read(e);if(i){if(!ri(i,t))throw new S("SESSION_CHANGED","The recording session changed hands; leaving the new record untouched");await Nr.promises.unlink(this.sessionPath(e)),await this.syncDir()}}async exists(e){try{return await Nr.promises.lstat(e),!0}catch{return!1}}async syncDir(){try{let e=await Nr.promises.open(this.recordDir,"r");try{await e.sync()}finally{await e.close()}}catch{}}};var QA={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},cv=4e3;function Ss(n){return new Promise(e=>setTimeout(e,n))}function Kc(){return ZA(2).toString("hex")}var lv=["SIGINT","SIGTERM","SIGHUP"];function eI(n,e){let t=()=>{n.requested||(n.requested=!0,e?.(),n.wake())};for(let r of lv)process.on(r,t);return()=>{for(let r of lv)process.off(r,t)}}var ln=class{constructor(e,t={}){this.toolProvider=e;let r=av.join(F(),"record");this.deps={store:t.store??new Yc(r),lock:t.lock??new qc(r),device:t.device??new zc(e.hdcPath),timing:{...QA,...t.timing}}}deps;async startDetached(e,t){let r=await this.resolveTarget(e),i=await Wp(t,r.name,new Date,Kc());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=eI(o,r.onStopRequested);try{let a=await this.resolveTarget(e),c=await Wp(t,a.name,new Date,Kc()),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(Bw(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=Lw(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(!ri(i,s))continue;let a=$p(o,s);return Uw(a)}throw new S("STATE_CHANGING","The recording session keeps changing; try again")}async resolveTarget(e){let t=await ce.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 $p(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=Nw(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=Mw(s);if(a.plan==="error")throw a.error}return this.toggleAndRegister(e,t,r)}async toggleAndRegister(e,t,r){await Bp(t);let i=Gw(new Date,Kc()),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=jw(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 Ss(Math.min(this.deps.timing.observeIntervalMs,r))}}async observeActiveId(e,t,r){let i=await this.deps.device.observeOnce(e,r),o=Fw(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 Ss(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 Ss(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=Fp(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=_w(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=$w(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=Fp(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=Hw(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=Ww(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 rv(t.localPath);try{let a=await this.receiveUntilValid(e,o,t,s,r,i);await r.assertOwned();let c=await iv(a,t.localPath);return await this.deleteSessionAfterSave(e,t,r,c),{kind:"saved",localPath:c,warnings:i}}finally{await ov(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)]??cv,cv,o);i+=1,await Ss(a)}}async receiveUntilValid(e,t,r,i,o,s){for(let a=0;a<this.deps.timing.mediaRecvAttempts;a++){await o.assertOwned();let c=zw(r.fileName,Kc()),l=await this.receiveOnce(e,t,c,i,r.fileName,o,s);try{return await nv(l),l}catch(d){if(d.code!=="MEDIA_NOT_READY")throw d;m(`Received file incomplete (attempt ${a+1}); retrying export`),await Ss(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=av.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 Xc={left:"0",right:"1",up:"2",down:"3"};function Be(n,e){let t=Number(n);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function Vp(n,e){n!==void 0&&Be(n,e)}function dv(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function Zc(n,e){if(n!==void 0&&n.length===0)throw new Error(`${e} must not be empty`)}function Es(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 uv(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function pv(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 ro(n,e,t,r,i=!0){dv(n,e),Zc(t,"--id"),Vp(n,"x"),Vp(e,"y"),uv(r),pv(n!==void 0,!!t,!!r,i)}async function dr(n){let e=await P.new(),t=await T(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function no(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 Ar(n,e).listWindows({all:!0}),c=new Ir(n);return tI(c,e,a,i,o)}async function tI(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 nI(s,r)}return rI(n,e,t,r)}async function rI(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 Xi([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 mv(s[0].node,r)}function nI(n,e){let t=Xi(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 mv(t[0],e)}function mv(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 kt(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 iI,inflateSync as oI}from"zlib";import sI from"fs";var fv=8,hv=32,aI=.06,cI=.04,Gp=10,Qc=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<=Gp}}analyzeFile(e){let t;try{t=sI.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
72
72
  
73
- `,"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",iA(a),i)),o.push(n.pngChunk("IEND",Buffer.alloc(0),i)),Buffer.concat(o)}cropChrome(e,t,r){let i=Math.floor(t*aA),o=Math.floor(t*(1-cA));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,hv,hv),s=this.dct2(o),a=[];for(let d=0;d<fv;d++)a.push(s[d].slice(0,fv));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)),h=c-l,w=[];for(let D=0;D<t;D++){let z=(D+.5)*o/t-.5,ie=Math.max(0,Math.min(o-1,Math.floor(z))),dt=Math.max(0,Math.min(o-1,ie+1)),Xt=z-ie,_n=e[l][ie],$n=e[l][dt],Fn=e[d][ie],_h=e[d][dt];w.push(_n*(1-Xt)*(1-h)+$n*Xt*(1-h)+Fn*(1-Xt)*h+_h*Xt*h)}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 h=0;h<t;h++)d+=a[h]*Math.cos(Math.PI*(h+.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=oA(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
73
+ `,"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",iI(a),i)),o.push(n.pngChunk("IEND",Buffer.alloc(0),i)),Buffer.concat(o)}cropChrome(e,t,r){let i=Math.floor(t*aI),o=Math.floor(t*(1-cI));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,hv,hv),s=this.dct2(o),a=[];for(let d=0;d<fv;d++)a.push(s[d].slice(0,fv));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)),h=c-l,w=[];for(let R=0;R<t;R++){let J=(R+.5)*o/t-.5,ye=Math.max(0,Math.min(o-1,Math.floor(J))),dt=Math.max(0,Math.min(o-1,ye+1)),Zt=J-ye,Fn=e[l][ye],jn=e[l][dt],Hn=e[d][ye],_h=e[d][dt];w.push(Fn*(1-Zt)*(1-h)+jn*Zt*(1-h)+Hn*(1-Zt)*h+_h*Zt*h)}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 h=0;h<t;h++)d+=a[h]*Math.cos(Math.PI*(h+.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=oI(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
74
74
  
75
- `)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 h=0;h<r;h++){let w=e[c++];d.set(e.subarray(c,c+s)),c+=s,this.applyPngFilter(w,d,l,o);for(let D=0;D<t;D++){let z=(h*t+D)*3,ie=D*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 Or from"fs";import jt from"path";import{randomUUID as fA}from"crypto";var lA=/^smoke-screenshot-\d+\.png$/,dA=/^smoke-crash-\d+\.log$/,uA=/^run-\d+-\d+-[0-9a-f]{4}$/;function gv(n){return`smoke-screenshot-${n}.png`}function yv(n){return`smoke-crash-${n}.log`}function wv(n){return lA.test(n)||dA.test(n)}var Ss="RUNNING",qp="ENDED",pA=1440*60*1e3,mA=1440*60*1e3;function vv(n,e,t){return`run-${n}-${e}-${t}`}function bv(n){return uA.test(n)}function Sv(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 Ev(n,e,t){return n===null?!0:n==="ended"?e?.endedAt===void 0?!0:t.now-e.endedAt>=pA:!e||!Number.isInteger(e.pid)||e.pid<=0||t.now-e.startedAt>=mA?!0:!t.isPidAlive(e.pid)}var hA="smoke";function gA(n){try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}var Es=class{constructor(e,t=gA){this.baseDir=e;this.isPidAlive=t;this.runsRoot=jt.join(e,hA)}runsRoot;static resolveBaseDir(e,t){return t??jt.join(e,".hvigor")}createRun(){let e=jt.join(this.runsRoot,vv(Date.now(),process.pid,fA().slice(0,4)));Or.mkdirSync(e,{recursive:!0});let t={pid:process.pid,startedAt:Date.now()};return Or.writeFileSync(jt.join(e,Ss),JSON.stringify(t),"utf8"),e}prune(e,t=Date.now()){this.pruneLegacyFlatArtifacts(),this.pruneEndedRuns(e,t)}finalize(e){try{let t=this.readMarker(e,Ss),r={pid:t?.pid??process.pid,startedAt:t?.startedAt??Date.now(),endedAt:Date.now()};Or.writeFileSync(jt.join(e,qp),JSON.stringify(r),"utf8"),Or.rmSync(jt.join(e,Ss),{force:!0})}catch(t){m(`Smoke: finalize run failed (${e}): ${t.message}`)}}discard(e){try{Or.rmSync(e,{recursive:!0,force:!0})}catch(t){m(`Smoke: discard run failed (${e}): ${t.message}`)}}pruneLegacyFlatArtifacts(){let e;try{e=Or.readdirSync(this.baseDir,{withFileTypes:!0})}catch{return}for(let t of e)!t.isFile()||!wv(t.name)||this.removeQuietly(jt.join(this.baseDir,t.name))}pruneEndedRuns(e,t){let r;try{r=Or.readdirSync(this.runsRoot,{withFileTypes:!0})}catch{return}for(let i of r){if(!i.isDirectory()||!bv(i.name))continue;let o=jt.join(this.runsRoot,i.name);if(jt.resolve(o)===jt.resolve(e))continue;let s=this.readMarkerState(o);Ev(s.kind,s.marker,{now:t,isPidAlive:this.isPidAlive})&&this.removeQuietly(o)}}readMarkerState(e){let t=this.readMarker(e,qp);if(t!==void 0)return{kind:"ended",marker:t};let r=this.readMarker(e,Ss);return r!==void 0?{kind:"running",marker:r}:{kind:null,marker:null}}readMarker(e,t){try{return Sv(Or.readFileSync(jt.join(e,t),"utf8"))}catch(r){return r.code==="ENOENT"?void 0:null}}removeQuietly(e){try{Or.rmSync(e,{recursive:!0,force:!0})}catch(t){m(`Smoke: prune artifact failed (${e}): ${t.message}`)}}};var Pv=3e3;function wA(){let n=process.env.DEVECO_CLI_SMOKE_WAIT_MS;if(n===void 0||n==="")return Pv;let e=Number(n);return Number.isFinite(e)&&e>=0?Math.floor(e):Pv}var el=class{constructor(e,t,r){this.hdc=t;this.projectRoot=r;this.hilog=new on(e),this.screenshots=new Qn(e)}phash=new Zc;hilog;screenshots;runDir;runStore;async collect(e){this.openRun(e);let t=wA();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(Ps(`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 Es(Es.resolveBaseDir(this.projectRoot,e.screenshotDir)),r=t.createRun();t.prune(r),this.runStore=t,this.runDir=r}artifactPath(e){return yA.join(this.runDir??"",e)}discardEvidence(e){for(let t of[e.screenshotPath,e.crashLogPath])if(t)try{Qc.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(gv(Date.now()));try{await this.screenshots.captureToPath(e.targetDeviceId,t)}catch(i){return this.skipBlank(`screenshot failed (${i.message})`)}if(!Qc.existsSync(t)||Qc.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(Ps(`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(Ps(`Smoke: crash log query failed (${r.message}).`));return}if(!t?.trim()){console.warn(Ps("Smoke: no crash log found on device."));return}try{let r=this.artifactPath(yv(Date.now()));return Qc.writeFileSync(r,t,"utf8"),r}catch(r){console.warn(Ps(`Smoke: failed to save crash log (${r.message}).`));return}}};var tl=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 ${Gp}, 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 rl=class{inspector;judge=new tl;formatter=new Lc;constructor(e,t,r){let i=r??new de(e);this.inspector=new el(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 zp(n){await new rl(n.toolProvider,n.projectRoot,n.hdcAdapter).execute(n)}function Jp(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 il(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(`
75
+ `)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 h=0;h<r;h++){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 J=(h*t+R)*3,ye=R*o;a[J]=d[ye],a[J+1]=d[ye+1],a[J+2]=d[ye+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 Mr from"fs";import Ht from"path";import{randomUUID as fI}from"crypto";var lI=/^smoke-screenshot-\d+\.png$/,dI=/^smoke-crash-\d+\.log$/,uI=/^run-\d+-\d+-[0-9a-f]{4}$/;function gv(n){return`smoke-screenshot-${n}.png`}function yv(n){return`smoke-crash-${n}.log`}function wv(n){return lI.test(n)||dI.test(n)}var Ps="RUNNING",qp="ENDED",pI=1440*60*1e3,mI=1440*60*1e3;function vv(n,e,t){return`run-${n}-${e}-${t}`}function bv(n){return uI.test(n)}function Sv(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 Ev(n,e,t){return n===null?!0:n==="ended"?e?.endedAt===void 0?!0:t.now-e.endedAt>=pI:!e||!Number.isInteger(e.pid)||e.pid<=0||t.now-e.startedAt>=mI?!0:!t.isPidAlive(e.pid)}var hI="smoke";function gI(n){try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}var Cs=class{constructor(e,t=gI){this.baseDir=e;this.isPidAlive=t;this.runsRoot=Ht.join(e,hI)}runsRoot;static resolveBaseDir(e,t){return t??Ht.join(e,".hvigor")}createRun(){let e=Ht.join(this.runsRoot,vv(Date.now(),process.pid,fI().slice(0,4)));Mr.mkdirSync(e,{recursive:!0});let t={pid:process.pid,startedAt:Date.now()};return Mr.writeFileSync(Ht.join(e,Ps),JSON.stringify(t),"utf8"),e}prune(e,t=Date.now()){this.pruneLegacyFlatArtifacts(),this.pruneEndedRuns(e,t)}finalize(e){try{let t=this.readMarker(e,Ps),r={pid:t?.pid??process.pid,startedAt:t?.startedAt??Date.now(),endedAt:Date.now()};Mr.writeFileSync(Ht.join(e,qp),JSON.stringify(r),"utf8"),Mr.rmSync(Ht.join(e,Ps),{force:!0})}catch(t){m(`Smoke: finalize run failed (${e}): ${t.message}`)}}discard(e){try{Mr.rmSync(e,{recursive:!0,force:!0})}catch(t){m(`Smoke: discard run failed (${e}): ${t.message}`)}}pruneLegacyFlatArtifacts(){let e;try{e=Mr.readdirSync(this.baseDir,{withFileTypes:!0})}catch{return}for(let t of e)!t.isFile()||!wv(t.name)||this.removeQuietly(Ht.join(this.baseDir,t.name))}pruneEndedRuns(e,t){let r;try{r=Mr.readdirSync(this.runsRoot,{withFileTypes:!0})}catch{return}for(let i of r){if(!i.isDirectory()||!bv(i.name))continue;let o=Ht.join(this.runsRoot,i.name);if(Ht.resolve(o)===Ht.resolve(e))continue;let s=this.readMarkerState(o);Ev(s.kind,s.marker,{now:t,isPidAlive:this.isPidAlive})&&this.removeQuietly(o)}}readMarkerState(e){let t=this.readMarker(e,qp);if(t!==void 0)return{kind:"ended",marker:t};let r=this.readMarker(e,Ps);return r!==void 0?{kind:"running",marker:r}:{kind:null,marker:null}}readMarker(e,t){try{return Sv(Mr.readFileSync(Ht.join(e,t),"utf8"))}catch(r){return r.code==="ENOENT"?void 0:null}}removeQuietly(e){try{Mr.rmSync(e,{recursive:!0,force:!0})}catch(t){m(`Smoke: prune artifact failed (${e}): ${t.message}`)}}};var Pv=3e3;function wI(){let n=process.env.DEVECO_CLI_SMOKE_WAIT_MS;if(n===void 0||n==="")return Pv;let e=Number(n);return Number.isFinite(e)&&e>=0?Math.floor(e):Pv}var tl=class{constructor(e,t,r){this.hdc=t;this.projectRoot=r;this.hilog=new an(e),this.screenshots=new ei(e)}phash=new Qc;hilog;screenshots;runDir;runStore;async collect(e){this.openRun(e);let t=wI();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(ks(`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 Cs(Cs.resolveBaseDir(this.projectRoot,e.screenshotDir)),r=t.createRun();t.prune(r),this.runStore=t,this.runDir=r}artifactPath(e){return yI.join(this.runDir??"",e)}discardEvidence(e){for(let t of[e.screenshotPath,e.crashLogPath])if(t)try{el.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(gv(Date.now()));try{await this.screenshots.captureToPath(e.targetDeviceId,t)}catch(i){return this.skipBlank(`screenshot failed (${i.message})`)}if(!el.existsSync(t)||el.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(ks(`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(ks(`Smoke: crash log query failed (${r.message}).`));return}if(!t?.trim()){console.warn(ks("Smoke: no crash log found on device."));return}try{let r=this.artifactPath(yv(Date.now()));return el.writeFileSync(r,t,"utf8"),r}catch(r){console.warn(ks(`Smoke: failed to save crash log (${r.message}).`));return}}};var rl=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 ${Gp}, 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 nl=class{inspector;judge=new rl;formatter=new _c;constructor(e,t,r){let i=r??new le(e);this.inspector=new tl(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 zp(n){await new nl(n.toolProvider,n.projectRoot,n.hdcAdapter).execute(n)}function Jp(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 ol(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(`
76
76
  `),"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 Yp(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>...].
77
77
  Available runnable modules:
78
78
  `+t.map(r=>` - ${r.name}`).join(`
79
79
  `),"Specify module error.")}function Cv(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 kv(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(`
80
- 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(Cs(`
80
+ 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(Ds(`
81
81
  Application '${t}': ${s}`))}else console.log(`
82
- Application '${t}' installed successfully (no ability to launch).`)}function SA(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 EA=new vA("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=SA(n),t=Date.now(),r=!0,i=null;try{let o=await CA(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(bA(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await R.track(e,o)}});async function PA(n,e,t,r,i){let o=new Ui(e,n.rootDir),s=new ft(e,n.rootDir),a=new Set,c=new Set;for(let{moduleName:D,targetName:z}of t)for(let ie of n.collectNonHarDependentModuleList(D))a.add(`${ie}@${z}`),c.add(ie);let l=[...a],d=gp(n,l),h={type:"modules",modulesToBuild:l,moduleTasks:d};for(let D of c)Ic.generate(n.rootDir,D,r,e);let w=await zn(n.rootDir,()=>yp(o,s,r,i,h,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion..."));return console.log(`
83
- `+Cs("Build completed successfully.")),w}async function CA(n,e){let t=B.discover(process.cwd());await tt.warnInvalidBundledLinks(t.rootDir),console.warn(nl("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 RA(n,t,r);return}if(n.hotreload){await DA(n,t,r);return}if(n.apply){await IA(n,t,r);return}return Dv(n,t,r)}async function kA(n,e,t){n.onSocketDisconnect(()=>{console.log("Daemon disconnected (likely via --hotreload stop). Exiting watch session."),process.exit(0)});let r=new ft(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 DA(n,e,t){if(n.hotreload==="stop"){await uw(t,e);return}let i=Yp(e,n.module).map(Jp),{moduleName:o,targetName:s}=i[0];Dp(n.module,o);let a=new de(t),c=le.from(t),l=await il(c,n.device),d=l.includes("127.0.0.1")||l.includes("localhost"),h=n.product||"default";e.validateProduct(h);let w=e.getBundleName(h),D=Cv(e,i,n.ability);Ac.generate(e.rootDir,o,h,t);let z=new ft(t,e.rootDir);console.log(Cs("Ensuring hvigor daemon is running (via --sync --daemon, no hap build)...")),await z.ensureDaemonRunning();let ie=[`${o}@${h}`];for(let _n of e.collectNonHarDependentModuleList(o))ie.includes(`${_n}@${h}`)||ie.push(`${_n}@${h}`);console.log(Cs("Building hap + starting watch session (socket -> CommonBuild assembleHap --hot-reload-build --watch, kept open)..."));let dt=new Yi(e.rootDir,t);await dt.startWatchSession({moduleSpecs:ie,productName:h});let Xt=dw(e,o,s,d,h);await kv(a,l,w,Xt,D,!!n.uninstall),console.log(Cs("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 kA(dt,t,e)}async function RA(n,e,t){let r=n.hotreloadApply;if(!r)throw new Error("hotreload-apply requires --hotreload-apply <fileName> (under .hvigor/)");if(ks.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let i=Yp(e,n.module),{moduleName:o}=Jp(i[0]);Dp(n.module,o);let s=le.from(t),a=await il(s,n.device),c=n.product||"default";e.validateProduct(c);let l=e.getBundleName(c);lw(e,o,r);let d=[`${o}@${c}`],h=await cw({applyFileName:r,projectPath:e.rootDir,moduleName:o,productName:c,bundleName:l,toolProvider:t,targetDeviceId:a,moduleSpecs:d});if(!h.success)throw new Error(h.message)}function xA(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 Dv(n,e,t){let i=Yp(e,n.module).map(Jp);for(let{moduleName:ie}of i){let dt=e.getModuleType(ie);if(dt!=="entry"&&dt!=="feature"&&dt!=="shared")throw new y(`Module '${ie}' '${dt}' is not runnable. Specify an entry or feature module.`,"Module is not runnable.")}let o=new de(t),s=le.from(t),a=await il(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",h;n.skipBuild||(h=await PA(e,t,i,l,d));let w=xA(e,i,c,l),D=e.getBundleName(l),z=Cv(e,i,n.ability);return await kv(o,a,D,w,z,!!n.uninstall),z&&await zp({toolProvider:t,projectRoot:e.rootDir,hdcAdapter:o,targetDeviceId:a,bundleName:D}),h}async function IA(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(ks.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let i=ks.join(e.rootDir,".hvigor",r),o=le.from(t),s=await il(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",h=new xc(t,e.rootDir);try{await h.execute({applyFile:i,productName:a,targetDeviceId:s,bundleName:c,abilityName:d})}catch(w){console.warn(nl(`[Apply] failed: ${w.message}`)),console.warn(nl('[Apply] Falling back to full "devecocli run"...')),await Dv(n,e,t);return}console.log(nl('[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 zp({toolProvider:t,projectRoot:e.rootDir,targetDeviceId:s,bundleName:c})}var Rv=EA;import{Command as BA}from"commander";import*as Qp from"path";import{red as Av,cyan as cl,yellow as Xp}from"colorette";import{execa as ll}from"execa";import{execa as AA}from"execa";function ol(n){return Array.isArray(n)?n[0]:n}async function no(n){let e=Qr();m(`Executing: npm view ${Er}@${e} --json`);let{stdout:t}=await AA("npm",["view",`${Er}@${e}`,"--json"]),r=ol(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 ${Er}@${e}`);let o=r.versions?.[i],s=r.dist??o?.dist;if(!s)throw new Error(`Could not resolve dist for ${Er}@${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 xv}from"execa";import*as Ht from"path";import*as ye from"fs/promises";import*as Iv from"crypto";async function TA(n,e){let t=`${n}.tmp.${process.pid}`;await ye.writeFile(t,JSON.stringify(e,null,2),"utf-8"),await ye.rename(t,n)}function OA(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 Iv.createHash(r).update(n).digest().equals(o)}async function NA(n,e,t){m(`Executing: npm pack ${Er}@${n}`);let{stdout:r}=await xv("npm",["pack",`${Er}@${n}`],{cwd:t}),i=r.trim().split(`
84
- `).pop(),o=Ht.join(t,i),s=await ye.readFile(o);if(!OA(s,e))throw await ye.unlink(o).catch(()=>{}),new Error("Documentation package integrity verification failed");return o}async function MA(n,e,t){let r=Ht.join(t,e),i=Ht.join(t,`.tmp-${e}-${process.pid}`);return await ye.rm(r,{recursive:!0,force:!0}),await ye.rm(i,{recursive:!0,force:!0}),await ye.mkdir(i,{recursive:!0}),m(`Executing: tar -xzf ${Ht.basename(n)} -C ${i}`),await xv("tar",["-xzf",n,"-C",i]),await ye.rename(Ht.join(i,"package"),r),await ye.rm(i,{recursive:!0,force:!0}),await ye.unlink(n).catch(()=>{}),await ye.access(Ht.join(r,"dist","engine","index.js")),await ye.access(Ht.join(r,"docs.zip")),await ye.access(Ht.join(r,"index.zip")),r}async function sl(n,e,t){await ye.mkdir(e,{recursive:!0});let r=await NA(n.version,n.dist.integrity,e);return await MA(r,n.version,e),await TA(Ht.join(e,"current.json"),{version:n.version,apiVersion:n.apiVersion,installedAt:Date.now(),installedBy:t}),{version:n.version,apiVersion:n.apiVersion}}import*as al from"fs";import*as io from"path";import{execa as LA}from"execa";import{yellow as _A}from"colorette";function $A(n){return n?n.endsWith(".ts"):!0}function FA(n,e){let t=io.join(n,"package.json");try{return JSON.parse(al.readFileSync(t,"utf8")).name===e}catch{return!1}}function jA(n,e){let t;try{t=io.dirname(al.realpathSync(n))}catch{return null}for(let r=0;r<20&&t&&t!==io.dirname(t);r++){if(FA(t,e))return t;t=io.dirname(t)}return null}async function HA(){try{m("Executing: npm root -g");let{stdout:n}=await LA("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 UA(n,e){return $u(n,e)}async function Kp(n){if(process.env.DEVECO_CLI_SKIP_INSTALL_CHECK)return;let e=process.argv[1];if($A(e))return;let t=await HA();if(!t)return;let r=jA(e,n);if(!r){m("[install-check] running package root not found, skipping");return}UA(r,t)||(console.log(),console.log(_A(`Warning: devecocli is running from
82
+ Application '${t}' installed successfully (no ability to launch).`)}function SI(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 EI=new vI("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=SI(n),t=Date.now(),r=!0,i=null;try{let o=await CI(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(bI(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 PI(n,e,t,r,i){let o=new Bi(e,n.rootDir),s=new ft(e,n.rootDir),a=new Set;for(let{moduleName:w,targetName:R}of t)for(let J of n.collectNonHarDependentModuleList(w))a.add(`${J}@${R}`);let c=[...a],l=yp(n,c),d={type:"modules",modulesToBuild:c,moduleTasks:l},h=await kr(n.rootDir,()=>(sr.removeAll(n),wp(o,s,r,i,d,n.rootDir)),()=>console.log("Another build is already running for this project. Waiting for completion..."));return console.log(`
83
+ `+Ds("Build completed successfully.")),h}async function CI(n,e){let t=B.discover(process.cwd());await tt.warnInvalidBundledLinks(t.rootDir),console.warn(il("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 RI(n,t,r);return}if(n.hotreload){await DI(n,t,r);return}if(n.apply){await AI(n,t,r);return}return Dv(n,t,r)}async function kI(n,e,t){n.onSocketDisconnect(()=>{console.log("Daemon disconnected (likely via --hotreload stop). Exiting watch session."),process.exit(0)});let r=new ft(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 DI(n,e,t){if(n.hotreload==="stop"){await uw(t,e);return}let i=Yp(e,n.module).map(Jp),{moduleName:o,targetName:s}=i[0];Dp(n.module,o);let a=new le(t),c=ce.from(t),l=await ol(c,n.device),d=l.includes("127.0.0.1")||l.includes("localhost"),h=n.product||"default";e.validateProduct(h);let w=e.getBundleName(h),R=Cv(e,i,n.ability);Tc.generate(e.rootDir,o,h,t);let J=new ft(t,e.rootDir);console.log(Ds("Ensuring hvigor daemon is running (via --sync --daemon, no hap build)...")),await J.ensureDaemonRunning();let ye=[`${o}@${h}`];for(let Fn of e.collectNonHarDependentModuleList(o))ye.includes(`${Fn}@${h}`)||ye.push(`${Fn}@${h}`);console.log(Ds("Building hap + starting watch session (socket -> CommonBuild assembleHap --hot-reload-build --watch, kept open)..."));let dt=new Ki(e.rootDir,t);await dt.startWatchSession({moduleSpecs:ye,productName:h});let Zt=dw(e,o,s,d,h);await kv(a,l,w,Zt,R,!!n.uninstall),console.log(Ds("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 kI(dt,t,e)}async function RI(n,e,t){let r=n.hotreloadApply;if(!r)throw new Error("hotreload-apply requires --hotreload-apply <fileName> (under .hvigor/)");if(Rs.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let i=Yp(e,n.module),{moduleName:o}=Jp(i[0]);Dp(n.module,o);let s=ce.from(t),a=await ol(s,n.device),c=n.product||"default";e.validateProduct(c);let l=e.getBundleName(c);lw(e,o,r);let d=[`${o}@${c}`],h=await cw({applyFileName:r,projectPath:e.rootDir,moduleName:o,productName:c,bundleName:l,toolProvider:t,targetDeviceId:a,moduleSpecs:d});if(!h.success)throw new Error(h.message)}function xI(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 Dv(n,e,t){let i=Yp(e,n.module).map(Jp);for(let{moduleName:ye}of i){let dt=e.getModuleType(ye);if(dt!=="entry"&&dt!=="feature"&&dt!=="shared")throw new y(`Module '${ye}' '${dt}' is not runnable. Specify an entry or feature module.`,"Module is not runnable.")}let o=new le(t),s=ce.from(t),a=await ol(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",h;n.skipBuild||(h=await PI(e,t,i,l,d));let w=xI(e,i,c,l),R=e.getBundleName(l),J=Cv(e,i,n.ability);return await kv(o,a,R,w,J,!!n.uninstall),J&&await zp({toolProvider:t,projectRoot:e.rootDir,hdcAdapter:o,targetDeviceId:a,bundleName:R}),h}async function AI(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(Rs.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let i=Rs.join(e.rootDir,".hvigor",r),o=ce.from(t),s=await ol(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",h=new Ic(t,e.rootDir);try{await h.execute({applyFile:i,productName:a,targetDeviceId:s,bundleName:c,abilityName:d})}catch(w){console.warn(il(`[Apply] failed: ${w.message}`)),console.warn(il('[Apply] Falling back to full "devecocli run"...')),await Dv(n,e,t);return}console.log(il('[Apply] Done. If changes did not take effect, run "devecocli run" for a full build.')),await zp({toolProvider:t,projectRoot:e.rootDir,targetDeviceId:s,bundleName:c})}var Rv=EI;import{Command as BI}from"commander";import*as Qp from"path";import{red as Iv,cyan as ll,yellow as Xp}from"colorette";import{execa as dl}from"execa";import{execa as II}from"execa";function sl(n){return Array.isArray(n)?n[0]:n}async function io(n){let e=tn();m(`Executing: npm view ${Pr}@${e} --json`);let{stdout:t}=await II("npm",["view",`${Pr}@${e}`,"--json"]),r=sl(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 ${Pr}@${e}`);let o=r.versions?.[i],s=r.dist??o?.dist;if(!s)throw new Error(`Could not resolve dist for ${Pr}@${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 xv}from"execa";import*as Ut from"path";import*as ge from"fs/promises";import*as Av from"crypto";async function TI(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 OI(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 Av.createHash(r).update(n).digest().equals(o)}async function NI(n,e,t){m(`Executing: npm pack ${Pr}@${n}`);let{stdout:r}=await xv("npm",["pack",`${Pr}@${n}`],{cwd:t}),i=r.trim().split(`
84
+ `).pop(),o=Ut.join(t,i),s=await ge.readFile(o);if(!OI(s,e))throw await ge.unlink(o).catch(()=>{}),new Error("Documentation package integrity verification failed");return o}async function MI(n,e,t){let r=Ut.join(t,e),i=Ut.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 ${Ut.basename(n)} -C ${i}`),await xv("tar",["-xzf",n,"-C",i]),await ge.rename(Ut.join(i,"package"),r),await ge.rm(i,{recursive:!0,force:!0}),await ge.unlink(n).catch(()=>{}),await ge.access(Ut.join(r,"dist","engine","index.js")),await ge.access(Ut.join(r,"docs.zip")),await ge.access(Ut.join(r,"index.zip")),r}async function al(n,e,t){await ge.mkdir(e,{recursive:!0});let r=await NI(n.version,n.dist.integrity,e);return await MI(r,n.version,e),await TI(Ut.join(e,"current.json"),{version:n.version,apiVersion:n.apiVersion,installedAt:Date.now(),installedBy:t}),{version:n.version,apiVersion:n.apiVersion}}import*as cl from"fs";import*as oo from"path";import{execa as LI}from"execa";import{yellow as _I}from"colorette";function $I(n){return n?n.endsWith(".ts"):!0}function FI(n,e){let t=oo.join(n,"package.json");try{return JSON.parse(cl.readFileSync(t,"utf8")).name===e}catch{return!1}}function jI(n,e){let t;try{t=oo.dirname(cl.realpathSync(n))}catch{return null}for(let r=0;r<20&&t&&t!==oo.dirname(t);r++){if(FI(t,e))return t;t=oo.dirname(t)}return null}async function HI(){try{m("Executing: npm root -g");let{stdout:n}=await LI("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 UI(n,e){return Fu(n,e)}async function Kp(n){if(process.env.DEVECO_CLI_SKIP_INSTALL_CHECK)return;let e=process.argv[1];if($I(e))return;let t=await HI();if(!t)return;let r=jI(e,n);if(!r){m("[install-check] running package root not found, skipping");return}UI(r,t)||(console.log(),console.log(_I(`Warning: devecocli is running from
85
85
  ${r}
86
86
  but \`npm\` in PATH installs global packages to
87
87
  ${t}
88
88
  The devecocli binary in PATH does not match the npm that \`devecocli update\` uses.
89
89
  The update would land in the wrong place and would not reach the binary you are running.
90
90
  Continuing with update \u2014 abort if this is unexpected.
91
- 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 em=new BA("update").description("Update deveco-cli to latest");em.command("_check",{hidden:!0}).action(async()=>{let n=Date.now(),e=new en(Qp.join(F(),"update"));try{let t=Qr(),r=Oi();m(`Executing: npm view ${r}@${t} --json`);let{stdout:i}=await ll("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,ir(),t,a),await Tv(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 Tv(n,!1,i)}});async function WA(){let n=_t(),{latest:e,compatible:t}=await no(n);return{latestDocsVersion:e.version,latestDocsApiVersion:e.apiVersion,latestCompatibleDocsVersion:t?.version??null,checkedAgainstDocsApi:n}}function VA(n,e){let t=ol(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 GA={event:v.CommandExecuted,args:["update"]},qA={event:v.CommandExecuted,args:["update","_check"]};async function Zp(n,e,t){let r={duration_ms:Date.now()-n,success:e,error_code:t};await R.track(GA,r).catch(()=>{})}async function Tv(n,e,t){let r={duration_ms:Date.now()-n,success:e,error_code:t};await R.track(qA,r).catch(()=>{})}async function zA(n,e,t){let r=t,i=r.code??r.name??"UnknownError";console.error(Av(`Failed to update ${n}`)),r.message&&console.error(Av(r.message)),await Zp(e,!1,i),process.exit(1)}em.action(async()=>{if(Ni()==="all")throw new Error("devecocli update is disabled (DEVECO_CLI_DISABLE_UPDATE=all).");await Kp(Oi());let n=Date.now(),e=ir(),t=Qr(),r=Oi();console.log(cl("Checking for updates..."));try{let{stdout:i}=await ll("npm",["view",r,`dist-tags.${t}`]),o=i.trim();if(!o||o===e){console.log(Xp(`
92
- ${r} is already up to date (v${e}, tag: ${t})`)),await Zp(n,!0,null);return}console.log(cl(`
93
- New version found: ${o} (current: ${e})`)),console.log(cl(`Updating ${r}...`)),await ll("npm",["install","-g",`${r}@${t}`],{stdio:"inherit"}),console.log(Xp(`
94
- CLI successfully updated to ${o}`)),await JA(o).catch(s=>{m(`Docs auto-sync failed: ${s instanceof Error?s.message:String(s)}`)}),await Zp(n,!0,null)}catch(i){await zA(r,n,i)}});async function JA(n){let e=Oi();m(`Executing: npm view ${e}@${n} --json`);let{stdout:t}=await ll("npm",["view",`${e}@${n}`,"--json"]),r=ol(JSON.parse(t)),i=typeof r.supportedDocsApi=="number"?r.supportedDocsApi:_t(),{compatible:o}=await no(i);if(!o){m("Docs auto-sync: no compatible docs version found, skipping");return}let s=Qp.join(F(),"doc-data"),a=await Li();(!a||Zr(o.version,a)>0)&&await sl({version:o.version,apiVersion:o.apiVersion,dist:o.dist},s,"cli-update"),console.log(Xp(`Docs has been automatically synced to the compatible version ${o.version}`));let c=await no(i).catch(()=>null);c?.compatible&&Zr(c.compatible.version,o.version)>0&&console.log(cl(`New docs version ${c.compatible.version} available, run \`devecocli docs update\` to upgrade`))}var Ov=em;import{Command as xN,Option as bb}from"commander";import{execa as dl}from"execa";function _e(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}function Nv(n){let e=n.normalize("NFKC").match(/\((\d+)(?:\.\d+)*\)/)?.[1];return e!==void 0&&Number(e)>=26}import{spawn as YA}from"child_process";var KA=2500;function XA(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 ZA(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)),XA(n,l,s,a,c,o)}function Mv(n,e,t){m(`Spawning emulator: ${n} ${t.join(" ")}`);let r=[],i=YA(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&&!Xe()?Hi(i.pid,500,!0):void 0,s=new Promise((a,c)=>{ZA(i,r,a,c)});return{pid:i.pid,started:s,tracker:o}}import*as oo from"path";function QA(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 eT(n){let e=n.instancePath?.trim();if(e)return oo.dirname(oo.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?oo.dirname(oo.normalize(t)).replace(/\\/g,"/"):""}function tT(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function Lv(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 rT(n,e,t,r){let i=[Lv(["-start",n],t,r)],o=eT(e);if(o)for(let s of tT(e.imageRoot))i.push(Lv(["-hvd",n,"-path",o,...s],t,r));return QA(i)}async function _v(n,e,t,r,i){let o=new Error("No start strategy ran"),s=rT(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 nT(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 tm(n){return(await le.withHdcPath(n).listDevices()).map(t=>t.serial).filter(sr)}async function rm(n){let e=await tm(n);return e.length===0?[]:(await Promise.all(e.map(r=>Rc(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function $v(n,e){return(await rm(n)).includes(e)}async function Fv(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||!sr(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=nT(s.stdout);if(a!==void 0)return a}throw new Error(`Cannot determine the battery charging state for emulator "${e}".`)}import*as ao from"path";import{existsSync as iT,statSync as oT}from"fs";function so(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function sT(n){let e=so(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 aT(n){return so(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function cT(n,e){for(let t of e){let r=n[t];if(!(r==null||r===""))return r===!0||String(r).toLowerCase()==="true"}}function lT(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=ao.dirname(ao.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let i=E.ensurePathWithinRoot(t,ao.join(t,r.name));iT(i)&&oT(i).isDirectory()&&(r.instancePath=i.replace(/\\/g,"/"))}}function dT(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=aT(t),i=so(t,["deviceType","DeviceType","devicetype"]),o=so(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:sT(t),path:so(t,["path","Path","hvdPath","hvd_path"]),imageRoot:so(t,["imageRoot","image_root","ImageRoot"]),uuid:r||void 0,deviceType:i||void 0,osVersion:o||void 0,hotBoot:cT(t,["isHotBoot","ishotboot","hotBoot"])}}).filter(t=>t.name):null}catch{return null}}function uT(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 jv(n){let t=dT(n)??uT(n);return lT(t),t}function nm(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function pT(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function mT(n){let e=nm(n,["osVersion","OsVersion","OSVersion"]),t=nm(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=nm(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function Hv(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=mT(s);a&&i.push(a)}return i}catch{return[]}}function Uv(n){return Hv(n)}function Bv(n){return Hv(n,pT)}var Wv=/no images are available/i,fT=/Scenario simulation failed\s*[::]/i,hT="7.0.0";function Nr(n){return n.normalize("NFKC").trim().toLowerCase()}function gT(n){let e=n.message||"";return Wv.test(e)}function yT(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function Ds(n,e){return`${n} ${e.join(" ")}`.trim()}function wT(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 co=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: ${Ds(this.emulatorPath,e)}`),dl(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return Mv(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 jv(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(_e(r.name),r.deviceType)}catch{}return e}async startEmulator(e,t){let r=await this.listEmulators(),i=_e(e),o=r.find(c=>_e(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 _v(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.
91
+ 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 em=new BI("update").description("Update deveco-cli to latest");em.command("_check",{hidden:!0}).action(async()=>{let n=Date.now(),e=new rn(Qp.join(F(),"update"));try{let t=tn(),r=Ni();m(`Executing: npm view ${r}@${t} --json`);let{stdout:i}=await dl("npm",["view",`${r}@${t}`,"--json"]),{latestVersion:o,blockedVersions:s}=VI(i,t),a=await WI().catch(c=>{m(`Docs version check failed: ${c instanceof Error?c.message:String(c)}`)});await e.writeSuccess(o,s,or(),t,a),await Tv(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 Tv(n,!1,i)}});async function WI(){let n=_t(),{latest:e,compatible:t}=await io(n);return{latestDocsVersion:e.version,latestDocsApiVersion:e.apiVersion,latestCompatibleDocsVersion:t?.version??null,checkedAgainstDocsApi:n}}function VI(n,e){let t=sl(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 GI={event:v.CommandExecuted,args:["update"]},qI={event:v.CommandExecuted,args:["update","_check"]};async function Zp(n,e,t){let r={duration_ms:Date.now()-n,success:e,error_code:t};await D.track(GI,r).catch(()=>{})}async function Tv(n,e,t){let r={duration_ms:Date.now()-n,success:e,error_code:t};await D.track(qI,r).catch(()=>{})}async function zI(n,e,t){let r=t,i=r.code??r.name??"UnknownError";console.error(Iv(`Failed to update ${n}`)),r.message&&console.error(Iv(r.message)),await Zp(e,!1,i),process.exit(1)}em.action(async()=>{if(Mi()==="all")throw new Error("devecocli update is disabled (DEVECO_CLI_DISABLE_UPDATE=all).");await Kp(Ni());let n=Date.now(),e=or(),t=tn(),r=Ni();console.log(ll("Checking for updates..."));try{let{stdout:i}=await dl("npm",["view",r,`dist-tags.${t}`]),o=i.trim();if(!o||o===e){console.log(Xp(`
92
+ ${r} is already up to date (v${e}, tag: ${t})`)),await Zp(n,!0,null);return}console.log(ll(`
93
+ New version found: ${o} (current: ${e})`)),console.log(ll(`Updating ${r}...`)),await dl("npm",["install","-g",`${r}@${t}`],{stdio:"inherit"}),console.log(Xp(`
94
+ CLI successfully updated to ${o}`)),await JI(o).catch(s=>{m(`Docs auto-sync failed: ${s instanceof Error?s.message:String(s)}`)}),await Zp(n,!0,null)}catch(i){await zI(r,n,i)}});async function JI(n){let e=Ni();m(`Executing: npm view ${e}@${n} --json`);let{stdout:t}=await dl("npm",["view",`${e}@${n}`,"--json"]),r=sl(JSON.parse(t)),i=typeof r.supportedDocsApi=="number"?r.supportedDocsApi:_t(),{compatible:o}=await io(i);if(!o){m("Docs auto-sync: no compatible docs version found, skipping");return}let s=Qp.join(F(),"doc-data"),a=await _i();(!a||en(o.version,a)>0)&&await al({version:o.version,apiVersion:o.apiVersion,dist:o.dist},s,"cli-update"),console.log(Xp(`Docs has been automatically synced to the compatible version ${o.version}`));let c=await io(i).catch(()=>null);c?.compatible&&en(c.compatible.version,o.version)>0&&console.log(ll(`New docs version ${c.compatible.version} available, run \`devecocli docs update\` to upgrade`))}var Ov=em;import{Command as xN,Option as bb}from"commander";import{execa as ul}from"execa";function _e(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}function Nv(n){let e=n.normalize("NFKC").match(/\((\d+)(?:\.\d+)*\)/)?.[1];return e!==void 0&&Number(e)>=26}import{spawn as YI}from"child_process";var KI=2500;function XI(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 ZI(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,KI);n.once("error",d=>c(d.message)),XI(n,l,s,a,c,o)}function Mv(n,e,t){m(`Spawning emulator: ${n} ${t.join(" ")}`);let r=[],i=YI(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&&!Xe()?Ui(i.pid,500,!0):void 0,s=new Promise((a,c)=>{ZI(i,r,a,c)});return{pid:i.pid,started:s,tracker:o}}import*as so from"path";function QI(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 eT(n){let e=n.instancePath?.trim();if(e)return so.dirname(so.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?so.dirname(so.normalize(t)).replace(/\\/g,"/"):""}function tT(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function Lv(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 rT(n,e,t,r){let i=[Lv(["-start",n],t,r)],o=eT(e);if(o)for(let s of tT(e.imageRoot))i.push(Lv(["-hvd",n,"-path",o,...s],t,r));return QI(i)}async function _v(n,e,t,r,i){let o=new Error("No start strategy ran"),s=rT(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 nT(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 tm(n){return(await ce.withHdcPath(n).listDevices()).map(t=>t.serial).filter(cr)}async function rm(n){let e=await tm(n);return e.length===0?[]:(await Promise.all(e.map(r=>Ac(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function $v(n,e){return(await rm(n)).includes(e)}async function Fv(n,e){let t=await ce.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||!cr(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=nT(s.stdout);if(a!==void 0)return a}throw new Error(`Cannot determine the battery charging state for emulator "${e}".`)}import*as co from"path";import{existsSync as iT,statSync as oT}from"fs";function ao(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function sT(n){let e=ao(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 aT(n){return ao(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function cT(n,e){for(let t of e){let r=n[t];if(!(r==null||r===""))return r===!0||String(r).toLowerCase()==="true"}}function lT(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=co.dirname(co.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let i=E.ensurePathWithinRoot(t,co.join(t,r.name));iT(i)&&oT(i).isDirectory()&&(r.instancePath=i.replace(/\\/g,"/"))}}function dT(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=aT(t),i=ao(t,["deviceType","DeviceType","devicetype"]),o=ao(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:sT(t),path:ao(t,["path","Path","hvdPath","hvd_path"]),imageRoot:ao(t,["imageRoot","image_root","ImageRoot"]),uuid:r||void 0,deviceType:i||void 0,osVersion:o||void 0,hotBoot:cT(t,["isHotBoot","ishotboot","hotBoot"])}}).filter(t=>t.name):null}catch{return null}}function uT(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 jv(n){let t=dT(n)??uT(n);return lT(t),t}function nm(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function pT(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function mT(n){let e=nm(n,["osVersion","OsVersion","OSVersion"]),t=nm(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=nm(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function Hv(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=mT(s);a&&i.push(a)}return i}catch{return[]}}function Uv(n){return Hv(n)}function Bv(n){return Hv(n,pT)}var Wv=/no images are available/i,fT=/Scenario simulation failed\s*[::]/i,hT="7.0.0";function Lr(n){return n.normalize("NFKC").trim().toLowerCase()}function gT(n){let e=n.message||"";return Wv.test(e)}function yT(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function xs(n,e){return`${n} ${e.join(" ")}`.trim()}function wT(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 lo=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: ${xs(this.emulatorPath,e)}`),ul(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return Mv(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 jv(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(_e(r.name),r.deviceType)}catch{}return e}async startEmulator(e,t){let r=await this.listEmulators(),i=_e(e),o=r.find(c=>_e(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 _v(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.
95
95
  Last error: ${a.lastError.message||"unknown"}`,`Unable to start emulator. All methods failed.
96
- 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:$v(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=_e(e),i=t.find(a=>_e(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 Fv(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 ${wT(t)} -> ${Ds(this.emulatorPath,o)}`),await this.runEmulatorChecked(o,{extraReject:t.type==="folded-state"?[fT]:void 0,printOutputOnSuccess:!1})}async assertControlCommandSupported(){let e=this.emulatorPath;if(n.supportedControlPaths.has(e))return;let t=["-version"];m(`Executing: ${Ds(this.emulatorPath,t)}`);let{stdout:r,stderr:i,exitCode:o}=await dl(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(`
97
- `).trim(),a=yT(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,hT)<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: ${Ds(this.emulatorPath,e)}`);let{exitCode:t}=await dl(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=Nr(e.deviceType),i=Nr(e.osVersion);return Uv(t).some(o=>Nr(o.deviceType)===r&&Nr(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(!gT(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}
98
- `:"";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=Bv(t),i=Nr(e.deviceType),o=Nr(e.osVersion);return r.filter(s=>Nr(s.deviceType)===i&&(Nr(s.osVersion)===o||Nr(s.softwareVersion)===o))}async runUninstallImageChecked(e,t){await this.runEmulatorChecked(["-uninstall","-deviceType",e,"-osVersion",t,"-force"],{printOutputOnSuccess:!0,extraReject:[Wv]})}async runEmulatorChecked(e,t){m(`Executing: ${Ds(this.emulatorPath,e)}`);let{stdout:r,stderr:i,exitCode:o}=await dl(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
+ 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:$v(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=_e(e),i=t.find(a=>_e(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 Fv(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 ${wT(t)} -> ${xs(this.emulatorPath,o)}`),await this.runEmulatorChecked(o,{extraReject:t.type==="folded-state"?[fT]:void 0,printOutputOnSuccess:!1})}async assertControlCommandSupported(){let e=this.emulatorPath;if(n.supportedControlPaths.has(e))return;let t=["-version"];m(`Executing: ${xs(this.emulatorPath,t)}`);let{stdout:r,stderr:i,exitCode:o}=await ul(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(`
97
+ `).trim(),a=yT(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,hT)<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: ${xs(this.emulatorPath,e)}`);let{exitCode:t}=await ul(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=Lr(e.deviceType),i=Lr(e.osVersion);return Uv(t).some(o=>Lr(o.deviceType)===r&&Lr(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(!gT(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}
98
+ `:"";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=Bv(t),i=Lr(e.deviceType),o=Lr(e.osVersion);return r.filter(s=>Lr(s.deviceType)===i&&(Lr(s.osVersion)===o||Lr(s.softwareVersion)===o))}async runUninstallImageChecked(e,t){await this.runEmulatorChecked(["-uninstall","-deviceType",e,"-osVersion",t,"-force"],{printOutputOnSuccess:!0,extraReject:[Wv]})}async runEmulatorChecked(e,t){m(`Executing: ${xs(this.emulatorPath,e)}`);let{stdout:r,stderr:i,exitCode:o}=await ul(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(`
99
99
  `).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=_e(e.name),i=t.find(o=>_e(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??(Nv(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(`
100
100
  `)}),!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=>_e(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=_e(e),o=r.find(c=>_e(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}
101
- 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 IN,gray as AN}from"colorette";import TN from"ora";import{green as vT}from"colorette";var bT=[[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]],ST=[[0,31],[127,159],[768,879],[6832,6911],[7616,7679],[8203,8207],[8400,8447],[65024,65039],[65056,65071],[8205,8205]],ET=new RegExp("\x1B\\[([0-9;]*)[a-zA-Z]","g");function Vv(n,e){for(let[t,r]of e)if(n>=t&&n<=r)return!0;return!1}function im(n){let e=n.replace(ET,""),t=0,r=0;for(;r<e.length;){let i=e.codePointAt(r);if(i===void 0)break;Vv(i,ST)||(Vv(i,bT)?t+=2:t+=1),r+=i>65535?2:1}return t}function Gv(n,e){let t=im(n);return n+" ".repeat(Math.max(0,e-t))}function PT(n,e){return n.map((t,r)=>{let i=im(t);for(let o of e){let s=o.cells[r]??"";i=Math.max(i,im(s))}return i})}function Mr(n,e){let t=PT(n,e),r=[];r.push(n.map((i,o)=>Gv(i,t[o])).join(" ")),r.push(t.map(i=>"-".repeat(i)).join(" "));for(let i of e){let o=i.cells.map((s,a)=>Gv(s??"",t[a])).join(" ").trimEnd();r.push(i.highlight?vT(o):o)}return r.join(`
102
- `)}import{red as CT}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(CT(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await R.track(n,o)}}async function N(){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 kT,Option as dm}from"commander";import{yellow as um}from"colorette";import{existsSync as zv}from"fs";import Lr from"ora";function qv(n,e){let t=n.match(e);return t?t[1]:void 0}function om(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:qv(r,/app name \[([^\]]+)\]/),abilityName:qv(r,/main name \[([^\]]+)\]/)})}return e}function sm(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 am(n){let e=n.indexOf("{");if(e===-1)return null;try{return JSON.parse(n.slice(e))}catch{return null}}function cm(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 lm(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 dr=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 DT(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(um("No installed apps found."))}async function RT(n,e,t="default"){let r=await T(n,e),i=new dr(n.hdcPath),o=Lr({text:"Listing installed apps...",color:"cyan"}).start();try{let s=await i.listInstalledApps(r);o.stop();let a=sm(s);DT(a,t)}catch(s){throw o.stop(),new y(`Failed to list apps: ${s.message}`,"Failed to list apps.")}}function xT(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"?"[]":um("No foreground app."))}async function IT(n,e,t="default"){let r=await T(n,e),i=new dr(n.hdcPath),o=Lr({text:"Querying foreground app...",color:"cyan"}).start();try{let s=await i.getForegroundApp(r);o.stop();let a=om(s);xT(a,t)}catch(s){throw o.stop(),new y(`Failed to get foreground app: ${s.message}`,"Failed to get foreground app.")}}async function AT(n,e,t,r="default"){let i=await T(n,t),o=new dr(n.hdcPath),s=Lr({text:`Querying app info for ${e}...`,color:"cyan"}).start();try{let a=await o.getAppInfo(i,e);s.stop();let c=am(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=lm(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 TT(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 dr(n.hdcPath),i=e.bundle??"(no bundle)",o=Lr({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}=cm(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 OT(n,e){let t=await T(n,e.device),r=new de(n),i=Lr({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 NT(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(!zv(t))throw new y(`HAP file not found: ${t}`,"HAP file not found.");if(e.shared){for(let t of e.shared)if(!zv(t))throw new y(`Shared HSP file not found: ${t}`,"Shared HSP file not found.")}}function MT(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 LT(n,e,t){let r=await T(n,t.device);NT(e,t);let i={replace:t.replace,shared:t.shared,wait:t.wait,user:t.user},o=new de(n),s=MT(e,t),a=Lr({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 _T(n,e){let t=await T(n,e.device),r=new de(n),i=Lr({text:`Uninstalling ${e.bundle}...`,color:"cyan"}).start();try{let o=await r.uninstallApp(t,e.bundle);i.stop(),console.log(o?`Uninstalled ${e.bundle}.`:um(`${e.bundle} was not installed.`))}catch(o){throw i.stop(),new y(`Failed to uninstall app: ${o.message}`,"Failed to uninstall app.")}}async function $T(n,e){E.assertBundleNameStrict(e.bundle);let t=await T(n,e.device),r=new dr(n.hdcPath),i=Lr({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 FT(n,e){E.assertBundleNameStrict(e.bundle);let t=await T(n,e.device),r=new dr(n.hdcPath),i=Lr({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 Ut=new kT("app").description("Manage apps on a connected device");Ut.command("list").description("List installed apps").option("--device <name|serial>","Target device (name or serial)").addOption(new dm("--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 N();await RT(i,e,t)})});Ut.command("foreground").description("Show current foreground app info").option("--device <name|serial>","Target device (name or serial)").addOption(new dm("--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 N();await IT(i,e,t)})});Ut.command("info").description("Show app info").option("--device <name|serial>","Target device (name or serial)").addOption(new dm("--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 N();await AT(o,n,t,r)})});Ut.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 N();await TT(t,n)})});Ut.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 N();await LT(r,n,e)})});Ut.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 N();await _T(t,n)})});Ut.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 N();await OT(t,n)})});Ut.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 N();await $T(t,n)})});Ut.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 N();await FT(t,n)})});import{Command as cn}from"commander";import{red as Jv,yellow as jT}from"colorette";import ln from"ora";function We(n){let e=`${n.stdout}
103
- ${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 gt=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 We(t),t.stdout}async setTime(e,t){let r=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","set-time",t]);return We(r),r.stdout}async getTimezone(e){let t=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","get-timezone"]);return We(t),t.stdout}async setTimezone(e,t){let r=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","set-timezone",t]);return We(r),r.stdout}};function ni(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 pm(n){let e=n.match(/Current State:\s*(\w+)/);return e?e[1]:null}var lo=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 HT=["phone","tablet"];async function mm(n,e){let i=(await new gt(n).getDeviceType(e)).trim().toLowerCase();if(!HT.includes(i))throw new y(`This command is only supported on phone and tablet devices (current: ${i||"unknown"}).`,"Unsupported device type.")}async function UT(n,e){let t=await T(n,e),r=new gt(n),i=ln({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 BT(n,e){let t=await T(n,e),r=new gt(n),i=ln({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 WT(n,e){let t=await T(n,e),r=new gt(n),i=ln({text:"Querying screen status...",color:"cyan"}).start();try{let o=await r.getScreenStatus(t);i.stop();let s=pm(o);console.log(s?` Screen State: ${s}`:jT("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 VT(n,e){let t=await T(n,e);await mm(n,t);let r=new gt(n),i=ln({text:"Unlocking screen...",color:"cyan"}).start();try{await r.wakeScreen(t);let o=await r.getDisplayInfo(t),s=ni(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 GT(n,e){let t=await T(n,e);await mm(n,t);let r=new gt(n),i=ln({text:"Opening control center...",color:"cyan"}).start();try{let o=await r.getDisplayInfo(t),s=ni(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 qT(n,e){let t=await T(n,e);await mm(n,t);let r=new gt(n),i=ln({text:"Opening notification center...",color:"cyan"}).start();try{let o=await r.getDisplayInfo(t),s=ni(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 zT=/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;async function JT(n,e,t){let r=await T(n,t),i=new gt(n),o=e!==void 0;if(o&&!zT.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=ln({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(Jv(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 YT(n,e,t){let r=await T(n,t),i=new gt(n),o=e!==void 0,s=ln({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(Jv(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 Yv=[new cn("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 N();await UT(r,e)})}),new cn("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 N();await BT(r,e)})}),new cn("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 N();await WT(r,e)})}),new cn("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 N();await VT(r,e)})}),new cn("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 N();await GT(r,e)})}),new cn("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 N();await qT(r,e)})}),new cn("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 N();await JT(i,n,t)})}),new cn("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 N();await YT(i,n,t)})})];import{Command as nN,Option as iN}from"commander";import{yellow as oN}from"colorette";import Bs from"ora";import{appendFileSync as F4}from"fs";var Bt={TRACE:10,DEBUG:20,INFO:30,WARN:40,ERROR:50,SILENT:100},Xv={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",100:"SILENT"};function fm(n){if(typeof n=="number")return n;let e=String(n||"").toUpperCase();return e in Bt?Bt[e]:Bt.INFO}function KT(n){return{write:n}}function XT({useStderr:n}={}){return KT((e,t)=>{let r=`${ZT[Xv[e.level]]||""}${t}`;n||e.level>=Bt.ERROR?process.stderr.write(r+`
101
+ 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 AN,gray as IN}from"colorette";import TN from"ora";import{green as vT}from"colorette";var bT=[[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]],ST=[[0,31],[127,159],[768,879],[6832,6911],[7616,7679],[8203,8207],[8400,8447],[65024,65039],[65056,65071],[8205,8205]],ET=new RegExp("\x1B\\[([0-9;]*)[a-zA-Z]","g");function Vv(n,e){for(let[t,r]of e)if(n>=t&&n<=r)return!0;return!1}function im(n){let e=n.replace(ET,""),t=0,r=0;for(;r<e.length;){let i=e.codePointAt(r);if(i===void 0)break;Vv(i,ST)||(Vv(i,bT)?t+=2:t+=1),r+=i>65535?2:1}return t}function Gv(n,e){let t=im(n);return n+" ".repeat(Math.max(0,e-t))}function PT(n,e){return n.map((t,r)=>{let i=im(t);for(let o of e){let s=o.cells[r]??"";i=Math.max(i,im(s))}return i})}function _r(n,e){let t=PT(n,e),r=[];r.push(n.map((i,o)=>Gv(i,t[o])).join(" ")),r.push(t.map(i=>"-".repeat(i)).join(" "));for(let i of e){let o=i.cells.map((s,a)=>Gv(s??"",t[a])).join(" ").trimEnd();r.push(i.highlight?vT(o):o)}return r.join(`
102
+ `)}import{red as CT}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(CT(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 N(){try{let n=await P.new();return{manager:ce.from(n),toolProvider:n}}catch(n){throw new y(`Failed to initialize device manager: ${n.message}`,"Failed to initialize device manager.")}}import{Command as kT,Option as dm}from"commander";import{yellow as um}from"colorette";import{existsSync as zv}from"fs";import $r from"ora";function qv(n,e){let t=n.match(e);return t?t[1]:void 0}function om(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:qv(r,/app name \[([^\]]+)\]/),abilityName:qv(r,/main name \[([^\]]+)\]/)})}return e}function sm(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 am(n){let e=n.indexOf("{");if(e===-1)return null;try{return JSON.parse(n.slice(e))}catch{return null}}function cm(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 lm(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 ur=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 DT(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(um("No installed apps found."))}async function RT(n,e,t="default"){let r=await T(n,e),i=new ur(n.hdcPath),o=$r({text:"Listing installed apps...",color:"cyan"}).start();try{let s=await i.listInstalledApps(r);o.stop();let a=sm(s);DT(a,t)}catch(s){throw o.stop(),new y(`Failed to list apps: ${s.message}`,"Failed to list apps.")}}function xT(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"?"[]":um("No foreground app."))}async function AT(n,e,t="default"){let r=await T(n,e),i=new ur(n.hdcPath),o=$r({text:"Querying foreground app...",color:"cyan"}).start();try{let s=await i.getForegroundApp(r);o.stop();let a=om(s);xT(a,t)}catch(s){throw o.stop(),new y(`Failed to get foreground app: ${s.message}`,"Failed to get foreground app.")}}async function IT(n,e,t,r="default"){let i=await T(n,t),o=new ur(n.hdcPath),s=$r({text:`Querying app info for ${e}...`,color:"cyan"}).start();try{let a=await o.getAppInfo(i,e);s.stop();let c=am(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=lm(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 TT(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 ur(n.hdcPath),i=e.bundle??"(no bundle)",o=$r({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}=cm(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 OT(n,e){let t=await T(n,e.device),r=new le(n),i=$r({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 NT(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(!zv(t))throw new y(`HAP file not found: ${t}`,"HAP file not found.");if(e.shared){for(let t of e.shared)if(!zv(t))throw new y(`Shared HSP file not found: ${t}`,"Shared HSP file not found.")}}function MT(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 LT(n,e,t){let r=await T(n,t.device);NT(e,t);let i={replace:t.replace,shared:t.shared,wait:t.wait,user:t.user},o=new le(n),s=MT(e,t),a=$r({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 _T(n,e){let t=await T(n,e.device),r=new le(n),i=$r({text:`Uninstalling ${e.bundle}...`,color:"cyan"}).start();try{let o=await r.uninstallApp(t,e.bundle);i.stop(),console.log(o?`Uninstalled ${e.bundle}.`:um(`${e.bundle} was not installed.`))}catch(o){throw i.stop(),new y(`Failed to uninstall app: ${o.message}`,"Failed to uninstall app.")}}async function $T(n,e){E.assertBundleNameStrict(e.bundle);let t=await T(n,e.device),r=new ur(n.hdcPath),i=$r({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 FT(n,e){E.assertBundleNameStrict(e.bundle);let t=await T(n,e.device),r=new ur(n.hdcPath),i=$r({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 Bt=new kT("app").description("Manage apps on a connected device");Bt.command("list").description("List installed apps").option("--device <name|serial>","Target device (name or serial)").addOption(new dm("--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 N();await RT(i,e,t)})});Bt.command("foreground").description("Show current foreground app info").option("--device <name|serial>","Target device (name or serial)").addOption(new dm("--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 N();await AT(i,e,t)})});Bt.command("info").description("Show app info").option("--device <name|serial>","Target device (name or serial)").addOption(new dm("--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 N();await IT(o,n,t,r)})});Bt.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 N();await TT(t,n)})});Bt.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 N();await LT(r,n,e)})});Bt.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 N();await _T(t,n)})});Bt.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 N();await OT(t,n)})});Bt.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 N();await $T(t,n)})});Bt.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 N();await FT(t,n)})});import{Command as dn}from"commander";import{red as Jv,yellow as jT}from"colorette";import un from"ora";function We(n){let e=`${n.stdout}
103
+ ${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 gt=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 We(t),t.stdout}async setTime(e,t){let r=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","set-time",t]);return We(r),r.stdout}async getTimezone(e){let t=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","get-timezone"]);return We(t),t.stdout}async setTimezone(e,t){let r=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","set-timezone",t]);return We(r),r.stdout}};function ii(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 pm(n){let e=n.match(/Current State:\s*(\w+)/);return e?e[1]:null}var uo=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 HT=["phone","tablet"];async function mm(n,e){let i=(await new gt(n).getDeviceType(e)).trim().toLowerCase();if(!HT.includes(i))throw new y(`This command is only supported on phone and tablet devices (current: ${i||"unknown"}).`,"Unsupported device type.")}async function UT(n,e){let t=await T(n,e),r=new gt(n),i=un({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 BT(n,e){let t=await T(n,e),r=new gt(n),i=un({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 WT(n,e){let t=await T(n,e),r=new gt(n),i=un({text:"Querying screen status...",color:"cyan"}).start();try{let o=await r.getScreenStatus(t);i.stop();let s=pm(o);console.log(s?` Screen State: ${s}`:jT("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 VT(n,e){let t=await T(n,e);await mm(n,t);let r=new gt(n),i=un({text:"Unlocking screen...",color:"cyan"}).start();try{await r.wakeScreen(t);let o=await r.getDisplayInfo(t),s=ii(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 GT(n,e){let t=await T(n,e);await mm(n,t);let r=new gt(n),i=un({text:"Opening control center...",color:"cyan"}).start();try{let o=await r.getDisplayInfo(t),s=ii(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 qT(n,e){let t=await T(n,e);await mm(n,t);let r=new gt(n),i=un({text:"Opening notification center...",color:"cyan"}).start();try{let o=await r.getDisplayInfo(t),s=ii(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 zT=/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;async function JT(n,e,t){let r=await T(n,t),i=new gt(n),o=e!==void 0;if(o&&!zT.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=un({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(Jv(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 YT(n,e,t){let r=await T(n,t),i=new gt(n),o=e!==void 0,s=un({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(Jv(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 Yv=[new dn("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 N();await UT(r,e)})}),new dn("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 N();await BT(r,e)})}),new dn("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 N();await WT(r,e)})}),new dn("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 N();await VT(r,e)})}),new dn("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 N();await GT(r,e)})}),new dn("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 N();await qT(r,e)})}),new dn("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 N();await JT(i,n,t)})}),new dn("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 N();await YT(i,n,t)})})];import{Command as nN,Option as iN}from"commander";import{yellow as oN}from"colorette";import Vs from"ora";import{appendFileSync as B4}from"fs";var Wt={TRACE:10,DEBUG:20,INFO:30,WARN:40,ERROR:50,SILENT:100},Xv={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",100:"SILENT"};function fm(n){if(typeof n=="number")return n;let e=String(n||"").toUpperCase();return e in Wt?Wt[e]:Wt.INFO}function KT(n){return{write:n}}function XT({useStderr:n}={}){return KT((e,t)=>{let r=`${ZT[Xv[e.level]]||""}${t}`;n||e.level>=Wt.ERROR?process.stderr.write(r+`
104
104
  `):process.stdout.write(r+`
105
- `)})}var ZT={TRACE:"",DEBUG:"",INFO:"",WARN:"",ERROR:""};function QT(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 Rs=class n{name;level;transports;fields;timestamp;constructor(e={}){this.name=e.name||"hm",this.level=fm(e.level??"info"),this.transports=e.transports||[XT()],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=fm(e),this}addTransport(e){return this.transports.push(e),this}isLevelEnabled(e){return fm(e)>=this.level}trace(e,...t){this._log(Bt.TRACE,e,t)}debug(e,...t){this._log(Bt.DEBUG,e,t)}info(e,...t){this._log(Bt.INFO,e,t)}warn(e,...t){this._log(Bt.WARN,e,t)}error(e,...t){this._log(Bt.ERROR,e,t)}timeStart(e,t=Bt.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:Kv(t),r&&r.length&&(i+=" "+r.map(l=>l instanceof Error?`${l.name}: ${l.message}`:typeof l=="string"?l:Kv(l)).join(" "))}catch{i=String(t)}let o=eO(this.fields),a=`${this.timestamp?`[${QT(Date.now())}] `:""}[${Xv[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 eO(n){let e=Object.keys(n||{});return e.length?" "+e.map(t=>`${t}=${n[t]}`).join(" "):""}function Kv(n){try{return JSON.stringify(n)}catch{return String(n)}}var hm=new Rs({name:"hm",level:"info"});function gm(n={}){return hm=new Rs({name:"hm",...n}),hm}function xs(n){return hm.child(n,{})}import{spawn as tO}from"child_process";var uo=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}}},ii=class extends uo{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||""}},dn=class extends ii{static code="HDC_TIMEOUT";constructor(e,t={}){super(e,{...t,code:"HDC_TIMEOUT"})}},Is=class extends ii{static code="HDC_COMMAND_FAILED";constructor(e,t={}){super(e,{...t,code:"HDC_COMMAND_FAILED"})}},Dt=class extends uo{static code="DEVICE_ERROR";constructor(e,t={}){super(e,{...t,code:t.code||"DEVICE_ERROR"})}},un=class extends Dt{static code="DEVICE_NOT_FOUND";constructor(e,t={}){super(e,{...t,code:"DEVICE_NOT_FOUND"})}},pn=class extends Dt{static code="DEVICE_FILE_ERROR";constructor(e,t={}){super(e,{...t,code:"DEVICE_FILE_ERROR"})}},ur=class extends uo{static code="RPC_ERROR";endpoint;constructor(e,t={}){super(e,{...t,code:t.code||"RPC_ERROR"}),this.endpoint=t.details?.endpoint||""}},pr=class extends ur{static code="RPC_LIFECYCLE_ERROR";constructor(e,t={}){super(e,{...t,code:"RPC_LIFECYCLE_ERROR"})}},_r=class extends pr{static code="RPC_DISPOSED";constructor(e,t={}){super(e,{...t,code:"RPC_DISPOSED"})}},$e=class extends ur{static code="RPC_TRANSPORT_ERROR";constructor(e,t={}){super(e,{...t,code:"RPC_TRANSPORT_ERROR"})}},mn=class extends ur{static code="RPC_TIMEOUT";constructor(e,t={}){super(e,{...t,code:"RPC_TIMEOUT"})}},Wt=class extends ur{static code="RPC_PROTOCOL_ERROR";constructor(e,t={}){super(e,{...t,code:"RPC_PROTOCOL_ERROR"})}},As=class extends ur{static code="RPC_REMOTE_ERROR";remote;constructor(e,t={}){super(e,{...t,code:"RPC_REMOTE_ERROR"}),this.remote=t.details?.remote}};function Zv(n){return n instanceof $e||n instanceof mn||n instanceof Wt}function ym(n){return n instanceof _r?!1:Zv(n)||n instanceof pr}var Ts=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 Is(`${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}},Os=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 ii("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 Qv(t.stdout)}};function Qv(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 wm(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 vm(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 oi=class extends Os{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(" ")}`),tO(this.bin,e,{env:t,stdio:["ignore","pipe","pipe"],windowsHide:this.windowsHide})}catch(o){return r&&r({ok:0}),i(new dn(`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(),h=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} (${h}ms)`),s.timedOut){c(new dn(`hdc ${t.join(" ")} timeout after ${r}ms`,{details:{args:t,stdout:l,stderr:d}}));return}a(new Ts({args:t,code:e??-1,stdout:l,stderr:d,durationMs:h}))}handleChildError(e,t,r,i,o){i.settled||(i.settled=!0,i.timer&&clearTimeout(i.timer),r&&r({ok:0}),o(new dn(`hdc ${t.join(" ")} spawn error: ${e.message}`,{cause:e})))}};var eb=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}}),rO={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 pl(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function bm(n){if(typeof structuredClone=="function")try{return structuredClone(n)}catch{}return JSON.parse(JSON.stringify(n))}function ul(n,e){let t=bm(n);for(let[r,i]of Object.entries(e||{}))i!==void 0&&(pl(i)&&pl(t[r])?t[r]=ul(t[r],i):t[r]=bm(i));return t}function nO(n,e){return e.split(".").reduce((t,r)=>{if(!(t==null||typeof t!="object"))return t[r]},n)}function tb(n,e,t){let r=e.split("."),i=r.pop(),o=n;for(let s of r)pl(o[s])||(o[s]={}),o=o[s];return o[i]=t,n}var ml=class{_data;constructor(e={}){this._data=ul(eb,iO()),e&&Object.keys(e).length&&(this._data=ul(this._data,e))}slice(e){let t=this.get(e);return pl(t)?t:{}}get(e,t){let r=nO(this._data,e);return r===void 0?t:r}set(e,t){return tb(this._data,e,t),this}merge(e){return this._data=ul(this._data,e),this}snapshot(){return bm(this._data)}toJSON(){return this.snapshot()}};function iO(){let n={};for(let[e,t]of Object.entries(rO)){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}tb(n,t,i)}return n}function Ns(n){return new ml(n)}var fl=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:rb(this.records,"counter"),timers:rb(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 rb(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 hl=class n{enabled;tags;sinks;slowThresholdMs;logger;constructor(e={}){this.enabled=e.enabled!==!1,this.tags={...e.tags||{}},this.sinks=e.sinks||[new fl],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 fl);return e?e.snapshot():null}reset(){for(let e of this.sinks)typeof e.reset=="function"&&e.reset()}};function Ms(n={}){return new hl(n)}function po(n){return new Promise(e=>setTimeout(e,n))}async function gl(n,{timeoutMs:e,intervalMs:t=200,firstDelayMs:r=0,description:i="condition"}){let o=Date.now()+e;r>0&&await po(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 po(t)}}var mo=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()}}},fo=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()}},si=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 oO=64*1024*1024,Sm={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>oO||e<0)throw new Wt(`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 Wt(`response is not valid JSON: ${t.slice(0,200)}`)}return{value:r,rest:n.subarray(4+e)}}},yl={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 sO(n){if(!n||n.length===0)return null;let e=n[0];return e===123||e===91?"raw":"length-prefixed"}function Em(n="auto"){return n==="raw"?yl:n==="length-prefixed"?Sm:aO()}function aO(){let n=null;return{name:"auto",frameDelimited:!1,get detected(){return n},encode(e){return yl.encode(e)},decode(e){return n||(n=sO(e)),n==="length-prefixed"?Sm.decode(e):yl.decode(e)}}}var Pm=0;function mr(n="hm"){Pm=(Pm+1)%1e6;let e=new Date().toISOString().replace(/[-:T]/g,"").replace(/\..+/,""),t=Math.random().toString(36).slice(2,8);return`${n}-${e}-${Pm.toString(36)}-${t}`}import Cm from"net";function km(n,e,t=500){return new Promise(r=>{let i=new Cm.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 Dm({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 lO(n,o))return o}throw new Error(`no free port in range ${e}-${t}`)}var cO=Dm;function lO(n,e){return new Promise(t=>{let r=Cm.createServer();r.once("error",()=>t(!1)),r.once("listening",()=>{r.close(()=>t(!0))}),r.listen(e,n)})}async function dO({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 km(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 nb({hdcHost:n="127.0.0.1",start:e,end:t,exclude:r}={}){return!n||n==="127.0.0.1"||n==="localhost"?{port:await cO({host:n||"127.0.0.1",start:e,end:t,exclude:r}),scope:"local"}:{port:await dO({host:n,start:e,end:t,exclude:r,stepDelayMs:50}),scope:"remote"}}function wl({host:n,port:e,timeoutMs:t=5e3,keepAliveMs:r}){return new Promise((i,o)=>{let s=new Cm.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 Vt(n,e){let t=ib(n),r=ib(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 ib(n){return String(n||"").trim().split(/[.\-+_]/).filter(Boolean).map(e=>{let t=parseInt(e,10);return Number.isNaN(t)?0:t})}function ho(n){let e=/(\d+(?:\.\d+)+)/.exec(String(n||""));return e?e[1]:null}var uO=/^[A-Za-z0-9_@%+=:,./-]+$/,pO=/'/g,mO="'\\''";function ai(n){let e=n==null?"":String(n);return e===""?"''":uO.test(e)?e:`'${e.replace(pO,mO)}'`}function Rt(n){if(!Array.isArray(n))throw new TypeError("shellJoin expects an array of arguments");return n.filter(e=>e!=null&&e!=="").map(e=>ai(e)).join(" ")}function Rm(n){let e=String(n??"");if(/[\r\n\0]/.test(e))throw new fr("shell command must not contain newline or NUL characters");return e}function hr(n){let e=String(n??"").trim();if(!e)throw new fr("remote path is empty");if(!e.startsWith("/"))throw new fr(`remote path must be absolute: ${JSON.stringify(n)}`);if(/[\r\n\0]/.test(e))throw new fr("remote path must not contain newline or NUL characters");return e}function xm(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new fr(`invalid pid: ${JSON.stringify(n)}`);return e}function vl(n){let e=String(n??"").trim();if(!/^(localabstract|localfilesystem|tcp|jdwp):[A-Za-z0-9_.-]+$/.test(e))throw new fr(`invalid device endpoint: ${JSON.stringify(n)}`);return e}function bl(n){let e=Number(n);if(!Number.isInteger(e)||e<1||e>65535)throw new fr(`invalid host port: ${JSON.stringify(n)}`);return e}var fr=class extends Error{constructor(e){super(e),this.name="ShellSafetyError"}};import{stat as JO}from"fs/promises";var wO="6.0.2.2";async function ob(n,e={}){let t=e.minVersion||wO,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=vO(o)||o,a=Vt(s,t)>=0;return{version:s,arch:i,isNewUiTest:a,endpointStyle:a&&i!=="x86_64"?"unix":"tcp",fileOutput:r}}function vO(n){let e=/(\d+(?:\.\d+)+)/.exec(String(n||""));return e?e[1]:null}import{fileURLToPath as kO}from"url";import{dirname as DO,join as cb}from"path";import{readdirSync as bO}from"fs";import{join as SO,basename as N6}from"path";var EO=/^uitest_agent_v(\d+\.\d+\.\d+)(\.x86_64)?\.so$/,PO="/data/local/tmp/agent.so",Im="UITEST_AGENT_LIBRARY";function CO(n){let e;try{e=bO(n)}catch{return[]}return e.filter(t=>t.endsWith(".so"))}function sb({dir:n,arch:e,isNewUiTest:t}){let r=e==="x86_64",i=[];for(let s of CO(n)){let a=EO.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=Vt(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)=>Vt(a.version,s.version));let o=i[0];return{fileName:o.fileName,localPath:SO(n,o.fileName),version:o.version,x86_64:o.x86_64,remotePath:PO,versionProbe:Im}}function ab(n){let e=String(n||""),t=e.indexOf("#"),r=t>=0?e.slice(t+1):e;return ho(r)}var RO=cb(DO(kO(import.meta.url)),"..",".."),xO=cb(RO,"resources"),Sl=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")||xO}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=sb({dir:this.resourcesDir,arch:t.arch,isNewUiTest:t.isNewUiTest});if(!r)throw new Dt(`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||Vt(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 ${ai(e)} | ${Rt(["grep","-a",Im])}`);return ab(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 Am}from"path";import{mkdir as IO,readFile as lb,writeFile as db,unlink as AO,readdir as TO}from"fs/promises";function OO(n){return String(n||"unknown").replace(/[^A-Za-z0-9._-]/g,"_")}var NO=Am(F(),"fast-mode"),El=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 NO}pathFor(e){return Am(this.dir,`${OO(e)}.json`)}async _ensureDir(){await IO(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 db(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 lb(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 AO(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 db(this.pathFor(e),JSON.stringify(r,null,2),{mode:384}),!0):this.forget(e))}async list(){let e;try{e=await TO(this.dir)}catch{return[]}let t=[];for(let r of e)if(r.endsWith(".json"))try{t.push(JSON.parse(await lb(Am(this.dir,r),"utf8")))}catch{}return t}};var gr={AUTO:"auto",PIPELINED:"pipelined",SERIAL:"serial"},Ls=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=Em(e.framing||"auto"),this.frameDelimited=this.codec.frameDelimited===!0,this.concurrency=e.concurrency||gr.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 fo(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===gr.SERIAL?"serial":this.frameDelimited?this.concurrency===gr.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 wl({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 mn(`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 Wt?r:new Wt(`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 Wt(`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===gr.SERIAL||!this.frameDelimited?1:this.concurrency===gr.PIPELINED?this.maxInFlight:this._serverEchoesRequestId===!0?this.maxInFlight:1}_initialLimit(){return this.concurrency===gr.SERIAL||!this.frameDelimited?1:this.concurrency===gr.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=mr();for(;this.pending.has(t);)t=mr();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 mn(`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 Pl="com.ohos.devicetest.hypiumApiHelper",Tm="callHypiumApi";function Cl({module:n,method:e,params:t={},requestId:r}){return{module:n,method:e,params:t,request_id:r||mr()}}function kl(n){if(!n||typeof n!="object")return!1;let e=n.exception;return e!=null&&e!==""}function Dl(n){return n?n.result:void 0}var ke={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"},_s=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=ke.IDLE,this.transport=null,this._mutex=new mo,this._epoch=0,this._readyFlight=new si,this._resetFlight=new si,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===ke.READY&&!!this.transport&&this.transport.isConnected}async ensureReady(){if(this._disposed)throw new _r(`${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 _r(`${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 _r(`${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=ke.RESOURCES_READY,await this._ensureProcess(t),this.state=ke.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=ke.FORWARDED,await this._connectAndProbe(i,{probe:!0}),this.state=ke.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=ke.ERROR,t&&t({ok:0}),this.dfx&&this.dfx.counter("rpc.lifecycle.error",1,{code:e?.code||e?.name});let r=e instanceof ur?e:new pr(`${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=ke.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||Vt(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 ${ai(e.remotePath)} | ${Rt(["grep","-a",e.versionProbe])}`);if(!t)return null;let r=t.split("#"),i=r.length>1?r[r.length-1]:t;return ho(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 gl(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 pr(`${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 pr(`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 Ls({host:this.device.hdcHost,port:e,name:this.name,framing:this.config.get("rpc.framing","auto"),concurrency:this.config.get("rpc.concurrency",gr.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=ke.CONNECTED,t&&await this._probe()}_onTransportClose(e,t){this.transport===e&&(this._bumpEpoch(),(this.state===ke.READY||this.state===ke.CONNECTED)&&(this.state=this.mode==="fast"?ke.WARM:ke.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(kl(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 Dl(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 _r(`${this.name} rpc is disposed, request rejected`,{details:{endpoint:this.name}});let h=this._epoch;try{await this.ensureReady(),h=this._epoch;let w=await this._sendOnce(e,{timeoutMs:r});return this._logRecovered(c+l),w}catch(w){a=w;let D=await this._handleRequestError(w,o,s,h,c,l,i.delayMs);c=D.ownRecoveries,l=D.borrowedRecoveries}}throw a||new pr(`${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||!ym(e))throw e;return this._epoch===i?o=await this._attemptOwnRecovery(e,r,o):s=this._attemptBorrowedRecovery(e,r,s),a&&await po(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(kl(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 As(`remote exception: ${r}`,{details:{endpoint:this.name,remote:t}});throw this.dfx&&this.dfx.counter("rpc.request.remoteError",1,{endpoint:this.name}),i}return Dl(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=ke.IDLE}async release(){if(await this._safeCloseTransport("release"),this.mode==="fast"&&this.config.get("rpc.fast.keepOnRelease",!0)){this.state=ke.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=ke.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=ke.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 Om={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=>Rt(["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 | ${Rt(["grep",this.socketName])}`)).includes(this.socketName):(await n.shell(`netstat -anp | ${Rt(["grep",String(this.devicePort)])}`)).includes("LISTEN")}};var $s=class extends _s{constructor(e){super({...e,endpoint:Om})}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 Cl({module:Pl,method:"ping",params:{},requestId:mr()})}async call(e,t="",r=[],i={}){let o=Cl({module:Pl,method:Tm,params:{api:e,this:t,args:r,message_type:"hypium"},requestId:mr()});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 MO(n){if(n!==void 0)return Array.isArray(n)?{value:String(n[0]),pattern:n[1]}:{value:String(n)}}function Nm(n){return ub(n)}function ub(n){let e={};return n.text!==void 0&&(e.text=MO(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 pb(n){let e=ub(n);return n.isBefore&&(e.isBefore=Nm(n.isBefore)),n.isAfter&&(e.isAfter=Nm(n.isAfter)),n.within&&(e.within=Nm(n.within)),e}function LO(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 Ve=class n{spec;constructor(e={}){this.spec=e}static from(e){return new n(pb(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=LO(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 Fs=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 Ve?e:Ve.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 Ve?e:Ve.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 _O=600,Mm=1,Rl=16;function $O(n,e){return Math.hypot(e.x-n.x,e.y-n.y)}function mb(n,e,t,r){if(r!==void 0&&r>0)return Math.max(Mm,Math.round(r/Rl));let i=$O(n,e);if(i<=0||t<=0)return Mm;let o=i/t*1e3;return Math.max(Mm,Math.round(o/Rl))}function xl(n,e,t){return Math.round(n+(e-n)*t)}function fb(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 FO(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 jO(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=mb(i,o,t,e.durationMs);for(let a=1;a<=s;a++){let c=a/s;n.push({pressed:r.pressed,x:xl(i.x,o.x,c),y:xl(i.y,o.y,c)})}r.cur=o}function HO(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=mb(i,o,t,e.durationMs);for(let a=1;a<=s;a++){let c=a/s;n.push({pressed:r.pressed,x:xl(i.x,o.x,c),y:xl(i.y,o.y,c)})}r.cur=o}function UO(n,e,t){fb(n,t.cur,t.pressed,Math.max(1,Math.round(e.durationMs/Rl)))}function BO(n,e,t){if(!t.pressed)throw new Error("pressHold before down");fb(n,t.cur,t.pressed,Math.max(1,Math.round(e.durationMs/Rl)))}function WO(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 VO(n,e){let t=[],r={cur:null,pressed:!1};for(let i of n.actions)switch(i.type){case"down":{FO(t,i,r);break}case"moveTo":{jO(t,i,e,r);break}case"move":{HO(t,i,e,r);break}case"wait":{UO(t,i,r);break}case"pressHold":{BO(t,i,r);break}case"up":{WO(t,r);break}default:{let o=i;throw new Error(`Unknown gesture action: ${JSON.stringify(o)}`)}}return t}function Lm(n){if(!n.fingers.length)throw new Error("Gesture requires at least one finger");let e=n.speed??_O,t=n.fingers.map(o=>VO(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 GO="PointerMatrix#seed";async function _m(n,e){let{fingers:t,speed:r}=Lm(e);if(t.length===0)throw new Error("Empty gesture");let i=t[0].length,o=await n.create("PointerMatrix.create",[t.length,i],GO);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 hb="Driver.create",qO="BackendObjectsCleaner";var $m="On#seed";async function Il(n,e){let t=e.filter(r=>r&&r!==$m);if(t.length!==0)try{for(let r=0;r<t.length;r+=10)await n.call(qO,"",[t.slice(r,r+10)])}catch{}}var fn=class{constructor(e){this.rpc=e}refs=[];async create(e,t=[],r=$m){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!==$m&&this.refs.push(e),e}trackAll(e){for(let t of e)this.track(t);return e}async dispose(){await Il(this.rpc,this.refs),this.refs.length=0}async run(e){try{return await e(this)}finally{await this.dispose()}}};var js=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 Hs=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(hb,"",[])),this.driverRef)}selector(e){return e?Ve.from(e):new Ve}findComponent(e,t=0){let r=e instanceof Ve?e:Ve.from(e);return new Fs(this,r,t)}async withComponentRef(e,t,r){let i=await this.ensureDriver();return new fn(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(h=>setTimeout(h,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 js(this,e,t)}async withWindowRef(e,t,r){let i=await this.ensureDriver();return new fn(this.rpc).run(async s=>{let a;if(t===0){let c=await s.call("Driver.findWindow",i,[zO(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 fn(this.rpc).run(async i=>{let{ref:o,speed:s}=await _m(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 Ve?e:Ve.from(e),i=await this.ensureDriver();return new fn(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 Il(this.rpc,[this.driverRef]),this.driverRef=null)}};function zO(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 gb({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 oi(i)}var Us=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:Ns(e.config||{});e.mode&&t.set("rpc.mode",e.mode);let r=e.logger||xs("HMDeviceManager"),i=e.dfx||Ms({logger:r,tags:{mode:t.get("rpc.mode")}}),o=gb({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 un("no device connected");let o=e;if(o){if(!i.includes(o))throw new un(`device ${o} is not found, connected: [${i.join(", ")}]`)}else if(this.config.get("device.autoSelectFirst",!0))o=i[0];else throw new un("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 ci({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 un(`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 YO="6.0.2.2",KO={uitest:n=>new $s({device:n,config:n.config,logger:n.logger,dfx:n.dfx,mode:n.rpcMode})},ci=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 Sl({device:this,config:r,logger:this.logger,dfx:this.dfx}),this.fastStore=new El({config:r,logger:this.logger}),this._rpcs=new Map,this._rpcFactories=new Map(Object.entries(KO)),this.file=new Fm(this),this.fport=new jm(this),this.proc=new Hm(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 Rm(e),(await this.exec(["shell",e],t)).stdout}async shellArgs(e,t={}){return this.shell(Rt(e),t)}async fileSend(e,t,r={}){hr(t),await XO(e);let i=await this.exec(["file","send",e,t],r);if(!(i.ok&&i.stdout.includes("FileTransfer finish")))throw new pn(`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(hr(e),!await this.fileExists(e))throw new pn(`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 pn(`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){hr(e);let t=await this.shellArgs(["ls","-ld",e]);return!!t&&!t.includes("No such file or directory")}async isDirectory(e){hr(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 hr(e),await this.shellArgs(t?["rm","-f",e]:["rm",e]),!0}async mkdir(e){return hr(e),await this.shellArgs(["mkdir","-p",e]),!0}async readRemoteText(e){hr(e);let t=await this.shellArgs(["cat",e]);if(t.includes("No such file or directory"))throw new pn(`remote file does not exist: ${e}`);return t}async listDir(e="/data/local/tmp"){hr(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){bl(e),vl(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){bl(e),t&&vl(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 wm(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 nb({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 Dt(`no free device port in range ${e}-${t}`)}async findProcesses(){let e=await this.shellArgs(["ps","-ef"]);return vm(e)}async killProcess(e){let t=xm(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 ob(this,{minVersion:this.config.get("device.newUiTestMinVersion",YO)});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 Dt(`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 Dt(`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 Hs(this.uitestRpc,{shell:e=>this.shell(e),fileRecv:(e,t)=>this.fileRecv(e,t)})),this._uitestDriver}static async create(e={}){let t=await Us.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})`}},Fm=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)}},jm=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()}},Hm=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 XO(n){try{if(!(await JO(n)).isFile())throw new Error("not a file")}catch(e){throw new Dt(`local file does not exist: ${n}`,{cause:e})}}import{fileURLToPath as QO}from"url";import{dirname as eN,join as Um}from"path";import{existsSync as tN}from"fs";var ZO={write:(n,e)=>m(e)};gm({name:"uitest",level:"trace",transports:[ZO]});function rN(){let n=eN(QO(import.meta.url)),e=[Um(n,"../../resources/uitest"),Um(n,"../src/resources/uitest")];return e.find(t=>tN(Um(t,"uitest_agent_v1.1.9.so")))||e[1]}async function Al(n,e){let t=xs("HMDevice"),r=Ms({logger:t,tags:{mode:"fast"}}),i=new oi({bin:n,logger:t,dfx:r}),o=Ns({device:{resourcesDir:rN()}}),s=new ci({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 sN(n,e,t="default"){let r=await T(n,e),i=new lo(n),o=Bs({text:"Querying screen size...",color:"cyan"}).start();try{let s=await i.getDisplayInfo(r);o.stop();let a=ni(s);console.log(a?t==="json"?JSON.stringify({width:a.width,height:a.height},null,2):`${a.width}x${a.height}`:oN("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 aN(n,e,t){let r=await T(n,t),i=new lo(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 cN(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 Al(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 lN(n,e){let t=await T(n,e),r=Bs({text:"Querying screen rotation...",color:"cyan"}).start();try{let{driver:i,dispose:o}=await Al(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 dN(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 Al(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 li=new nN("screen").description("Query and manage screen properties");li.command("size").description("Query screen resolution").option("--device <name|serial>","Target device (name or serial)").addOption(new iN("--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 N();await sN(i,e,t)})});li.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 N();await lN(r,e)})});li.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 N();await aN(i,Number(n),t)})});li.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 N();await cN(s,r,t)})});li.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 N();await dN(i,n==="on",t)})});import{Command as uN}from"commander";import{gray as pN}from"colorette";import mN from"ora";var Ws=class{constructor(e){this.toolProvider=e}async readClipboard(e){let t=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","get-pastedata"]);if(We(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(We(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(We(t),t.exitCode!==0)throw new Error(t.stderr||t.stdout||"clear clipboard failed");return t.stdout}};async function Bm(n,e,t,r){let i=await T(n,r),o=new Ws(n),s=mN({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||pN("(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 Vs=new uN("clipboard").description("Read, write, or clear the device clipboard");Vs.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 N();await Bm(r,"read",void 0,e)})});Vs.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 N();await Bm(i,"write",n,t)})});Vs.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 N();await Bm(r,"clear",void 0,e)})});import{Command as fN}from"commander";import{yellow as hN}from"colorette";import{existsSync as gN}from"fs";import Wm from"ora";import{execa as Tl}from"execa";var go=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 Tl(r,i,{env:{...process.env}});o=`${s}
105
+ `)})}var ZT={TRACE:"",DEBUG:"",INFO:"",WARN:"",ERROR:""};function QT(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 As=class n{name;level;transports;fields;timestamp;constructor(e={}){this.name=e.name||"hm",this.level=fm(e.level??"info"),this.transports=e.transports||[XT()],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=fm(e),this}addTransport(e){return this.transports.push(e),this}isLevelEnabled(e){return fm(e)>=this.level}trace(e,...t){this._log(Wt.TRACE,e,t)}debug(e,...t){this._log(Wt.DEBUG,e,t)}info(e,...t){this._log(Wt.INFO,e,t)}warn(e,...t){this._log(Wt.WARN,e,t)}error(e,...t){this._log(Wt.ERROR,e,t)}timeStart(e,t=Wt.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:Kv(t),r&&r.length&&(i+=" "+r.map(l=>l instanceof Error?`${l.name}: ${l.message}`:typeof l=="string"?l:Kv(l)).join(" "))}catch{i=String(t)}let o=eO(this.fields),a=`${this.timestamp?`[${QT(Date.now())}] `:""}[${Xv[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 eO(n){let e=Object.keys(n||{});return e.length?" "+e.map(t=>`${t}=${n[t]}`).join(" "):""}function Kv(n){try{return JSON.stringify(n)}catch{return String(n)}}var hm=new As({name:"hm",level:"info"});function gm(n={}){return hm=new As({name:"hm",...n}),hm}function Is(n){return hm.child(n,{})}import{spawn as tO}from"child_process";var po=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}}},oi=class extends po{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||""}},pn=class extends oi{static code="HDC_TIMEOUT";constructor(e,t={}){super(e,{...t,code:"HDC_TIMEOUT"})}},Ts=class extends oi{static code="HDC_COMMAND_FAILED";constructor(e,t={}){super(e,{...t,code:"HDC_COMMAND_FAILED"})}},Dt=class extends po{static code="DEVICE_ERROR";constructor(e,t={}){super(e,{...t,code:t.code||"DEVICE_ERROR"})}},mn=class extends Dt{static code="DEVICE_NOT_FOUND";constructor(e,t={}){super(e,{...t,code:"DEVICE_NOT_FOUND"})}},fn=class extends Dt{static code="DEVICE_FILE_ERROR";constructor(e,t={}){super(e,{...t,code:"DEVICE_FILE_ERROR"})}},pr=class extends po{static code="RPC_ERROR";endpoint;constructor(e,t={}){super(e,{...t,code:t.code||"RPC_ERROR"}),this.endpoint=t.details?.endpoint||""}},mr=class extends pr{static code="RPC_LIFECYCLE_ERROR";constructor(e,t={}){super(e,{...t,code:"RPC_LIFECYCLE_ERROR"})}},Fr=class extends mr{static code="RPC_DISPOSED";constructor(e,t={}){super(e,{...t,code:"RPC_DISPOSED"})}},$e=class extends pr{static code="RPC_TRANSPORT_ERROR";constructor(e,t={}){super(e,{...t,code:"RPC_TRANSPORT_ERROR"})}},hn=class extends pr{static code="RPC_TIMEOUT";constructor(e,t={}){super(e,{...t,code:"RPC_TIMEOUT"})}},Vt=class extends pr{static code="RPC_PROTOCOL_ERROR";constructor(e,t={}){super(e,{...t,code:"RPC_PROTOCOL_ERROR"})}},Os=class extends pr{static code="RPC_REMOTE_ERROR";remote;constructor(e,t={}){super(e,{...t,code:"RPC_REMOTE_ERROR"}),this.remote=t.details?.remote}};function Zv(n){return n instanceof $e||n instanceof hn||n instanceof Vt}function ym(n){return n instanceof Fr?!1:Zv(n)||n instanceof mr}var Ns=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 Ts(`${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}},Ms=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 oi("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 Qv(t.stdout)}};function Qv(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 wm(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 vm(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 si=class extends Ms{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(" ")}`),tO(this.bin,e,{env:t,stdio:["ignore","pipe","pipe"],windowsHide:this.windowsHide})}catch(o){return r&&r({ok:0}),i(new pn(`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(),h=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} (${h}ms)`),s.timedOut){c(new pn(`hdc ${t.join(" ")} timeout after ${r}ms`,{details:{args:t,stdout:l,stderr:d}}));return}a(new Ns({args:t,code:e??-1,stdout:l,stderr:d,durationMs:h}))}handleChildError(e,t,r,i,o){i.settled||(i.settled=!0,i.timer&&clearTimeout(i.timer),r&&r({ok:0}),o(new pn(`hdc ${t.join(" ")} spawn error: ${e.message}`,{cause:e})))}};var eb=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}}),rO={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 ml(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function bm(n){if(typeof structuredClone=="function")try{return structuredClone(n)}catch{}return JSON.parse(JSON.stringify(n))}function pl(n,e){let t=bm(n);for(let[r,i]of Object.entries(e||{}))i!==void 0&&(ml(i)&&ml(t[r])?t[r]=pl(t[r],i):t[r]=bm(i));return t}function nO(n,e){return e.split(".").reduce((t,r)=>{if(!(t==null||typeof t!="object"))return t[r]},n)}function tb(n,e,t){let r=e.split("."),i=r.pop(),o=n;for(let s of r)ml(o[s])||(o[s]={}),o=o[s];return o[i]=t,n}var fl=class{_data;constructor(e={}){this._data=pl(eb,iO()),e&&Object.keys(e).length&&(this._data=pl(this._data,e))}slice(e){let t=this.get(e);return ml(t)?t:{}}get(e,t){let r=nO(this._data,e);return r===void 0?t:r}set(e,t){return tb(this._data,e,t),this}merge(e){return this._data=pl(this._data,e),this}snapshot(){return bm(this._data)}toJSON(){return this.snapshot()}};function iO(){let n={};for(let[e,t]of Object.entries(rO)){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}tb(n,t,i)}return n}function Ls(n){return new fl(n)}var hl=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:rb(this.records,"counter"),timers:rb(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 rb(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 gl=class n{enabled;tags;sinks;slowThresholdMs;logger;constructor(e={}){this.enabled=e.enabled!==!1,this.tags={...e.tags||{}},this.sinks=e.sinks||[new hl],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 hl);return e?e.snapshot():null}reset(){for(let e of this.sinks)typeof e.reset=="function"&&e.reset()}};function _s(n={}){return new gl(n)}function mo(n){return new Promise(e=>setTimeout(e,n))}async function yl(n,{timeoutMs:e,intervalMs:t=200,firstDelayMs:r=0,description:i="condition"}){let o=Date.now()+e;r>0&&await mo(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 mo(t)}}var fo=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()}}},ho=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()}},ai=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 oO=64*1024*1024,Sm={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>oO||e<0)throw new Vt(`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 Vt(`response is not valid JSON: ${t.slice(0,200)}`)}return{value:r,rest:n.subarray(4+e)}}},wl={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 sO(n){if(!n||n.length===0)return null;let e=n[0];return e===123||e===91?"raw":"length-prefixed"}function Em(n="auto"){return n==="raw"?wl:n==="length-prefixed"?Sm:aO()}function aO(){let n=null;return{name:"auto",frameDelimited:!1,get detected(){return n},encode(e){return wl.encode(e)},decode(e){return n||(n=sO(e)),n==="length-prefixed"?Sm.decode(e):wl.decode(e)}}}var Pm=0;function fr(n="hm"){Pm=(Pm+1)%1e6;let e=new Date().toISOString().replace(/[-:T]/g,"").replace(/\..+/,""),t=Math.random().toString(36).slice(2,8);return`${n}-${e}-${Pm.toString(36)}-${t}`}import Cm from"net";function km(n,e,t=500){return new Promise(r=>{let i=new Cm.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 Dm({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 lO(n,o))return o}throw new Error(`no free port in range ${e}-${t}`)}var cO=Dm;function lO(n,e){return new Promise(t=>{let r=Cm.createServer();r.once("error",()=>t(!1)),r.once("listening",()=>{r.close(()=>t(!0))}),r.listen(e,n)})}async function dO({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 km(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 nb({hdcHost:n="127.0.0.1",start:e,end:t,exclude:r}={}){return!n||n==="127.0.0.1"||n==="localhost"?{port:await cO({host:n||"127.0.0.1",start:e,end:t,exclude:r}),scope:"local"}:{port:await dO({host:n,start:e,end:t,exclude:r,stepDelayMs:50}),scope:"remote"}}function vl({host:n,port:e,timeoutMs:t=5e3,keepAliveMs:r}){return new Promise((i,o)=>{let s=new Cm.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 Gt(n,e){let t=ib(n),r=ib(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 ib(n){return String(n||"").trim().split(/[.\-+_]/).filter(Boolean).map(e=>{let t=parseInt(e,10);return Number.isNaN(t)?0:t})}function go(n){let e=/(\d+(?:\.\d+)+)/.exec(String(n||""));return e?e[1]:null}var uO=/^[A-Za-z0-9_@%+=:,./-]+$/,pO=/'/g,mO="'\\''";function ci(n){let e=n==null?"":String(n);return e===""?"''":uO.test(e)?e:`'${e.replace(pO,mO)}'`}function Rt(n){if(!Array.isArray(n))throw new TypeError("shellJoin expects an array of arguments");return n.filter(e=>e!=null&&e!=="").map(e=>ci(e)).join(" ")}function Rm(n){let e=String(n??"");if(/[\r\n\0]/.test(e))throw new hr("shell command must not contain newline or NUL characters");return e}function gr(n){let e=String(n??"").trim();if(!e)throw new hr("remote path is empty");if(!e.startsWith("/"))throw new hr(`remote path must be absolute: ${JSON.stringify(n)}`);if(/[\r\n\0]/.test(e))throw new hr("remote path must not contain newline or NUL characters");return e}function xm(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new hr(`invalid pid: ${JSON.stringify(n)}`);return e}function bl(n){let e=String(n??"").trim();if(!/^(localabstract|localfilesystem|tcp|jdwp):[A-Za-z0-9_.-]+$/.test(e))throw new hr(`invalid device endpoint: ${JSON.stringify(n)}`);return e}function Sl(n){let e=Number(n);if(!Number.isInteger(e)||e<1||e>65535)throw new hr(`invalid host port: ${JSON.stringify(n)}`);return e}var hr=class extends Error{constructor(e){super(e),this.name="ShellSafetyError"}};import{stat as JO}from"fs/promises";var wO="6.0.2.2";async function ob(n,e={}){let t=e.minVersion||wO,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=vO(o)||o,a=Gt(s,t)>=0;return{version:s,arch:i,isNewUiTest:a,endpointStyle:a&&i!=="x86_64"?"unix":"tcp",fileOutput:r}}function vO(n){let e=/(\d+(?:\.\d+)+)/.exec(String(n||""));return e?e[1]:null}import{fileURLToPath as kO}from"url";import{dirname as DO,join as cb}from"path";import{readdirSync as bO}from"fs";import{join as SO,basename as $6}from"path";var EO=/^uitest_agent_v(\d+\.\d+\.\d+)(\.x86_64)?\.so$/,PO="/data/local/tmp/agent.so",Am="UITEST_AGENT_LIBRARY";function CO(n){let e;try{e=bO(n)}catch{return[]}return e.filter(t=>t.endsWith(".so"))}function sb({dir:n,arch:e,isNewUiTest:t}){let r=e==="x86_64",i=[];for(let s of CO(n)){let a=EO.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=Gt(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)=>Gt(a.version,s.version));let o=i[0];return{fileName:o.fileName,localPath:SO(n,o.fileName),version:o.version,x86_64:o.x86_64,remotePath:PO,versionProbe:Am}}function ab(n){let e=String(n||""),t=e.indexOf("#"),r=t>=0?e.slice(t+1):e;return go(r)}var RO=cb(DO(kO(import.meta.url)),"..",".."),xO=cb(RO,"resources"),El=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")||xO}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=sb({dir:this.resourcesDir,arch:t.arch,isNewUiTest:t.isNewUiTest});if(!r)throw new Dt(`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||Gt(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 ${ci(e)} | ${Rt(["grep","-a",Am])}`);return ab(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 Im}from"path";import{mkdir as AO,readFile as lb,writeFile as db,unlink as IO,readdir as TO}from"fs/promises";function OO(n){return String(n||"unknown").replace(/[^A-Za-z0-9._-]/g,"_")}var NO=Im(F(),"fast-mode"),Pl=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 NO}pathFor(e){return Im(this.dir,`${OO(e)}.json`)}async _ensureDir(){await AO(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 db(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 lb(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 IO(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 db(this.pathFor(e),JSON.stringify(r,null,2),{mode:384}),!0):this.forget(e))}async list(){let e;try{e=await TO(this.dir)}catch{return[]}let t=[];for(let r of e)if(r.endsWith(".json"))try{t.push(JSON.parse(await lb(Im(this.dir,r),"utf8")))}catch{}return t}};var yr={AUTO:"auto",PIPELINED:"pipelined",SERIAL:"serial"},$s=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=Em(e.framing||"auto"),this.frameDelimited=this.codec.frameDelimited===!0,this.concurrency=e.concurrency||yr.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 ho(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===yr.SERIAL?"serial":this.frameDelimited?this.concurrency===yr.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 vl({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 hn(`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 Vt?r:new Vt(`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 Vt(`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===yr.SERIAL||!this.frameDelimited?1:this.concurrency===yr.PIPELINED?this.maxInFlight:this._serverEchoesRequestId===!0?this.maxInFlight:1}_initialLimit(){return this.concurrency===yr.SERIAL||!this.frameDelimited?1:this.concurrency===yr.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=fr();for(;this.pending.has(t);)t=fr();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 hn(`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 Cl="com.ohos.devicetest.hypiumApiHelper",Tm="callHypiumApi";function kl({module:n,method:e,params:t={},requestId:r}){return{module:n,method:e,params:t,request_id:r||fr()}}function Dl(n){if(!n||typeof n!="object")return!1;let e=n.exception;return e!=null&&e!==""}function Rl(n){return n?n.result:void 0}var ke={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=ke.IDLE,this.transport=null,this._mutex=new fo,this._epoch=0,this._readyFlight=new ai,this._resetFlight=new ai,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===ke.READY&&!!this.transport&&this.transport.isConnected}async ensureReady(){if(this._disposed)throw new Fr(`${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 Fr(`${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 Fr(`${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=ke.RESOURCES_READY,await this._ensureProcess(t),this.state=ke.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=ke.FORWARDED,await this._connectAndProbe(i,{probe:!0}),this.state=ke.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=ke.ERROR,t&&t({ok:0}),this.dfx&&this.dfx.counter("rpc.lifecycle.error",1,{code:e?.code||e?.name});let r=e instanceof pr?e:new mr(`${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=ke.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||Gt(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 ${ci(e.remotePath)} | ${Rt(["grep","-a",e.versionProbe])}`);if(!t)return null;let r=t.split("#"),i=r.length>1?r[r.length-1]:t;return go(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 yl(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 mr(`${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 mr(`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 $s({host:this.device.hdcHost,port:e,name:this.name,framing:this.config.get("rpc.framing","auto"),concurrency:this.config.get("rpc.concurrency",yr.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=ke.CONNECTED,t&&await this._probe()}_onTransportClose(e,t){this.transport===e&&(this._bumpEpoch(),(this.state===ke.READY||this.state===ke.CONNECTED)&&(this.state=this.mode==="fast"?ke.WARM:ke.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(Dl(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 Rl(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 Fr(`${this.name} rpc is disposed, request rejected`,{details:{endpoint:this.name}});let h=this._epoch;try{await this.ensureReady(),h=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,h,c,l,i.delayMs);c=R.ownRecoveries,l=R.borrowedRecoveries}}throw a||new mr(`${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||!ym(e))throw e;return this._epoch===i?o=await this._attemptOwnRecovery(e,r,o):s=this._attemptBorrowedRecovery(e,r,s),a&&await mo(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(Dl(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 Os(`remote exception: ${r}`,{details:{endpoint:this.name,remote:t}});throw this.dfx&&this.dfx.counter("rpc.request.remoteError",1,{endpoint:this.name}),i}return Rl(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=ke.IDLE}async release(){if(await this._safeCloseTransport("release"),this.mode==="fast"&&this.config.get("rpc.fast.keepOnRelease",!0)){this.state=ke.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=ke.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=ke.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 Om={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=>Rt(["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 | ${Rt(["grep",this.socketName])}`)).includes(this.socketName):(await n.shell(`netstat -anp | ${Rt(["grep",String(this.devicePort)])}`)).includes("LISTEN")}};var js=class extends Fs{constructor(e){super({...e,endpoint:Om})}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 kl({module:Cl,method:"ping",params:{},requestId:fr()})}async call(e,t="",r=[],i={}){let o=kl({module:Cl,method:Tm,params:{api:e,this:t,args:r,message_type:"hypium"},requestId:fr()});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 MO(n){if(n!==void 0)return Array.isArray(n)?{value:String(n[0]),pattern:n[1]}:{value:String(n)}}function Nm(n){return ub(n)}function ub(n){let e={};return n.text!==void 0&&(e.text=MO(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 pb(n){let e=ub(n);return n.isBefore&&(e.isBefore=Nm(n.isBefore)),n.isAfter&&(e.isAfter=Nm(n.isAfter)),n.within&&(e.within=Nm(n.within)),e}function LO(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 Ve=class n{spec;constructor(e={}){this.spec=e}static from(e){return new n(pb(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=LO(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 Hs=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 Ve?e:Ve.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 Ve?e:Ve.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 _O=600,Mm=1,xl=16;function $O(n,e){return Math.hypot(e.x-n.x,e.y-n.y)}function mb(n,e,t,r){if(r!==void 0&&r>0)return Math.max(Mm,Math.round(r/xl));let i=$O(n,e);if(i<=0||t<=0)return Mm;let o=i/t*1e3;return Math.max(Mm,Math.round(o/xl))}function Al(n,e,t){return Math.round(n+(e-n)*t)}function fb(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 FO(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 jO(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=mb(i,o,t,e.durationMs);for(let a=1;a<=s;a++){let c=a/s;n.push({pressed:r.pressed,x:Al(i.x,o.x,c),y:Al(i.y,o.y,c)})}r.cur=o}function HO(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=mb(i,o,t,e.durationMs);for(let a=1;a<=s;a++){let c=a/s;n.push({pressed:r.pressed,x:Al(i.x,o.x,c),y:Al(i.y,o.y,c)})}r.cur=o}function UO(n,e,t){fb(n,t.cur,t.pressed,Math.max(1,Math.round(e.durationMs/xl)))}function BO(n,e,t){if(!t.pressed)throw new Error("pressHold before down");fb(n,t.cur,t.pressed,Math.max(1,Math.round(e.durationMs/xl)))}function WO(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 VO(n,e){let t=[],r={cur:null,pressed:!1};for(let i of n.actions)switch(i.type){case"down":{FO(t,i,r);break}case"moveTo":{jO(t,i,e,r);break}case"move":{HO(t,i,e,r);break}case"wait":{UO(t,i,r);break}case"pressHold":{BO(t,i,r);break}case"up":{WO(t,r);break}default:{let o=i;throw new Error(`Unknown gesture action: ${JSON.stringify(o)}`)}}return t}function Lm(n){if(!n.fingers.length)throw new Error("Gesture requires at least one finger");let e=n.speed??_O,t=n.fingers.map(o=>VO(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 GO="PointerMatrix#seed";async function _m(n,e){let{fingers:t,speed:r}=Lm(e);if(t.length===0)throw new Error("Empty gesture");let i=t[0].length,o=await n.create("PointerMatrix.create",[t.length,i],GO);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 hb="Driver.create",qO="BackendObjectsCleaner";var $m="On#seed";async function Il(n,e){let t=e.filter(r=>r&&r!==$m);if(t.length!==0)try{for(let r=0;r<t.length;r+=10)await n.call(qO,"",[t.slice(r,r+10)])}catch{}}var gn=class{constructor(e){this.rpc=e}refs=[];async create(e,t=[],r=$m){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!==$m&&this.refs.push(e),e}trackAll(e){for(let t of e)this.track(t);return e}async dispose(){await Il(this.rpc,this.refs),this.refs.length=0}async run(e){try{return await e(this)}finally{await this.dispose()}}};var Us=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 Bs=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(hb,"",[])),this.driverRef)}selector(e){return e?Ve.from(e):new Ve}findComponent(e,t=0){let r=e instanceof Ve?e:Ve.from(e);return new Hs(this,r,t)}async withComponentRef(e,t,r){let i=await this.ensureDriver();return new gn(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(h=>setTimeout(h,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 Us(this,e,t)}async withWindowRef(e,t,r){let i=await this.ensureDriver();return new gn(this.rpc).run(async s=>{let a;if(t===0){let c=await s.call("Driver.findWindow",i,[zO(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 gn(this.rpc).run(async i=>{let{ref:o,speed:s}=await _m(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 Ve?e:Ve.from(e),i=await this.ensureDriver();return new gn(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 Il(this.rpc,[this.driverRef]),this.driverRef=null)}};function zO(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 gb({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 si(i)}var Ws=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:Ls(e.config||{});e.mode&&t.set("rpc.mode",e.mode);let r=e.logger||Is("HMDeviceManager"),i=e.dfx||_s({logger:r,tags:{mode:t.get("rpc.mode")}}),o=gb({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 mn("no device connected");let o=e;if(o){if(!i.includes(o))throw new mn(`device ${o} is not found, connected: [${i.join(", ")}]`)}else if(this.config.get("device.autoSelectFirst",!0))o=i[0];else throw new mn("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 li({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 mn(`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 YO="6.0.2.2",KO={uitest:n=>new js({device:n,config:n.config,logger:n.logger,dfx:n.dfx,mode:n.rpcMode})},li=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 El({device:this,config:r,logger:this.logger,dfx:this.dfx}),this.fastStore=new Pl({config:r,logger:this.logger}),this._rpcs=new Map,this._rpcFactories=new Map(Object.entries(KO)),this.file=new Fm(this),this.fport=new jm(this),this.proc=new Hm(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 Rm(e),(await this.exec(["shell",e],t)).stdout}async shellArgs(e,t={}){return this.shell(Rt(e),t)}async fileSend(e,t,r={}){gr(t),await XO(e);let i=await this.exec(["file","send",e,t],r);if(!(i.ok&&i.stdout.includes("FileTransfer finish")))throw new fn(`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(gr(e),!await this.fileExists(e))throw new fn(`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 fn(`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){gr(e);let t=await this.shellArgs(["ls","-ld",e]);return!!t&&!t.includes("No such file or directory")}async isDirectory(e){gr(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 gr(e),await this.shellArgs(t?["rm","-f",e]:["rm",e]),!0}async mkdir(e){return gr(e),await this.shellArgs(["mkdir","-p",e]),!0}async readRemoteText(e){gr(e);let t=await this.shellArgs(["cat",e]);if(t.includes("No such file or directory"))throw new fn(`remote file does not exist: ${e}`);return t}async listDir(e="/data/local/tmp"){gr(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){Sl(e),bl(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){Sl(e),t&&bl(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 wm(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 nb({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 Dt(`no free device port in range ${e}-${t}`)}async findProcesses(){let e=await this.shellArgs(["ps","-ef"]);return vm(e)}async killProcess(e){let t=xm(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 ob(this,{minVersion:this.config.get("device.newUiTestMinVersion",YO)});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 Dt(`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 Dt(`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 Bs(this.uitestRpc,{shell:e=>this.shell(e),fileRecv:(e,t)=>this.fileRecv(e,t)})),this._uitestDriver}static async create(e={}){let t=await Ws.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})`}},Fm=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)}},jm=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()}},Hm=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 XO(n){try{if(!(await JO(n)).isFile())throw new Error("not a file")}catch(e){throw new Dt(`local file does not exist: ${n}`,{cause:e})}}import{fileURLToPath as QO}from"url";import{dirname as eN,join as Um}from"path";import{existsSync as tN}from"fs";var ZO={write:(n,e)=>m(e)};gm({name:"uitest",level:"trace",transports:[ZO]});function rN(){let n=eN(QO(import.meta.url)),e=[Um(n,"../../resources/uitest"),Um(n,"../src/resources/uitest")];return e.find(t=>tN(Um(t,"uitest_agent_v1.1.9.so")))||e[1]}async function Tl(n,e){let t=Is("HMDevice"),r=_s({logger:t,tags:{mode:"fast"}}),i=new si({bin:n,logger:t,dfx:r}),o=Ls({device:{resourcesDir:rN()}}),s=new li({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 sN(n,e,t="default"){let r=await T(n,e),i=new uo(n),o=Vs({text:"Querying screen size...",color:"cyan"}).start();try{let s=await i.getDisplayInfo(r);o.stop();let a=ii(s);console.log(a?t==="json"?JSON.stringify({width:a.width,height:a.height},null,2):`${a.width}x${a.height}`:oN("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 aN(n,e,t){let r=await T(n,t),i=new uo(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=Vs({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 cN(n,e,t){let r=await T(n,t),i=Vs({text:`Setting screen rotation to ROTATION_${e}...`,color:"cyan"}).start();try{let{driver:o,dispose:s}=await Tl(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 lN(n,e){let t=await T(n,e),r=Vs({text:"Querying screen rotation...",color:"cyan"}).start();try{let{driver:i,dispose:o}=await Tl(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 dN(n,e,t){let r=await T(n,t),i=Vs({text:`${e?"Locking":"Unlocking"} screen rotation...`,color:"cyan"}).start();try{let{driver:o,dispose:s}=await Tl(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 di=new nN("screen").description("Query and manage screen properties");di.command("size").description("Query screen resolution").option("--device <name|serial>","Target device (name or serial)").addOption(new iN("--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 N();await sN(i,e,t)})});di.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 N();await lN(r,e)})});di.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 N();await aN(i,Number(n),t)})});di.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 N();await cN(s,r,t)})});di.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 N();await dN(i,n==="on",t)})});import{Command as uN}from"commander";import{gray as pN}from"colorette";import mN from"ora";var Gs=class{constructor(e){this.toolProvider=e}async readClipboard(e){let t=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","get-pastedata"]);if(We(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(We(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(We(t),t.exitCode!==0)throw new Error(t.stderr||t.stdout||"clear clipboard failed");return t.stdout}};async function Bm(n,e,t,r){let i=await T(n,r),o=new Gs(n),s=mN({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||pN("(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 qs=new uN("clipboard").description("Read, write, or clear the device clipboard");qs.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 N();await Bm(r,"read",void 0,e)})});qs.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 N();await Bm(i,"write",n,t)})});qs.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 N();await Bm(r,"clear",void 0,e)})});import{Command as fN}from"commander";import{yellow as hN}from"colorette";import{existsSync as gN}from"fs";import Wm from"ora";import{execa as Ol}from"execa";var yo=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 Ol(r,i,{env:{...process.env}});o=`${s}
106
106
  ${a}`}catch(s){let a=s;if(o=`${a.stdout??""}
107
107
  ${a.stderr??""}
108
- ${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 Tl(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 Tl(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 Tl(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 yb(n,e,t,r,i){let o=await T(n,i),s=e==="send";if(s&&!gN(t))throw new y(`File not found: ${t}`,"File not found.");let a=new de(n),c=Wm({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 yN(n,e,t){let r=await T(n,t),i=new go(n),o=Wm({text:`Checking ${e}...`,color:"cyan"}).start();try{let s=await i.fileExists(r,e);o.stop(),s?console.log(`exists: ${e}`):(console.log(hN(`not found: ${e}`)),process.exitCode=1)}catch(s){throw o.stop(),new y(`Existence check failed: ${s.message}`,"Existence check failed.")}}async function wN(n,e,t){let r=await T(n,t),i=new go(n),o=Wm({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 yo=new fN("file").description("Transfer files between the host and a connected device");yo.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 N();await yb(o,"send",n,e,r)})});yo.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 N();await yb(o,"recv",n,e,r)})});yo.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 N();await yN(i,n,t)})});yo.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 N();await wN(i,n,t)})});import{Command as bN}from"commander";import{red as SN}from"colorette";import{existsSync as EN}from"fs";import PN from"ora";import{basename as vN}from"path";var Gs=class{constructor(e){this.toolProvider=e;this.hdc=new de(e)}hdc;async pushFontToDevice(e,t){let r=`/data/local/tmp/${vN(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 We(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 We(i),i.stdout}async uninstallFont(e,t){let r=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","uninstall-font",t]);return We(r),r.stdout}};async function Vm(n,e,t,r){let i=await T(n,r);if(e!=="uninstall"&&!EN(t))throw new y(`Font file not found: ${t}`,"Font file not found.");let o=new Gs(n),s=PN({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(SN(c)),process.exitCode=1):console.log(c)}catch(a){throw s.stop(),new y(a.message,`Font ${e} failed.`)}}var qs=new bN("font").description("Manage device fonts");qs.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 N();await Vm(i,"install",n,t)})});qs.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 N();await Vm(i,"info",n,t)})});qs.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 N();await Vm(i,"uninstall",n,t)})});import{Command as CN}from"commander";import{red as kN}from"colorette";import DN from"ora";var zs=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 We(r),/already set to/i.test(r.stdout)?r.stdout.replace(/^Error:\s*/i,"").trim():r.stdout}};async function RN(n,e,t){let r=await T(n,t),i=new zs(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=DN({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(kN(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 wb=new CN("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 N();await RN(i,n,t)})});function ON(n,e){if(e.size!==0)for(let t of n){if(!t.isEmulator||!t.name)continue;let r=e.get(_e(t.name));r&&(t.deviceType=r)}}var NN=["Name","Serial","Kind","Device Type"];function MN(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function Sb(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function LN(){console.log(IN(" No active devices.")),console.log(AN(" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function _N(n){let t=[...n].sort(Sb).map(MN);console.log(Mr(NN,t))}function $N(n){return{name:n.name??n.serial,serial:n.serial,kind:n.isEmulator?"emulator":"device",deviceType:n.deviceType}}function FN(n){let e=[...n].sort(Sb);console.log(JSON.stringify(e.map($N),null,2))}async function jN(n,e){if(!n.some(i=>i.isEmulator)||!e.emulatorPath)return;let r=await co.from(e).getDeviceTypeByName();ON(n,r)}async function vb(n,e,t,r="table"){try{let i=await n.getConnectedEntries();if(await jN(i,e),t?.stop(),r==="json"){FN(i);return}i.length===0?LN():_N(i)}catch(i){throw new y(`Failed to list devices: ${i.message}`,"Failed to list devices.")}finally{t?.stop()}}async function HN(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(`
109
- `),"Multiple devices connected.")}async function UN(n,e,t="table"){e||await HN(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:sr(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 BN(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 Gt=new xN("device").description("Manage connected devices");Gt.command("list").description("List all connected devices").addOption(new bb("--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 N();if(n.format==="json"){await vb(t,r,void 0,"json");return}let i=TN({text:"Querying connected devices\u2026",color:"cyan"}).start();await vb(t,r,i,"table")})});Gt.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").addOption(new bb("--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 N();await UN(t,n.target,n.format)})});Gt.addCommand(Ut);Gt.addCommand(yo);Gt.addCommand(Vs);Gt.addCommand(li);Gt.addCommand(qs);Gt.addCommand(wb);for(let n of Yv)Gt.addCommand(n);Gt.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 N();await BN(i,n,e,t.device)})});var Eb=Gt;import{Argument as Qm,Command as ef,InvalidArgumentError as Xm,Option as Ge}from"commander";import{green as Ks,cyan as vo,red as tf,yellow as gn,gray as Zm}from"colorette";import iM from"ora";import WN from"readline/promises";import{execa as Cb}from"execa";import*as hn from"fs/promises";import*as qm from"os";import*as di from"path";var Gm=`1/4:\r
108
+ ${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 Ol(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 Ol(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 Ol(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 yb(n,e,t,r,i){let o=await T(n,i),s=e==="send";if(s&&!gN(t))throw new y(`File not found: ${t}`,"File not found.");let a=new le(n),c=Wm({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 yN(n,e,t){let r=await T(n,t),i=new yo(n),o=Wm({text:`Checking ${e}...`,color:"cyan"}).start();try{let s=await i.fileExists(r,e);o.stop(),s?console.log(`exists: ${e}`):(console.log(hN(`not found: ${e}`)),process.exitCode=1)}catch(s){throw o.stop(),new y(`Existence check failed: ${s.message}`,"Existence check failed.")}}async function wN(n,e,t){let r=await T(n,t),i=new yo(n),o=Wm({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 wo=new fN("file").description("Transfer files between the host and a connected device");wo.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 N();await yb(o,"send",n,e,r)})});wo.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 N();await yb(o,"recv",n,e,r)})});wo.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 N();await yN(i,n,t)})});wo.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 N();await wN(i,n,t)})});import{Command as bN}from"commander";import{red as SN}from"colorette";import{existsSync as EN}from"fs";import PN from"ora";import{basename as vN}from"path";var zs=class{constructor(e){this.toolProvider=e;this.hdc=new le(e)}hdc;async pushFontToDevice(e,t){let r=`/data/local/tmp/${vN(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 We(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 We(i),i.stdout}async uninstallFont(e,t){let r=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","uninstall-font",t]);return We(r),r.stdout}};async function Vm(n,e,t,r){let i=await T(n,r);if(e!=="uninstall"&&!EN(t))throw new y(`Font file not found: ${t}`,"Font file not found.");let o=new zs(n),s=PN({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(SN(c)),process.exitCode=1):console.log(c)}catch(a){throw s.stop(),new y(a.message,`Font ${e} failed.`)}}var Js=new bN("font").description("Manage device fonts");Js.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 N();await Vm(i,"install",n,t)})});Js.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 N();await Vm(i,"info",n,t)})});Js.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 N();await Vm(i,"uninstall",n,t)})});import{Command as CN}from"commander";import{red as kN}from"colorette";import DN from"ora";var Ys=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 We(r),/already set to/i.test(r.stdout)?r.stdout.replace(/^Error:\s*/i,"").trim():r.stdout}};async function RN(n,e,t){let r=await T(n,t),i=new Ys(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=DN({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(kN(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 wb=new CN("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 N();await RN(i,n,t)})});function ON(n,e){if(e.size!==0)for(let t of n){if(!t.isEmulator||!t.name)continue;let r=e.get(_e(t.name));r&&(t.deviceType=r)}}var NN=["Name","Serial","Kind","Device Type"];function MN(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function Sb(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function LN(){console.log(AN(" No active devices.")),console.log(IN(" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function _N(n){let t=[...n].sort(Sb).map(MN);console.log(_r(NN,t))}function $N(n){return{name:n.name??n.serial,serial:n.serial,kind:n.isEmulator?"emulator":"device",deviceType:n.deviceType}}function FN(n){let e=[...n].sort(Sb);console.log(JSON.stringify(e.map($N),null,2))}async function jN(n,e){if(!n.some(i=>i.isEmulator)||!e.emulatorPath)return;let r=await lo.from(e).getDeviceTypeByName();ON(n,r)}async function vb(n,e,t,r="table"){try{let i=await n.getConnectedEntries();if(await jN(i,e),t?.stop(),r==="json"){FN(i);return}i.length===0?LN():_N(i)}catch(i){throw new y(`Failed to list devices: ${i.message}`,"Failed to list devices.")}finally{t?.stop()}}async function HN(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(`
109
+ `),"Multiple devices connected.")}async function UN(n,e,t="table"){e||await HN(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:cr(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 BN(n,e,t,r){let i=await T(n,r),o=new le(n);try{await o.runSqlite3(i,e,t)}catch(s){throw new y(`sqlite3 failed: ${s.message}`,"sqlite3 failed.")}}var qt=new xN("device").description("Manage connected devices");qt.command("list").description("List all connected devices").addOption(new bb("--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 N();if(n.format==="json"){await vb(t,r,void 0,"json");return}let i=TN({text:"Querying connected devices\u2026",color:"cyan"}).start();await vb(t,r,i,"table")})});qt.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").addOption(new bb("--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 N();await UN(t,n.target,n.format)})});qt.addCommand(Bt);qt.addCommand(wo);qt.addCommand(qs);qt.addCommand(di);qt.addCommand(Js);qt.addCommand(wb);for(let n of Yv)qt.addCommand(n);qt.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 N();await BN(i,n,e,t.device)})});var Eb=qt;import{Argument as Qm,Command as ef,InvalidArgumentError as Xm,Option as Ge}from"commander";import{green as Zs,cyan as bo,red as tf,yellow as wn,gray as Zm}from"colorette";import iM from"ora";import WN from"readline/promises";import{execa as Cb}from"execa";import*as yn from"fs/promises";import*as qm from"os";import*as ui from"path";var Gm=`1/4:\r
110
110
  ---------------------------------------\r
111
111
  Statement About HarmonyOS and Privacy\r
112
112
  \r
@@ -1276,13 +1276,13 @@ Part I: Chinese mainland.\r
1276
1276
  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
1277
1277
  \r
1278
1278
  Part III: Other countries and regions.\r
1279
- ---------------------------------------\r`;var VN=new Set,Ol=new Map,zm="HarmonyOS_Software_Service_Agreement",kb=["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(`
1280
- `),Db=kb,Jm="HarmonyOS_SDK_Agreement";function Rb(n,e){return`${n}\0${e}`}function xb(){VN.clear(),Ol.clear()}var GN=kb,$r=class extends Error{constructor(e=GN){super(e),this.name="EmulatorLicenseBlockedError"}};function Ib(n,e){return[n??"",e??""].join(`
1281
- `)}function Ab(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 qN(n){return`Emulator${n.trim()}`}function Tb(n){let e=qN(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 di.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return di.join(qm.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||di.join(qm.homedir(),".cache");return di.join(t,"Huawei",e,".emu_config")}async function zN(n,e,t){let r=Rb(n,e),i=Ol.get(r);if(i!==void 0)return i;let o=await Cb(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=Ib(o.stdout,o.stderr).trim();if(o.exitCode!==0||!s)throw new $r(t);return Ol.set(r,s),s}function JN(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function YN(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 KN(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=JN(e.slice(r+1).trim());return{key:i,entry:{value:o,delimiter:t}}}}function XN(n){let e={};for(let t of n.split(/\r?\n/)){let r=KN(t);r&&(e[r.key]=r.entry)}return e}function ZN(n){let e=n.trim();if(!e)return{};let t=YN(e);return t||XN(n)}function QN(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function Ob(n,e,t,r){let i=await zN(n,e,r),o=Ab(i);if(!o)throw new $r(r);let s=Tb(o),a;try{a=await hn.readFile(s,"utf8")}catch(d){throw d.code==="ENOENT"?new $r(r):d}let l=ZN(a)[t];if(!l)throw new $r(r);if(l.delimiter==="=")throw new $r(r);if(!QN(l.value))throw new $r(r)}async function Ym(n,e){await Ob(n,e,zm,Db)}async function Km(n,e){await Ob(n,e,Jm,Db)}async function eM(n,e){let t=await Cb(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),r=Ib(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=Rb(n,e);return Ol.set(i,r),r}async function Nb(n,e){let t=await eM(n,e),r=Ab(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
1282
- ${t}.`);return Tb(r)}function Pb(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function tM(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[zm]="agree",r[Jm]="agree",await hn.writeFile(n,`${JSON.stringify(r,null,2)}
1283
- `,"utf8"),!0}catch{}return!1}async function rM(n,e){let t=zm,r=Jm,i=[{k:t,re:new RegExp(`^\\s*${Pb(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${Pb(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:h}of i)if(h.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 hn.writeFile(n,s.join(`
1279
+ ---------------------------------------\r`;var VN=new Set,Nl=new Map,zm="HarmonyOS_Software_Service_Agreement",kb=["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(`
1280
+ `),Db=kb,Jm="HarmonyOS_SDK_Agreement";function Rb(n,e){return`${n}\0${e}`}function xb(){VN.clear(),Nl.clear()}var GN=kb,jr=class extends Error{constructor(e=GN){super(e),this.name="EmulatorLicenseBlockedError"}};function Ab(n,e){return[n??"",e??""].join(`
1281
+ `)}function Ib(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 qN(n){return`Emulator${n.trim()}`}function Tb(n){let e=qN(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 ui.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return ui.join(qm.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||ui.join(qm.homedir(),".cache");return ui.join(t,"Huawei",e,".emu_config")}async function zN(n,e,t){let r=Rb(n,e),i=Nl.get(r);if(i!==void 0)return i;let o=await Cb(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=Ab(o.stdout,o.stderr).trim();if(o.exitCode!==0||!s)throw new jr(t);return Nl.set(r,s),s}function JN(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function YN(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 KN(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=JN(e.slice(r+1).trim());return{key:i,entry:{value:o,delimiter:t}}}}function XN(n){let e={};for(let t of n.split(/\r?\n/)){let r=KN(t);r&&(e[r.key]=r.entry)}return e}function ZN(n){let e=n.trim();if(!e)return{};let t=YN(e);return t||XN(n)}function QN(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function Ob(n,e,t,r){let i=await zN(n,e,r),o=Ib(i);if(!o)throw new jr(r);let s=Tb(o),a;try{a=await yn.readFile(s,"utf8")}catch(d){throw d.code==="ENOENT"?new jr(r):d}let l=ZN(a)[t];if(!l)throw new jr(r);if(l.delimiter==="=")throw new jr(r);if(!QN(l.value))throw new jr(r)}async function Ym(n,e){await Ob(n,e,zm,Db)}async function Km(n,e){await Ob(n,e,Jm,Db)}async function eM(n,e){let t=await Cb(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),r=Ab(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=Rb(n,e);return Nl.set(i,r),r}async function Nb(n,e){let t=await eM(n,e),r=Ib(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
1282
+ ${t}.`);return Tb(r)}function Pb(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function tM(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[zm]="agree",r[Jm]="agree",await yn.writeFile(n,`${JSON.stringify(r,null,2)}
1283
+ `,"utf8"),!0}catch{}return!1}async function rM(n,e){let t=zm,r=Jm,i=[{k:t,re:new RegExp(`^\\s*${Pb(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${Pb(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:h}of i)if(h.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 yn.writeFile(n,s.join(`
1284
1284
  `)+(s.length>0?`
1285
- `:""),"utf8")}async function Mb(n){await hn.mkdir(di.dirname(n),{recursive:!0});let e="";try{e=await hn.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await tM(n,e,t)||await rM(n,e)}async function Lb(n,e){return console.log(Gm),0}var nM="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function _b(n,e){try{return await Ym(n,e),await Km(n,e),!0}catch(t){if(t instanceof $r)return!1;throw t}}async function $b(n,e){if(await _b(n,e))return console.log("Emulator license agreements are already accepted."),0;if(console.log(Gm),!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=WN.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await r.question(nM)}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 Nb(n,e);await Mb(s),xb()}catch(s){return console.error(s.message),1}return console.log("Emulator license agreements accepted."),0}async function Fb(n,e){if(await _b(n,e))return console.log("Emulator license agreements are already accepted."),0;try{let t=await Nb(n,e);await Mb(t),xb()}catch(t){return console.error(t.message),1}return console.log("Emulator license agreements accepted."),0}async function xt(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=X(o),console.error(tf(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await R.track(n,o)}}var oM=["ohos.qemu.hvd.name","const.product.name","const.product.model"],jb=["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"],sM=`
1285
+ `:""),"utf8")}async function Mb(n){await yn.mkdir(ui.dirname(n),{recursive:!0});let e="";try{e=await yn.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await tM(n,e,t)||await rM(n,e)}async function Lb(n,e){return console.log(Gm),0}var nM="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function _b(n,e){try{return await Ym(n,e),await Km(n,e),!0}catch(t){if(t instanceof jr)return!1;throw t}}async function $b(n,e){if(await _b(n,e))return console.log("Emulator license agreements are already accepted."),0;if(console.log(Gm),!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=WN.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await r.question(nM)}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 Nb(n,e);await Mb(s),xb()}catch(s){return console.error(s.message),1}return console.log("Emulator license agreements accepted."),0}async function Fb(n,e){if(await _b(n,e))return console.log("Emulator license agreements are already accepted."),0;try{let t=await Nb(n,e);await Mb(t),xb()}catch(t){return console.error(t.message),1}return console.log("Emulator license agreements accepted."),0}async function xt(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=X(o),console.error(tf(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await D.track(n,o)}}var oM=["ohos.qemu.hvd.name","const.product.name","const.product.model"],jb=["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"],sM=`
1286
1286
  Folded state scene mappings:
1287
1287
  foldableFold (3):
1288
1288
  open Fully expanded state
@@ -1305,40 +1305,40 @@ Folded state scene mappings:
1305
1305
  left-half-folded-right-folded
1306
1306
  left-expanded-right-half-folded
1307
1307
  left-half-folded-right-half-folded
1308
- `,aM="6.1.0";function cM(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function lM(n){let e=n.trim();if(!jb.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${jb.join(", ")}`);return e}function Ub(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 Bb(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&&!dM(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 dM(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function ui(n,e,t,r,i){return Number(Bb(n,e,t,r,i))}var uM=["Name","Status","Serial","Device Type","OS Version"];function pM(n){return{cells:[n.name,n.status,n.serial??"-",n.deviceType??"-",n.osVersion??"-"],highlight:n.status==="running"}}async function mM(n,e){let t=await Promise.all(e.map(async r=>{let i=await qi(n,r,oM);return[r,i]}));return new Map(t)}async function fM(n){let e=await tm(n),t=await mM(n,e);return{serials:e,params:t}}function hM(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 gM(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&&hM(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 yM(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 wM(n,e,t,r){try{let[i,o]=await Promise.all([n.listEmulators(),fM(e)]);if(i.length===0){r?.stop(),console.log(t==="json"?"[]":gn(" No emulator instances found."));return}let s=i.filter(h=>h.isRunning).map(h=>h.name),{productSerialMap:a,hvdSerialMap:c}=gM(o.serials,o.params,s);r?.stop();let l=yM(i,a,c);if(t==="json"){console.log(JSON.stringify(l,null,2));return}let d=l.map(pM);console.log(Mr(uM,d))}catch(i){throw r?.stop(),new Error(`Failed to list emulators: ${i.message}`,{cause:i})}}function Wb(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(tf(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(Zm(s.stdout)),s.stderr&&console.error(Zm(s.stderr))}return r}var vM=2e3,bM=6e4;async function SM(n,e){let t=_e(e);return(await rm(n)).some(i=>_e(i)===t)}async function Vb(n,e,t,r=bM,i=vM){let o=Date.now()+r;for(;Date.now()<o;){if(await SM(n,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}function EM(n){if(!n)return null;let e=n.indexOf("-bootmode");return e>=0&&e+1<n.length&&n[e+1]==="snapshot"}async function PM(n,e,t,r){let i=await n.startEmulator(t,r);if(i.status==="already-running")return console.log(gn(`Emulator "${t}" is already running.`)),{started:!1,memoryBytes:0,hotBoot:null};console.log(vo(`Starting emulator "${t}"...`));let o=i.tracker,s=0,a=EM(i.args);try{let c=await Vb(e,t,!0);console.log(c?Ks(`Emulator "${t}" started successfully.`):gn(`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 CM(n,e,t,r){let i=await Promise.allSettled(t.map(a=>PM(n,e,a,r)));if(Wb(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 Gb(n,e){let t=e.trim();if(!sr(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 kM(n,e,t){let r=await Gb(e,t);if(console.log(vo(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(gn(`Emulator "${r}" is already stopped.`));return}let o=await Vb(e,r,!1);console.log(o?Ks(`Emulator "${r}" stopped successfully.`):gn(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function DM(n,e,t){let r=await Promise.allSettled(t.map(i=>kM(n,e,i)));Wb(r,t,"stop")}async function It(){let n=await P.new();return{manager:co.from(n),toolProvider:n}}async function Fr(n,e,t){let r={event:v.CommandExecuted,args:["emulator",t,"--target"]};await xt(r,async()=>{let i=cM(n.target),o=e(),s=Array.isArray(o)?o:[o],{manager:a,toolProvider:c}=await It(),l=await Gb(c.hdcPath,i);for(let d of s)await a.controlEmulator(l,d);console.log(Ks(`Emulator "${i}" operation completed.`))})}function RM(n){let e=[];if(Nl(e,"longitude",n.longitude,-180,180,8),Nl(e,"latitude",n.latitude,-90,90,8),Nl(e,"altitude",n.altitude,-1e4,1e4,2),Nl(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(gn("Warning: --longitude and --latitude should be specified together to form a valid location.")),e}function xM(n){let e=[];if(Js(e,"light",n.lightIntensity,0,1e5,!1,"--light-intensity"),Js(e,"humidity",n.humidity,0,100,!1),Js(e,"temperature",n.temperature,-273.1,100,!1),Js(e,"steps",n.steps,0,1e4,!0),Js(e,"heartrate",n.heartrate,0,255,!0),e.length===0)throw new Error("Specify at least one sensor option.");return e}function Nl(n,e,t,r,i,o,s=`--${e}`){t!==void 0&&n.push({type:"gps",key:e,value:Bb(s,t,r,i,o)})}function Js(n,e,t,r,i,o,s=`--${e}`){if(t===void 0)return;let a=o?Ub(s,t,r,i):ui(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:Ub("--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 ef("emulator").description("Manage emulator instances");Se.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
1309
- ${gn("Tip: ")}${Zm("An option value containing spaces/parentheses must be quoted. Use:")}
1310
- ${vo('devecocli emulator <subcommand> --<option> "value with spaces"')}
1311
- ${vo('devecocli emulator <subcommand> --<option>="value with spaces"')}
1312
- `)}});Se.hook("preAction",async()=>{(await P.new()).require({studio:aM})});var AM=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function rf(n){let e=new Ge("--device-type <type>","Emulator device type").choices([...AM]);return n?e.makeOptionMandatory():e}function TM(){return new Ge("--device-type <type>","Emulator device type (case-insensitive)").argParser(n=>{if(!n.trim())throw new Xm("--device-type must not be empty.");return n}).makeOptionMandatory()}function OM(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).`);ui(`${i} width`,r[0],720,3500),ui(`${i} height`,r[1],720,3500),ui(`${i} DPI`,r[2],240,640),ui(`${i} screen diagonal length`,r[3],3.5,9)}return n}}function NM(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 wo(n,e){for(let t of e)if(t in n)return n[t]}function Ys(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function Hb(n){let e=Ys(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var MM=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],LM="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";async function _M(n,e,t){if(!await n.hasAvailableEmulatorImage({deviceType:e,osVersion:t}))throw new Error(`Invalid --os-version value "${t}".
1313
- Run \`devecocli emulator image list --all\` and use an exact OS Version value.`)}function qb(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function zb(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let i=r,o=Ys(wo(i,["osVersion","OsVersion","OSVersion","os_version"])),s=Ys(wo(i,["deviceType","DeviceType","device_type"])),a=Hb(wo(i,["downloaded","Downloaded","isDownloaded"])),c=Ys(wo(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=Ys(wo(i,["releaseType","ReleaseType","release_type"])),d=Hb(wo(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,l,d,a],highlight:e&&a==="true"})}return t}function $M(n){let e=n.trim();if(!e)return!0;let t=qb(e);return t===null?!1:t.length===0?!0:zb(t,!0).length===0}function FM(n,e){let t=n.trim();if(!t)return"";let r=qb(t);if(!r)return n.trimEnd();let i=zb(r,e);return Mr(MM,i)}var Ml=new ef("image").description("HarmonyOS emulator system images (download, list, remove)");Ml.command("download").description("Download system image").addOption(rf(!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 xt(e,async()=>{let{manager:t,toolProvider:r}=await It();await Km(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 _M(t,i,o),await t.installEmulatorImage({deviceType:i,osVersion:o,force:n.force===!0})})});Ml.command("remove").description("Remove a downloaded system image").addOption(rf(!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 xt(e,async()=>{let{manager:t}=await It();await t.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})})});Ml.command("list").description("List system images").addOption(rf(!1)).option("--all","List all images (local and remote)").addOption(new Ge("--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 xt(e,async()=>{let{manager:t}=await It(),r;n.all?r=void 0:r=!0;let i=await t.listEmulatorImages({deviceType:n.deviceType,downloaded:r});if($M(i)){console.log(gn(LM));return}if(n.format==="json"){console.log(i.trimEnd());return}let o=FM(i,n.all===!0);console.log(o)})});Se.addCommand(Ml);var Ll=new ef("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");Ll.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let n={event:v.CommandExecuted,args:["emulator","license","view"]};await xt(n,async()=>{let{toolProvider:e}=await It(),t=await Lb(e.emulatorPath,e.sdkPath);process.exitCode=t})});Ll.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 xt(n,async()=>{let{toolProvider:e}=await It(),t=await Fb(e.emulatorPath,e.sdkPath);process.exitCode=t})});Ll.action(async()=>{let n={event:v.CommandExecuted,args:["emulator","license"]};await xt(n,async()=>{let{toolProvider:e}=await It(),t=await $b(e.emulatorPath,e.sdkPath);process.exitCode=t})});Se.addCommand(Ll);Se.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Fr(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=>Fr(n,()=>({type:"power"}),"power"));Se.command("rotate").description("Rotate emulator").addOption(new Ge("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Qm("<direction>").choices(["left","right"])).action((n,e)=>Fr(e,()=>({type:"rotation",direction:n}),"rotate"));Se.command("volume").description("Change volume").addOption(new Ge("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Qm("<direction>").choices(["up","down"])).action((n,e)=>Fr(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",sM).action((n,e)=>Fr(e,()=>({type:"folded-state",state:lM(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 Ge("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>Fr(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=>Fr(n,()=>RM(n),"geolocation"));Se.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new Qm("<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 Fr(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=>Fr(n,()=>xM(n),"sensor"));Se.command("list").description("List all emulator instances").addOption(new Ge("--details","Output the raw JSON of `Emulator -list -details` without transformation").conflicts("format")).addOption(new Ge("--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 xt(e,async()=>{let{manager:t,toolProvider:r}=await It();if(n.details){let o=await t.listEmulatorDetails();console.log(o.trimEnd());return}let i=n.format==="table"?iM({text:"Listing emulators\u2026",color:"cyan"}).start():void 0;await wM(t,r.hdcPath,n.format,i)})});function jM(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Xm("--hdcport must be an integer in [10000, 16555].");let t=Number(e);if(t<1e4||t>16555)throw new Xm("--hdcport must be in [10000, 16555].");return t}function HM(n){return{hdcPort:n.hdcport,bootMode:n.bootMode,noWindow:n.window===!1}}function UM(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 Ge("--hdcport <port>","hdc port of the emulator, 10000-16555 (Emulator -hdcport)").argParser(jM)).addOption(new Ge("--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 Ge("--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",...UM(e)],emulatorMemory:"unknown",hotBoot:null};await xt(t,async()=>{let{manager:r,toolProvider:i}=await It();if(await Ym(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 CM(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 xt(e,async()=>{let{manager:t,toolProvider:r}=await It();if(!n?.length){console.error(tf("Error: missing required argument 'names'")),process.exitCode=1;return}await DM(t,r.hdcPath,n)})});var BM=Se.command("create <name>").description("Create a local emulator instance.").addOption(TM()).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 Ge("--path, --instance-path <path>","Emulator instance path")).option("--image-root <path>","Emulator image path").option("--screen-profile <model>","Emulator screen profile").addOption(new Ge("--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 Ge("--hot-boot <boolean>","Enable or disable hot boot").choices(["true","false"])).option("--force","Overwrite an existing emulator instance");BM.action(async(n,e)=>{let t={event:v.CommandExecuted,args:["emulator","create",...NM(e)]};await xt(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:OM(e.screen),storage:e.storage===void 0?void 0:ui("--storage",e.storage,2,1023),memory:e.memory===void 0?void 0:ui("--memory",e.memory,2,32),hotBoot:e.hotBoot===void 0?void 0:e.hotBoot==="true",force:e.force===!0},{manager:i}=await It();console.log(vo(`Creating emulator "${n}"...`)),await i.createVirtualDevice(r),console.log(Ks(`Emulator "${n}" created successfully.`))})});Se.command("delete <name>").description("Delete a local emulator instance").addOption(new Ge("--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 xt(t,async()=>{let{manager:r}=await It();console.log(vo(`Deleting emulator "${n}"...`));let i=await r.deleteVirtualDevice(n,e.instancePath);console.log(Ks(`Emulator "${i}" deleted successfully.`))})});var Jb=Se;import{Command as oL}from"commander";import{red as uf,cyan as qt}from"colorette";import*as gS from"readline";import*as fS from"crypto";import*as Yb from"http";import*as Kb from"crypto";import{URL as WM}from"url";var _l=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=Yb.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&&Kb.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 st from"fs";import*as yn from"path";import{homedir as zM}from"os";var jr={};IC(jr,{LocalCrypto:()=>jr,decryptForLocalStorage:()=>af,decryptForLocalStorageFromDirectory:()=>qM,encryptForLocalStorage:()=>sf,isEncryptedBlob:()=>cf});import*as pe from"fs";import*as ze from"path";import*as ot from"crypto";import*as Zb from"os";import{homedir as Qb}from"os";var qe=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var Xs=jn.ALGORITHM,eS=jn.IV_LENGTH,Zs=jn.KEY_LENGTH,Qs=jn.KEY_LENGTH,pi=jn.KEK_VERSIONS,$l=process.env.DEVECO_CLI_DATA_DIR?F():ze.join(Qb(),be.CONFIG_DIR_NAME,be.APP_NAME),Fl=ze.join(Qb(),".local","share",be.APP_NAME,"keys"),bo=ze.join($l,be.KEY_FILE_NAME);function Xb(n){return Zb.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 nf(n){return ze.join(Fl,`${n}.bin`)}function tS(){if(!pe.existsSync($l))try{pe.mkdirSync($l,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new qe(Xb($l)):n}if(!pe.existsSync(Fl))try{pe.mkdirSync(Fl,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new qe(Xb(ze.dirname(Fl))):n}}function rS(){tS();for(let n of pi){let e=nf(n);pe.existsSync(e)||pe.writeFileSync(e,ot.randomBytes(Zs),{mode:384})}}function nS(n){if(!pi.includes(n))throw new Error(`Invalid kekId: ${n}`);rS();let e=nf(n),t=pe.readFileSync(e);if(t.length===Zs)return t;let r=ot.randomBytes(Zs);return pe.writeFileSync(e,r,{mode:384}),r}function of(n,e){let t=ot.randomBytes(eS),r=nS(e),i=ot.createCipheriv(Xs,r,t),o=Buffer.concat([i.update(n),i.final()]),s=i.getAuthTag();return{version:1,algorithm:Xs,kekId:e,encryptedDek:o.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function iS(n,e){return oS(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function oS(n,e,t,r){let i=ot.createDecipheriv(Xs,e,Buffer.from(t,"base64"));return i.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([i.update(n),i.final()])}function sS(n,e){return oS(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function VM(){if(rS(),pe.existsSync(bo))return;let n=ot.randomBytes(Qs),e=of(n,pi[0]);pe.writeFileSync(bo,JSON.stringify(e,null,2),{mode:384})}function aS(){VM();let n=JSON.parse(pe.readFileSync(bo,"utf8")),e=iS(n,nS(n.kekId));if(e.length===Qs)return e;let t=ot.randomBytes(Qs),r=of(t,pi[0]);return pe.writeFileSync(bo,JSON.stringify(r,null,2),{mode:384}),t}function GM(){tS();for(let t of pi){let r=nf(t);pe.existsSync(r)||pe.writeFileSync(r,ot.randomBytes(Zs),{mode:384})}if(pe.existsSync(bo))return;let n=ot.randomBytes(Qs),e=of(n,pi[0]);pe.writeFileSync(bo,JSON.stringify(e,null,2),{mode:384})}function sf(n){let e=aS(),t=ot.randomBytes(eS),r=ot.createCipheriv(Xs,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o=r.getAuthTag();return{version:1,algorithm:Xs,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:o.toString("base64"),timeStamp:Date.now()}}function af(n){try{return sS(n,aS())}catch{throw GM(),new Error("Failed to decrypt local ciphertext")}}function qM(n,e){let t=ze.join(e,be.KEY_FILE_NAME),r=JSON.parse(pe.readFileSync(t,"utf8"));if(!pi.includes(r.kekId))throw new Error(`Invalid kekId: ${r.kekId}`);let i=ze.join(e,"keys",`${r.kekId}.bin`),o=ze.resolve(i),s=ze.resolve(ze.join(e,"keys"));if(!o.startsWith(s+ze.sep)&&o!==s)throw new Error("kekId resolves outside the keys directory");let a=pe.readFileSync(o);if(a.length!==Zs)throw new Error("Invalid external root key");let c=iS(r,a);if(c.length!==Qs)throw new Error("Invalid external data encryption key");return sS(n,c)}function cf(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 yt(){return process.env.DEVECO_CLI_AUTH_SOURCE===be.AUTH_SOURCE_DEVECO_CODE}var jl=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR?F():yn.join(zM(),be.CONFIG_DIR_NAME,be.APP_NAME);return yn.join(e,be.TOKEN_FILE_NAME)}ensureConfigDir(){let e=yn.dirname(this.getLocalTokenFilePath());st.existsSync(e)||st.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=jr.encryptForLocalStorage(e);this.ensureConfigDir();let r=this.getLocalTokenFilePath();st.writeFileSync(r,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return yt()?this.loadDevecoCodeToken():this.loadLocalJwtToken()}loadDevecoCodeToken(){if(!yt())return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;let t=yn.resolve(e);try{let r=yn.join(t,be.TOKEN_FILE_NAME);if(!st.existsSync(r))return null;let i=JSON.parse(st.readFileSync(r,"utf8"));return jr.isEncryptedBlob(i)?jr.decryptForLocalStorageFromDirectory(i,e):null}catch{return null}}async loadLocalJwtToken(){let e=this.getLocalTokenFilePath();try{if(!st.existsSync(e))return null;let t=JSON.parse(st.readFileSync(e,"utf8"));return jr.isEncryptedBlob(t)?jr.decryptForLocalStorage(t):null}catch(t){let r=t.code;return r==="EACCES"||r==="EPERM"||r==="ENOENT"||await this.clearToken(),null}}async clearToken(){if(yt()){m("clearToken: skipped, session managed by DevEco Code");return}let e=this.getLocalTokenFilePath();try{st.existsSync(e)&&st.unlinkSync(e)}catch(t){throw new Error("Failed to clear token",{cause:t})}}},Hr=new jl;import{spawn as JM}from"child_process";function YM(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 cS(n){if(!YM(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=JM(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}`))})})}function lS(n){let e=n.split(".");return e.length===3&&e.every(t=>t.length>0)}var Ur={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},mi={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},Hl={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},XM={[Ur.CHINA]:mi.CHINA,[Ur.RUSSIA]:mi.RUSSIA,[Ur.EUROPE]:mi.EUROPE,[Ur.SINGAPORE]:mi.CHINA},ZM={[Hl.CHINA]:Ur.CHINA,[Hl.SINGAPORE]:Ur.SINGAPORE,[Hl.EUROPE]:Ur.EUROPE,[Hl.RUSSIA]:Ur.RUSSIA};function dS(n){return XM[n]??mi.CHINA}function uS(n){return ZM[n]??Ur.CHINA}var lf=class{async getJwtToken(e,t,r,i,o){let s=e.split("&")[0],a=uS(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 h=d.data.trim();if(!lS(h))throw new Error("Invalid jwtToken format");return h}},pS=new lf;var df=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 Hr.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 Hr.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:dS(i.userInfo.nationalCode),isRealName:String(i.userInfo.realName)==="true"}}async fetchUserInfo(e,t){let r=await Hr.loadJwtToken();return r?this.getUserInfoFromJwt(r,e,t):null}},So=new df;import QM from"querystring";import{spawn as eL}from"child_process";function mS(n){try{let e=JSON.stringify({signInfo:[{agrType:Go.PRIVACY_ID,country:"CN",language:"zh_CN",isAgree:!0}]}),t=QM.stringify({nsp_svc:"as.user.sign",access_token:n,request:e}),r=eL("curl",["-s","-X","POST",Go.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 Ul=class{config;server=null;constructor(e){this.config={...qo,...e}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}async login(){try{m(`Login started, isDevecoCodeAuth: ${yt()}`);let e=this.generateClientSecret();this.server=new _l(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 qe("Non-China accounts are not supported.");let r=await pS.getJwtToken(t.tempToken,t.siteId,oe.CN_LOGIN_URL,this.config.tempTokenCheckUrl,this.config.appId);m("JWT token received");let i=await So.getUserInfoFromJwt(r,oe.CN_LOGIN_URL);if(!i)throw new qe("Login failed: failed to get user info");return m(`User info received: ${i.userName}`),await Hr.saveJwtToken(r),m("JWT token saved"),mS(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 Hr.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 Hr.clearToken()}return!0}async getUserInfo(e=!0){return So.fetchUserInfo(oe.CN_LOGIN_URL,e)}generateClientSecret(){return fS.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 cS(i)}async refreshToken(){return So.refreshToken(oe.CN_LOGIN_URL)}},Je=new Ul;function rL(){return yt()?"Not logged in. Please login via DevEco Code first.":"Please run `devecocli auth login` first."}function nL(n){if(n.length===0)return"";let e=Math.max(1,Math.floor(n.length/2));return`${n.slice(0,e)}****`}function iL(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:nL(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 Bl=class{config;constructor(e){this.config={...qo,...e}}updateConfig(e){this.config={...this.config,...e}}async listTeams(){let e=await So.fetchUserInfo(oe.CN_LOGIN_URL,!0);if(!e)throw new qe(rL());let t=await this.fetchTeamList(e.accessToken,e.userId),r=iL(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:mi.CHINA},timeout:15e3})}catch(o){let s=o.message;throw s.includes("401")?new qe("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}},hS=new Bl;async function wn(){return hS.listTeams()}async function Wl(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 R.track(n,s)}}function sL(n){if(n.length===0)return qt("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 aL(){return new Promise(n=>{let e=gS.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}var ea=new oL("auth").description("Authentication commands (login, logout, status, team)");async function cL(n){if(n||!process.stdin.isTTY){console.log(qt(n?"Opening browser for login... (--no-prompt: Enter confirmation skipped)":"Non-interactive terminal: opening browser for login without the Enter confirmation..."));return}console.log(qt("Press Enter to open browser for login (or pass --no-prompt to skip)...")),await aL()}async function lL(n){if(yt()){console.log(uf("Login is managed by DevEco Code. Login from DevEco Code instead."));return}let e={event:v.CommandExecuted,args:["auth","login"]};await Wl(e,async()=>{let t=await Je.getUserInfo();if(t){console.log(qt(`Already logged in, User Name:${t.userName}`));return}console.log(qt("Starting login process...")),await cL(n.prompt===!1);let r=await Je.login();console.log(qt(`Login successful. Logged in as ${r.userName}.`))},t=>{throw t instanceof qe||(t instanceof Error?t.message:String(t)).includes("Network connection failed")?t:new Error("Login failed",{cause:t})})}ea.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 lL(n)});ea.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(yt()){console.log(uf("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}let n={event:v.CommandExecuted,args:["auth","logout"]};await Wl(n,async()=>{let e=await Je.logout();console.log(e?qt("Logout successful"):qt("Already logged out."))},e=>new Error("Logout failed",{cause:e}))});ea.command("status").description("Show the currently logged-in user").action(async()=>{let n={event:v.CommandExecuted,args:["auth","status"]};await Wl(n,async()=>{let e=await Je.getUserInfo();if(!e){console.log(qt("Not logged in"));return}console.log(qt(`Current user: ${e.userName}`))},()=>{console.log(qt("Not logged in"))})});var dL=ea.command("team").description("Team-related commands");dL.command("list").description("List team accounts the current user has joined").action(async()=>{let n={event:v.CommandExecuted,args:["auth","team","list"]};await Wl(n,async()=>{let e=await wn();console.log(sL(e.teamList))},e=>{if(e instanceof qe){console.log(uf(e.message));return}throw new Error("Failed to list teams",{cause:e})})});var yS=ea;import{Command as pL}from"commander";import{green as mL,red as ta,cyan as wS,yellow as vS,dim as bS}from"colorette";import fL from"p-limit";import uL from"ora";var wt=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=uL(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)}};var hL="deveco";async function gL(n){let e=await es();if(n.all)return(await Qa(e)).map(r=>r.enName);{let r=(await ec(n.skill,e)).find(i=>i.enName===n.skill);if(!r)throw new Eo("errorCode",`Skill "${n.skill}" not found`);return[r.enName]}}function yL(n){if(n.all&&n.skill)throw new Eo("errorCode","`--all` and `--skill` cannot be specified together.");if(!n.all&&!n.skill)throw new Eo("errorCode","Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=$i(n.path,n.project,n.agent);return t&&Pr(t,"Project directory",n.force),e&&Pr(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}function wL(n,e,t){return!!(e||t||n.path||n.project||n.agent)}function vL(){return{agents:[hL],projectAgents:[],customPath:void 0}}async function bL(n,e,t){let r=yt()&&!wL(n,e,t)?vL():await Fi(n,e,t);return{skillNames:await gL(n),targets:r}}async function SL(n,e,t,r){let i=[],o=0,s=n.length,a=fL(5),c=n.map(l=>a(()=>EL(l)));for(let l=0;l<n.length;l++){let d=n[l],h=s>1?` (${l+1}/${s})`:"";t.start(`Installing ${d}${h}...`);let w=await c[l];if(!w.success){t.fail(),console.log(ta(`${d}: Download failed - ${w.error}`)),i.push({success:!1});continue}o+=w.buffer.length,t.stop();let D=await new nr().installArchiveSkill(d,w.buffer,e,r);i.push(...D)}return{results:i,diskBytes:o}}async function EL(n){try{return{buffer:await qu(n),success:!0}}catch(e){return{error:e instanceof Error?e.message:"unknown error",success:!1}}}async function PL(n){let e=new wt;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=yL(n),{skillNames:i,targets:o}=await bL(n,t,r),{results:s,diskBytes:a}=await SL(i,o,e,n.force??!1);return e.stop(),_i(s),{diskBytes:a,results:s}}catch(t){throw e.stop(),t}}function SS(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=>CL(s.error)))];return{opTotal:e,opSuccess:t,opFailed:i,opSkipped:r,...o.length>0?{failedErrors:o}:{}}}function CL(n){let e=/^([A-Za-z_][A-Za-z0-9_-]*)/.exec(n.trim());return e?e[1].slice(0,32):"error"}var Eo=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function kL(n){let e=n;return n instanceof Eo?n.code:e.code??e.name??"UnknownError"}function Vl(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 Gl(n,e,t){let r=Date.now(),i=!0,o=null,s={};try{s=await e()}catch(a){throw i=!1,o=kL(a),a}finally{let a={event:v.SkillOperation,subAction:n,args:t,...s};await R.track(a,{duration_ms:Date.now()-r,success:i,error_code:o})}}function DL(n){return Gl("add",async()=>{let{diskBytes:e,results:t}=await PL(n);return{diskUsage:ce(e),...n.skill?{skillName:n.skill}:{},...SS(t)}},Vl("add",n))}function RL(n){let{resolvedPath:e,resolvedProject:t}=$i(n.path,n.project,n.agent);return t&&Pr(t,"Project directory"),e&&Pr(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function xL(n,e){let t=new wt;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:i}=RL(e);t.stop();let o=await IL(e,n,r,i);return t.stop(),_i(o),o}catch(r){throw t.stop(),r}}async function IL(n,e,t,r){let i=n.agent||t?await Fi(n,t,r):r?{agents:[],explicitAgents:!1,projectAgents:Ze().map(o=>({project:r,agent:o}))}:{agents:Ze(),projectAgents:[]};return new nr().removeSkill(e,i)}var ra=new pL("skills").description("Manage HarmonyOS skills");ra.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async n=>{try{await Gl("list",async()=>{let e=new wt;try{e.start("Fetching skills...");let t=await es(),r=await Qa(t);if(r.length===0)return e.stop(),console.log(vS("No skills available.")),{resultTotal:0};e.succeed(`Fetched ${r.length} skills`);for(let i of r){if(!n.long){console.log(i.enName);continue}console.log(wS(i.enName)),console.log(bS(i.description));let o=Wu(i.enName);o.length>0&&console.log(mL(`Installed for: ${o.join(", ")}`)),console.log()}return{resultTotal:r.length}}finally{e.stop()}},Vl("list",n))}catch(e){console.error(ta(e.message)),process.exitCode=1}});ra.command("find <keyword>").description("Search skills by keyword").action(async n=>{try{await Gl("find",async()=>{let e=new wt;try{e.start("Searching skills...");let t=await es(),r=await ec(n,t);if(r.length===0)return console.log(vS(`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(wS(i.enName)),console.log(bS(i.description)),console.log();return{resultTotal:r.length,queryLen:n.length,keyword:n}}finally{e.stop()}},Vl("find"))}catch(e){console.error(ta(e.message)),process.exitCode=1}});ra.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","Replace existing Skill content; create missing project or custom target directories").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 DL(n)}catch(e){console.error(ta(e.message)),process.exitCode=1}});ra.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 Gl("remove",async()=>{let e=await xL(n.skill,n);return{skillName:n.skill,...SS(e)}},Vl("remove",n))}catch(e){console.error(ta(e.message)),process.exitCode=1}});var ES=ra;import{Command as AL,InvalidArgumentError as ql}from"commander";import{cyan as pf,red as CS}from"colorette";import TL from"ora";function OL(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 NL(n){return{event:v.CommandExecuted,args:OL(n),logType:n.crash?"crash":"common",level:n.level??"ALL",bundleName:n.bundleName??"ALL"}}function ML(n){return n instanceof y?n.traceMessage:n instanceof Error?n.code??n.name:"UnknownError"}async function LL(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=ML(o),console.error(CS(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await R.track(n,o).catch(()=>{})}}function _L(n){try{return E.parsePositiveInteger(n,"tail")}catch{throw new ql("`tail` must be a positive integer.")}}function PS(n,e){try{return E.parseDurationToSeconds(n,e)}catch{throw new ql(`${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 $L(n){try{return E.assertHilogLevel(n),n}catch{throw new ql("`level` must be one of: D, I, W, E, F.")}}function FL(n){try{return E.assertBundleNameStrict(n),n}catch(e){throw new ql(e.message)}}function jL(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.")}async function HL(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 UL(n,e,t,r){let i=E.filterLogsByRelativeWindow(n,t,r);return e.tail?E.getLastLines(i,e.tail):i}var BL=new AL("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(CS(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",$L).option("--bundle-name <bundle-name>","Filter by application bundle name",FL).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",_L).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>PS(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>PS(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await LL(NL(n),()=>WL(n))});async function WL(n){let e=TL({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};e.start();try{jL(n);let r=n.from,i=n.to,o=await P.new(),s=new on(o),a=await s.selectDevice(n.device);if(!a)throw new y("No active devices found.","No active devices found.");m(pf(`deviceId: ${a}`)),m(pf(`type: ${n.crash?"Crash logs":"Common logs"}`)),m(pf("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await HL(s,a,n,r,i);t(),n.crash&&c&&(c=UL(c,n,r,i)),c&&console.log(c)}finally{t()}}var kS=BL;import ia from"path";import Br from"fs";import hf from"process";import LS from"os";import{Command as n_}from"commander";import{green as TS,red as mf,cyan as i_,yellow as OS}from"colorette";import we from"fs-extra";import q from"path";import*as xS from"os";import{fileURLToPath as VL}from"url";var DS={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"}},GL=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"],Po=["phone","tablet","2in1","car","wearable","tv"],RS=["entry","src","main","module.json5"];function qL(){let n=import.meta.url,e=VL(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 IS(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()){IS(r,i);continue}we.existsSync(i)||(we.mkdirSync(q.dirname(i),{recursive:!0}),we.copyFileSync(r,i))}}function na(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 zL(n){if(DS[n])return DS[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function JL(n,e){if(e===22)return;let t=zL(e);t&&(na(q.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),na(q.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),na(q.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function YL(n){return GL.filter(t=>!we.existsSync(q.join(n,t))).length===0}function KL(n,e){let t=RS.join("/"),r=q.join(n,...RS),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
1308
+ `,aM="6.1.0";function cM(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function lM(n){let e=n.trim();if(!jb.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${jb.join(", ")}`);return e}function Ub(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 Bb(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&&!dM(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 dM(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function pi(n,e,t,r,i){return Number(Bb(n,e,t,r,i))}var uM=["Name","Status","Serial","Device Type","OS Version"];function pM(n){return{cells:[n.name,n.status,n.serial??"-",n.deviceType??"-",n.osVersion??"-"],highlight:n.status==="running"}}async function mM(n,e){let t=await Promise.all(e.map(async r=>{let i=await zi(n,r,oM);return[r,i]}));return new Map(t)}async function fM(n){let e=await tm(n),t=await mM(n,e);return{serials:e,params:t}}function hM(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 gM(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&&hM(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 yM(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 wM(n,e,t,r){try{let[i,o]=await Promise.all([n.listEmulators(),fM(e)]);if(i.length===0){r?.stop(),console.log(t==="json"?"[]":wn(" No emulator instances found."));return}let s=i.filter(h=>h.isRunning).map(h=>h.name),{productSerialMap:a,hvdSerialMap:c}=gM(o.serials,o.params,s);r?.stop();let l=yM(i,a,c);if(t==="json"){console.log(JSON.stringify(l,null,2));return}let d=l.map(pM);console.log(_r(uM,d))}catch(i){throw r?.stop(),new Error(`Failed to list emulators: ${i.message}`,{cause:i})}}function Wb(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(tf(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(Zm(s.stdout)),s.stderr&&console.error(Zm(s.stderr))}return r}var vM=2e3,bM=6e4;async function SM(n,e){let t=_e(e);return(await rm(n)).some(i=>_e(i)===t)}async function Vb(n,e,t,r=bM,i=vM){let o=Date.now()+r;for(;Date.now()<o;){if(await SM(n,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}function EM(n){if(!n)return null;let e=n.indexOf("-bootmode");return e>=0&&e+1<n.length&&n[e+1]==="snapshot"}async function PM(n,e,t,r){let i=await n.startEmulator(t,r);if(i.status==="already-running")return console.log(wn(`Emulator "${t}" is already running.`)),{started:!1,memoryBytes:0,hotBoot:null};console.log(bo(`Starting emulator "${t}"...`));let o=i.tracker,s=0,a=EM(i.args);try{let c=await Vb(e,t,!0);console.log(c?Zs(`Emulator "${t}" started successfully.`):wn(`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 CM(n,e,t,r){let i=await Promise.allSettled(t.map(a=>PM(n,e,a,r)));if(Wb(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":ae(o.reduce((a,c)=>a+c.memoryBytes,0)),hotBoot:o.length===0?null:o.every(a=>a.hotBoot===!0)}}async function Gb(n,e){let t=e.trim();if(!cr(t))return t;let r=await ce.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 kM(n,e,t){let r=await Gb(e,t);if(console.log(bo(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(wn(`Emulator "${r}" is already stopped.`));return}let o=await Vb(e,r,!1);console.log(o?Zs(`Emulator "${r}" stopped successfully.`):wn(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function DM(n,e,t){let r=await Promise.allSettled(t.map(i=>kM(n,e,i)));Wb(r,t,"stop")}async function At(){let n=await P.new();return{manager:lo.from(n),toolProvider:n}}async function Hr(n,e,t){let r={event:v.CommandExecuted,args:["emulator",t,"--target"]};await xt(r,async()=>{let i=cM(n.target),o=e(),s=Array.isArray(o)?o:[o],{manager:a,toolProvider:c}=await At(),l=await Gb(c.hdcPath,i);for(let d of s)await a.controlEmulator(l,d);console.log(Zs(`Emulator "${i}" operation completed.`))})}function RM(n){let e=[];if(Ml(e,"longitude",n.longitude,-180,180,8),Ml(e,"latitude",n.latitude,-90,90,8),Ml(e,"altitude",n.altitude,-1e4,1e4,2),Ml(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(wn("Warning: --longitude and --latitude should be specified together to form a valid location.")),e}function xM(n){let e=[];if(Ks(e,"light",n.lightIntensity,0,1e5,!1,"--light-intensity"),Ks(e,"humidity",n.humidity,0,100,!1),Ks(e,"temperature",n.temperature,-273.1,100,!1),Ks(e,"steps",n.steps,0,1e4,!0),Ks(e,"heartrate",n.heartrate,0,255,!0),e.length===0)throw new Error("Specify at least one sensor option.");return e}function Ml(n,e,t,r,i,o,s=`--${e}`){t!==void 0&&n.push({type:"gps",key:e,value:Bb(s,t,r,i,o)})}function Ks(n,e,t,r,i,o,s=`--${e}`){if(t===void 0)return;let a=o?Ub(s,t,r,i):pi(s,t,r,i,1);n.push({type:"sensor",key:e,value:a})}function AM(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:Ub("--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 ef("emulator").description("Manage emulator instances");Se.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
1309
+ ${wn("Tip: ")}${Zm("An option value containing spaces/parentheses must be quoted. Use:")}
1310
+ ${bo('devecocli emulator <subcommand> --<option> "value with spaces"')}
1311
+ ${bo('devecocli emulator <subcommand> --<option>="value with spaces"')}
1312
+ `)}});Se.hook("preAction",async()=>{(await P.new()).require({studio:aM})});var IM=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function rf(n){let e=new Ge("--device-type <type>","Emulator device type").choices([...IM]);return n?e.makeOptionMandatory():e}function TM(){return new Ge("--device-type <type>","Emulator device type (case-insensitive)").argParser(n=>{if(!n.trim())throw new Xm("--device-type must not be empty.");return n}).makeOptionMandatory()}function OM(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).`);pi(`${i} width`,r[0],720,3500),pi(`${i} height`,r[1],720,3500),pi(`${i} DPI`,r[2],240,640),pi(`${i} screen diagonal length`,r[3],3.5,9)}return n}}function NM(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 vo(n,e){for(let t of e)if(t in n)return n[t]}function Xs(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function Hb(n){let e=Xs(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var MM=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],LM="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";async function _M(n,e,t){if(!await n.hasAvailableEmulatorImage({deviceType:e,osVersion:t}))throw new Error(`Invalid --os-version value "${t}".
1313
+ Run \`devecocli emulator image list --all\` and use an exact OS Version value.`)}function qb(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function zb(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let i=r,o=Xs(vo(i,["osVersion","OsVersion","OSVersion","os_version"])),s=Xs(vo(i,["deviceType","DeviceType","device_type"])),a=Hb(vo(i,["downloaded","Downloaded","isDownloaded"])),c=Xs(vo(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=Xs(vo(i,["releaseType","ReleaseType","release_type"])),d=Hb(vo(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,l,d,a],highlight:e&&a==="true"})}return t}function $M(n){let e=n.trim();if(!e)return!0;let t=qb(e);return t===null?!1:t.length===0?!0:zb(t,!0).length===0}function FM(n,e){let t=n.trim();if(!t)return"";let r=qb(t);if(!r)return n.trimEnd();let i=zb(r,e);return _r(MM,i)}var Ll=new ef("image").description("HarmonyOS emulator system images (download, list, remove)");Ll.command("download").description("Download system image").addOption(rf(!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 xt(e,async()=>{let{manager:t,toolProvider:r}=await At();await Km(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 _M(t,i,o),await t.installEmulatorImage({deviceType:i,osVersion:o,force:n.force===!0})})});Ll.command("remove").description("Remove a downloaded system image").addOption(rf(!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 xt(e,async()=>{let{manager:t}=await At();await t.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})})});Ll.command("list").description("List system images").addOption(rf(!1)).option("--all","List all images (local and remote)").addOption(new Ge("--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 xt(e,async()=>{let{manager:t}=await At(),r;n.all?r=void 0:r=!0;let i=await t.listEmulatorImages({deviceType:n.deviceType,downloaded:r});if($M(i)){console.log(wn(LM));return}if(n.format==="json"){console.log(i.trimEnd());return}let o=FM(i,n.all===!0);console.log(o)})});Se.addCommand(Ll);var _l=new ef("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");_l.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let n={event:v.CommandExecuted,args:["emulator","license","view"]};await xt(n,async()=>{let{toolProvider:e}=await At(),t=await Lb(e.emulatorPath,e.sdkPath);process.exitCode=t})});_l.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 xt(n,async()=>{let{toolProvider:e}=await At(),t=await Fb(e.emulatorPath,e.sdkPath);process.exitCode=t})});_l.action(async()=>{let n={event:v.CommandExecuted,args:["emulator","license"]};await xt(n,async()=>{let{toolProvider:e}=await At(),t=await $b(e.emulatorPath,e.sdkPath);process.exitCode=t})});Se.addCommand(_l);Se.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Hr(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=>Hr(n,()=>({type:"power"}),"power"));Se.command("rotate").description("Rotate emulator").addOption(new Ge("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Qm("<direction>").choices(["left","right"])).action((n,e)=>Hr(e,()=>({type:"rotation",direction:n}),"rotate"));Se.command("volume").description("Change volume").addOption(new Ge("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Qm("<direction>").choices(["up","down"])).action((n,e)=>Hr(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",sM).action((n,e)=>Hr(e,()=>({type:"folded-state",state:lM(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 Ge("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>Hr(n,()=>AM(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=>Hr(n,()=>RM(n),"geolocation"));Se.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new Qm("<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 Hr(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=>Hr(n,()=>xM(n),"sensor"));Se.command("list").description("List all emulator instances").addOption(new Ge("--details","Output the raw JSON of `Emulator -list -details` without transformation").conflicts("format")).addOption(new Ge("--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 xt(e,async()=>{let{manager:t,toolProvider:r}=await At();if(n.details){let o=await t.listEmulatorDetails();console.log(o.trimEnd());return}let i=n.format==="table"?iM({text:"Listing emulators\u2026",color:"cyan"}).start():void 0;await wM(t,r.hdcPath,n.format,i)})});function jM(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Xm("--hdcport must be an integer in [10000, 16555].");let t=Number(e);if(t<1e4||t>16555)throw new Xm("--hdcport must be in [10000, 16555].");return t}function HM(n){return{hdcPort:n.hdcport,bootMode:n.bootMode,noWindow:n.window===!1}}function UM(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 Ge("--hdcport <port>","hdc port of the emulator, 10000-16555 (Emulator -hdcport)").argParser(jM)).addOption(new Ge("--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 Ge("--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",...UM(e)],emulatorMemory:"unknown",hotBoot:null};await xt(t,async()=>{let{manager:r,toolProvider:i}=await At();if(await Ym(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 CM(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 xt(e,async()=>{let{manager:t,toolProvider:r}=await At();if(!n?.length){console.error(tf("Error: missing required argument 'names'")),process.exitCode=1;return}await DM(t,r.hdcPath,n)})});var BM=Se.command("create <name>").description("Create a local emulator instance.").addOption(TM()).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 Ge("--path, --instance-path <path>","Emulator instance path")).option("--image-root <path>","Emulator image path").option("--screen-profile <model>","Emulator screen profile").addOption(new Ge("--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 Ge("--hot-boot <boolean>","Enable or disable hot boot").choices(["true","false"])).option("--force","Overwrite an existing emulator instance");BM.action(async(n,e)=>{let t={event:v.CommandExecuted,args:["emulator","create",...NM(e)]};await xt(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:OM(e.screen),storage:e.storage===void 0?void 0:pi("--storage",e.storage,2,1023),memory:e.memory===void 0?void 0:pi("--memory",e.memory,2,32),hotBoot:e.hotBoot===void 0?void 0:e.hotBoot==="true",force:e.force===!0},{manager:i}=await At();console.log(bo(`Creating emulator "${n}"...`)),await i.createVirtualDevice(r),console.log(Zs(`Emulator "${n}" created successfully.`))})});Se.command("delete <name>").description("Delete a local emulator instance").addOption(new Ge("--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 xt(t,async()=>{let{manager:r}=await At();console.log(bo(`Deleting emulator "${n}"...`));let i=await r.deleteVirtualDevice(n,e.instancePath);console.log(Zs(`Emulator "${i}" deleted successfully.`))})});var Jb=Se;import{Command as oL}from"commander";import{red as uf,cyan as zt}from"colorette";import*as gS from"readline";import*as fS from"crypto";import*as Yb from"http";import*as Kb from"crypto";import{URL as WM}from"url";var $l=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=Yb.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&&Kb.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 st from"fs";import*as vn from"path";import{homedir as zM}from"os";var Ur={};AC(Ur,{LocalCrypto:()=>Ur,decryptForLocalStorage:()=>af,decryptForLocalStorageFromDirectory:()=>qM,encryptForLocalStorage:()=>sf,isEncryptedBlob:()=>cf});import*as ue from"fs";import*as ze from"path";import*as ot from"crypto";import*as Zb from"os";import{homedir as Qb}from"os";var qe=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var Qs=Un.ALGORITHM,eS=Un.IV_LENGTH,ea=Un.KEY_LENGTH,ta=Un.KEY_LENGTH,mi=Un.KEK_VERSIONS,Fl=process.env.DEVECO_CLI_DATA_DIR?F():ze.join(Qb(),be.CONFIG_DIR_NAME,be.APP_NAME),jl=ze.join(Qb(),".local","share",be.APP_NAME,"keys"),So=ze.join(Fl,be.KEY_FILE_NAME);function Xb(n){return Zb.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 nf(n){return ze.join(jl,`${n}.bin`)}function tS(){if(!ue.existsSync(Fl))try{ue.mkdirSync(Fl,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new qe(Xb(Fl)):n}if(!ue.existsSync(jl))try{ue.mkdirSync(jl,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new qe(Xb(ze.dirname(jl))):n}}function rS(){tS();for(let n of mi){let e=nf(n);ue.existsSync(e)||ue.writeFileSync(e,ot.randomBytes(ea),{mode:384})}}function nS(n){if(!mi.includes(n))throw new Error(`Invalid kekId: ${n}`);rS();let e=nf(n),t=ue.readFileSync(e);if(t.length===ea)return t;let r=ot.randomBytes(ea);return ue.writeFileSync(e,r,{mode:384}),r}function of(n,e){let t=ot.randomBytes(eS),r=nS(e),i=ot.createCipheriv(Qs,r,t),o=Buffer.concat([i.update(n),i.final()]),s=i.getAuthTag();return{version:1,algorithm:Qs,kekId:e,encryptedDek:o.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function iS(n,e){return oS(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function oS(n,e,t,r){let i=ot.createDecipheriv(Qs,e,Buffer.from(t,"base64"));return i.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([i.update(n),i.final()])}function sS(n,e){return oS(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function VM(){if(rS(),ue.existsSync(So))return;let n=ot.randomBytes(ta),e=of(n,mi[0]);ue.writeFileSync(So,JSON.stringify(e,null,2),{mode:384})}function aS(){VM();let n=JSON.parse(ue.readFileSync(So,"utf8")),e=iS(n,nS(n.kekId));if(e.length===ta)return e;let t=ot.randomBytes(ta),r=of(t,mi[0]);return ue.writeFileSync(So,JSON.stringify(r,null,2),{mode:384}),t}function GM(){tS();for(let t of mi){let r=nf(t);ue.existsSync(r)||ue.writeFileSync(r,ot.randomBytes(ea),{mode:384})}if(ue.existsSync(So))return;let n=ot.randomBytes(ta),e=of(n,mi[0]);ue.writeFileSync(So,JSON.stringify(e,null,2),{mode:384})}function sf(n){let e=aS(),t=ot.randomBytes(eS),r=ot.createCipheriv(Qs,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o=r.getAuthTag();return{version:1,algorithm:Qs,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:o.toString("base64"),timeStamp:Date.now()}}function af(n){try{return sS(n,aS())}catch{throw GM(),new Error("Failed to decrypt local ciphertext")}}function qM(n,e){let t=ze.join(e,be.KEY_FILE_NAME),r=JSON.parse(ue.readFileSync(t,"utf8"));if(!mi.includes(r.kekId))throw new Error(`Invalid kekId: ${r.kekId}`);let i=ze.join(e,"keys",`${r.kekId}.bin`),o=ze.resolve(i),s=ze.resolve(ze.join(e,"keys"));if(!o.startsWith(s+ze.sep)&&o!==s)throw new Error("kekId resolves outside the keys directory");let a=ue.readFileSync(o);if(a.length!==ea)throw new Error("Invalid external root key");let c=iS(r,a);if(c.length!==ta)throw new Error("Invalid external data encryption key");return sS(n,c)}function cf(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 yt(){return process.env.DEVECO_CLI_AUTH_SOURCE===be.AUTH_SOURCE_DEVECO_CODE}var Hl=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR?F():vn.join(zM(),be.CONFIG_DIR_NAME,be.APP_NAME);return vn.join(e,be.TOKEN_FILE_NAME)}ensureConfigDir(){let e=vn.dirname(this.getLocalTokenFilePath());st.existsSync(e)||st.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=Ur.encryptForLocalStorage(e);this.ensureConfigDir();let r=this.getLocalTokenFilePath();st.writeFileSync(r,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return yt()?this.loadDevecoCodeToken():this.loadLocalJwtToken()}loadDevecoCodeToken(){if(!yt())return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;let t=vn.resolve(e);try{let r=vn.join(t,be.TOKEN_FILE_NAME);if(!st.existsSync(r))return null;let i=JSON.parse(st.readFileSync(r,"utf8"));return Ur.isEncryptedBlob(i)?Ur.decryptForLocalStorageFromDirectory(i,e):null}catch{return null}}async loadLocalJwtToken(){let e=this.getLocalTokenFilePath();try{if(!st.existsSync(e))return null;let t=JSON.parse(st.readFileSync(e,"utf8"));return Ur.isEncryptedBlob(t)?Ur.decryptForLocalStorage(t):null}catch(t){let r=t.code;return r==="EACCES"||r==="EPERM"||r==="ENOENT"||await this.clearToken(),null}}async clearToken(){if(yt()){m("clearToken: skipped, session managed by DevEco Code");return}let e=this.getLocalTokenFilePath();try{st.existsSync(e)&&st.unlinkSync(e)}catch(t){throw new Error("Failed to clear token",{cause:t})}}},Br=new Hl;import{spawn as JM}from"child_process";function YM(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 cS(n){if(!YM(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=JM(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}`))})})}function lS(n){let e=n.split(".");return e.length===3&&e.every(t=>t.length>0)}var Wr={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},fi={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},Ul={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},XM={[Wr.CHINA]:fi.CHINA,[Wr.RUSSIA]:fi.RUSSIA,[Wr.EUROPE]:fi.EUROPE,[Wr.SINGAPORE]:fi.CHINA},ZM={[Ul.CHINA]:Wr.CHINA,[Ul.SINGAPORE]:Wr.SINGAPORE,[Ul.EUROPE]:Wr.EUROPE,[Ul.RUSSIA]:Wr.RUSSIA};function dS(n){return XM[n]??fi.CHINA}function uS(n){return ZM[n]??Wr.CHINA}var lf=class{async getJwtToken(e,t,r,i,o){let s=e.split("&")[0],a=uS(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 h=d.data.trim();if(!lS(h))throw new Error("Invalid jwtToken format");return h}},pS=new lf;var df=class{async checkJwtToken(e,t,r=!1){let i={refresh:String(r),jwtToken:e},o=`${t}/${ie.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 Br.loadJwtToken();return t?this.refreshTokenWithToken(t,e):null}async refreshTokenWithToken(e,t){try{let r={refresh:"true",jwtToken:e},i=`${t}/${ie.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 Br.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:dS(i.userInfo.nationalCode),isRealName:String(i.userInfo.realName)==="true"}}async fetchUserInfo(e,t){let r=await Br.loadJwtToken();return r?this.getUserInfoFromJwt(r,e,t):null}},Eo=new df;import QM from"querystring";import{spawn as eL}from"child_process";function mS(n){try{let e=JSON.stringify({signInfo:[{agrType:qo.PRIVACY_ID,country:"CN",language:"zh_CN",isAgree:!0}]}),t=QM.stringify({nsp_svc:"as.user.sign",access_token:n,request:e}),r=eL("curl",["-s","-X","POST",qo.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 Bl=class{config;server=null;constructor(e){this.config={...zo,...e}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}async login(){try{m(`Login started, isDevecoCodeAuth: ${yt()}`);let e=this.generateClientSecret();this.server=new $l(e,ie.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 qe("Non-China accounts are not supported.");let r=await pS.getJwtToken(t.tempToken,t.siteId,ie.CN_LOGIN_URL,this.config.tempTokenCheckUrl,this.config.appId);m("JWT token received");let i=await Eo.getUserInfoFromJwt(r,ie.CN_LOGIN_URL);if(!i)throw new qe("Login failed: failed to get user info");return m(`User info received: ${i.userName}`),await Br.saveJwtToken(r),m("JWT token saved"),mS(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 Br.loadJwtToken();if(!e)return!1;let r=`${ie.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 Br.clearToken()}return!0}async getUserInfo(e=!0){return Eo.fetchUserInfo(ie.CN_LOGIN_URL,e)}generateClientSecret(){return fS.randomUUID().replace(/-/g,"")}async openLoginPage(e,t){let i=`${ie.CN_LOGIN_URL}/${this.config.authUrl}?port=${e}&appid=${this.config.appId}&code=${t}`;await cS(i)}async refreshToken(){return Eo.refreshToken(ie.CN_LOGIN_URL)}},Je=new Bl;function rL(){return yt()?"Not logged in. Please login via DevEco Code first.":"Please run `devecocli auth login` first."}function nL(n){if(n.length===0)return"";let e=Math.max(1,Math.floor(n.length/2));return`${n.slice(0,e)}****`}function iL(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:nL(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 Wl=class{config;constructor(e){this.config={...zo,...e}}updateConfig(e){this.config={...this.config,...e}}async listTeams(){let e=await Eo.fetchUserInfo(ie.CN_LOGIN_URL,!0);if(!e)throw new qe(rL());let t=await this.fetchTeamList(e.accessToken,e.userId),r=iL(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:fi.CHINA},timeout:15e3})}catch(o){let s=o.message;throw s.includes("401")?new qe("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}},hS=new Wl;async function bn(){return hS.listTeams()}async function Vl(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 sL(n){if(n.length===0)return zt("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 aL(){return new Promise(n=>{let e=gS.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}var ra=new oL("auth").description("Authentication commands (login, logout, status, team)");async function cL(n){if(n||!process.stdin.isTTY){console.log(zt(n?"Opening browser for login... (--no-prompt: Enter confirmation skipped)":"Non-interactive terminal: opening browser for login without the Enter confirmation..."));return}console.log(zt("Press Enter to open browser for login (or pass --no-prompt to skip)...")),await aL()}async function lL(n){if(yt()){console.log(uf("Login is managed by DevEco Code. Login from DevEco Code instead."));return}let e={event:v.CommandExecuted,args:["auth","login"]};await Vl(e,async()=>{let t=await Je.getUserInfo();if(t){console.log(zt(`Already logged in, User Name:${t.userName}`));return}console.log(zt("Starting login process...")),await cL(n.prompt===!1);let r=await Je.login();console.log(zt(`Login successful. Logged in as ${r.userName}.`))},t=>{throw t instanceof qe||(t instanceof Error?t.message:String(t)).includes("Network connection failed")?t:new Error("Login failed",{cause:t})})}ra.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 lL(n)});ra.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(yt()){console.log(uf("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}let n={event:v.CommandExecuted,args:["auth","logout"]};await Vl(n,async()=>{let e=await Je.logout();console.log(e?zt("Logout successful"):zt("Already logged out."))},e=>new Error("Logout failed",{cause:e}))});ra.command("status").description("Show the currently logged-in user").action(async()=>{let n={event:v.CommandExecuted,args:["auth","status"]};await Vl(n,async()=>{let e=await Je.getUserInfo();if(!e){console.log(zt("Not logged in"));return}console.log(zt(`Current user: ${e.userName}`))},()=>{console.log(zt("Not logged in"))})});var dL=ra.command("team").description("Team-related commands");dL.command("list").description("List team accounts the current user has joined").action(async()=>{let n={event:v.CommandExecuted,args:["auth","team","list"]};await Vl(n,async()=>{let e=await bn();console.log(sL(e.teamList))},e=>{if(e instanceof qe){console.log(uf(e.message));return}throw new Error("Failed to list teams",{cause:e})})});var yS=ra;import{Command as pL}from"commander";import{green as mL,red as na,cyan as wS,yellow as vS,dim as bS}from"colorette";import fL from"p-limit";import uL from"ora";var wt=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=uL(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)}};var hL="deveco";async function gL(n){let e=await ts();if(n.all)return(await tc(e)).map(r=>r.enName);{let r=(await rc(n.skill,e)).find(i=>i.enName===n.skill);if(!r)throw new Po("errorCode",`Skill "${n.skill}" not found`);return[r.enName]}}function yL(n){if(n.all&&n.skill)throw new Po("errorCode","`--all` and `--skill` cannot be specified together.");if(!n.all&&!n.skill)throw new Po("errorCode","Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=Fi(n.path,n.project,n.agent);return t&&Cr(t,"Project directory",n.force),e&&Cr(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}function wL(n,e,t){return!!(e||t||n.path||n.project||n.agent)}function vL(){return{agents:[hL],projectAgents:[],customPath:void 0}}async function bL(n,e,t){let r=yt()&&!wL(n,e,t)?vL():await ji(n,e,t);return{skillNames:await gL(n),targets:r}}async function SL(n,e,t,r){let i=[],o=0,s=n.length,a=fL(5),c=n.map(l=>a(()=>EL(l)));for(let l=0;l<n.length;l++){let d=n[l],h=s>1?` (${l+1}/${s})`:"";t.start(`Installing ${d}${h}...`);let w=await c[l];if(!w.success){t.fail(),console.log(na(`${d}: Download failed - ${w.error}`)),i.push({success:!1});continue}o+=w.buffer.length,t.stop();let R=await new ir().installArchiveSkill(d,w.buffer,e,r);i.push(...R)}return{results:i,diskBytes:o}}async function EL(n){try{return{buffer:await zu(n),success:!0}}catch(e){return{error:e instanceof Error?e.message:"unknown error",success:!1}}}async function PL(n){let e=new wt;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=yL(n),{skillNames:i,targets:o}=await bL(n,t,r),{results:s,diskBytes:a}=await SL(i,o,e,n.force??!1);return e.stop(),$i(s),{diskBytes:a,results:s}}catch(t){throw e.stop(),t}}function SS(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=>CL(s.error)))];return{opTotal:e,opSuccess:t,opFailed:i,opSkipped:r,...o.length>0?{failedErrors:o}:{}}}function CL(n){let e=/^([A-Za-z_][A-Za-z0-9_-]*)/.exec(n.trim());return e?e[1].slice(0,32):"error"}var Po=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function kL(n){let e=n;return n instanceof Po?n.code:e.code??e.name??"UnknownError"}function Gl(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 ql(n,e,t){let r=Date.now(),i=!0,o=null,s={};try{s=await e()}catch(a){throw i=!1,o=kL(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 DL(n){return ql("add",async()=>{let{diskBytes:e,results:t}=await PL(n);return{diskUsage:ae(e),...n.skill?{skillName:n.skill}:{},...SS(t)}},Gl("add",n))}function RL(n){let{resolvedPath:e,resolvedProject:t}=Fi(n.path,n.project,n.agent);return t&&Cr(t,"Project directory"),e&&Cr(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function xL(n,e){let t=new wt;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:i}=RL(e);t.stop();let o=await AL(e,n,r,i);return t.stop(),$i(o),o}catch(r){throw t.stop(),r}}async function AL(n,e,t,r){let i=n.agent||t?await ji(n,t,r):r?{agents:[],explicitAgents:!1,projectAgents:Ze().map(o=>({project:r,agent:o}))}:{agents:Ze(),projectAgents:[]};return new ir().removeSkill(e,i)}var ia=new pL("skills").description("Manage HarmonyOS skills");ia.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async n=>{try{await ql("list",async()=>{let e=new wt;try{e.start("Fetching skills...");let t=await ts(),r=await tc(t);if(r.length===0)return e.stop(),console.log(vS("No skills available.")),{resultTotal:0};e.succeed(`Fetched ${r.length} skills`);for(let i of r){if(!n.long){console.log(i.enName);continue}console.log(wS(i.enName)),console.log(bS(i.description));let o=Vu(i.enName);o.length>0&&console.log(mL(`Installed for: ${o.join(", ")}`)),console.log()}return{resultTotal:r.length}}finally{e.stop()}},Gl("list",n))}catch(e){console.error(na(e.message)),process.exitCode=1}});ia.command("find <keyword>").description("Search skills by keyword").action(async n=>{try{await ql("find",async()=>{let e=new wt;try{e.start("Searching skills...");let t=await ts(),r=await rc(n,t);if(r.length===0)return console.log(vS(`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(wS(i.enName)),console.log(bS(i.description)),console.log();return{resultTotal:r.length,queryLen:n.length,keyword:n}}finally{e.stop()}},Gl("find"))}catch(e){console.error(na(e.message)),process.exitCode=1}});ia.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","Replace existing Skill content; create missing project or custom target directories").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 DL(n)}catch(e){console.error(na(e.message)),process.exitCode=1}});ia.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 ql("remove",async()=>{let e=await xL(n.skill,n);return{skillName:n.skill,...SS(e)}},Gl("remove",n))}catch(e){console.error(na(e.message)),process.exitCode=1}});var ES=ia;import{Command as IL,InvalidArgumentError as zl}from"commander";import{cyan as pf,red as CS}from"colorette";import TL from"ora";function OL(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 NL(n){return{event:v.CommandExecuted,args:OL(n),logType:n.crash?"crash":"common",level:n.level??"ALL",bundleName:n.bundleName??"ALL"}}function ML(n){return n instanceof y?n.traceMessage:n instanceof Error?n.code??n.name:"UnknownError"}async function LL(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=ML(o),console.error(CS(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 _L(n){try{return E.parsePositiveInteger(n,"tail")}catch{throw new zl("`tail` must be a positive integer.")}}function PS(n,e){try{return E.parseDurationToSeconds(n,e)}catch{throw new zl(`${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 $L(n){try{return E.assertHilogLevel(n),n}catch{throw new zl("`level` must be one of: D, I, W, E, F.")}}function FL(n){try{return E.assertBundleNameStrict(n),n}catch(e){throw new zl(e.message)}}function jL(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.")}async function HL(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 UL(n,e,t,r){let i=E.filterLogsByRelativeWindow(n,t,r);return e.tail?E.getLastLines(i,e.tail):i}var BL=new IL("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(CS(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",$L).option("--bundle-name <bundle-name>","Filter by application bundle name",FL).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",_L).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>PS(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>PS(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await LL(NL(n),()=>WL(n))});async function WL(n){let e=TL({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};e.start();try{jL(n);let r=n.from,i=n.to,o=await P.new(),s=new an(o),a=await s.selectDevice(n.device);if(!a)throw new y("No active devices found.","No active devices found.");m(pf(`deviceId: ${a}`)),m(pf(`type: ${n.crash?"Crash logs":"Common logs"}`)),m(pf("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await HL(s,a,n,r,i);t(),n.crash&&c&&(c=UL(c,n,r,i)),c&&console.log(c)}finally{t()}}var kS=BL;import sa from"path";import Vr from"fs";import hf from"process";import LS from"os";import{Command as n_}from"commander";import{green as TS,red as mf,cyan as i_,yellow as OS}from"colorette";import we from"fs-extra";import z from"path";import*as xS from"os";import{fileURLToPath as VL}from"url";var DS={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"}},GL=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"],Co=["phone","tablet","2in1","car","wearable","tv"],RS=["entry","src","main","module.json5"];function qL(){let n=import.meta.url,e=VL(n);if(e.includes("dist")){let o=z.dirname(e),s=z.dirname(o);return z.join(s,"templates","application")}let t=z.dirname(e),r=z.dirname(t),i=z.dirname(r);return z.join(i,"templates","application")}function AS(n,e){we.mkdirSync(e,{recursive:!0});for(let t of we.readdirSync(n,{withFileTypes:!0})){let r=z.join(n,t.name),i=z.join(e,t.name);if(t.isDirectory()){AS(r,i);continue}we.existsSync(i)||(we.mkdirSync(z.dirname(i),{recursive:!0}),we.copyFileSync(r,i))}}function oa(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 zL(n){if(DS[n])return DS[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function JL(n,e){if(e===22)return;let t=zL(e);t&&(oa(z.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),oa(z.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),oa(z.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function YL(n){return GL.filter(t=>!we.existsSync(z.join(n,t))).length===0}function KL(n,e){let t=RS.join("/"),r=z.join(n,...RS),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
1315
  `)?`\r
1316
1316
  `:`
1317
- `,a=o[1],c=e.map((d,h)=>`${a} "${d}"${h<e.length-1?",":""}`).join(s),l=`${a}"deviceTypes": [${s}${c}${s}${a}]`;we.writeFileSync(r,i.replace(o[0],()=>l),"utf-8")}function XL(){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 ZL(n){return xS.platform()==="darwin"?q.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):q.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function QL(n,e){let t=ZL(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 e_(n){let e=XL(),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 t_(n,e){e&&QL(n,e)||e_(n)}function r_(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 AS(n,e,t,r,i,o){let s=qL();if(!we.existsSync(s))throw new Error(`Template directory not found: ${s}`);we.mkdirSync(n,{recursive:!0}),IS(s,n),r_(n),t_(n,o),na(q.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),na(q.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),KL(n,i),JL(n,r);let a=YL(n);if(!a)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,deviceTypes:i,verified:a}}function o_(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 s_(n){if(!n||n.length===0)return[Po[0]];let e=n.map(r=>r.toLowerCase()),t=n.filter((r,i)=>!Po.includes(e[i]));if(t.length>0)throw new Ee("errorCode",`Unsupported device type(s): ${t.map(r=>`"${r}"`).join(", ")}. Supported types: ${Po.join(", ")}`);return[...new Set(e)]}function _S(n){if(LS.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function NS(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=LS.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=_S(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 a_(n){let e=n,t=ia.parse(n).root;for(;e!==t;){if(Br.existsSync(e))return e;e=ia.dirname(e)}return Br.existsSync(t)?t:null}function MS(n){let e=a_(n);if(!e)throw new Ee("errorCode",`No existing parent directory found for '${n}'. Cannot create project directory.`);try{Br.accessSync(e,Br.constants.W_OK)}catch{throw new Ee("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}let t=ia.join(e,`.deveco_write_test_${Date.now()}`);try{Br.writeFileSync(t,"test"),Br.unlinkSync(t)}catch{throw new Ee("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}}function c_(n){return`com.example.${n.toLowerCase()}`}function l_(n,e){if(e){let i=_S(e),o=ia.resolve(i);if(Br.existsSync(o)){if(Br.readdirSync(o).length>0)throw new Ee("errorCode",`Directory '${o}' is not empty. Cannot create project here.`)}else MS(o);return o}let t=hf.cwd(),r=ia.join(t,n);if(Br.existsSync(r))throw new Ee("errorCode",`Directory '${r}' already exists. Cannot create project here.`);return MS(r),r}function d_(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 u_(){try{return await P.new()}catch(n){console.error(OS(`DevEco Studio not found: ${n.message}`)),console.log(OS("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 ff(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 R.track(i,o).catch(()=>{})}function p_(n){console.log(`
1318
- `+TS("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(TS("Template integrity check passed."))}var m_=new n_("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: ${Po[0]}; supported: ${Po.join(", ")})`).action(async n=>{let e=Date.now();try{n.appName||(console.error(mf("Error: --app-name is required")),await ff(e,!1,"errorCode",n),hf.exit(1));let t=n.appName;o_(t);let r=s_(n.deviceTypes),i=n.bundleName||c_(t);E.assertBundleNameStrict(i),n.projectPath&&NS(n.projectPath);let o=l_(t,n.projectPath);NS(o),console.log(i_("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 u_(),a=d_(n,s);console.log(`API level: ${a}`);let c=s?.devecoStudioPath,l=AS(o,t,i,a,r,c);p_(l),await ff(e,!0,null,n)}catch(t){let r=t,o=t instanceof Ee?t.code:r.code??r.name??"UnknownError";console.error(mf(`
1319
- Failed to create project.`)),console.error(mf(r.message)),await ff(e,!1,o,n),hf.exit(1)}}),$S=m_;import{Command as f_}from"commander";import{red as h_,cyan as jS}from"colorette";function HS(n){return[...new Set([...n.agents,...n.projectAgents.map(({agent:e})=>e)])]}async function FS(n,e,t,r){await R.track(n,{duration_ms:Date.now()-e,success:t,error_code:r}).catch(()=>{})}async function g_(n,e,t,r,i){let o={event:v.SkillConfigOperation,subAction:"install",targetType:t?"path":r?"project":"global",agents:HS(n)},s=Date.now();try{let a=await new nr().installBundledSkill(e,n,i),c=a.every(l=>l.success);return await FS(o,s,c,c?null:"SKILL_INSTALL_FAILED"),a}catch(a){let c=a instanceof Error?a.code??a.name:"UnknownError";throw await FS(o,s,!1,c),a}}async function y_(n,e,t){let r=[];for(let{project:i,agent:o}of n.projectAgents){let s=await ac(o,i,t);r.push(s)}for(let i of n.agents){let o=await ac(i,e,t);r.push(o)}return r}async function w_(n,e){let t=[];for(let r of n){if(!Sr[r])continue;let o=await np(r,process.cwd(),e);t.push(o)}return t}function gf(n){return n!=="qoder"&&n!=="dsh"&&!!Sr[n]}async function v_(n,e,t){let r=HS(n).find(l=>!gf(l));if(t.agent&&r)throw new Error(`${r} 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=>gf(l.agent)),s=n.agents.filter(gf);if(o.length===0&&s.length===0)throw new Error("No agents supporting MCP configuration found; use --skill");let a={...n,projectAgents:o,agents:s},c=e?await y_(a,e,i):await w_(a.agents,i);c.length>0&&(console.log(jS("MCP Configuration:")),ip(c))}async function b_(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 v_(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 R.track(r,a)}}async function S_(n){if(n.path&&n.mcp)throw new Error("--path applies to Skill installation only; remove --mcp");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}=$i(n.path,n.project,n.agent);if(t&&Pr(t,"Project directory",n.force),e&&Pr(e,"Directory",n.force),n.mcp){let s=await op(n,t);await b_(s,t,n);return}let r=await Fi(n,e,t),i=qn(),o=await g_(r,i,e,t,n.force??!1);console.log(),o.length>0&&(console.log(jS("Skill Installation:")),_i(o))}var E_=new f_("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","Replace existing Skill content or MCP configuration; create missing target directories").action(async n=>{try{await S_(n)}catch(e){console.error(h_(e instanceof Error?e.message:String(e))),process.exitCode=1}}),US=E_;import{Command as T0}from"commander";import{McpServer as g0}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as y0}from"@modelcontextprotocol/sdk/server/stdio.js";import*as pa from"fs";import*as Fo from"path";import{z as De}from"zod";import zl from"path";function VS(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=P_(o);break;case"hover":s={hit:Co(o)!=null};break;case"definition":case"declaration":s=BS(o,t,r,i,!0);break;case"references":s=k_(o);break;case"implementation":s=BS(o,t,r,i,!1);break;case"documentSymbol":s=D_(o);break;case"callHierarchy":s=R_(o,t,r,i);break;case"workspaceSymbol":s=x_(o,t);break;default:s={}}return s}function GS(n){let e=Array.isArray(n.files)?n.files[0]:n.file;return typeof e!="string"||!e?void 0:zl.extname(e).toLowerCase().replace(/^\./,"")||void 0}function Co(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 P_(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"&&C_(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 C_(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 k_(n){let e=Co(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 BS(n,e,t,r,i){let o=Co(n);if(o==null)return{found:!1};let s=Array.isArray(o)?o:[o],a=s[0]?.uri;return i?{found:!0,sameFile:I_(a,e),sourceType:zS(a,t,r)}:{implTotal:s.length,found:!0}}function D_(n){let e=Co(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:yf(i)}}function R_(n,e,t,r){let o=Co(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 h=(a==="incoming"?l.from:l.to)?.uri,w=zS(h,t,r);c.set(w,(c.get(w)??0)+1)}return{callsTotal:s.length,calleeSrcDist:yf(c)}}function x_(n,e){let t=Co(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:yf(i),deprecatedHit:o},a=e.query;return typeof a=="string"&&(s.queryLen=a.length),s}function qS(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 zS(n,e,t){let r=qS(n);return r?e&&WS(r,e)?"user_project":t&&WS(r,t)?"sdk":"system":"unknown"}function I_(n,e){let t=qS(n),r=e.file;return!t||typeof r!="string"?!1:Jl(t)===Jl(r)}function Jl(n){try{return zl.resolve(n).replace(/\\/g,"/").toLowerCase()}catch{return n.replace(/\\/g,"/").toLowerCase()}}function WS(n,e){let t=zl.relative(Jl(e),Jl(n));return t!==""&&!t.startsWith("..")&&!zl.isAbsolute(t)}function yf(n){let e={};for(let[t,r]of n)e[String(t)]=r;return e}var Yl=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(g.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?VS(e,r,t,this.getProjectPath?.()??"",this.getSdkPath?.()??""):{},h=l?!1:a,w=l&&r?A_(r):c,D={event:v.McpToolCall,subAction:e,mcpMemory:o,lspMemory:s,fileExt:GS(t),...d};typeof t.direction=="string"&&(D.direction=t.direction),await this.telemetry.track(D,{duration_ms:Date.now()-i,success:h,error_code:w})}async resolveLspMemory(){let e=this.getAceServerPid?.()??null;if(e===null)return"unknown";let t=await mt(e);return t===null?"unknown":ce(Number(t)*1024)}};function A_(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 wf(n,e,t,r){return new Yl(n,e,t,r)}import*as At from"fs";import*as Fe from"path";function JS(n){return"method"in n&&!("id"in n)}import{spawn as YS}from"child_process";import*as KS from"crypto";import{EventEmitter as T_}from"events";import*as Wr from"fs";import*as XS from"net";import*as zt from"path";var O_=50*1024*1024,N_=60*1e3,M_=10*1e3,L_=64*1024;function __(n){let e=zt.resolve(n).replace(/\\/g,"/");return e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),process.platform==="win32"?e.toLowerCase():e}function $_(n){return KS.createHash("sha1").update(__(n)).digest("hex").slice(0,12)}function F_(n){let e=zt.resolve(n),t=e.split(zt.sep),r=t.lastIndexOf("out");return r>0?t.slice(0,r+1).join(zt.sep):zt.dirname(e)}var vn=class extends T_{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=zt.join(this.config.logPath,"lspLog");return Wr.existsSync(t)||Wr.mkdirSync(t,{recursive:!0}),Wr.existsSync(this.config.indexingDataLocation)||Wr.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=ls({serverPath:this.config.serverPath,lspLogPath:r,serverMaxSize:t}),o=Jn(this.config.nodePath);f.debug(`[LspClient] Starting process: node ${i.join(" ")}`),f.debug(`[LspClient] nodePath: ${o}`),this.process=YS(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=F_(this.config.serverPath),s=zt.join(i,".idea",".deveco","arkts",".cache",`lsp-socket-${$_(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(h){l=h instanceof Error?h:new Error(String(h)),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(!Wr.existsSync(t))return null;let i=Wr.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=ls({serverPath:this.config.serverPath,lspLogPath:r,serverMaxSize:t,transportFlag:"--scope=multi",projectPath:i}),s=Jn(this.config.nodePath);f.debug(`[LspClient] Starting process (socket): node ${o.join(" ")}`),f.debug(`[LspClient] nodePath: ${s}`),this.process=YS(s,o,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0,detached:!0});let a=await this.waitForPortFromStdout(N_);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 h=a.match(s);if(h){clearTimeout(c),o.removeListener("data",l),r(parseInt(h[1],10));return}a=a.slice(-L_)};o.on("data",l)})}connectSocket(t){return new Promise((r,i)=>{let o=XS.connect(t,"127.0.0.1"),s=setTimeout(()=>{o.destroy(),i(new Error(`TCP connection to LSP socket timed out (port ${t})`))},M_);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
1317
+ `,a=o[1],c=e.map((d,h)=>`${a} "${d}"${h<e.length-1?",":""}`).join(s),l=`${a}"deviceTypes": [${s}${c}${s}${a}]`;we.writeFileSync(r,i.replace(o[0],()=>l),"utf-8")}function XL(){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 ZL(n){return xS.platform()==="darwin"?z.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):z.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function QL(n,e){let t=ZL(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=z.join(t,i),a=z.join(n,o);we.existsSync(s)&&(we.mkdirSync(z.dirname(a),{recursive:!0}),we.copyFileSync(s,a))}return!0}function e_(n){let e=XL(),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=z.join(n,r);we.mkdirSync(z.dirname(i),{recursive:!0}),we.writeFileSync(i,e)}}function t_(n,e){e&&QL(n,e)||e_(n)}function r_(n){let e=[z.join(n,"gitignore.txt"),z.join(n,"entry","gitignore.txt")];for(let t of e)if(we.existsSync(t)){let r=z.dirname(t);we.renameSync(t,z.join(r,".gitignore"))}}function IS(n,e,t,r,i,o){let s=qL();if(!we.existsSync(s))throw new Error(`Template directory not found: ${s}`);we.mkdirSync(n,{recursive:!0}),AS(s,n),r_(n),t_(n,o),oa(z.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),oa(z.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),KL(n,i),JL(n,r);let a=YL(n);if(!a)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,deviceTypes:i,verified:a}}function o_(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 s_(n){if(!n||n.length===0)return[Co[0]];let e=n.map(r=>r.toLowerCase()),t=n.filter((r,i)=>!Co.includes(e[i]));if(t.length>0)throw new Ee("errorCode",`Unsupported device type(s): ${t.map(r=>`"${r}"`).join(", ")}. Supported types: ${Co.join(", ")}`);return[...new Set(e)]}function _S(n){if(LS.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function NS(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=LS.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=_S(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 a_(n){let e=n,t=sa.parse(n).root;for(;e!==t;){if(Vr.existsSync(e))return e;e=sa.dirname(e)}return Vr.existsSync(t)?t:null}function MS(n){let e=a_(n);if(!e)throw new Ee("errorCode",`No existing parent directory found for '${n}'. Cannot create project directory.`);try{Vr.accessSync(e,Vr.constants.W_OK)}catch{throw new Ee("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}let t=sa.join(e,`.deveco_write_test_${Date.now()}`);try{Vr.writeFileSync(t,"test"),Vr.unlinkSync(t)}catch{throw new Ee("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}}function c_(n){return`com.example.${n.toLowerCase()}`}function l_(n,e){if(e){let i=_S(e),o=sa.resolve(i);if(Vr.existsSync(o)){if(Vr.readdirSync(o).length>0)throw new Ee("errorCode",`Directory '${o}' is not empty. Cannot create project here.`)}else MS(o);return o}let t=hf.cwd(),r=sa.join(t,n);if(Vr.existsSync(r))throw new Ee("errorCode",`Directory '${r}' already exists. Cannot create project here.`);return MS(r),r}function d_(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 u_(){try{return await P.new()}catch(n){console.error(OS(`DevEco Studio not found: ${n.message}`)),console.log(OS("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 ff(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 p_(n){console.log(`
1318
+ `+TS("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(TS("Template integrity check passed."))}var m_=new n_("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: ${Co[0]}; supported: ${Co.join(", ")})`).action(async n=>{let e=Date.now();try{n.appName||(console.error(mf("Error: --app-name is required")),await ff(e,!1,"errorCode",n),hf.exit(1));let t=n.appName;o_(t);let r=s_(n.deviceTypes),i=n.bundleName||c_(t);E.assertBundleNameStrict(i),n.projectPath&&NS(n.projectPath);let o=l_(t,n.projectPath);NS(o),console.log(i_("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 u_(),a=d_(n,s);console.log(`API level: ${a}`);let c=s?.devecoStudioPath,l=IS(o,t,i,a,r,c);p_(l),await ff(e,!0,null,n)}catch(t){let r=t,o=t instanceof Ee?t.code:r.code??r.name??"UnknownError";console.error(mf(`
1319
+ Failed to create project.`)),console.error(mf(r.message)),await ff(e,!1,o,n),hf.exit(1)}}),$S=m_;import{Command as f_}from"commander";import{red as h_,cyan as jS}from"colorette";function HS(n){return[...new Set([...n.agents,...n.projectAgents.map(({agent:e})=>e)])]}async function FS(n,e,t,r){await D.track(n,{duration_ms:Date.now()-e,success:t,error_code:r}).catch(()=>{})}async function g_(n,e,t,r,i){let o={event:v.SkillConfigOperation,subAction:"install",targetType:t?"path":r?"project":"global",agents:HS(n)},s=Date.now();try{let a=await new ir().installBundledSkill(e,n,i),c=a.every(l=>l.success);return await FS(o,s,c,c?null:"SKILL_INSTALL_FAILED"),a}catch(a){let c=a instanceof Error?a.code??a.name:"UnknownError";throw await FS(o,s,!1,c),a}}async function y_(n,e,t){let r=[];for(let{project:i,agent:o}of n.projectAgents){let s=await lc(o,i,t);r.push(s)}for(let i of n.agents){let o=await lc(i,e,t);r.push(o)}return r}async function w_(n,e){let t=[];for(let r of n){if(!Er[r])continue;let o=await ip(r,process.cwd(),e);t.push(o)}return t}function gf(n){return n!=="qoder"&&n!=="dsh"&&!!Er[n]}async function v_(n,e,t){let r=HS(n).find(l=>!gf(l));if(t.agent&&r)throw new Error(`${r} 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=>gf(l.agent)),s=n.agents.filter(gf);if(o.length===0&&s.length===0)throw new Error("No agents supporting MCP configuration found; use --skill");let a={...n,projectAgents:o,agents:s},c=e?await y_(a,e,i):await w_(a.agents,i);c.length>0&&(console.log(jS("MCP Configuration:")),op(c))}async function b_(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 v_(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 S_(n){if(n.path&&n.mcp)throw new Error("--path applies to Skill installation only; remove --mcp");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}=Fi(n.path,n.project,n.agent);if(t&&Cr(t,"Project directory",n.force),e&&Cr(e,"Directory",n.force),n.mcp){let s=await sp(n,t);await b_(s,t,n);return}let r=await ji(n,e,t),i=Jn(),o=await g_(r,i,e,t,n.force??!1);console.log(),o.length>0&&(console.log(jS("Skill Installation:")),$i(o))}var E_=new f_("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","Replace existing Skill content or MCP configuration; create missing target directories").action(async n=>{try{await S_(n)}catch(e){console.error(h_(e instanceof Error?e.message:String(e))),process.exitCode=1}}),US=E_;import{Command as T0}from"commander";import{McpServer as g0}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as y0}from"@modelcontextprotocol/sdk/server/stdio.js";import*as fa from"fs";import*as jo from"path";import{z as De}from"zod";import Jl from"path";function VS(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=P_(o);break;case"hover":s={hit:ko(o)!=null};break;case"definition":case"declaration":s=BS(o,t,r,i,!0);break;case"references":s=k_(o);break;case"implementation":s=BS(o,t,r,i,!1);break;case"documentSymbol":s=D_(o);break;case"callHierarchy":s=R_(o,t,r,i);break;case"workspaceSymbol":s=x_(o,t);break;default:s={}}return s}function GS(n){let e=Array.isArray(n.files)?n.files[0]:n.file;return typeof e!="string"||!e?void 0:Jl.extname(e).toLowerCase().replace(/^\./,"")||void 0}function ko(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 P_(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"&&C_(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 C_(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 k_(n){let e=ko(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 BS(n,e,t,r,i){let o=ko(n);if(o==null)return{found:!1};let s=Array.isArray(o)?o:[o],a=s[0]?.uri;return i?{found:!0,sameFile:A_(a,e),sourceType:zS(a,t,r)}:{implTotal:s.length,found:!0}}function D_(n){let e=ko(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:yf(i)}}function R_(n,e,t,r){let o=ko(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 h=(a==="incoming"?l.from:l.to)?.uri,w=zS(h,t,r);c.set(w,(c.get(w)??0)+1)}return{callsTotal:s.length,calleeSrcDist:yf(c)}}function x_(n,e){let t=ko(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:yf(i),deprecatedHit:o},a=e.query;return typeof a=="string"&&(s.queryLen=a.length),s}function qS(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 zS(n,e,t){let r=qS(n);return r?e&&WS(r,e)?"user_project":t&&WS(r,t)?"sdk":"system":"unknown"}function A_(n,e){let t=qS(n),r=e.file;return!t||typeof r!="string"?!1:Yl(t)===Yl(r)}function Yl(n){try{return Jl.resolve(n).replace(/\\/g,"/").toLowerCase()}catch{return n.replace(/\\/g,"/").toLowerCase()}}function WS(n,e){let t=Jl.relative(Yl(e),Yl(n));return t!==""&&!t.startsWith("..")&&!Jl.isAbsolute(t)}function yf(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(g.debug(`[telemetry] mcp tool call: ${e}`),!this.telemetry)return r(t);let i=ae(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?VS(e,r,t,this.getProjectPath?.()??"",this.getSdkPath?.()??""):{},h=l?!1:a,w=l&&r?I_(r):c,R={event:v.McpToolCall,subAction:e,mcpMemory:o,lspMemory:s,fileExt:GS(t),...d};typeof t.direction=="string"&&(R.direction=t.direction),await this.telemetry.track(R,{duration_ms:Date.now()-i,success:h,error_code:w})}async resolveLspMemory(){let e=this.getAceServerPid?.()??null;if(e===null)return"unknown";let t=await mt(e);return t===null?"unknown":ae(Number(t)*1024)}};function I_(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 wf(n,e,t,r){return new Kl(n,e,t,r)}import*as It from"fs";import*as Fe from"path";function JS(n){return"method"in n&&!("id"in n)}import{spawn as YS}from"child_process";import*as KS from"crypto";import{EventEmitter as T_}from"events";import*as Gr from"fs";import*as XS from"net";import*as Jt from"path";var O_=50*1024*1024,N_=60*1e3,M_=10*1e3,L_=64*1024;function __(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 $_(n){return KS.createHash("sha1").update(__(n)).digest("hex").slice(0,12)}function F_(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 Sn=class extends T_{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 Gr.existsSync(t)||Gr.mkdirSync(t,{recursive:!0}),Gr.existsSync(this.config.indexingDataLocation)||Gr.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=us({serverPath:this.config.serverPath,lspLogPath:r,serverMaxSize:t}),o=Yn(this.config.nodePath);f.debug(`[LspClient] Starting process: node ${i.join(" ")}`),f.debug(`[LspClient] nodePath: ${o}`),this.process=YS(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=F_(this.config.serverPath),s=Jt.join(i,".idea",".deveco","arkts",".cache",`lsp-socket-${$_(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(h){l=h instanceof Error?h:new Error(String(h)),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(!Gr.existsSync(t))return null;let i=Gr.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=us({serverPath:this.config.serverPath,lspLogPath:r,serverMaxSize:t,transportFlag:"--scope=multi",projectPath:i}),s=Yn(this.config.nodePath);f.debug(`[LspClient] Starting process (socket): node ${o.join(" ")}`),f.debug(`[LspClient] nodePath: ${s}`),this.process=YS(s,o,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0,detached:!0});let a=await this.waitForPortFromStdout(N_);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 h=a.match(s);if(h){clearTimeout(c),o.removeListener("data",l),r(parseInt(h[1],10));return}a=a.slice(-L_)};o.on("data",l)})}connectSocket(t){return new Promise((r,i)=>{let o=XS.connect(t,"127.0.0.1"),s=setTimeout(()=>{o.destroy(),i(new Error(`TCP connection to LSP socket timed out (port ${t})`))},M_);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
1322
  \r
1323
1323
  ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this.buffer.indexOf(`\r
1324
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>O_){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 bn=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 Kl=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var ko=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 M(n){return typeof n=="object"&&n!==null}var ZS=20*1e3,j_=30*1e3,QS=300,H_=300;function U_(){let n=process.env.DEVECO_CLI_LSP_STANDARD_EXIT_TIMEOUT_MS;if(n===void 0||n==="")return QS;let e=parseInt(n,10);return Number.isFinite(e)?Math.max(H_,e):QS}var Xl=class{client;nextRequestId=1;stopOnce=null;callbacks=new ko;requestCallbacks=new bn;diagnosticMap=new Map;initProgressReset=null;notificationWaiters=new Map;get lspPid(){return this.client.pid}constructor(e){this.client=new vn(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(U_()),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,nt);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 h=this.nextRequestId++;this.client.sendRequest(b.INITIALIZE,e,h),this.requestCallbacks.registerPending(h,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 Kl(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=j_){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){M(e)&&this.broadcastToClients({jsonrpc:L,method:b.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,b.PUBLISH_DIAGNOSTICS,ZS,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${ZS}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 Zl=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 vf(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)}},vf=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var B_={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"},W_={MODULE_INIT_FINISH:Wi.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"},_={...B_,...W_},Sn={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"},eE=new Set([1e3,2e3,3e3,3001]);function V_(n){if(!M(n))return!1;let e=n.textDocument;return M(e)&&typeof e.uri=="string"}function G_(n){return M(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function q_(n){return M(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 Ql=class n{client;isInitialized=!1;stopOnce=null;callbacks=new ko;requestCallbacks=new bn;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;get lspPid(){return this.client.pid}constructor(e){this.client=new vn(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:{}}),Sn.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}}),Sn.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:L,id:0,result:{}}),Sn.EMPTY)}sendAsyncRequest(e,t,r,i){if(!M(t)){f.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!V_(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=$t(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(!G_(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(!M(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}}),Sn.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let i=$t(t);e.textDocument.uri=i,f.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new Zl(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}}}),Sn.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=$t(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}}}),Sn.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=$t(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}}}),Sn.DID_CLOSE)}getDiagnosticMessage(e){let t=$t(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: ${q_(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;M(t)&&M(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(!M(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(eE)&&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 bf from"path";import*as sd from"path";var ed=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var td=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var rd=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var nd=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var id=class{typeSetting=new rd;parameterNames=new nd};var od=class{constructor(e,t,r,i){this.rootUri=e;this.lspServerWorkspacePath=ge(sd.dirname(t)),this.indexingDataLocation=ge(i),this.loggerPath=ge(sd.join(r,"lspLog"))}modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new ed;gutterIconsSetting=new td;inlayHintsSetting=new id;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as tE from"path";var oa=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(ge(tE.join(e,"src","main","resources")))}};var z_="OS",Do=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${z_}`;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 oa(e)):this.buildProfileParam=new oa}toString(){return JSON.stringify(this)}};var Ro=class{constructor(e=[]){this.pages=e}pagesFileName="main_pages.json";metaDataList=[]};import*as Ye from"path";import*as Ao from"fs";var ad=class{modulePath;dependencies={};dynamicDependencies={}};var fi=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 xo=class{constructor(e,t,r){this.projectPath=e;this.moduleName=t;this.modulePath=r}dependencies=[];devDependencies=[];dynamicDependencies=[];finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[]};import*as Vr from"path";import*as cd from"fs";var Io=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},sa=`${V.HVIGOR_CACHE}/${V.DEPENDENCY}`,hi=`${V.DEPENDENCY}${V.JSON5}`,gne=Pe.SYNC_OUTPUT_PATH;var aa=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=Vr.join(this.dependencyPath,V.OH_PACKAGE_JSON5),r=ht(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(!M(e))return r;let i=e[t];if(!M(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 Io;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=Vr.normalize(Vr.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)),Vr.isAbsolute(s)){r.dependencyPath=o;return}i||(o=Vr.resolve(this.modulePath,s)),cd.existsSync(o)&&cd.statSync(o).isDirectory()&&(r.dependencyPath=o)}catch(o){f.error("parser dependency path is invalid",o)}}};import*as gi from"fs";import*as En from"path";import J_ from"json5";var ld=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 En.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(!gi.existsSync(e))return f.error("lock file does not exist"),this.clearDependencies(),null;try{let t=gi.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=gi.readFileSync(e,"utf8"),r=J_.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(!M(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(!M(e))return t;let r=0;for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;let o=e[i];if(!M(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(!M(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(M(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(!M(i))return f.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!M(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(!M(l))continue;let d=typeof l.specifier=="string"?l.specifier:"",h=typeof l.version=="string"?l.version:"",w=new Io;w.name=c,w.version=h.startsWith(n.FILE_DEPENDENCY_PREFIX)?h.substring(n.FILE_DEPENDENCY_PREFIX.length):h,this.parseDependencyPath(w,r,c,d,h);let D=`${c}@${h}`;this.storePathMap.has(D)&&(w.storePath=this.storePathMap.get(D)||""),o.push(w)}return o}parseDependencyPath(e,t,r,i,o){let s=En.resolve(this.projectPath,En.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=En.isAbsolute(a)?a:En.resolve(this.projectPath,a);gi.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 rE(n){return M(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var yi=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new kr(this.projectPath)}moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e,t){let r=this.projectPath,i=Ye.join(r,sa),o=Ye.join(i,hi);if(!Ao.existsSync(i)||!Ao.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 xo(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(rE(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=Ye.join(r,sa),o=Ye.join(i,hi);if(!Ao.existsSync(i)||!Ao.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 xo(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(!rE(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 h=Ye.resolve(this.projectPath,l.srcPath),w=Ye.join(i,d),D=ge(h),z=this.buildModuleDependencies(d,D,w,a);z.moduleName=d,t.push(z)}return t}parseSingleModule(e,t,r,i){let o=e.name,s=Ye.resolve(this.projectPath,e.srcPath),a=Ye.join(t,o),c=ge(s),l=new Do(c),d=this.buildModuleDependencies(o,c,a,r);this.parseModuleJson5(c,l);let h=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=o,l.moduleType=o,l.packageName=o,l.moduleDependencies=d,l.moduleJsonParam=new Ro(h),i.push(l)}buildModuleDependencies(e,t,r,i){let o=new xo(this.projectPath,e,t);aa.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 ad;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 fi(o);for(let o of e.finalDynamicDependencies)i[o.name]=new fi(o);t.dependencies=r,t.dynamicDependencies=i}parseProjectDependencies(e,t){let r=Ye.join(e,V.OH_PACKAGE_JSON5);if(!Ao.existsSync(r))return;aa.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 ld(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=Ye.join(e,"src","main","module.json5"),i=ht(r);if(!M(i)||!M(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(M(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)M(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=Ye.join(e,"src","main","resources","base","profile","main_pages.json"),r=ht(t);return!M(r)||!Array.isArray(r.src)?[]:r.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!M(t)||!M(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=Ye.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=ht(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!M(t)||!M(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!M(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=Ye.join(this.projectPath,"build-profile.json5");this.buildProfileCache=ht(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!M(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 dd=class{constructor(e=[]){this.valueSet=e}};var To=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var nE=(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))(nE||{}),iE=()=>Object.values(nE).filter(n=>typeof n=="number");var ud=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var pd=class{applyEdit=!0;workspaceEdit=new ud;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new dd(iE());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new To;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var md=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var fd=class{constructor(e=[]){this.valueSet=e}};var hd=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var oE=(A=>(A[A.Text=1]="Text",A[A.Method=2]="Method",A[A.Function=3]="Function",A[A.Constructor=4]="Constructor",A[A.Field=5]="Field",A[A.Variable=6]="Variable",A[A.Class=7]="Class",A[A.Interface=8]="Interface",A[A.Module=9]="Module",A[A.Property=10]="Property",A[A.Unit=11]="Unit",A[A.Value=12]="Value",A[A.Enum=13]="Enum",A[A.Keyword=14]="Keyword",A[A.Snippet=15]="Snippet",A[A.Color=16]="Color",A[A.File=17]="File",A[A.Reference=18]="Reference",A[A.Folder=19]="Folder",A[A.EnumMember=20]="EnumMember",A[A.Constant=21]="Constant",A[A.Struct=22]="Struct",A[A.Event=23]="Event",A[A.Operator=24]="Operator",A[A.TypeParameter=25]="TypeParameter",A))(oE||{}),sE=()=>Object.values(oE).filter(n=>typeof n=="number");var gd=class{completionItemKind=new fd(sE());completionItem=new hd;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var yd=class{synchronization=new md;completion=new gd;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 To;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var wd=class{workspace=new pd;textDocument=new yd;notebookDocument=null;window=null;general=null;experimental=null};var vd=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}};var bd=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=Ri(t,this.useStandardProtocol),this.logPath=by(),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 Xl(l):new Ql(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=$t(this.rootUri),s=new od(o,this.serverPath,this.logPath,this.indexLogPath),a=[],l=new yi(this.rootUri,this.sdkPath).getAllDependencyMap(a,r);if(l.status==="ERROR")throw new Error(`${l.message}`);this.fillModuleModelsPaths(a),s.modules=a;let d=bc(a.length,this.nodeMaxOldSpaceSize);await this.messageHandle.start(d),this.currentParams=new vd(o,s,new wd),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,Wi.MODULE_INIT_FINISH,nt,()=>{f.info("[LSP] initialize response received"),r(),t.sendInitialized()},r),f.info("[LSP] initialize response + onModuleInitFinish received, initialization complete")):(await t.sendInitializeResettable(e,nt),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",nt),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=M(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 yi(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,h)=>{(i.dependencies??={})[d]=this.makeDeleteEntry(d,h)}),this.markAddAndDeleteInDeps(a,l,(d,h)=>{(i.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,h)})}}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 fi({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Do(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new Ro([]),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=Gi(bf.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=Gi(bf.join(t,"default/openharmony/ets/api")),o=Gi(bf.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(!JS(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 Gr from"fs";import*as at from"path";import{createHash as K_}from"crypto";import{EventEmitter as X_}from"events";var Sd=class extends X_{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(!Gr.existsSync(t)){f.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Gr.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=at.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=at.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=at.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=at.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=ht(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=at.join(this.projectRoot,V.OH_PACKAGE_JSON5);Gr.existsSync(r)&&t.push(r);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=at.resolve(this.projectRoot,o.srcPath),a=at.join(s,V.OH_PACKAGE_JSON5);Gr.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return at.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Gr.readFileSync(t,"utf-8");return K_("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=Gr.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:at.basename(t),relativePath:at.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 Pn from"fs";import*as Jt from"path";import{createHash as Z_}from"crypto";import{EventEmitter as Q_}from"events";var Ed=class extends Q_{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=Jt.join(t,sa)}dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!Pn.existsSync(this.depMapDir)){f.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=Pn.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 ge(Jt.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===hi)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=Jt.join(this.depMapDir,r);Pn.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=Jt.join(this.depMapDir,V.OH_PACKAGE_JSON5),r=Jt.join(this.depMapDir,hi),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...i.map(s=>({path:(E.assertModuleName(s.name),Jt.join(this.depMapDir,s.name,V.OH_PACKAGE_JSON5)),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!Pn.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=Jt.join(this.depMapDir,hi);try{let r=ht(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 ge(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),Jt.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),Jt.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=Pn.readFileSync(t,"utf-8");return Z_("sha256").update(r).digest("hex")}catch{return null}}};import*as yr from"fs";import*as Pd from"path";import{EventEmitter as e0}from"events";var Sf={Created:1,Changed:2,Deleted:3},t0=new Set(["oh_modules","node_modules","build",".hvigor",".git",".idea",".cxx",".preview"]);function r0(n){let e=n.replace(/\\/g,"/");return e.endsWith("/ets")&&e.includes("/src/")}var Cd=class extends e0{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=yr.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(Pd.resolve(this.projectRoot),e,new Set,new Set),e}collectSourceDirs(e,t,r,i){let o;try{o=yr.realpathSync(e)}catch{return}if(i.has(o))return;i.add(o);let s;try{s=yr.readdirSync(e,{withFileTypes:!0})}catch{return}for(let a of s){if(!a.isDirectory()||t0.has(a.name))continue;let c=Pd.resolve(e,a.name);if(!r0(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:Ot(r),type:Sf.Changed}):t.push({uri:Ot(r),type:Sf.Created})}for(let[r]of this.snapshot)e.has(r)||t.push({uri:Ot(r),type:Sf.Deleted});return this.snapshot=e,t}collectEtsFiles(e,t){this.collectEtsFilesInto(e,t,new Set)}collectEtsFilesInto(e,t,r){let i;try{i=yr.realpathSync(e)}catch{return}if(r.has(i))return;r.add(i);let o;try{o=yr.readdirSync(e,{withFileTypes:!0})}catch{return}for(let s of o){let a=Pd.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=yr.statSync(e)}catch{return}t.set(e,{mtimeMs:r.mtimeMs,size:r.size})}};import{spawn as n0}from"child_process";var aE=["install","--all"];function cE(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 i0(n,e,t,r,i){return new Promise(o=>{f.info("[ohpm] spawning: %s %s %s, cwd=%s",n,e,aE.join(" "),t);let s=n0(n,[e,...aE],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),a="",c="";s.stdout?.on("data",l=>{a=cE(a+l.toString(),i)}),s.stderr?.on("data",l=>{c=cE(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 lE(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 i0(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 dE={UNINITIALIZED:-32099,UNKNOWN:-32e3},ca=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,dE.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,dE.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var Oo=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 gc(e,async()=>await lE(e,t,r??"",i??"",a)?l?(f.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await Dy(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 bd(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?ca.uninitialized(t):ca.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 Sd(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Ed(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 Cd(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 o0=10080*60*1e3,s0=7200*60*1e3,a0=120*1e3,No=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=xe(e),{logPath:o,indexPath:s}=this.getLogAndIndexPath(i);setImmediate(()=>{wu(s,o0,"[ArkTS-Check]"),wu(o,s0,"[ArkTS-Check]")}),vc(o);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a;g.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${c??"undefined \u2192 dynamic formula applies"}`);let l=this.sdkPath;g.info(`[ArktsCheck] sdkPath=${l}, arktsLangServerPath=${t}, useStandardProtocol=${r}, useSocket=${this.useSocket}`),this.manager=new Oo({sdkPath:l,arktsLangServerPath:t,workspaceRoot:ge(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,h)=>{this.initResolve=d,this.initReject=h,this.armInitTimer(nt),this.manager.start([],this.onDepParseProgress??void 0).catch(w=>{let D=w instanceof Error?w:new Error(String(w));this.failInit(D)})})}resolveProjectAndDeveco(){let e=br(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=_a(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=Ot(e),i=await At.promises.readFile(e,"utf8"),s=`deveco.apptool.${Fe.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){g.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:i,version:++this.documentVersion}});try{g.debug(`textDocument/diagnostic uri=${t}`);let o=await e.diagnostic({textDocument:{uri:t}});return c0(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"))},a0);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});g.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};g.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 g.error(`handleLspFeature ${e} failed: ${s}`),{content:[{type:"text",text:`${e} failed: ${s}`}],isError:!0}}}async handleWorkspaceSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();g.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 g.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 g.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};g.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 g.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};g.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 h=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(h)?l.push(...h):h&&l.push(h)}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 g.error(`handleCallHierarchy failed: ${i}`),{content:[{type:"text",text:`callHierarchy failed: ${i}`}],isError:!0}}}async withOpenFile(e,t){let r=Ot(e),i=await At.promises.readFile(e,"utf8"),s=`deveco.apptool.${Fe.extname(e).replace(/^\./,"")||"plaintext"}`;g.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=Fe.isAbsolute(e)?e:Fe.join(this.projectPath,e);return!At.existsSync(t)||!At.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=Fe.resolve(this.projectPath),i=[];for(let o of e){let s=Fe.resolve(Fe.isAbsolute(o)?o:Fe.join(r,o));if(!At.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!At.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 Zh(500);try{let o=await this.checkFile(i);r.push(l0(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(`
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>O_){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 En=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 Xl=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var Do=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 M(n){return typeof n=="object"&&n!==null}var ZS=20*1e3,j_=30*1e3,QS=300,H_=300;function U_(){let n=process.env.DEVECO_CLI_LSP_STANDARD_EXIT_TIMEOUT_MS;if(n===void 0||n==="")return QS;let e=parseInt(n,10);return Number.isFinite(e)?Math.max(H_,e):QS}var Zl=class{client;nextRequestId=1;stopOnce=null;callbacks=new Do;requestCallbacks=new En;diagnosticMap=new Map;initProgressReset=null;notificationWaiters=new Map;get lspPid(){return this.client.pid}constructor(e){this.client=new Sn(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(U_()),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,nt);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 h=this.nextRequestId++;this.client.sendRequest(b.INITIALIZE,e,h),this.requestCallbacks.registerPending(h,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 Xl(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=j_){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){M(e)&&this.broadcastToClients({jsonrpc:L,method:b.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,b.PUBLISH_DIAGNOSTICS,ZS,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${ZS}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 Ql=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 vf(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)}},vf=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var B_={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"},W_={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"},_={...B_,...W_},Pn={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"},eE=new Set([1e3,2e3,3e3,3001]);function V_(n){if(!M(n))return!1;let e=n.textDocument;return M(e)&&typeof e.uri=="string"}function G_(n){return M(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function q_(n){return M(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 ed=class n{client;isInitialized=!1;stopOnce=null;callbacks=new Do;requestCallbacks=new En;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;get lspPid(){return this.client.pid}constructor(e){this.client=new Sn(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:{}}),Pn.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}}),Pn.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:L,id:0,result:{}}),Pn.EMPTY)}sendAsyncRequest(e,t,r,i){if(!M(t)){f.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!V_(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=Ft(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(!G_(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(!M(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}}),Pn.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let i=Ft(t);e.textDocument.uri=i,f.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new Ql(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}}}),Pn.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=Ft(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}}}),Pn.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=Ft(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}}}),Pn.DID_CLOSE)}getDiagnosticMessage(e){let t=Ft(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: ${q_(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;M(t)&&M(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(!M(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(eE)&&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 bf from"path";import*as ad from"path";var td=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var rd=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var nd=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var id=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var od=class{typeSetting=new nd;parameterNames=new id};var sd=class{constructor(e,t,r,i){this.rootUri=e;this.lspServerWorkspacePath=he(ad.dirname(t)),this.indexingDataLocation=he(i),this.loggerPath=he(ad.join(r,"lspLog"))}modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new td;gutterIconsSetting=new rd;inlayHintsSetting=new od;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as tE from"path";var aa=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(tE.join(e,"src","main","resources")))}};var z_="OS",Ro=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${z_}`;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 aa(e)):this.buildProfileParam=new aa}toString(){return JSON.stringify(this)}};var xo=class{constructor(e=[]){this.pages=e}pagesFileName="main_pages.json";metaDataList=[]};import*as Ye from"path";import*as To from"fs";var cd=class{modulePath;dependencies={};dynamicDependencies={}};var hi=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 Ao=class{constructor(e,t,r){this.projectPath=e;this.moduleName=t;this.modulePath=r}dependencies=[];devDependencies=[];dynamicDependencies=[];finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[]};import*as qr from"path";import*as ld from"fs";var Io=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},ca=`${V.HVIGOR_CACHE}/${V.DEPENDENCY}`,gi=`${V.DEPENDENCY}${V.JSON5}`,bne=Pe.SYNC_OUTPUT_PATH;var la=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=qr.join(this.dependencyPath,V.OH_PACKAGE_JSON5),r=ht(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(!M(e))return r;let i=e[t];if(!M(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 Io;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=qr.normalize(qr.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)),qr.isAbsolute(s)){r.dependencyPath=o;return}i||(o=qr.resolve(this.modulePath,s)),ld.existsSync(o)&&ld.statSync(o).isDirectory()&&(r.dependencyPath=o)}catch(o){f.error("parser dependency path is invalid",o)}}};import*as yi from"fs";import*as Cn from"path";import J_ from"json5";var dd=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 Cn.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(!yi.existsSync(e))return f.error("lock file does not exist"),this.clearDependencies(),null;try{let t=yi.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=yi.readFileSync(e,"utf8"),r=J_.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(!M(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(!M(e))return t;let r=0;for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;let o=e[i];if(!M(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(!M(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(M(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(!M(i))return f.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!M(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(!M(l))continue;let d=typeof l.specifier=="string"?l.specifier:"",h=typeof l.version=="string"?l.version:"",w=new Io;w.name=c,w.version=h.startsWith(n.FILE_DEPENDENCY_PREFIX)?h.substring(n.FILE_DEPENDENCY_PREFIX.length):h,this.parseDependencyPath(w,r,c,d,h);let R=`${c}@${h}`;this.storePathMap.has(R)&&(w.storePath=this.storePathMap.get(R)||""),o.push(w)}return o}parseDependencyPath(e,t,r,i,o){let s=Cn.resolve(this.projectPath,Cn.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=Cn.isAbsolute(a)?a:Cn.resolve(this.projectPath,a);yi.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 rE(n){return M(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var wi=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new Rr(this.projectPath)}moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e,t){let r=this.projectPath,i=Ye.join(r,ca),o=Ye.join(i,gi);if(!To.existsSync(i)||!To.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 Ao(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(rE(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=Ye.join(r,ca),o=Ye.join(i,gi);if(!To.existsSync(i)||!To.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 Ao(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(!rE(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 h=Ye.resolve(this.projectPath,l.srcPath),w=Ye.join(i,d),R=he(h),J=this.buildModuleDependencies(d,R,w,a);J.moduleName=d,t.push(J)}return t}parseSingleModule(e,t,r,i){let o=e.name,s=Ye.resolve(this.projectPath,e.srcPath),a=Ye.join(t,o),c=he(s),l=new Ro(c),d=this.buildModuleDependencies(o,c,a,r);this.parseModuleJson5(c,l);let h=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=o,l.moduleType=o,l.packageName=o,l.moduleDependencies=d,l.moduleJsonParam=new xo(h),i.push(l)}buildModuleDependencies(e,t,r,i){let o=new Ao(this.projectPath,e,t);la.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 cd;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 hi(o);for(let o of e.finalDynamicDependencies)i[o.name]=new hi(o);t.dependencies=r,t.dynamicDependencies=i}parseProjectDependencies(e,t){let r=Ye.join(e,V.OH_PACKAGE_JSON5);if(!To.existsSync(r))return;la.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 dd(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=Ye.join(e,"src","main","module.json5"),i=ht(r);if(!M(i)||!M(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(M(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)M(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=Ye.join(e,"src","main","resources","base","profile","main_pages.json"),r=ht(t);return!M(r)||!Array.isArray(r.src)?[]:r.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!M(t)||!M(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=Ye.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=ht(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!M(t)||!M(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!M(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=Ye.join(this.projectPath,"build-profile.json5");this.buildProfileCache=ht(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!M(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 ud=class{constructor(e=[]){this.valueSet=e}};var Oo=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var nE=(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))(nE||{}),iE=()=>Object.values(nE).filter(n=>typeof n=="number");var pd=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var md=class{applyEdit=!0;workspaceEdit=new pd;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new ud(iE());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Oo;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var fd=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var hd=class{constructor(e=[]){this.valueSet=e}};var gd=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var oE=(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))(oE||{}),sE=()=>Object.values(oE).filter(n=>typeof n=="number");var yd=class{completionItemKind=new hd(sE());completionItem=new gd;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var wd=class{synchronization=new fd;completion=new yd;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 Oo;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var vd=class{workspace=new md;textDocument=new wd;notebookDocument=null;window=null;general=null;experimental=null};var bd=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}};var Sd=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=xi(t,this.useStandardProtocol),this.logPath=Ey(),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 Zl(l):new ed(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=Ft(this.rootUri),s=new sd(o,this.serverPath,this.logPath,this.indexLogPath),a=[],l=new wi(this.rootUri,this.sdkPath).getAllDependencyMap(a,r);if(l.status==="ERROR")throw new Error(`${l.message}`);this.fillModuleModelsPaths(a),s.modules=a;let d=Ec(a.length,this.nodeMaxOldSpaceSize);await this.messageHandle.start(d),this.currentParams=new bd(o,s,new vd),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,nt,()=>{f.info("[LSP] initialize response received"),r(),t.sendInitialized()},r),f.info("[LSP] initialize response + onModuleInitFinish received, initialization complete")):(await t.sendInitializeResettable(e,nt),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",nt),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=M(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 wi(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,h)=>{(i.dependencies??={})[d]=this.makeDeleteEntry(d,h)}),this.markAddAndDeleteInDeps(a,l,(d,h)=>{(i.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,h)})}}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 hi({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Ro(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new xo([]),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=qi(bf.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=qi(bf.join(t,"default/openharmony/ets/api")),o=qi(bf.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(!JS(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 zr from"fs";import*as at from"path";import{createHash as K_}from"crypto";import{EventEmitter as X_}from"events";var Ed=class extends X_{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(!zr.existsSync(t)){f.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=zr.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=at.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=at.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=at.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=at.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=ht(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=at.join(this.projectRoot,V.OH_PACKAGE_JSON5);zr.existsSync(r)&&t.push(r);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=at.resolve(this.projectRoot,o.srcPath),a=at.join(s,V.OH_PACKAGE_JSON5);zr.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return at.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=zr.readFileSync(t,"utf-8");return K_("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=zr.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:at.basename(t),relativePath:at.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 kn from"fs";import*as Yt from"path";import{createHash as Z_}from"crypto";import{EventEmitter as Q_}from"events";var Pd=class extends Q_{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=Yt.join(t,ca)}dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!kn.existsSync(this.depMapDir)){f.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=kn.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(Yt.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===gi)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=Yt.join(this.depMapDir,r);kn.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=Yt.join(this.depMapDir,V.OH_PACKAGE_JSON5),r=Yt.join(this.depMapDir,gi),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...i.map(s=>({path:(E.assertModuleName(s.name),Yt.join(this.depMapDir,s.name,V.OH_PACKAGE_JSON5)),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!kn.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=Yt.join(this.depMapDir,gi);try{let r=ht(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),Yt.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),Yt.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=kn.readFileSync(t,"utf-8");return Z_("sha256").update(r).digest("hex")}catch{return null}}};import*as wr from"fs";import*as Cd from"path";import{EventEmitter as e0}from"events";var Sf={Created:1,Changed:2,Deleted:3},t0=new Set(["oh_modules","node_modules","build",".hvigor",".git",".idea",".cxx",".preview"]);function r0(n){let e=n.replace(/\\/g,"/");return e.endsWith("/ets")&&e.includes("/src/")}var kd=class extends e0{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=wr.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(Cd.resolve(this.projectRoot),e,new Set,new Set),e}collectSourceDirs(e,t,r,i){let o;try{o=wr.realpathSync(e)}catch{return}if(i.has(o))return;i.add(o);let s;try{s=wr.readdirSync(e,{withFileTypes:!0})}catch{return}for(let a of s){if(!a.isDirectory()||t0.has(a.name))continue;let c=Cd.resolve(e,a.name);if(!r0(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:Ot(r),type:Sf.Changed}):t.push({uri:Ot(r),type:Sf.Created})}for(let[r]of this.snapshot)e.has(r)||t.push({uri:Ot(r),type:Sf.Deleted});return this.snapshot=e,t}collectEtsFiles(e,t){this.collectEtsFilesInto(e,t,new Set)}collectEtsFilesInto(e,t,r){let i;try{i=wr.realpathSync(e)}catch{return}if(r.has(i))return;r.add(i);let o;try{o=wr.readdirSync(e,{withFileTypes:!0})}catch{return}for(let s of o){let a=Cd.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=wr.statSync(e)}catch{return}t.set(e,{mtimeMs:r.mtimeMs,size:r.size})}};import{spawn as n0}from"child_process";var aE=["install","--all"];function cE(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 i0(n,e,t,r,i){return new Promise(o=>{f.info("[ohpm] spawning: %s %s %s, cwd=%s",n,e,aE.join(" "),t);let s=n0(n,[e,...aE],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),a="",c="";s.stdout?.on("data",l=>{a=cE(a+l.toString(),i)}),s.stderr?.on("data",l=>{c=cE(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 lE(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 i0(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 dE={UNINITIALIZED:-32099,UNKNOWN:-32e3},da=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,dE.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,dE.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var No=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 wc(e,async()=>await lE(e,t,r??"",i??"",a)?l?(f.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await xy(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 Sd(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?da.uninitialized(t):da.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 Ed(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Pd(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 kd(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 o0=10080*60*1e3,s0=7200*60*1e3,a0=120*1e3,Mo=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=xe(e),{logPath:o,indexPath:s}=this.getLogAndIndexPath(i);setImmediate(()=>{vu(s,o0,"[ArkTS-Check]"),vu(o,s0,"[ArkTS-Check]")}),Sc(o);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a;g.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${c??"undefined \u2192 dynamic formula applies"}`);let l=this.sdkPath;g.info(`[ArktsCheck] sdkPath=${l}, arktsLangServerPath=${t}, useStandardProtocol=${r}, useSocket=${this.useSocket}`),this.manager=new No({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,h)=>{this.initResolve=d,this.initReject=h,this.armInitTimer(nt),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=Sr(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=Fa(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=Ot(e),i=await It.promises.readFile(e,"utf8"),s=`deveco.apptool.${Fe.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){g.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:i,version:++this.documentVersion}});try{g.debug(`textDocument/diagnostic uri=${t}`);let o=await e.diagnostic({textDocument:{uri:t}});return c0(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"))},a0);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});g.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};g.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 g.error(`handleLspFeature ${e} failed: ${s}`),{content:[{type:"text",text:`${e} failed: ${s}`}],isError:!0}}}async handleWorkspaceSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();g.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 g.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 g.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};g.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 g.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};g.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 h=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(h)?l.push(...h):h&&l.push(h)}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 g.error(`handleCallHierarchy failed: ${i}`),{content:[{type:"text",text:`callHierarchy failed: ${i}`}],isError:!0}}}async withOpenFile(e,t){let r=Ot(e),i=await It.promises.readFile(e,"utf8"),s=`deveco.apptool.${Fe.extname(e).replace(/^\./,"")||"plaintext"}`;g.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=Fe.isAbsolute(e)?e:Fe.join(this.projectPath,e);return!It.existsSync(t)||!It.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=Fe.resolve(this.projectPath),i=[];for(let o of e){let s=Fe.resolve(Fe.isAbsolute(o)?o:Fe.join(r,o));if(!It.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!It.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 Zh(500);try{let o=await this.checkFile(i);r.push(l0(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
1327
  `)),t.length>0&&r.push(t.join(`
1328
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){g.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 Wi.INDEXING_PROGRESS_UPDATE:this.handleIndexingProgress(t.params);break;case b.PROGRESS:this.handleProgressNotification(t.params);break;case"arkts/initialized":{g.info("Received arkts/initialized");let i=this.initResolve;this.clearInitHandlers(),i?.();break}case"arkts/initializationFailed":{let i=t.params?.message??"unknown";g.error(`LSP initialization failed: ${i}`);let o=this.initReject;this.clearInitHandlers(),o?.(new Error(`LSP initialize failed: ${i}`));break}case"workspace/didChangeConfiguration":g.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(nt)}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(nt)}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"){g.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;g.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=Fe.join(Jr(),"ArkTSCheck"),r=Fe.join(t,"mapping-config.properties"),i=Qh(e,r),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=Fe.join(t,"lsp-log",String(i),o),a=Fe.join(t,"lsp-index",String(i));return At.mkdirSync(s,{recursive:!0}),At.mkdirSync(a,{recursive:!0}),{logPath:xe(s),indexPath:xe(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function c0(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 l0(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 Cn from"fs";import*as wi from"path";import{z as Ef}from"zod";function Mo(){return{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}function kd(n,e){let t=e instanceof Error?e.message:String(e);return g.error(`[CppLsp] ${n} failed: ${t}`),{content:[{type:"text",text:`${n} failed: ${t}`}],isError:!0}}var d0=500,Lo=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:Ef.object({files:Ef.array(Ef.string()).describe('List of C/C++ file paths to check, format: ["file1.cpp","file2.hpp",...]')})}}async handleCall(e){if(!this.manager.ready)return Mo();let t=[],r=[],i=this.collectValidFiles(e.files,t);if(i.length===0)return{content:[{type:"text",text:t.length>0?t.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){g.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":{g.info("Received arkts/initialized");let i=this.initResolve;this.clearInitHandlers(),i?.();break}case"arkts/initializationFailed":{let i=t.params?.message??"unknown";g.error(`LSP initialization failed: ${i}`);let o=this.initReject;this.clearInitHandlers(),o?.(new Error(`LSP initialize failed: ${i}`));break}case"workspace/didChangeConfiguration":g.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(nt)}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(nt)}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"){g.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;g.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=Fe.join(Kr(),"ArkTSCheck"),r=Fe.join(t,"mapping-config.properties"),i=Qh(e,r),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=Fe.join(t,"lsp-log",String(i),o),a=Fe.join(t,"lsp-index",String(i));return It.mkdirSync(s,{recursive:!0}),It.mkdirSync(a,{recursive:!0}),{logPath:xe(s),indexPath:xe(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function c0(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 l0(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 Dn from"fs";import*as vi from"path";import{z as Ef}from"zod";function Lo(){return{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}function Dd(n,e){let t=e instanceof Error?e.message:String(e);return g.error(`[CppLsp] ${n} failed: ${t}`),{content:[{type:"text",text:`${n} failed: ${t}`}],isError:!0}}var d0=500,_o=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:Ef.object({files:Ef.array(Ef.string()).describe('List of C/C++ file paths to check, format: ["file1.cpp","file2.hpp",...]')})}}async handleCall(e){if(!this.manager.ready)return Lo();let t=[],r=[],i=this.collectValidFiles(e.files,t);if(i.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
1330
1330
  `):"No valid C/C++ files"}],isError:!0};for(let c of i){await p0(d0);try{let l=await this.checkFile(c);r.push(u0(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
1331
  `)),r.length>0&&s.push(r.join(`
1332
1332
  `));let a=s.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=Ot(e),r=await Cn.promises.readFile(e,"utf8"),i=$a(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=wi.resolve(this.manager.projectRoot),i=[];for(let o of e){let s=wi.resolve(wi.isAbsolute(o)?o:wi.join(r,o));if(!Cn.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!Cn.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!Un(s)){t.push(`Not a supported C/C++ file: ${o}`);continue}try{i.push(Cn.realpathSync(s))}catch{i.push(s)}}return i}};function u0(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 p0(n){return new Promise(e=>setTimeout(e,n))}import*as $o from"fs";import*as Dd from"path";var _o=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 Mo();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};g.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 kd(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 g.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return Mo();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};g.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 kd("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return Mo();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};g.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 kd("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=Ot(e),i=await $o.promises.readFile(e,"utf8"),o=$a(e);g.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=Dd.isAbsolute(e)?e:Dd.join(this.manager.projectRoot,e);return!$o.existsSync(t)||!$o.statSync(t).isFile()||!Un(t)?null:t}};import{spawn as m0}from"child_process";import*as xd from"fs";import*as uE from"path";var f0=30*1e3,h0=30*1e3,Rd=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new bn;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 vn(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,nt),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}`))},h0);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=${ge(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];f.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=m0(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=Gi(this.config.workspaceRoot),t=$t(e),r=uE.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.7"},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=f0){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{xd.existsSync(this.config.logPath)||xd.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)),$t(r)}}catch{}return e}};import*as la from"path";import*as Pf from"fs";var da=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(nn(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let a=o?.skipCompileNative===!0,c=await gc(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 Ay(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(nt);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=br(this.config.workspaceRoot);this.resolvedRoot=e?xe(e):xe(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();vc(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??la.dirname(Hn(this.resolvedRoot));try{Pf.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 Rd({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=la.join(Jr(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=la.join(e,"lsp-log",t);return Pf.mkdirSync(r,{recursive:!0}),xe(r)}catch{return"auto"}}};function pE(n){let e=yc(n);return f.info(`[SyncGuard] ${e.reason}`),e}var fE=(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))(fE||{}),wr=3,Cf=600*1e3,kf=100,Id=["ohpm","hvigor","dep-parse","lsp-init"],mE={ohpm:"ohpm install",hvigor:"hvigor sync","dep-parse":"dependency parse","lsp-init":"LSP init"},ua=15,Ad=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,Bn(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),g.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",g.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,g.info(`Constructor: using configured path as startPath: '${t}'`));let i=br(t);g.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,g.info(`Constructor: sdkPath='${this.sdkPath}', arktsLangServerPath='${this.arktsLangServerPath??"(null)"}', cppEnabled=${this.cppEnabled}, cppCompileCommandsPath='${this.config.cppCompileCommandsPath??"(none)"}'`),this.server=new g0({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=wf(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:De.object({target:De.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:De.object({files:De.array(De.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){g.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=De.object({file:De.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:De.number().describe("Line number (0-based)"),character:De.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:De.object({query:De.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:De.object({file:De.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:De.object({file:De.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:De.number().describe("Line number (0-based)"),character:De.number().describe("Character offset in the line (0-based)"),direction:De.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 g.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=_a(e);return g.info(`ArktsCheck protocol: ${t?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${t})`),t}catch(e){return g.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 Xh(e,Jn(this.nodePath)),g.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 g.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>kf)return g.warn(`check tool called with ${t.length} files (max: ${kf})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${kf}.`}],isError:!0};let{etsFiles:r,cppFiles:i,unsupported:o}=w0(t);o.length>0&&g.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(`
1333
+ `).trim();return!o&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:o}}async checkFile(e){let t=Ot(e),r=await Dn.promises.readFile(e,"utf8"),i=ja(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=vi.resolve(this.manager.projectRoot),i=[];for(let o of e){let s=vi.resolve(vi.isAbsolute(o)?o:vi.join(r,o));if(!Dn.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!Dn.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!Wn(s)){t.push(`Not a supported C/C++ file: ${o}`);continue}try{i.push(Dn.realpathSync(s))}catch{i.push(s)}}return i}};function u0(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 p0(n){return new Promise(e=>setTimeout(e,n))}import*as Fo from"fs";import*as Rd from"path";var $o=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 Lo();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};g.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 Dd(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 g.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return Lo();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};g.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 Dd("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return Lo();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};g.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 Dd("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=Ot(e),i=await Fo.promises.readFile(e,"utf8"),o=ja(e);g.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!Fo.existsSync(t)||!Fo.statSync(t).isFile()||!Wn(t)?null:t}};import{spawn as m0}from"child_process";import*as Ad from"fs";import*as uE from"path";var f0=30*1e3,h0=30*1e3,xd=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new En;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 Sn(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,nt),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}`))},h0);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=m0(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=qi(this.config.workspaceRoot),t=Ft(e),r=uE.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.9"},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=f0){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{Ad.existsSync(this.config.logPath)||Ad.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)),Ft(r)}}catch{}return e}};import*as ua from"path";import*as Pf from"fs";var pa=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(sn(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let a=o?.skipCompileNative===!0,c=await wc(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 Oy(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(nt);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=Sr(this.config.workspaceRoot);this.resolvedRoot=e?xe(e):xe(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();Sc(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??ua.dirname(Bn(this.resolvedRoot));try{Pf.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 xd({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=ua.join(Kr(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=ua.join(e,"lsp-log",t);return Pf.mkdirSync(r,{recursive:!0}),xe(r)}catch{return"auto"}}};function pE(n){let e=vc(n);return f.info(`[SyncGuard] ${e.reason}`),e}var fE=(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))(fE||{}),vr=3,Cf=600*1e3,kf=100,Id=["ohpm","hvigor","dep-parse","lsp-init"],mE={ohpm:"ohpm install",hvigor:"hvigor sync","dep-parse":"dependency parse","lsp-init":"LSP init"},ma=15,Td=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,Vn(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),g.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",g.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,g.info(`Constructor: using configured path as startPath: '${t}'`));let i=Sr(t);g.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,g.info(`Constructor: sdkPath='${this.sdkPath}', arktsLangServerPath='${this.arktsLangServerPath??"(null)"}', cppEnabled=${this.cppEnabled}, cppCompileCommandsPath='${this.config.cppCompileCommandsPath??"(none)"}'`),this.server=new g0({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=wf(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:De.object({target:De.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:De.object({files:De.array(De.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){g.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=De.object({file:De.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:De.number().describe("Line number (0-based)"),character:De.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:De.object({query:De.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:De.object({file:De.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:De.object({file:De.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:De.number().describe("Line number (0-based)"),character:De.number().describe("Character offset in the line (0-based)"),direction:De.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 g.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=Fa(e);return g.info(`ArktsCheck protocol: ${t?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${t})`),t}catch(e){return g.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 Xh(e,Yn(this.nodePath)),g.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 g.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>kf)return g.warn(`check tool called with ${t.length} files (max: ${kf})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${kf}.`}],isError:!0};let{etsFiles:r,cppFiles:i,unsupported:o}=w0(t);o.length>0&&g.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(`
1334
1334
  `),s.join(`
1335
1335
  `)].filter(d=>d.trim().length>0).join(`
1336
- `).trim()||"No diagnostics collected"}],isError:c}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:return g.warn(`ArkTS check rejected: project is DISCOVERING, files: ${e.join(", ")}`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 2:return g.warn(`ArkTS check rejected: project is SYNCING, files: ${e.join(", ")}`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 3:return g.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 g.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 g.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){g.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(r)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){g.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 ${ua}s)`;case 3:return`initializing (retry ${ua}s)`;case 5:return`error (${this.initRetryCount}/${wr})`;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}/${wr})`;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 g.warn(`ArkTS ${e} rejected: project is DISCOVERING`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 2:return g.warn(`ArkTS ${e} rejected: project is SYNCING`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 3:return g.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 g.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"),g.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(g.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:`Initializing.${this.buildRetrySuffix()}`}],isError:!0}):(g.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>=wr?(g.error(`Init retry limit reached (${this.initRetryCount}/${wr}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${wr}). 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}):(g.info(`Error check: auto-retrying (${this.initRetryCount}/${wr})`),this.arktsInitProgress=null,this.ensureProjectReady(),{content:[{type:"text",text:`Project initialization failed, auto-retrying.${this.buildRetrySuffix()}`}],isError:!0})}buildRetrySuffix(){return` Retry in ${ua}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=Id.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] ${mE[e.phase]}: ${e.detail}${o} [${r}s, total ${i}s]`,this.buildPipelineLine(e.phase),`Retry in ${ua}s. Expected total: 30s\u201310min (depends on project size).`].join(`
1337
- `)}buildPipelineLine(e){return`Pipeline: ${Id.map(r=>{let i=Id.indexOf(r)<Id.indexOf(e),o=r===e,s=mE[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 g.warn(`C++ ${e} rejected: C++ project is ${fE[this.cppProjectState]}`),{content:[{type:"text",text:"C++ project is syncing (compileNative), please retry in 25 seconds"}],isError:!0};case 3:return g.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 g.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):Un(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",g.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>=wr?(g.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${wr}), will not auto-retry`),{content:[{type:"text",text:`C++ project initialization failed repeatedly (auto-retry exhausted: ${this.cppInitRetryCount}/${wr}). 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}):(g.info(`C++ error check: auto-retrying (${this.cppInitRetryCount}/${wr})`),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 ~${ua}s.`}]})}restartProject(e){g.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=>g.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,g.info("[restart] ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(e=>g.warn("Failed to re-init ArkTS project during restart:",e)))}restartCpp(){this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(e=>g.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,g.info("[restart] C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>g.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 y0;if(await this.server.connect(e),g.info("devecocli-mcp-server started"),!this.config.debug){let t=ng();t&&g.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=br(t);r?(g.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):g.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?g.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):g.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{g.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return g.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return g.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){g.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,g.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{g.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{g.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=>{g.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?br(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=br(this.originalProjectPath),t&&g.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=>{g.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,g.info("Project fully initialized, check tool is available"),await this.trackInit("init_arkts",e,!0,null,this.arktsCheckTool?.aceServerPid??null)}catch(t){g.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 No(this.config.projectPath,this.sdkPath,this.arktsLangServerPath,this.config.nodeMaxOldSpaceSize,this.nodePath,this.socketAvailable);return e.setOnConfigChanged(()=>{g.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=pE(e),r=pa.existsSync(Fo.join(e,"oh-package-lock.json5")),i=pa.existsSync(Fo.join(e,"oh_modules"))&&pa.readdirSync(Fo.join(e,"oh_modules")).length>0;if(r&&i)return t.required?(g.info(`Sync required: ${t.reason}`),this.runSync(e,{skipHvigorSync:!1})):(g.info(`Sync skipped: ${t.reason}`),!0);let o=!t.required;return g.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,g.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 Oo.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>=Cf?(g.error(`Sync skipped for ${r}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(g.warn(`Sync skipped: ${e.reason}, resetting to IDLE for retry (elapsed ${r}s / ${Cf/1e3}s)`),this.projectState=0,!1)}case"failed":return g.error(`Project sync failed: ${e.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return g.error(`Project sync: unknown status ${e.status}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}async ensureCppProjectReady(){if(!this.cppEnabled){g.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=>{g.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=Pc(this.config.cppCompileCommandsPath,this.config.projectPath),this.cppCustomCompileCommandsDir&&g.info(`[Cpp] Custom compile_commands dir resolved: ${this.cppCustomCompileCommandsDir}`)),this.cppCustomCompileCommandsDir}async doEnsureCppProjectReady(){let e=this.config.projectPath;if(!e){g.info("[Cpp] No project path, skipping C++ init");return}let t=this.resolveCppCustomDir();if(t){g.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=nn(e);if(r.length===0){g.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,g.info(`[Cpp] Found ${r.length} C++ module(s): ${r.map(s=>s.name).join(", ")}`);let i=My(e),o=!i.required;g.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 da({workspaceRoot:e,clangdPath:this.clangdPath??"",...this.cppCustomCompileCommandsDir?{compileCommandsDir:this.cppCustomCompileCommandsDir}:{}});let t=Date.now();try{await this.cppLspManager.start(),this.cppCheckTool=new Lo(this.cppLspManager),this.cppLspTool=new _o(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,g.info("[Cpp] C++ project fully initialized, C++ tools are available"),await this.trackInit("init_cpp",t,!0,null,this.cppLspManager?.clangdPid??null)}catch(r){g.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 mt(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,g.info("[Cpp] Starting C++ project sync (compileNative)...");let r=await da.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>=Cf?(g.error(`[Cpp] C++ sync skipped for ${o}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(g.warn(`[Cpp] C++ sync skipped: ${r.reason}, resetting to IDLE_CPP for retry (elapsed ${o}s)`),this.cppProjectState=0,!1)}case"failed":return g.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){g.warn("Failed to close MCP server connection:",e)}g.info("devecocli-mcp-server stopped"),rg(),tg()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function w0(n){let e=[],t=[],r=[];for(let i of n)Fo.extname(i).toLowerCase()===".ets"?e.push(i):Un(i)?t.push(i):r.push(i);return{etsFiles:e,cppFiles:t,unsupported:r}}function Df(n={}){return new Ad(n)}import*as Rf from"fs";import*as ma from"path";import{spawn as v0}from"child_process";async function hE(n){Bn(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:i,serverMaxSize:o,nodePath:s}=await b0(n),a=P0(e,t,r,i,o,s);g.info("ace-server started, bridging stdio (initialize is left to the client)"),C0(a),await If(a.pid,xf("--arkts",n))}function xf(n,e){return[n,...e.projectPath?["--project-path"]:[],...e.autoDetect?["--auto-detect"]:[]]}async function If(n,e){let t="unknown";if(n!==null){let i=await mt(n);i!==null&&(t=ce(Number(i)*1024))}let r={event:v.ServeLsp,args:e,lspMemory:t};await R.track(r)}async function b0(n){let e=await P.new(),t;if(n.projectPath)t=xe(ma.resolve(n.projectPath)),g.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let c=La(process.cwd());t=xe(c??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=xe(process.cwd()),g.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,i=e.arktsLangServerPath;i||(g.error("ace-server not found (install DevEco Studio / CLT)."),process.exit(1));let o=Ri(i,!0),s=ma.join(Jr(),"lsp-server",String(Date.now()));Rf.mkdirSync(s,{recursive:!0});let a=S0(t,r);return g.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 S0(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=E0(n,e),s=bc(o,i);return g.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${o}, override=${i??"none"})`),s}function E0(n,e){try{let t=[];return new yi(n,e).getAllDependencyMap(t).status==="OK"?t.length:new kr(n).getAllModuleInfo().length}catch{return 0}}function P0(n,e,t,r,i,o){let s=ma.join(e,"lspLog");Rf.mkdirSync(s,{recursive:!0});let a=ls({serverPath:n,lspLogPath:s,serverMaxSize:i,projectPath:t,sdkPath:r}),c=Jn(o);return g.info(`[serve-lsp] spawn: ${c} ${a.join(" ")}`),v0(c,a,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function C0(n){n.on("error",e=>{g.error(`[ace-server] spawn error: ${e.message}`),process.exit(1)}),n.stdout?.on("error",e=>{g.error(`[ace-server] stdout error: ${e.message}`)}),n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("error",e=>{g.error(`[ace-server] stderr error: ${e.message}`)}),n.stderr?.on("data",e=>{g.error(`[ace-server] ${e.toString("utf8").trim()}`)}),n.stdin?.on("error",e=>{g.error(`[ace-server] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{g.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as gE from"fs";import*as vi from"path";import{spawn as k0}from"child_process";async function yE(n){Bn(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await D0(n),i=vi.join(t,"compile_commands.json");gE.existsSync(i)||g.warn(`compile_commands.json not found at ${i}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let o=x0(e,t,r);g.info("clangd started, bridging stdio (initialize is left to the client)"),A0(o),await If(o.pid,xf("--cpp",n))}async function D0(n){let e=await R0();e?.clangdPath||(g.error("clangd not found. Ensure DevEco Studio / CLT is installed."),process.exit(1));let t;if(n.projectPath)t=xe(vi.resolve(n.projectPath)),g.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let c=La(process.cwd());t=xe(c??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=xe(vi.resolve(process.cwd())),g.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,i=e.clangdPath,o=Hn(t),s=vi.dirname(o),a=Pc(process.env.DEVECO_CLI_CPP_COMPILE_COMMANDS,t);return a&&(g.info(`Using custom compile_commands dir: ${a}`),s=a),g.info(`projectPath=${t}, sdkPath=${r}, clangdPath=${i}, compileCommandsDir=${s}`),{projectPath:t,clangdPath:i,compileCommandsDir:s}}async function R0(){try{return await P.new()}catch{let n=Kh();if(!n)return null;try{return P.fromIDE(n)}catch{return null}}}function x0(n,e,t){let r=I0(e);return g.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),k0(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function I0(n){return[`--compile-commands-dir=${ge(n)}`,"--log=info","--pch-storage=memory"]}function A0(n){n.on("error",e=>{g.error(`[clangd] spawn error: ${e.message}`),process.exit(1)}),n.stdout?.on("error",e=>{g.error(`[clangd] stdout error: ${e.message}`)}),n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("error",e=>{g.error(`[clangd] stderr error: ${e.message}`)}),n.stderr?.on("data",e=>{g.error(`[clangd] ${e.toString("utf8").trim()}`)}),n.stdin?.on("error",e=>{g.error(`[clangd] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{g.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function O0(){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=Df({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:R}),c,l=new Promise(h=>{c=h}),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(h){console.error("Failed to start MCP server:",h instanceof Error?h.message:String(h)),process.exit(1)}await l}var Af=new T0("serve").description("Host bundled auxiliary protocol servers");Af.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await O0()});Af.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 hE({projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await yE({projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var wE=Af;import{Command as j0,InvalidArgumentError as EE}from"commander";import{red as H0,dim as U0}from"colorette";import{Command as N0}from"commander";import{cyan as Td,yellow as Od}from"colorette";import*as vE from"path";function M0(n){return Od(`If you want the latest docs(${n}), please update CLI first: run \`devecocli update\` to update`)}function L0(n){console.log(Od(`Latest docs v${n.version} (apiVersion ${n.apiVersion}) is incompatible with current CLI.`)),console.log(M0(n.version))}function _0(n,e,t){console.log(t?Td(`New docs version ${n} found (current v${e??"none"})`):Td(`Documentation is already up to date v${n}`))}async function $0(n){let e=_t();console.log(Td("Checking for documentation updates..."));let{latest:t,compatible:r}=await no(e);if(!r){L0(t);return}let i=await Li(),o=!i||Zr(r.version,i)>0;if(n.check){_0(r.version,i,o);return}if(!n.force&&!o){console.log(Od(`Docs is already up to date v${r.version}`));return}console.log(Td(`Downloading documentation package v${r.version}...`)),await sl({version:r.version,apiVersion:r.apiVersion,dist:r.dist},vE.join(F(),"doc-data"),"docs-update"),console.log(Od(`Docs successfully upgrade to ${r.version}`))}var F0=new N0("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 $0(n)}),bE=F0;async function Tf(n,e){let t=Date.now();try{let r=await e();return await SE(n,Date.now()-t,!0,null),r}catch(r){let i=r instanceof Error?r.code??r.name:"UnknownError";throw await SE(n,Date.now()-t,!1,i),r}}async function SE(n,e,t,r){await R.track(n,{duration_ms:e,success:t,error_code:r}).catch(()=>{})}function B0(n){return n instanceof Error&&(n.name==="CacheDirError"||n.name==="DocPathSafetyError")}function Of(n){console.error(H0(W0(n))),process.exitCode=1}function W0(n){let e=n instanceof Error?n.message:String(n);return B0(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 PE(...n){return e=>{if(!n.includes(e))throw new EE(`Allowed values: ${n.join(", ")}`);return e}}function V0(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new EE("Must be a positive integer.");return e}var G0=PE("json","default"),q0=PE("json","default");function z0(n){let e=n.map(t=>t.trim()).filter(Boolean);if(e.length===0)throw new Error("Keywords cannot be empty.");return e}function J0(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 fa=new j0("docs").description("HarmonyOS documentation commands (search, read, catalog, update)");fa.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)",G0,"default").option("--limit <n>","Max number of results",V0,10).action(async(n,e)=>{let t={event:v.DocOperation,subAction:"search",keywords:n,queryLen:n.join(" ").length,catalog:e.catalog??"all"};try{await Tf(t,async()=>{let r=z0(n),i=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await nc(),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:F()});try{let c=await a.search({keywords:r,catalog:i,limit:e.limit});e.format==="json"?console.log(JSON.stringify(c,null,2)):J0(c)}finally{await a.close()}})}catch(r){Of(r)}});fa.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 Tf(t,async()=>{if(!e)throw new Error("Document ID cannot be empty.");let i=await(await nc()).createDocsEngine({cacheDir:F()});try{let o=await i.read({relativePath:e});console.log(o)}finally{await i.close()}})}catch(r){Of(r)}});fa.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",q0,"default").action(async n=>{let e={event:v.DocOperation,subAction:"catalog",fmt:n.format??"default"};try{await Tf(e,async()=>{let r=await(await nc()).createDocsEngine({cacheDir:F()});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)} ${U0(o.nodeName)}`)}finally{await r.close()}})}catch(t){Of(t)}});fa.addCommand(bE);var CE=fa;import{Command as j$}from"commander";import{Command as Lf,InvalidArgumentError as Nf,Option as ha}from"commander";import _f from"ora";var DE=["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(`
1336
+ `).trim()||"No diagnostics collected"}],isError:c}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:return g.warn(`ArkTS check rejected: project is DISCOVERING, files: ${e.join(", ")}`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 2:return g.warn(`ArkTS check rejected: project is SYNCING, files: ${e.join(", ")}`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 3:return g.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 g.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 g.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){g.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(r)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){g.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 ${ma}s)`;case 3:return`initializing (retry ${ma}s)`;case 5:return`error (${this.initRetryCount}/${vr})`;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}/${vr})`;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 g.warn(`ArkTS ${e} rejected: project is DISCOVERING`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 2:return g.warn(`ArkTS ${e} rejected: project is SYNCING`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 3:return g.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 g.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"),g.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(g.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:`Initializing.${this.buildRetrySuffix()}`}],isError:!0}):(g.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>=vr?(g.error(`Init retry limit reached (${this.initRetryCount}/${vr}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${vr}). 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}):(g.info(`Error check: auto-retrying (${this.initRetryCount}/${vr})`),this.arktsInitProgress=null,this.ensureProjectReady(),{content:[{type:"text",text:`Project initialization failed, auto-retrying.${this.buildRetrySuffix()}`}],isError:!0})}buildRetrySuffix(){return` Retry in ${ma}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=Id.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] ${mE[e.phase]}: ${e.detail}${o} [${r}s, total ${i}s]`,this.buildPipelineLine(e.phase),`Retry in ${ma}s. Expected total: 30s\u201310min (depends on project size).`].join(`
1337
+ `)}buildPipelineLine(e){return`Pipeline: ${Id.map(r=>{let i=Id.indexOf(r)<Id.indexOf(e),o=r===e,s=mE[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 g.warn(`C++ ${e} rejected: C++ project is ${fE[this.cppProjectState]}`),{content:[{type:"text",text:"C++ project is syncing (compileNative), please retry in 25 seconds"}],isError:!0};case 3:return g.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 g.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):Wn(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",g.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>=vr?(g.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${vr}), will not auto-retry`),{content:[{type:"text",text:`C++ project initialization failed repeatedly (auto-retry exhausted: ${this.cppInitRetryCount}/${vr}). 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}):(g.info(`C++ error check: auto-retrying (${this.cppInitRetryCount}/${vr})`),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 ~${ma}s.`}]})}restartProject(e){g.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=>g.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,g.info("[restart] ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(e=>g.warn("Failed to re-init ArkTS project during restart:",e)))}restartCpp(){this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(e=>g.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,g.info("[restart] C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>g.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 y0;if(await this.server.connect(e),g.info("devecocli-mcp-server started"),!this.config.debug){let t=ng();t&&g.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=Sr(t);r?(g.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):g.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?g.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):g.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{g.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return g.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return g.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){g.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,g.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{g.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{g.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=>{g.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?Sr(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=Sr(this.originalProjectPath),t&&g.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=>{g.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,g.info("Project fully initialized, check tool is available"),await this.trackInit("init_arkts",e,!0,null,this.arktsCheckTool?.aceServerPid??null)}catch(t){g.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 Mo(this.config.projectPath,this.sdkPath,this.arktsLangServerPath,this.config.nodeMaxOldSpaceSize,this.nodePath,this.socketAvailable);return e.setOnConfigChanged(()=>{g.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=pE(e),r=fa.existsSync(jo.join(e,"oh-package-lock.json5")),i=fa.existsSync(jo.join(e,"oh_modules"))&&fa.readdirSync(jo.join(e,"oh_modules")).length>0;if(r&&i)return t.required?(g.info(`Sync required: ${t.reason}`),this.runSync(e,{skipHvigorSync:!1})):(g.info(`Sync skipped: ${t.reason}`),!0);let o=!t.required;return g.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,g.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 No.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>=Cf?(g.error(`Sync skipped for ${r}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(g.warn(`Sync skipped: ${e.reason}, resetting to IDLE for retry (elapsed ${r}s / ${Cf/1e3}s)`),this.projectState=0,!1)}case"failed":return g.error(`Project sync failed: ${e.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return g.error(`Project sync: unknown status ${e.status}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}async ensureCppProjectReady(){if(!this.cppEnabled){g.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=>{g.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=kc(this.config.cppCompileCommandsPath,this.config.projectPath),this.cppCustomCompileCommandsDir&&g.info(`[Cpp] Custom compile_commands dir resolved: ${this.cppCustomCompileCommandsDir}`)),this.cppCustomCompileCommandsDir}async doEnsureCppProjectReady(){let e=this.config.projectPath;if(!e){g.info("[Cpp] No project path, skipping C++ init");return}let t=this.resolveCppCustomDir();if(t){g.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=sn(e);if(r.length===0){g.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,g.info(`[Cpp] Found ${r.length} C++ module(s): ${r.map(s=>s.name).join(", ")}`);let i=_y(e),o=!i.required;g.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 pa({workspaceRoot:e,clangdPath:this.clangdPath??"",...this.cppCustomCompileCommandsDir?{compileCommandsDir:this.cppCustomCompileCommandsDir}:{}});let t=Date.now();try{await this.cppLspManager.start(),this.cppCheckTool=new _o(this.cppLspManager),this.cppLspTool=new $o(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,g.info("[Cpp] C++ project fully initialized, C++ tools are available"),await this.trackInit("init_cpp",t,!0,null,this.cppLspManager?.clangdPid??null)}catch(r){g.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 mt(o);l!==null&&(s=ae(Number(l)*1024))}let a={event:v.McpToolCall,subAction:e,mcpMemory:ae(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,g.info("[Cpp] Starting C++ project sync (compileNative)...");let r=await pa.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>=Cf?(g.error(`[Cpp] C++ sync skipped for ${o}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(g.warn(`[Cpp] C++ sync skipped: ${r.reason}, resetting to IDLE_CPP for retry (elapsed ${o}s)`),this.cppProjectState=0,!1)}case"failed":return g.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){g.warn("Failed to close MCP server connection:",e)}g.info("devecocli-mcp-server stopped"),rg(),tg()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function w0(n){let e=[],t=[],r=[];for(let i of n)jo.extname(i).toLowerCase()===".ets"?e.push(i):Wn(i)?t.push(i):r.push(i);return{etsFiles:e,cppFiles:t,unsupported:r}}function Df(n={}){return new Td(n)}import*as Rf from"fs";import*as ha from"path";import{spawn as v0}from"child_process";async function hE(n){Vn(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:i,serverMaxSize:o,nodePath:s}=await b0(n),a=P0(e,t,r,i,o,s);g.info("ace-server started, bridging stdio (initialize is left to the client)"),C0(a),await Af(a.pid,xf("--arkts",n))}function xf(n,e){return[n,...e.projectPath?["--project-path"]:[],...e.autoDetect?["--auto-detect"]:[]]}async function Af(n,e){let t="unknown";if(n!==null){let i=await mt(n);i!==null&&(t=ae(Number(i)*1024))}let r={event:v.ServeLsp,args:e,lspMemory:t};await D.track(r)}async function b0(n){let e=await P.new(),t;if(n.projectPath)t=xe(ha.resolve(n.projectPath)),g.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let c=$a(process.cwd());t=xe(c??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=xe(process.cwd()),g.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,i=e.arktsLangServerPath;i||(g.error("ace-server not found (install DevEco Studio / CLT)."),process.exit(1));let o=xi(i,!0),s=ha.join(Kr(),"lsp-server",String(Date.now()));Rf.mkdirSync(s,{recursive:!0});let a=S0(t,r);return g.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 S0(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=E0(n,e),s=Ec(o,i);return g.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${o}, override=${i??"none"})`),s}function E0(n,e){try{let t=[];return new wi(n,e).getAllDependencyMap(t).status==="OK"?t.length:new Rr(n).getAllModuleInfo().length}catch{return 0}}function P0(n,e,t,r,i,o){let s=ha.join(e,"lspLog");Rf.mkdirSync(s,{recursive:!0});let a=us({serverPath:n,lspLogPath:s,serverMaxSize:i,projectPath:t,sdkPath:r}),c=Yn(o);return g.info(`[serve-lsp] spawn: ${c} ${a.join(" ")}`),v0(c,a,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function C0(n){n.on("error",e=>{g.error(`[ace-server] spawn error: ${e.message}`),process.exit(1)}),n.stdout?.on("error",e=>{g.error(`[ace-server] stdout error: ${e.message}`)}),n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("error",e=>{g.error(`[ace-server] stderr error: ${e.message}`)}),n.stderr?.on("data",e=>{g.error(`[ace-server] ${e.toString("utf8").trim()}`)}),n.stdin?.on("error",e=>{g.error(`[ace-server] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{g.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as gE from"fs";import*as bi from"path";import{spawn as k0}from"child_process";async function yE(n){Vn(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await D0(n),i=bi.join(t,"compile_commands.json");gE.existsSync(i)||g.warn(`compile_commands.json not found at ${i}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let o=x0(e,t,r);g.info("clangd started, bridging stdio (initialize is left to the client)"),I0(o),await Af(o.pid,xf("--cpp",n))}async function D0(n){let e=await R0();e?.clangdPath||(g.error("clangd not found. Ensure DevEco Studio / CLT is installed."),process.exit(1));let t;if(n.projectPath)t=xe(bi.resolve(n.projectPath)),g.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let c=$a(process.cwd());t=xe(c??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=xe(bi.resolve(process.cwd())),g.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,i=e.clangdPath,o=Bn(t),s=bi.dirname(o),a=kc(process.env.DEVECO_CLI_CPP_COMPILE_COMMANDS,t);return a&&(g.info(`Using custom compile_commands dir: ${a}`),s=a),g.info(`projectPath=${t}, sdkPath=${r}, clangdPath=${i}, compileCommandsDir=${s}`),{projectPath:t,clangdPath:i,compileCommandsDir:s}}async function R0(){try{return await P.new()}catch{let n=Kh();if(!n)return null;try{return P.fromIDE(n)}catch{return null}}}function x0(n,e,t){let r=A0(e);return g.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),k0(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function A0(n){return[`--compile-commands-dir=${he(n)}`,"--log=info","--pch-storage=memory"]}function I0(n){n.on("error",e=>{g.error(`[clangd] spawn error: ${e.message}`),process.exit(1)}),n.stdout?.on("error",e=>{g.error(`[clangd] stdout error: ${e.message}`)}),n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("error",e=>{g.error(`[clangd] stderr error: ${e.message}`)}),n.stderr?.on("data",e=>{g.error(`[clangd] ${e.toString("utf8").trim()}`)}),n.stdin?.on("error",e=>{g.error(`[clangd] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{g.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function O0(){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=Df({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(h=>{c=h}),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(h){console.error("Failed to start MCP server:",h instanceof Error?h.message:String(h)),process.exit(1)}await l}var If=new T0("serve").description("Host bundled auxiliary protocol servers");If.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await O0()});If.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 hE({projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await yE({projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var wE=If;import{Command as j0,InvalidArgumentError as EE}from"commander";import{red as H0,dim as U0}from"colorette";import{Command as N0}from"commander";import{cyan as Od,yellow as Nd}from"colorette";import*as vE from"path";function M0(n){return Nd(`If you want the latest docs(${n}), please update CLI first: run \`devecocli update\` to update`)}function L0(n){console.log(Nd(`Latest docs v${n.version} (apiVersion ${n.apiVersion}) is incompatible with current CLI.`)),console.log(M0(n.version))}function _0(n,e,t){console.log(t?Od(`New docs version ${n} found (current v${e??"none"})`):Od(`Documentation is already up to date v${n}`))}async function $0(n){let e=_t();console.log(Od("Checking for documentation updates..."));let{latest:t,compatible:r}=await io(e);if(!r){L0(t);return}let i=await _i(),o=!i||en(r.version,i)>0;if(n.check){_0(r.version,i,o);return}if(!n.force&&!o){console.log(Nd(`Docs is already up to date v${r.version}`));return}console.log(Od(`Downloading documentation package v${r.version}...`)),await al({version:r.version,apiVersion:r.apiVersion,dist:r.dist},vE.join(F(),"doc-data"),"docs-update"),console.log(Nd(`Docs successfully upgrade to ${r.version}`))}var F0=new N0("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 $0(n)}),bE=F0;async function Tf(n,e){let t=Date.now();try{let r=await e();return await SE(n,Date.now()-t,!0,null),r}catch(r){let i=r instanceof Error?r.code??r.name:"UnknownError";throw await SE(n,Date.now()-t,!1,i),r}}async function SE(n,e,t,r){await D.track(n,{duration_ms:e,success:t,error_code:r}).catch(()=>{})}function B0(n){return n instanceof Error&&(n.name==="CacheDirError"||n.name==="DocPathSafetyError")}function Of(n){console.error(H0(W0(n))),process.exitCode=1}function W0(n){let e=n instanceof Error?n.message:String(n);return B0(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 PE(...n){return e=>{if(!n.includes(e))throw new EE(`Allowed values: ${n.join(", ")}`);return e}}function V0(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new EE("Must be a positive integer.");return e}var G0=PE("json","default"),q0=PE("json","default");function z0(n){let e=n.map(t=>t.trim()).filter(Boolean);if(e.length===0)throw new Error("Keywords cannot be empty.");return e}function J0(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 ga=new j0("docs").description("HarmonyOS documentation commands (search, read, catalog, update)");ga.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)",G0,"default").option("--limit <n>","Max number of results",V0,10).action(async(n,e)=>{let t={event:v.DocOperation,subAction:"search",keywords:n,queryLen:n.join(" ").length,catalog:e.catalog??"all"};try{await Tf(t,async()=>{let r=z0(n),i=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await oc(),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:F()});try{let c=await a.search({keywords:r,catalog:i,limit:e.limit});e.format==="json"?console.log(JSON.stringify(c,null,2)):J0(c)}finally{await a.close()}})}catch(r){Of(r)}});ga.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 Tf(t,async()=>{if(!e)throw new Error("Document ID cannot be empty.");let i=await(await oc()).createDocsEngine({cacheDir:F()});try{let o=await i.read({relativePath:e});console.log(o)}finally{await i.close()}})}catch(r){Of(r)}});ga.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",q0,"default").action(async n=>{let e={event:v.DocOperation,subAction:"catalog",fmt:n.format??"default"};try{await Tf(e,async()=>{let r=await(await oc()).createDocsEngine({cacheDir:F()});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)} ${U0(o.nodeName)}`)}finally{await r.close()}})}catch(t){Of(t)}});ga.addCommand(bE);var CE=ga;import{Command as j$}from"commander";import{Command as Lf,InvalidArgumentError as Nf,Option as ya}from"commander";import _f from"ora";var DE=["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
1339
  `);function Y0(n){let e=parseInt(n,10);if(!Number.isInteger(e)||e<0||String(e)!==n.trim())throw new Nf("depth must be a non-negative integer");return e}function Mf(n){let e=Number(n);if(!Number.isFinite(e)||e<=0)throw new Nf("timeout must be a positive number");if(e>36e4)throw new Nf("timeout must not exceed 360000ms");return e}function RE(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 xE(n,e=0){let t=[],r=" ".repeat(e);for(let i of n)t.push(`${r}${RE(i)}`),i.children.length>0&&t.push(...xE(i.children,e+1).split(`
1340
1340
  `));return t.join(`
1341
- `)}function K0(n){if(n.allWindows&&n.window)throw new Error("--all-windows and --window are mutually exclusive.")}function X0(n,e){let t=Ki(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 Z0(n,e){return e.id?X0(n,e.id):e.format==="json"?JSON.stringify(n,null,2):xE(n)}async function Q0(n){K0(n);let e=_f({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let i=await P.new(),o=await T(i,n.device),s=new xr(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=Z0(t,n);return console.log(r),Buffer.byteLength(r,"utf8")}function e$(n){return{event:v.CommandExecuted,args:["ui","layout",...n.device?["--device"]:[]],mode:n.mode,outputSize:0}}async function t$(n){let e=e$(n),t=Date.now(),r=!0,i=null;try{e.outputSize=await Q0(n)}catch(o){throw r=!1,i=X(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await R.track(e,o)}}var IE=new Lf("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 ha("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(Y0).default(0)).addOption(new ha("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new ha("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async n=>{await t$(n)});function AE(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 RE(e)}function kE(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 ga(){for(let n of Np())console.warn(n)}async function r$(n){if(!n.selector)throw new Error("Provide a selector expression.");let e=_f({text:"Finding element\u2026",color:"cyan"}).start(),t;try{let r=await P.new(),i=await T(r,n.device);t=await new Zi(r.hdcPath).find(i,n.selector,{window:n.window,all:n.all,timeoutMs:n.timeout})}catch(r){throw e.stop(),ga(),new Error(`Failed to find element: ${r.message}`,{cause:r})}if(e.stop(),ga(),n.format==="json"){let r=n.all?t.map(i=>kE(i)):kE(t[0]);console.log(JSON.stringify(r,null,2))}else{let r=n.all===!0;for(let i of t){let o=AE(i);console.log(r?`#${i.index} ${o}`:o)}}}var TE=new Lf("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 ha("--timeout <ms>","Max wait time in milliseconds for the element to appear").argParser(Mf).default(3e3)).addOption(new ha("--format <format>","Output format").choices(["default","json"]).default("default")).action(async(n,e)=>{await r$({...e,selector:n})}).addHelpText("after",DE);function n$(n){return AE(n)}async function i$(n){await new Promise(e=>setTimeout(e,n)),console.log(`Waited ${n}ms`)}async function o$(n,e,t,r,i){await n.waitForDisappear(e,t,r,i),console.log(`Element disappeared: ${t}`)}async function s$(n,e,t,r,i){let o=await n.waitForAppearance(e,t,r,i);console.log(n$(o))}async function a$(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=Mf(t);ga(),await i$(a);return}let i=t,o=n[1]?Mf(n[1]):3e3,s=_f({text:"Waiting\u2026",color:"cyan"}).start();try{let a=await P.new(),c=await T(a,e.device),l=new Zi(a.hdcPath);e.disappear?await o$(l,c,i,o,e.window):await s$(l,c,i,o,e.window),s.stop(),ga()}catch(a){throw s.stop(),ga(),new Error(`Failed to wait: ${a.message}`,{cause:a})}}var OE=new Lf("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 a$(n,e)}).addHelpText("after",DE);import{Command as c$,Option as l$}from"commander";import{yellow as d$}from"colorette";import u$ from"ora";var p$=["Id","Name","Pid","DisplayId","Focused"];function m$(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(Mr(p$,t))}async function f$(n){let e=u$({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let r=await P.new(),i=await T(r,n.device);t=await new Rr(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(d$(" No windows found."));return}m$(t,n.format)}function h$(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 g$(n){let e=h$(n),t=Date.now(),r=!0,i=null;try{await f$(n)}catch(o){throw r=!1,i=X(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await R.track(e,o)}}var $f=new c$("window").description("Manage device windows");$f.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new l$("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async n=>{await g$(n)});import{Command as y$}from"commander";import{green as w$}from"colorette";function v$(n){return{event:v.CommandExecuted,args:["ui","screenshot",...n.device?["--device"]:[]]}}function b$(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}async function S$(n){let e=v$(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?b$(n.display):void 0,s=await P.new(),a=new Qn(s),c=a.resolveDestinationPath(n.path),l=await T(s,n.device);await a.captureToPath(l,c,o),console.log(w$(`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 R.track(e,o)}}var NE=new y$("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(S$);import{Command as Nd,Option as E$}from"commander";import{green as Ff,yellow as P$}from"colorette";import LE from"ora";var Md=["--device <name|serial>","Target physical device name or serial; required when multiple devices are connected"],_E=["--path <dir|file.mp4>","Required writable destination: existing directory or a new .mp4 file"];function Ld(n){return new S("INVALID_ARGUMENT",n)}function ME(n){if(n!==void 0&&!n.trim())throw Ld("--device must not be empty.")}function _d(n,e){let t=n.parent?.opts()?.device;if(ME(t),ME(e),t&&e&&t!==e)throw Ld(`Conflicting --device values: ${JSON.stringify(t)} and ${JSON.stringify(e)}`);return e??t}function $E(n,e){if(n.parent?.opts()?.path!==void 0)throw Ld(`--path is not valid for ui screenrecord ${e}.`)}function FE(n,e){let t=n.parent?.opts()?.path;if(t!==void 0&&e!==void 0&&t!==e)throw Ld(`Conflicting --path values: ${JSON.stringify(t)} and ${JSON.stringify(e)}`);return e??t}function $d(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 C$(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 R.track(r,a)}}function jE(n){if(n.kind==="saved"){console.log(Ff(`Saved successfully to ${n.localPath}`));for(let e of n.warnings??[])console.error(P$(`Warning: ${e}`))}else n.kind==="external-stopped"&&console.log(Ff("Recording stopped. View the file in the device gallery; this CLI cannot retrieve it."))}async function k$(n,e){let t=$d(e,[{name:"--device",value:n.device},{name:"--path",value:n.path}]);await Fd([],t,async()=>{let r=_d(e,n.device),i=FE(e,n.path),o=new an(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=LE({text:"Stopping and saving the recording\u2026",color:"cyan"}).start()}})}finally{s?.stop()}jE(a)})}async function D$(n,e){let t=$d(e,[{name:"--device",value:n.device},{name:"--path",value:n.path}]);await Fd(["start"],t,async()=>{let r=_d(e,n.device),i=FE(e,n.path);await new an(await P.new()).startDetached(r,i),console.log(Ff("Recording started. Stop with devecocli ui screenrecord stop"))})}async function R$(n,e){let t=[...$d(e,[{name:"--device",value:n.device}]),...n.force?["--force"]:[]];await Fd(["stop"],t,async()=>{let r=_d(e,n.device);$E(e,"stop");let i=new an(await P.new()),o=LE({text:"Stopping recording\u2026",color:"cyan"}).start(),s;try{s=await i.stopRecording(r,n.force??!1)}finally{o.stop()}jE(s)})}var x$={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 I$(n,e){let t=[...$d(e,[{name:"--device",value:n.device}]),...C$(e,"format")?["--format"]:[]];await Fd(["status"],t,async()=>{let r=_d(e,n.device);$E(e,"status");let o=await new an(await P.new()).getRecordingStatus(r);if(n.format==="json"){console.log(JSON.stringify(o));return}console.log(x$[o.status]),o.status==="idle"&&o.note&&console.log(o.note)})}var ya=new Nd("screenrecord").description("Record the screen of a physical device to an MP4 file").option(...Md).option(..._E).action(k$);ya.addCommand(new Nd("start").description("Start recording and return immediately (detached)").option(...Md).option(..._E).action(D$));ya.addCommand(new Nd("stop").description("Stop the current recording and save the file").option(...Md).option("--force","Stop a recording that was not started by this CLI (no download)").action(R$));ya.addCommand(new Nd("status").description("Show the recording status without changing it").option(...Md).addOption(new E$("--format <format>","Output format").choices(["table","json"]).default("table")).action(I$));import{Command as kn}from"commander";function Dn(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 A$(n){let t=`"$(printf '%s' '${Buffer.from(n,"utf8").toString("base64")}' | base64 -d)"`;return m(`escapeShellText: ${n} -> ${t}`),t}async function Rn(n,e,t,r){let i=new wt;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 R.track(t,c)}}async function T$(n,e,t){let r=Dn("click",t);await Rn("Executing click...","click failed",r,async i=>{to(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await lr(t.device),{x:a,y:c}=await ro(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await kt(o,s,["uitest","uiInput","click",String(a),String(c)]),i.succeed(`click at (${a}, ${c})`)})}async function O$(n,e,t){let r=Dn("doubleclick",t);await Rn("Executing doubleclick...","doubleclick failed",r,async i=>{to(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await lr(t.device),{x:a,y:c}=await ro(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await kt(o,s,["uitest","uiInput","doubleClick",String(a),String(c)]),i.succeed(`doubleclick at (${a}, ${c})`)})}async function N$(n,e,t){let r=Dn("longclick",t);await Rn("Executing longclick...","longclick failed",r,async i=>{to(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await lr(t.device),{x:a,y:c}=await ro(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await kt(o,s,["uitest","uiInput","longClick",String(a),String(c)]),i.succeed(`longclick at (${a}, ${c})`)})}async function M$(n,e,t,r,i){let o=Dn("swipe",i);await Rn("Executing swipe...","swipe failed",o,async s=>{Be(n,"x1"),Be(e,"y1"),Be(t,"x2"),Be(r,"y2");let a=bs(i.speed),{hdcPath:c,deviceId:l}=await lr(i.device),d=["uitest","uiInput","swipe",n,e,t,r];a&&d.push(a),await kt(c,l,d),s.succeed(`swipe from (${n}, ${e}) to (${t}, ${r})`)})}async function L$(n,e,t,r,i){let o=Dn("fling",i);await Rn("Executing fling...","fling failed",o,async s=>{Be(n,"x1"),Be(e,"y1"),Be(t,"x2"),Be(r,"y2");let a=bs(i.speed),{hdcPath:c,deviceId:l}=await lr(i.device),d=["uitest","uiInput","fling",n,e,t,r];a&&d.push(a),await kt(c,l,d),s.succeed(`fling from (${n}, ${e}) to (${t}, ${r})`)})}async function _$(n,e,t,r,i){let o=Dn("drag",i);await Rn("Executing drag...","drag failed",o,async s=>{Be(n,"x1"),Be(e,"y1"),Be(t,"x2"),Be(r,"y2");let a=bs(i.speed),{hdcPath:c,deviceId:l}=await lr(i.device),d=["uitest","uiInput","drag",n,e,t,r];a&&d.push(a),await kt(c,l,d),s.succeed(`drag from (${n}, ${e}) to (${t}, ${r})`)})}async function $$(n,e){let t=Dn("dircfling",e);await Rn("Executing dircfling...","dircfling failed",t,async r=>{let i=Kc[n];if(i===void 0)throw new Error(`Invalid direction "${n}". Valid values: ${Object.keys(Kc).join(", ")}`);let{hdcPath:o,deviceId:s}=await lr(e.device);await kt(o,s,["uitest","uiInput","dircFling",i]),r.succeed(`dircfling ${n}`)})}async function F$(n,e,t,r){let i=Dn("text",r);await Rn("Executing text input...","input failed",i,async o=>{to(e,t,r.id,r.window,!1),Xc(n,"text");let{hdcPath:s,deviceId:a}=await lr(r.device),c=A$(n);if(e!==void 0)await kt(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 ro(s,a,void 0,void 0,r.id,r.window);await kt(s,a,[`uitest uiInput inputText ${l} ${d} ${c}`]),o.succeed(`input ${n} at (${l}, ${d})`)}else await kt(s,a,[`uitest uiInput text ${c}`]),o.succeed(`input ${n}`)})}var HE=new kn("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(T$),UE=new kn("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(O$),BE=new kn("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(N$),WE=new kn("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(M$),VE=new kn("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(L$),GE=new kn("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(_$),qE=new kn("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action($$),zE=new kn("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(F$);var Ke=new j$("ui").description("Inspect and interact with UI on a connected device");Ke.addCommand(IE);Ke.addCommand(TE);Ke.addCommand(OE);Ke.addCommand($f);Ke.addCommand(NE);Ke.addCommand(ya);Ke.addCommand(HE);Ke.addCommand(UE);Ke.addCommand(BE);Ke.addCommand(WE);Ke.addCommand(VE);Ke.addCommand(GE);Ke.addCommand(qE);Ke.addCommand(zE);var JE=Ke;import{Command as IP,InvalidArgumentError as Lj}from"commander";import{execa as lF}from"execa";import vr from"fs";import*as Wf from"os";import*as W from"path";var H$=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),U$=/\r/g,B$=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,W$=/^<+\s*/,V$=/\s*>+$/,G$=[/^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\.$/],q$=new Set([1]);function Hf(n){if(!n)return"";let e=n.replace(H$,"").replace(U$,`
1341
+ `)}function K0(n){if(n.allWindows&&n.window)throw new Error("--all-windows and --window are mutually exclusive.")}function X0(n,e){let t=Xi(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 Z0(n,e){return e.id?X0(n,e.id):e.format==="json"?JSON.stringify(n,null,2):xE(n)}async function Q0(n){K0(n);let e=_f({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let i=await P.new(),o=await T(i,n.device),s=new Ir(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=Z0(t,n);return console.log(r),Buffer.byteLength(r,"utf8")}function e$(n){return{event:v.CommandExecuted,args:["ui","layout",...n.device?["--device"]:[]],mode:n.mode,outputSize:0}}async function t$(n){let e=e$(n),t=Date.now(),r=!0,i=null;try{e.outputSize=await Q0(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 AE=new Lf("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 ya("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(Y0).default(0)).addOption(new ya("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new ya("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async n=>{await t$(n)});function IE(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 RE(e)}function kE(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 wa(){for(let n of Np())console.warn(n)}async function r$(n){if(!n.selector)throw new Error("Provide a selector expression.");let e=_f({text:"Finding element\u2026",color:"cyan"}).start(),t;try{let r=await P.new(),i=await T(r,n.device);t=await new Qi(r.hdcPath).find(i,n.selector,{window:n.window,all:n.all,timeoutMs:n.timeout})}catch(r){throw e.stop(),wa(),new Error(`Failed to find element: ${r.message}`,{cause:r})}if(e.stop(),wa(),n.format==="json"){let r=n.all?t.map(i=>kE(i)):kE(t[0]);console.log(JSON.stringify(r,null,2))}else{let r=n.all===!0;for(let i of t){let o=IE(i);console.log(r?`#${i.index} ${o}`:o)}}}var TE=new Lf("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 ya("--timeout <ms>","Max wait time in milliseconds for the element to appear").argParser(Mf).default(3e3)).addOption(new ya("--format <format>","Output format").choices(["default","json"]).default("default")).action(async(n,e)=>{await r$({...e,selector:n})}).addHelpText("after",DE);function n$(n){return IE(n)}async function i$(n){await new Promise(e=>setTimeout(e,n)),console.log(`Waited ${n}ms`)}async function o$(n,e,t,r,i){await n.waitForDisappear(e,t,r,i),console.log(`Element disappeared: ${t}`)}async function s$(n,e,t,r,i){let o=await n.waitForAppearance(e,t,r,i);console.log(n$(o))}async function a$(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=Mf(t);wa(),await i$(a);return}let i=t,o=n[1]?Mf(n[1]):3e3,s=_f({text:"Waiting\u2026",color:"cyan"}).start();try{let a=await P.new(),c=await T(a,e.device),l=new Qi(a.hdcPath);e.disappear?await o$(l,c,i,o,e.window):await s$(l,c,i,o,e.window),s.stop(),wa()}catch(a){throw s.stop(),wa(),new Error(`Failed to wait: ${a.message}`,{cause:a})}}var OE=new Lf("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 a$(n,e)}).addHelpText("after",DE);import{Command as c$,Option as l$}from"commander";import{yellow as d$}from"colorette";import u$ from"ora";var p$=["Id","Name","Pid","DisplayId","Focused"];function m$(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(_r(p$,t))}async function f$(n){let e=u$({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let r=await P.new(),i=await T(r,n.device);t=await new Ar(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(d$(" No windows found."));return}m$(t,n.format)}function h$(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 g$(n){let e=h$(n),t=Date.now(),r=!0,i=null;try{await f$(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 $f=new c$("window").description("Manage device windows");$f.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new l$("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async n=>{await g$(n)});import{Command as y$}from"commander";import{green as w$}from"colorette";function v$(n){return{event:v.CommandExecuted,args:["ui","screenshot",...n.device?["--device"]:[]]}}function b$(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}async function S$(n){let e=v$(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?b$(n.display):void 0,s=await P.new(),a=new ei(s),c=a.resolveDestinationPath(n.path),l=await T(s,n.device);await a.captureToPath(l,c,o),console.log(w$(`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 NE=new y$("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(S$);import{Command as Md,Option as E$}from"commander";import{green as Ff,yellow as P$}from"colorette";import LE from"ora";var Ld=["--device <name|serial>","Target physical device name or serial; required when multiple devices are connected"],_E=["--path <dir|file.mp4>","Required writable destination: existing directory or a new .mp4 file"];function _d(n){return new S("INVALID_ARGUMENT",n)}function ME(n){if(n!==void 0&&!n.trim())throw _d("--device must not be empty.")}function $d(n,e){let t=n.parent?.opts()?.device;if(ME(t),ME(e),t&&e&&t!==e)throw _d(`Conflicting --device values: ${JSON.stringify(t)} and ${JSON.stringify(e)}`);return e??t}function $E(n,e){if(n.parent?.opts()?.path!==void 0)throw _d(`--path is not valid for ui screenrecord ${e}.`)}function FE(n,e){let t=n.parent?.opts()?.path;if(t!==void 0&&e!==void 0&&t!==e)throw _d(`Conflicting --path values: ${JSON.stringify(t)} and ${JSON.stringify(e)}`);return e??t}function Fd(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 C$(n,e){return n.getOptionValueSource(e)==="cli"}async function jd(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 jE(n){if(n.kind==="saved"){console.log(Ff(`Saved successfully to ${n.localPath}`));for(let e of n.warnings??[])console.error(P$(`Warning: ${e}`))}else n.kind==="external-stopped"&&console.log(Ff("Recording stopped. View the file in the device gallery; this CLI cannot retrieve it."))}async function k$(n,e){let t=Fd(e,[{name:"--device",value:n.device},{name:"--path",value:n.path}]);await jd([],t,async()=>{let r=$d(e,n.device),i=FE(e,n.path),o=new ln(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=LE({text:"Stopping and saving the recording\u2026",color:"cyan"}).start()}})}finally{s?.stop()}jE(a)})}async function D$(n,e){let t=Fd(e,[{name:"--device",value:n.device},{name:"--path",value:n.path}]);await jd(["start"],t,async()=>{let r=$d(e,n.device),i=FE(e,n.path);await new ln(await P.new()).startDetached(r,i),console.log(Ff("Recording started. Stop with devecocli ui screenrecord stop"))})}async function R$(n,e){let t=[...Fd(e,[{name:"--device",value:n.device}]),...n.force?["--force"]:[]];await jd(["stop"],t,async()=>{let r=$d(e,n.device);$E(e,"stop");let i=new ln(await P.new()),o=LE({text:"Stopping recording\u2026",color:"cyan"}).start(),s;try{s=await i.stopRecording(r,n.force??!1)}finally{o.stop()}jE(s)})}var x$={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 A$(n,e){let t=[...Fd(e,[{name:"--device",value:n.device}]),...C$(e,"format")?["--format"]:[]];await jd(["status"],t,async()=>{let r=$d(e,n.device);$E(e,"status");let o=await new ln(await P.new()).getRecordingStatus(r);if(n.format==="json"){console.log(JSON.stringify(o));return}console.log(x$[o.status]),o.status==="idle"&&o.note&&console.log(o.note)})}var va=new Md("screenrecord").description("Record the screen of a physical device to an MP4 file").option(...Ld).option(..._E).action(k$);va.addCommand(new Md("start").description("Start recording and return immediately (detached)").option(...Ld).option(..._E).action(D$));va.addCommand(new Md("stop").description("Stop the current recording and save the file").option(...Ld).option("--force","Stop a recording that was not started by this CLI (no download)").action(R$));va.addCommand(new Md("status").description("Show the recording status without changing it").option(...Ld).addOption(new E$("--format <format>","Output format").choices(["table","json"]).default("table")).action(A$));import{Command as Rn}from"commander";function xn(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 I$(n){let t=`"$(printf '%s' '${Buffer.from(n,"utf8").toString("base64")}' | base64 -d)"`;return m(`escapeShellText: ${n} -> ${t}`),t}async function An(n,e,t,r){let i=new wt;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 T$(n,e,t){let r=xn("click",t);await An("Executing click...","click failed",r,async i=>{ro(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await dr(t.device),{x:a,y:c}=await no(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await kt(o,s,["uitest","uiInput","click",String(a),String(c)]),i.succeed(`click at (${a}, ${c})`)})}async function O$(n,e,t){let r=xn("doubleclick",t);await An("Executing doubleclick...","doubleclick failed",r,async i=>{ro(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await dr(t.device),{x:a,y:c}=await no(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await kt(o,s,["uitest","uiInput","doubleClick",String(a),String(c)]),i.succeed(`doubleclick at (${a}, ${c})`)})}async function N$(n,e,t){let r=xn("longclick",t);await An("Executing longclick...","longclick failed",r,async i=>{ro(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await dr(t.device),{x:a,y:c}=await no(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await kt(o,s,["uitest","uiInput","longClick",String(a),String(c)]),i.succeed(`longclick at (${a}, ${c})`)})}async function M$(n,e,t,r,i){let o=xn("swipe",i);await An("Executing swipe...","swipe failed",o,async s=>{Be(n,"x1"),Be(e,"y1"),Be(t,"x2"),Be(r,"y2");let a=Es(i.speed),{hdcPath:c,deviceId:l}=await dr(i.device),d=["uitest","uiInput","swipe",n,e,t,r];a&&d.push(a),await kt(c,l,d),s.succeed(`swipe from (${n}, ${e}) to (${t}, ${r})`)})}async function L$(n,e,t,r,i){let o=xn("fling",i);await An("Executing fling...","fling failed",o,async s=>{Be(n,"x1"),Be(e,"y1"),Be(t,"x2"),Be(r,"y2");let a=Es(i.speed),{hdcPath:c,deviceId:l}=await dr(i.device),d=["uitest","uiInput","fling",n,e,t,r];a&&d.push(a),await kt(c,l,d),s.succeed(`fling from (${n}, ${e}) to (${t}, ${r})`)})}async function _$(n,e,t,r,i){let o=xn("drag",i);await An("Executing drag...","drag failed",o,async s=>{Be(n,"x1"),Be(e,"y1"),Be(t,"x2"),Be(r,"y2");let a=Es(i.speed),{hdcPath:c,deviceId:l}=await dr(i.device),d=["uitest","uiInput","drag",n,e,t,r];a&&d.push(a),await kt(c,l,d),s.succeed(`drag from (${n}, ${e}) to (${t}, ${r})`)})}async function $$(n,e){let t=xn("dircfling",e);await An("Executing dircfling...","dircfling failed",t,async r=>{let i=Xc[n];if(i===void 0)throw new Error(`Invalid direction "${n}". Valid values: ${Object.keys(Xc).join(", ")}`);let{hdcPath:o,deviceId:s}=await dr(e.device);await kt(o,s,["uitest","uiInput","dircFling",i]),r.succeed(`dircfling ${n}`)})}async function F$(n,e,t,r){let i=xn("text",r);await An("Executing text input...","input failed",i,async o=>{ro(e,t,r.id,r.window,!1),Zc(n,"text");let{hdcPath:s,deviceId:a}=await dr(r.device),c=I$(n);if(e!==void 0)await kt(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 no(s,a,void 0,void 0,r.id,r.window);await kt(s,a,[`uitest uiInput inputText ${l} ${d} ${c}`]),o.succeed(`input ${n} at (${l}, ${d})`)}else await kt(s,a,[`uitest uiInput text ${c}`]),o.succeed(`input ${n}`)})}var HE=new Rn("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(T$),UE=new Rn("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(O$),BE=new Rn("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(N$),WE=new Rn("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(M$),VE=new Rn("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(L$),GE=new Rn("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(_$),qE=new Rn("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action($$),zE=new Rn("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(F$);var Ke=new j$("ui").description("Inspect and interact with UI on a connected device");Ke.addCommand(AE);Ke.addCommand(TE);Ke.addCommand(OE);Ke.addCommand($f);Ke.addCommand(NE);Ke.addCommand(va);Ke.addCommand(HE);Ke.addCommand(UE);Ke.addCommand(BE);Ke.addCommand(WE);Ke.addCommand(VE);Ke.addCommand(GE);Ke.addCommand(qE);Ke.addCommand(zE);var JE=Ke;import{Command as AP,InvalidArgumentError as Lj}from"commander";import{execa as lF}from"execa";import br from"fs";import*as Wf from"os";import*as W from"path";var H$=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),U$=/\r/g,B$=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,W$=/^<+\s*/,V$=/\s*>+$/,G$=[/^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\.$/],q$=new Set([1]);function Hf(n){if(!n)return"";let e=n.replace(H$,"").replace(U$,`
1342
1342
  `).split(`
1343
1343
  `).map(z$).map(t=>t.trimEnd()).filter(t=>Y$(t));return e.length>0?`${e.join(`
1344
1344
  `)}
@@ -1348,37 +1348,37 @@ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this
1348
1348
  `);if(t.length>1&&t.every(jf))return{jsonText:JSON.stringify(t.map(o=>JSON.parse(o))),diagnostics:""};let r=K$(e);if(!r)return{jsonText:void 0,diagnostics:`${e}
1349
1349
  `};let i=[e.slice(0,r.start).trim(),e.slice(r.end).trim()].filter(Boolean).join(`
1350
1350
  `);return{jsonText:e.slice(r.start,r.end),diagnostics:i?`${i}
1351
- `:""}}function J$(n){return B$.test(n.trim())}function Y$(n){let e=n.trim();return!!e&&!J$(e)&&!G$.some(t=>t.test(e))}function jf(n){try{return JSON.parse(n),!0}catch{return!1}}function K$(n){for(let e=0;e<n.length;e++){let t=n[e];if(t!=="["&&t!=="{")continue;let i=X$(n,e,t,t==="["?"]":"}");if(i!==-1&&jf(n.slice(e,i+1)))return{start:e,end:i+1}}}function X$(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 KE=["Error","Warning","Suggestion","Info","Off","Unknown"];function eP(n){let e=Uf(n);return{issues:tF(e),summary:Z$(n,e)}}function Z$(n,e){let t=nF(e);return{filesChecked:iF(n).size,issues:e.length,errors:t.get("Error")??0,warnings:t.get("Warning")??0,suggestions:t.get("Suggestion")??0}}function Uf(n,e=""){if(Array.isArray(n))return n.flatMap(o=>Uf(o,e));if(!tP(n))return[];let t=wa(n,["filePath","file","path"])??e,r=Q$(n,t);if(r.length>0)return r;let i=eF(n,t);return i?[i]:[]}function Q$(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=>Uf(s,e));if(o.length>0)return o}}return[]}function eF(n,e){let t=wa(n,["message","description","desc","detail"])??"",r=cF(wa(n,["rule","ruleId","ruleName"])),i=sF(n,["severity","level"]),o=wa(n,["filePath","file","path"])??e;if(!(!t&&!r&&i==="Unknown"))return{file:o,line:ZE(n,["line","reportLine"]),column:ZE(n,["column","reportColumn"]),severity:i,rule:r,message:t}}function tF(n){return[...n].sort((e,t)=>{let r=XE(e.severity)-XE(t.severity);return r===0?rF(e,t):r})}function rF(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 nF(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 iF(n){let e=new Set;return Bf(e,n,""),e}function Bf(n,e,t){if(Array.isArray(e)){for(let i of e)Bf(n,i,t);return}if(!tP(e))return;let r=wa(e,["filePath","file","path"])??t;r&&n.add(r),oF(n,e,r)}function oF(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)Bf(n,s,t)}}function sF(n,e){for(let t of e){let r=n[t];if(typeof r=="string"||typeof r=="number")return aF(r)}return"Unknown"}function aF(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 cF(n){let e=n?.normalize("NFKC").trim();if(e)return e.replace(W$,"").replace(V$,"").toLowerCase()}function XE(n){let e=KE.indexOf(n);return e===-1?KE.length:e}function wa(n,e){for(let t of e){let r=n[t];if(typeof r=="string")return r}}function ZE(n,e){for(let t of e){let r=n[t];if(typeof r=="number")return r}}function tP(n){return typeof n=="object"&&n!==null}var xn=class extends Error{code;constructor(e,t,r){super(t,r),this.name="ValidationError",this.code=e}},rP="deveco-codelinter-",nP=[".ets",".ts",".js"],va=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=vr.mkdtempSync(W.join(Wf.tmpdir(),rP)),r=W.join(t,"report.json");try{let i=n.resolveProjectRoot(this.cwd),o=this.resolveLintTarget(e.lintPath,i);await tt.warnInvalidBundledLinks(o.projectRoot??i);let s=this.resolveConfigPath(e.configPath,o),a=this.buildNativeArgs(e,o.path,s,r,t,o.projectRoot??i),c=await this.run(a),l=QE(c.stdout),d=l.diagnostics+Hf(c.stderr);try{let h=this.readJsonReport(r,l.jsonText);return{exitCode:c.exitCode,diagnostics:d,report:eP(h)}}catch(h){return{exitCode:c.exitCode,diagnostics:d,reportError:h}}}finally{this.removeTempDir(t)}}resolveLintTarget(e,t){let r=e?W.resolve(this.cwd,e):t,i=this.resolveRealPath(r,"Lint path"),o=vr.statSync(i);if(!o.isFile()&&!o.isDirectory())throw new xn("errorCode",`Lint path must be a file or directory: ${r}`);if(o.isFile()){let a=W.extname(i).toLowerCase();if(!nP.some(l=>l===a))throw new Error(`Unsupported lint file extension "${a||"<none>"}": ${i}. Supported extensions: ${nP.join(", ")}.`)}let s=this.discoverProjectRoot(i,o.isDirectory());if(e!==void 0&&s===void 0)throw new xn("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?W.resolve(this.cwd,e):W.join(t.projectRoot??this.cwd,"code-linter.json5"),i=this.resolveRealPath(r,"`--config-path`");if(!vr.statSync(i).isFile())throw new xn("errorCode",`--config-path must point to a file: ${r}`);if(t.projectRoot){let o=this.discoverProjectRoot(i,!1);if(o===void 0||W.relative(t.projectRoot,o)!=="")throw new xn("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:W.dirname(e);try{return vr.realpathSync(B.discover(r).rootDir)}catch{return}}resolveRealPath(e,t){try{return vr.realpathSync(e)}catch(r){throw new xn("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=W.join(i,"check-paths.json");vr.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",W.join(i,"codelinter.log"),"--workdir",W.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 lF(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??[])vr.mkdirSync(e,{recursive:!0})}readJsonReport(e,t){let i=(vr.existsSync(e)?vr.readFileSync(e,"utf-8").trim():void 0)||t?.trim();if(!i)throw new xn("errorCode","Native JSON report was not generated.");return JSON.parse(i)}removeTempDir(e){let t=W.resolve(e),r=W.resolve(Wf.tmpdir());!(t.startsWith(`${r}${W.sep}`)||t===r)||!W.basename(t).startsWith(rP)||vr.rmSync(t,{recursive:!0,force:!0})}static isModernStudioEntry(e){let t=["plugins","codelinter","run","index.js"],r=W.normalize(e).split(W.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(W.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=[W.dirname(e.nodePath)];return t==="ide"&&e.javaPath&&r.unshift(W.dirname(e.javaPath)),r}static getResultDirectory(e){return W.resolve(e,"..","linter","result")}static getSource(e){return e.sourceType==="studio"?"ide":"command-line-tools"}};import{red as Hd,yellow as uP}from"colorette";import{Argument as bF,Command as SF,InvalidArgumentError as An}from"commander";import Sa from"fs";import*as ct from"path";import*as ba from"path";var iP="n/a",oP=/\\/g,dF=/\|/g,uF=/\r?\n/g;function sP(n,e){if(n.issues.length===0)return`No defects found.
1351
+ `:""}}function J$(n){return B$.test(n.trim())}function Y$(n){let e=n.trim();return!!e&&!J$(e)&&!G$.some(t=>t.test(e))}function jf(n){try{return JSON.parse(n),!0}catch{return!1}}function K$(n){for(let e=0;e<n.length;e++){let t=n[e];if(t!=="["&&t!=="{")continue;let i=X$(n,e,t,t==="["?"]":"}");if(i!==-1&&jf(n.slice(e,i+1)))return{start:e,end:i+1}}}function X$(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 KE=["Error","Warning","Suggestion","Info","Off","Unknown"];function eP(n){let e=Uf(n);return{issues:tF(e),summary:Z$(n,e)}}function Z$(n,e){let t=nF(e);return{filesChecked:iF(n).size,issues:e.length,errors:t.get("Error")??0,warnings:t.get("Warning")??0,suggestions:t.get("Suggestion")??0}}function Uf(n,e=""){if(Array.isArray(n))return n.flatMap(o=>Uf(o,e));if(!tP(n))return[];let t=ba(n,["filePath","file","path"])??e,r=Q$(n,t);if(r.length>0)return r;let i=eF(n,t);return i?[i]:[]}function Q$(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=>Uf(s,e));if(o.length>0)return o}}return[]}function eF(n,e){let t=ba(n,["message","description","desc","detail"])??"",r=cF(ba(n,["rule","ruleId","ruleName"])),i=sF(n,["severity","level"]),o=ba(n,["filePath","file","path"])??e;if(!(!t&&!r&&i==="Unknown"))return{file:o,line:ZE(n,["line","reportLine"]),column:ZE(n,["column","reportColumn"]),severity:i,rule:r,message:t}}function tF(n){return[...n].sort((e,t)=>{let r=XE(e.severity)-XE(t.severity);return r===0?rF(e,t):r})}function rF(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 nF(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 iF(n){let e=new Set;return Bf(e,n,""),e}function Bf(n,e,t){if(Array.isArray(e)){for(let i of e)Bf(n,i,t);return}if(!tP(e))return;let r=ba(e,["filePath","file","path"])??t;r&&n.add(r),oF(n,e,r)}function oF(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)Bf(n,s,t)}}function sF(n,e){for(let t of e){let r=n[t];if(typeof r=="string"||typeof r=="number")return aF(r)}return"Unknown"}function aF(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 cF(n){let e=n?.normalize("NFKC").trim();if(e)return e.replace(W$,"").replace(V$,"").toLowerCase()}function XE(n){let e=KE.indexOf(n);return e===-1?KE.length:e}function ba(n,e){for(let t of e){let r=n[t];if(typeof r=="string")return r}}function ZE(n,e){for(let t of e){let r=n[t];if(typeof r=="number")return r}}function tP(n){return typeof n=="object"&&n!==null}var In=class extends Error{code;constructor(e,t,r){super(t,r),this.name="ValidationError",this.code=e}},rP="deveco-codelinter-",nP=[".ets",".ts",".js"],Sa=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=br.mkdtempSync(W.join(Wf.tmpdir(),rP)),r=W.join(t,"report.json");try{let i=n.resolveProjectRoot(this.cwd),o=this.resolveLintTarget(e.lintPath,i);await tt.warnInvalidBundledLinks(o.projectRoot??i);let s=this.resolveConfigPath(e.configPath,o),a=this.buildNativeArgs(e,o.path,s,r,t,o.projectRoot??i),c=await this.run(a),l=QE(c.stdout),d=l.diagnostics+Hf(c.stderr);try{let h=this.readJsonReport(r,l.jsonText);return{exitCode:c.exitCode,diagnostics:d,report:eP(h)}}catch(h){return{exitCode:c.exitCode,diagnostics:d,reportError:h}}}finally{this.removeTempDir(t)}}resolveLintTarget(e,t){let r=e?W.resolve(this.cwd,e):t,i=this.resolveRealPath(r,"Lint path"),o=br.statSync(i);if(!o.isFile()&&!o.isDirectory())throw new In("errorCode",`Lint path must be a file or directory: ${r}`);if(o.isFile()){let a=W.extname(i).toLowerCase();if(!nP.some(l=>l===a))throw new Error(`Unsupported lint file extension "${a||"<none>"}": ${i}. Supported extensions: ${nP.join(", ")}.`)}let s=this.discoverProjectRoot(i,o.isDirectory());if(e!==void 0&&s===void 0)throw new In("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?W.resolve(this.cwd,e):W.join(t.projectRoot??this.cwd,"code-linter.json5"),i=this.resolveRealPath(r,"`--config-path`");if(!br.statSync(i).isFile())throw new In("errorCode",`--config-path must point to a file: ${r}`);if(t.projectRoot){let o=this.discoverProjectRoot(i,!1);if(o===void 0||W.relative(t.projectRoot,o)!=="")throw new In("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:W.dirname(e);try{return br.realpathSync(B.discover(r).rootDir)}catch{return}}resolveRealPath(e,t){try{return br.realpathSync(e)}catch(r){throw new In("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=W.join(i,"check-paths.json");br.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",W.join(i,"codelinter.log"),"--workdir",W.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 lF(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??[])br.mkdirSync(e,{recursive:!0})}readJsonReport(e,t){let i=(br.existsSync(e)?br.readFileSync(e,"utf-8").trim():void 0)||t?.trim();if(!i)throw new In("errorCode","Native JSON report was not generated.");return JSON.parse(i)}removeTempDir(e){let t=W.resolve(e),r=W.resolve(Wf.tmpdir());!(t.startsWith(`${r}${W.sep}`)||t===r)||!W.basename(t).startsWith(rP)||br.rmSync(t,{recursive:!0,force:!0})}static isModernStudioEntry(e){let t=["plugins","codelinter","run","index.js"],r=W.normalize(e).split(W.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(W.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=[W.dirname(e.nodePath)];return t==="ide"&&e.javaPath&&r.unshift(W.dirname(e.javaPath)),r}static getResultDirectory(e){return W.resolve(e,"..","linter","result")}static getSource(e){return e.sourceType==="studio"?"ide":"command-line-tools"}};import{red as Ud,yellow as uP}from"colorette";import{Argument as bF,Command as SF,InvalidArgumentError as On}from"commander";import Pa from"fs";import*as ct from"path";import*as Ea from"path";var iP="n/a",oP=/\\/g,dF=/\|/g,uF=/\r?\n/g;function sP(n,e){if(n.issues.length===0)return`No defects found.
1352
1352
  ${Vf(n.summary)}
1353
1353
  `;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[mF(t),Vf(n.summary)];return e!==void 0&&t.length<n.issues.length&&r.push(pF(n.issues.length,t.length)),`${r.join(`
1354
1354
  `)}
1355
1355
  `}function aP(n,e){return[Vf(n.summary),`Full report: ${Gf(e)}`,""].join(`
1356
1356
  `)}function cP(n){let e=["# CodeLinter report",""];return n.issues.length===0?e.push("No defects found.",""):e.push(...fF(n.issues),""),e.push("## Summary","",...gF(n.summary),""),e.join(`
1357
1357
  `)}function lP(n){return`${JSON.stringify(n,null,2)}
1358
- `}function Vf(n){return`Summary: Issues: ${Tt(n.issues)} | Errors: ${Tt(n.errors)} | Warnings: ${Tt(n.warnings)} | Suggestions: ${Tt(n.suggestions)} | Files checked: ${Tt(n.filesChecked)}`}function pF(n,e){return`Showing ${Tt(e)} of ${Tt(n)} issues. Use --output-path <path> to write all results.`}function mF(n){let e=["No","File","Line","Column","Severity","Rule","Message"],t=n.map((r,i)=>({cells:wF(r,i+1)}));return["CodeLinter report","",Mr(e,t)].join(`
1359
- `)}function fF(n){let e=["| No | File | Line | Column | Severity | Rule | Message |","| ---: | --- | ---: | ---: | --- | --- | --- |"];for(let[t,r]of n.entries())e.push(hF(r,t+1));return e}function hF(n,e){return`| ${[String(e),Gf(In(n.file)),jd(n.line),jd(n.column),In(n.severity),In(n.rule),In(n.message)].map(yF).join(" | ")} |`}function gF(n){return[`- Issues: ${Tt(n.issues)}`,`- Errors: ${Tt(n.errors)}`,`- Warnings: ${Tt(n.warnings)}`,`- Suggestions: ${Tt(n.suggestions)}`,`- Files checked: ${Tt(n.filesChecked)}`]}function yF(n){return n.replace(oP,"\\\\").replace(dF,"\\|").replace(uF,"<br>")}function wF(n,e){return[String(e),Gf(In(vF(n.file))),jd(n.line),jd(n.column),In(n.severity),In(n.rule),In(n.message)]}function vF(n){if(!ba.isAbsolute(n))return n;let e=ba.relative(process.cwd(),n);return!e||e.startsWith("..")||ba.isAbsolute(e)?n:e}function Gf(n){return n.replace(oP,"/")}function In(n){let e=n?.trim();return e||iP}function jd(n){return n===void 0?iP:String(n)}function Tt(n){return n.toLocaleString("en-US")}var qf=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function EF(n){let e=n;return n instanceof qf?n.code:e.code??e.name??"UnknownError"}async function dP(n,e,t,r){let i=await mt(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 R.track(s,a).catch(()=>{})}var PF=/^-?\d+$/;function zf(){return new SF("lint").description("Run DevEco Code Linter checks for TS/ArkTS code").helpOption("-h, --help","display help for command").addArgument(new bF("[path]","File or directory to lint").argParser(xF)).option("--fix","Auto-fix fixable code issues").option("--incremental","Only check uncommitted files").option("--config-path <path>","Path to lint configuration file",kF).option("--product <product>","Product name defined in build-profile.json5",DF,"default").option("--format <format>","Report format (choices: default, json)",CF,"default").option("--output-path <path>","Complete report file or directory",RF).option("--limit <number>","Maximum terminal issues to display when --output-path is omitted",IF).action(AF)}function CF(n){if(n==="default"||n==="json")return n;throw new An("Invalid --format. Expected one of: default, json.")}function kF(n){Jf(n,"--config-path");let e=ct.extname(n).toLowerCase();if(e!==".json"&&e!==".json5")throw new An("`--config-path` must point to a .json or .json5 file.");return n}function DF(n){return pP(n,"product"),n}function RF(n){return Jf(n,"--output-path"),n}function xF(n){return Jf(n,"path"),n}function IF(n){if(pP(n,"limit"),!PF.test(n))throw new An("`--limit` must be a positive integer.");let e=Number.parseInt(n,10);if(e<=0||!Number.isSafeInteger(e))throw new An("`--limit` must be an integer greater than 0.");return e}function pP(n,e){if(n.trim().length===0||hP(n))throw new An(`Invalid --${e} value.`)}function Jf(n,e){let t=`\`${e}\``;if(n.length===0||hP(n))throw new An(`${t} must be a non-empty path without control characters.`)}async function AF(n,e,t){let r=Date.now(),i=["check","lint"];try{let o=process.cwd(),s=await P.new(),a=new va(s,o),c=NF(s,a,t,e),l=$F(c.outputPath,c.format,o);e.fix&&console.warn(uP("Running codelinter with --fix. Ensure your project source is trusted."));let d=await TF(a,n,e);BF(d.diagnostics),process.exitCode=LF(d,l,c.format,e.limit,o),await dP(r,!0,null,i)}catch(o){let s=EF(o);throw await dP(r,!1,s,i),o}}async function TF(n,e,t){return MF(n,{lintPath:e,configPath:t.configPath,product:t.product,fix:t.fix,incremental:t.incremental})}function OF(n){return[["format","--format"],["outputPath","--output-path"]].filter(([e])=>n.getOptionValueSource(e)==="cli").map(([,e])=>e)}function NF(n,e,t,r){let i=OF(t);if(i.length===0||e.supportsReportOptions)return r;let o=tn(n.toolchainRoot),s=i.length===1?"option":"options";return console.warn(uP(`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 MF(n,e){let t=new wt;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 LF(n,e,t,r,i){if(!n.report)return console.error(Hd("Failed to generate Code Linter report.")),console.error(Hd(n.reportError?.message??"Native JSON report was not generated.")),n.exitCode===0?1:n.exitCode;try{if(e){_F(e,t,n.report);let o=fP(e,i);process.stdout.write(aP(n.report,o))}else process.stdout.write(sP(n.report,r));return n.exitCode}catch(o){return console.error(Hd("Failed to generate Code Linter report.")),console.error(Hd(o.message)),n.exitCode===0?1:n.exitCode}}function _F(n,e,t){Sa.mkdirSync(ct.dirname(n),{recursive:!0});let r=e==="json"?lP(t):cP(t);try{Sa.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 $F(n,e,t){if(!n)return;let r=HF(n,t),i=jF(n,r),o=i?ct.join(r,UF(e)):r;if(i||FF(n,e),Sa.existsSync(o))throw new An(`Output file already exists: ${fP(o,t)}`);return o}function FF(n,e){let t=mP(e);if(ct.extname(n).toLowerCase()!==t)throw new An(`--output-path must use the ${t} extension for --format ${e}.`)}function jF(n,e){return Sa.existsSync(e)?Sa.statSync(e).isDirectory():n.endsWith("/")||n.endsWith("\\")||ct.extname(n)===""}function HF(n,e){return ct.resolve(e,n)}function UF(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}${mP(n)}`}function mP(n){return n==="json"?".json":".md"}function fP(n,e){let t=ct.relative(e,n);return t&&!t.startsWith("..")&&!ct.isAbsolute(t)?t:n}function BF(n){n&&process.stderr.write(n)}function hP(n){for(let e of n){let t=e.charCodeAt(0);if(t<=31||t===127)return!0}return!1}import{execa as WF}from"execa";import qr from"fs";import VF from"os";import*as te from"path";import{fileURLToPath as GF}from"url";var gP=te.join("resources","arkts-check.cjs"),Ea=class{toolProvider;cwd;constructor(e,t){this.toolProvider=e,this.cwd=t}async check(e){let t=this.resolveProjectRoot(e.projectRoot,e.files);await tt.warnInvalidBundledLinks(t);let 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 WF(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(!qr.existsSync(i))throw new Error(`Project path not found: ${i}`);if(qr.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}
1358
+ `}function Vf(n){return`Summary: Issues: ${Tt(n.issues)} | Errors: ${Tt(n.errors)} | Warnings: ${Tt(n.warnings)} | Suggestions: ${Tt(n.suggestions)} | Files checked: ${Tt(n.filesChecked)}`}function pF(n,e){return`Showing ${Tt(e)} of ${Tt(n)} issues. Use --output-path <path> to write all results.`}function mF(n){let e=["No","File","Line","Column","Severity","Rule","Message"],t=n.map((r,i)=>({cells:wF(r,i+1)}));return["CodeLinter report","",_r(e,t)].join(`
1359
+ `)}function fF(n){let e=["| No | File | Line | Column | Severity | Rule | Message |","| ---: | --- | ---: | ---: | --- | --- | --- |"];for(let[t,r]of n.entries())e.push(hF(r,t+1));return e}function hF(n,e){return`| ${[String(e),Gf(Tn(n.file)),Hd(n.line),Hd(n.column),Tn(n.severity),Tn(n.rule),Tn(n.message)].map(yF).join(" | ")} |`}function gF(n){return[`- Issues: ${Tt(n.issues)}`,`- Errors: ${Tt(n.errors)}`,`- Warnings: ${Tt(n.warnings)}`,`- Suggestions: ${Tt(n.suggestions)}`,`- Files checked: ${Tt(n.filesChecked)}`]}function yF(n){return n.replace(oP,"\\\\").replace(dF,"\\|").replace(uF,"<br>")}function wF(n,e){return[String(e),Gf(Tn(vF(n.file))),Hd(n.line),Hd(n.column),Tn(n.severity),Tn(n.rule),Tn(n.message)]}function vF(n){if(!Ea.isAbsolute(n))return n;let e=Ea.relative(process.cwd(),n);return!e||e.startsWith("..")||Ea.isAbsolute(e)?n:e}function Gf(n){return n.replace(oP,"/")}function Tn(n){let e=n?.trim();return e||iP}function Hd(n){return n===void 0?iP:String(n)}function Tt(n){return n.toLocaleString("en-US")}var qf=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function EF(n){let e=n;return n instanceof qf?n.code:e.code??e.name??"UnknownError"}async function dP(n,e,t,r){let i=await mt(process.pid),o=i!==null?ae(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 PF=/^-?\d+$/;function zf(){return new SF("lint").description("Run DevEco Code Linter checks for TS/ArkTS code").helpOption("-h, --help","display help for command").addArgument(new bF("[path]","File or directory to lint").argParser(xF)).option("--fix","Auto-fix fixable code issues").option("--incremental","Only check uncommitted files").option("--config-path <path>","Path to lint configuration file",kF).option("--product <product>","Product name defined in build-profile.json5",DF,"default").option("--format <format>","Report format (choices: default, json)",CF,"default").option("--output-path <path>","Complete report file or directory",RF).option("--limit <number>","Maximum terminal issues to display when --output-path is omitted",AF).action(IF)}function CF(n){if(n==="default"||n==="json")return n;throw new On("Invalid --format. Expected one of: default, json.")}function kF(n){Jf(n,"--config-path");let e=ct.extname(n).toLowerCase();if(e!==".json"&&e!==".json5")throw new On("`--config-path` must point to a .json or .json5 file.");return n}function DF(n){return pP(n,"product"),n}function RF(n){return Jf(n,"--output-path"),n}function xF(n){return Jf(n,"path"),n}function AF(n){if(pP(n,"limit"),!PF.test(n))throw new On("`--limit` must be a positive integer.");let e=Number.parseInt(n,10);if(e<=0||!Number.isSafeInteger(e))throw new On("`--limit` must be an integer greater than 0.");return e}function pP(n,e){if(n.trim().length===0||hP(n))throw new On(`Invalid --${e} value.`)}function Jf(n,e){let t=`\`${e}\``;if(n.length===0||hP(n))throw new On(`${t} must be a non-empty path without control characters.`)}async function IF(n,e,t){let r=Date.now(),i=["check","lint"];try{let o=process.cwd(),s=await P.new(),a=new Sa(s,o),c=NF(s,a,t,e),l=$F(c.outputPath,c.format,o);e.fix&&console.warn(uP("Running codelinter with --fix. Ensure your project source is trusted."));let d=await TF(a,n,e);BF(d.diagnostics),process.exitCode=LF(d,l,c.format,e.limit,o),await dP(r,!0,null,i)}catch(o){let s=EF(o);throw await dP(r,!1,s,i),o}}async function TF(n,e,t){return MF(n,{lintPath:e,configPath:t.configPath,product:t.product,fix:t.fix,incremental:t.incremental})}function OF(n){return[["format","--format"],["outputPath","--output-path"]].filter(([e])=>n.getOptionValueSource(e)==="cli").map(([,e])=>e)}function NF(n,e,t,r){let i=OF(t);if(i.length===0||e.supportsReportOptions)return r;let o=nn(n.toolchainRoot),s=i.length===1?"option":"options";return console.warn(uP(`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 MF(n,e){let t=new wt;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 LF(n,e,t,r,i){if(!n.report)return console.error(Ud("Failed to generate Code Linter report.")),console.error(Ud(n.reportError?.message??"Native JSON report was not generated.")),n.exitCode===0?1:n.exitCode;try{if(e){_F(e,t,n.report);let o=fP(e,i);process.stdout.write(aP(n.report,o))}else process.stdout.write(sP(n.report,r));return n.exitCode}catch(o){return console.error(Ud("Failed to generate Code Linter report.")),console.error(Ud(o.message)),n.exitCode===0?1:n.exitCode}}function _F(n,e,t){Pa.mkdirSync(ct.dirname(n),{recursive:!0});let r=e==="json"?lP(t):cP(t);try{Pa.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 $F(n,e,t){if(!n)return;let r=HF(n,t),i=jF(n,r),o=i?ct.join(r,UF(e)):r;if(i||FF(n,e),Pa.existsSync(o))throw new On(`Output file already exists: ${fP(o,t)}`);return o}function FF(n,e){let t=mP(e);if(ct.extname(n).toLowerCase()!==t)throw new On(`--output-path must use the ${t} extension for --format ${e}.`)}function jF(n,e){return Pa.existsSync(e)?Pa.statSync(e).isDirectory():n.endsWith("/")||n.endsWith("\\")||ct.extname(n)===""}function HF(n,e){return ct.resolve(e,n)}function UF(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}${mP(n)}`}function mP(n){return n==="json"?".json":".md"}function fP(n,e){let t=ct.relative(e,n);return t&&!t.startsWith("..")&&!ct.isAbsolute(t)?t:n}function BF(n){n&&process.stderr.write(n)}function hP(n){for(let e of n){let t=e.charCodeAt(0);if(t<=31||t===127)return!0}return!1}import{execa as WF}from"execa";import Jr from"fs";import VF from"os";import*as te from"path";import{fileURLToPath as GF}from"url";var gP=te.join("resources","arkts-check.cjs"),Ca=class{toolProvider;cwd;constructor(e,t){this.toolProvider=e,this.cwd=t}async check(e){let t=this.resolveProjectRoot(e.projectRoot,e.files);await tt.warnInvalidBundledLinks(t);let 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 WF(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(!Jr.existsSync(i))throw new Error(`Project path not found: ${i}`);if(Jr.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
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 qr.existsSync(c)?c:te.resolve(e,a)}),i=r.filter(a=>!qr.existsSync(a));if(i.length>0)throw new Error(`File(s) not found:
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 Jr.existsSync(c)?c:te.resolve(e,a)}),i=r.filter(a=>!Jr.existsSync(a));if(i.length>0)throw new Error(`File(s) not found:
1362
1362
  `+i.map(a=>` ${a}`).join(`
1363
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
1364
  `+o.map(a=>` ${a}`).join(`
1365
- `));let s=r.filter(a=>qr.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):
1365
+ `));let s=r.filter(a=>Jr.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
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(VF.platform()==="darwin"&&!qr.existsSync(te.join(e,"sdk"))){let t=te.join(e,"Contents");if(qr.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=GF(import.meta.url),t=te.dirname(e);if(e.includes("dist")){let s=te.dirname(t),a=te.join(s,"src",gP);if(qr.existsSync(a))return a}let r=te.dirname(t),i=te.dirname(r),o=te.join(i,"src",gP);if(qr.existsSync(o))return o;throw new Error("arkts-check.cjs not found in deveco-cli package resources. Reinstall deveco-cli.")}};import{red as Kf,yellow as Xf,green as yP}from"colorette";import{Command as qF}from"commander";function zF(n){let e=n;return e.code??e.name??"UnknownError"}async function Yf(n,e,t,r){let i=await mt(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 R.track(s,a).catch(()=>{})}function Zf(){return new qF("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 JF(n,e)})}async function JF(n,e){let t=Date.now(),r=["check","arkts"];try{let i=await P.new(),o=new Ea(i,process.cwd()),s=new wt;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(Kf(a.error)),process.exitCode=1,await Yf(t,!1,"CheckFailed",r);return}s.stop(),YF(a),await Yf(t,!0,null,r)}catch(i){throw await Yf(t,!1,zF(i),r),i}}function YF(n){let{errorCount:e,warnCount:t,fixedCount:r,fileCount:i}=n.summary;if(KF(n.fixed,r,n.alsoModified),e===0){console.log(yP(`No errors found in ${i} file(s).`)),wP(n.errors);return}XF(n.errors,e,t),process.exitCode=1}function KF(n,e,t){if(n.length!==0){console.log(yP(`\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(Xf(`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 XF(n,e,t){let r=n.filter(i=>i.severity==="error");console.error(Kf(`ArkTS check found ${e} error(s):`));for(let i of r){let o=i.rule?` (${i.rule})`:"";console.error(Kf(`${i.file}:${i.line}:${i.column} - ${i.severity}: ${i.message}${o}`))}wP(n,t)}function wP(n,e){let t=n.filter(i=>i.severity!=="error");if(t.length===0)return;let r=e??t.length;console.warn(Xf(`
1368
- Warnings (${r}):`));for(let i of t){let o=i.rule?` (${i.rule})`:"";console.warn(Xf(`${i.file}:${i.line}:${i.column} - ${i.severity}: ${i.message}${o}`))}}import{InvalidArgumentError as ZF}from"commander";import*as ne from"path";import*as Qf from"os";import{readdirSync as QF,existsSync as Ud,readFileSync as ej,unlinkSync as tj,copyFileSync as EP,writeFileSync as PP}from"fs";import{execa as rj}from"execa";import{cyan as Ae,yellow as CP}from"colorette";import nj from"ora";var me=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function eh(n){let e=n;return n instanceof me?n.code:e.code??e.name??"UnknownError"}async function jo(n,e,t,r){let i=await mt(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 R.track(s,a).catch(()=>{})}var ij=["default","csv","json"],vP=["default","json"];function oj(n){return[...n].sort((e,t)=>{let r=bP(e),i=bP(t);return r.apiVersion-i.apiVersion||r.suffix.localeCompare(i.suffix)})}function bP(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 kP(n){let t=QF(n,{withFileTypes:!0}).filter(r=>r.isFile()&&r.name.toLowerCase().endsWith(".json")).map(r=>r.name.slice(0,-5));return oj(t)}async function DP(n){if(n=n===void 0?"default":n,!vP.includes(n))throw new Error(`--format must be ${vP.join(" or ")}. got "${n}"`);let e=Date.now(),t=["check","compat","versions"];try{let r=await P.new(),{apiChangeDir:i}=r.getApiscanPaths();m(Ae(`[compat:versions] apiChangeDir: "${i}"`));let o=kP(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 jo(e,!0,null,t);return}console.log(o.join(`
1369
- `))}await jo(e,!0,null,t)}catch(r){let i=eh(r);throw await jo(e,!1,i,t),r}}var SP=new Set([".ets",".c",".cpp"]);function sj(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 aj(n){for(let e of n){let t=ne.resolve(e);if(!Ud(t))throw new me("errorCode",`File "${e}" does not exist.`);let r=ne.extname(t).toLowerCase();if(!SP.has(r)){let i=Array.from(SP).join(", ");throw new me("errorCode",`Unsupported file extension "${r}" for "${e}". Supported: ${i}.`)}}}function cj(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 lj(n){let e=[],t=[],r="",i=!1,o=0;for(;o<n.length;){let s=n[o];i?{field:r,inQuotes:i,i:o}=dj(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 dj(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 uj(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 pj(n){let e=ej(n,"utf8"),t=e.startsWith("\uFEFF")?e.slice(1):e,r=lj(t);if(r.length<2)return[];let[i,...o]=r;return uj(i,o)}function mj(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 fj(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(Ae("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 hj(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(Ae(`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(CP(` ... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function gj(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(CP(`... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function yj(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 wj(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}=cj(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=yj(t,r.modules);i.push("--modulePaths",o.join(","))}else i.push("--projectPath",t.rootDir);return i.push("--outputPath",Qf.tmpdir()),i}async function vj(n,e){let t=ne.dirname(e[0]);try{let i=(await rj(n.nodePath,e,{cwd:t,stdin:"ignore",stdout:"pipe",stderr:"inherit"})).stdout;return process.env.DEVECO_CLI_DEBUG&&(console.log(Ae("[compat:check] === scan stdout ===")),process.stdout.write(i),i.endsWith(`
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(VF.platform()==="darwin"&&!Jr.existsSync(te.join(e,"sdk"))){let t=te.join(e,"Contents");if(Jr.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=GF(import.meta.url),t=te.dirname(e);if(e.includes("dist")){let s=te.dirname(t),a=te.join(s,"src",gP);if(Jr.existsSync(a))return a}let r=te.dirname(t),i=te.dirname(r),o=te.join(i,"src",gP);if(Jr.existsSync(o))return o;throw new Error("arkts-check.cjs not found in deveco-cli package resources. Reinstall deveco-cli.")}};import{red as Kf,yellow as Xf,green as yP}from"colorette";import{Command as qF}from"commander";function zF(n){let e=n;return e.code??e.name??"UnknownError"}async function Yf(n,e,t,r){let i=await mt(process.pid),o=i!==null?ae(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 Zf(){return new qF("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 JF(n,e)})}async function JF(n,e){let t=Date.now(),r=["check","arkts"];try{let i=await P.new(),o=new Ca(i,process.cwd()),s=new wt;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(Kf(a.error)),process.exitCode=1,await Yf(t,!1,"CheckFailed",r);return}s.stop(),YF(a),await Yf(t,!0,null,r)}catch(i){throw await Yf(t,!1,zF(i),r),i}}function YF(n){let{errorCount:e,warnCount:t,fixedCount:r,fileCount:i}=n.summary;if(KF(n.fixed,r,n.alsoModified),e===0){console.log(yP(`No errors found in ${i} file(s).`)),wP(n.errors);return}XF(n.errors,e,t),process.exitCode=1}function KF(n,e,t){if(n.length!==0){console.log(yP(`\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(Xf(`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 XF(n,e,t){let r=n.filter(i=>i.severity==="error");console.error(Kf(`ArkTS check found ${e} error(s):`));for(let i of r){let o=i.rule?` (${i.rule})`:"";console.error(Kf(`${i.file}:${i.line}:${i.column} - ${i.severity}: ${i.message}${o}`))}wP(n,t)}function wP(n,e){let t=n.filter(i=>i.severity!=="error");if(t.length===0)return;let r=e??t.length;console.warn(Xf(`
1368
+ Warnings (${r}):`));for(let i of t){let o=i.rule?` (${i.rule})`:"";console.warn(Xf(`${i.file}:${i.line}:${i.column} - ${i.severity}: ${i.message}${o}`))}}import{InvalidArgumentError as ZF}from"commander";import*as ne from"path";import*as Qf from"os";import{readdirSync as QF,existsSync as Bd,readFileSync as ej,unlinkSync as tj,copyFileSync as EP,writeFileSync as PP}from"fs";import{execa as rj}from"execa";import{cyan as Ie,yellow as CP}from"colorette";import nj from"ora";var pe=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function eh(n){let e=n;return n instanceof pe?n.code:e.code??e.name??"UnknownError"}async function Ho(n,e,t,r){let i=await mt(process.pid),o=i!==null?ae(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 ij=["default","csv","json"],vP=["default","json"];function oj(n){return[...n].sort((e,t)=>{let r=bP(e),i=bP(t);return r.apiVersion-i.apiVersion||r.suffix.localeCompare(i.suffix)})}function bP(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 kP(n){let t=QF(n,{withFileTypes:!0}).filter(r=>r.isFile()&&r.name.toLowerCase().endsWith(".json")).map(r=>r.name.slice(0,-5));return oj(t)}async function DP(n){if(n=n===void 0?"default":n,!vP.includes(n))throw new Error(`--format must be ${vP.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=kP(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 Ho(e,!0,null,t);return}console.log(o.join(`
1369
+ `))}await Ho(e,!0,null,t)}catch(r){let i=eh(r);throw await Ho(e,!1,i,t),r}}var SP=new Set([".ets",".c",".cpp"]);function sj(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 pe("errorCode",`Module ${r.map(s=>`"${s}"`).join(", ")} ${o} not defined in build-profile.json5. Available modules: ${i}.`)}function aj(n){for(let e of n){let t=ne.resolve(e);if(!Bd(t))throw new pe("errorCode",`File "${e}" does not exist.`);let r=ne.extname(t).toLowerCase();if(!SP.has(r)){let i=Array.from(SP).join(", ");throw new pe("errorCode",`Unsupported file extension "${r}" for "${e}". Supported: ${i}.`)}}}function cj(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 lj(n){let e=[],t=[],r="",i=!1,o=0;for(;o<n.length;){let s=n[o];i?{field:r,inQuotes:i,i:o}=dj(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 dj(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 uj(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 pj(n){let e=ej(n,"utf8"),t=e.startsWith("\uFEFF")?e.slice(1):e,r=lj(t);if(r.length<2)return[];let[i,...o]=r;return uj(i,o)}function mj(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 fj(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 hj(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(CP(` ... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function gj(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(CP(`... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function yj(n,e){let t=[];for(let r of e){let i=n.profile.modules.find(o=>o.name===r);if(!i)throw new pe("errorCode",`Module "${r}" not found in build-profile.json5.`);t.push(ne.resolve(n.rootDir,i.srcPath))}return t}function wj(n,e,t,r){if(!r.sourceVersion||!r.targetVersion)throw new pe("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}=cj(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=yj(t,r.modules);i.push("--modulePaths",o.join(","))}else i.push("--projectPath",t.rootDir);return i.push("--outputPath",Qf.tmpdir()),i}async function vj(n,e){let t=ne.dirname(e[0]);try{let i=(await rj(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(`
1371
1371
  `)||process.stdout.write(`
1372
- `),console.log(Ae("[compat:check] === end stdout ==="))),i}catch(r){let i=r;process.env.DEVECO_CLI_DEBUG&&i.stdout&&(console.log(Ae("[compat:check] === scan stdout (on error) ===")),process.stdout.write(i.stdout),i.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(`
1373
1373
  `)||process.stdout.write(`
1374
- `),console.log(Ae("[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 bj(n,e){if(!ij.includes(e.format))throw new ZF(`--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 Sj(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 Ej(n,e,t,r,i){i==="none"&&(t==="json"?gj(n,r):hj(n,r)),fj(n,e)}function Pj(n,e){let t=ne.dirname(n),r=ne.basename(n),i=e.slice(1).map(o=>o.startsWith("--")?o:`"${o}"`).join(" ");m(Ae(`[compat:check] command: cd "${t}" && node "${r}" ${i}`))}function Cj(n){try{tj(n),m(Ae(`[compat:check] cleaned up tmp report: "${n}"`))}catch(e){m(Ae(`[compat:check] failed to clean up tmp report: ${e.message}`))}}var kj=[".csv",".json"];function Dj(n){return kj.includes(n.toLowerCase())}function Rj(n,e){if(!n)return{kind:"none"};let t=ne.extname(n).toLowerCase();if(!Dj(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 xj(n){if(n.kind==="file"){if(Ud(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(!Ud(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"&&!Ud(n.dirPath))throw new me("errorCode",`Target directory "${n.dirPath}" does not exist. Create it first, or choose a different --output-path.`)}function RP(n){return JSON.stringify({records:n,count:n.length},null,2)+`
1377
- `}function Ij(n,e,t,r){r===".csv"?EP(n,t):PP(t,RP(e),"utf8"),m(Ae(`[compat:check] saved report: "${t}"`))}function Aj(n,e,t,r){if(r==="json"){let o=ne.basename(n,".csv"),s=ne.join(t,`${o}.json`);return PP(s,RP(e),"utf8"),m(Ae(`[compat:check] saved report: "${s}"`)),s}let i=ne.join(t,ne.basename(n));return EP(n,i),m(Ae(`[compat:check] saved report: "${i}"`)),i}async function Tj(n,e){let t=new ft(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 Oj(n,e){bj(n,e);let t=B.discover(process.cwd());await tt.warnInvalidBundledLinks(t.rootDir),e.modules&&e.modules.length>0&&sj(t,e.modules),n.length>0&&aj(n);let r=await P.new(),{apiChangeDir:i,scriptPath:o}=r.getApiscanPaths();m(Ae(`[compat:check] script: "${o}"`));let s=kP(i);Sj(e,s),e.outputPath&&m(Ae(`[compat:check] outputPath: "${e.outputPath}"`));let a=Rj(e.outputPath,e.format);return m(Ae(`[compat:check] outputTarget: ${a.kind}`)),xj(a),{project:t,scriptPath:o,target:a,toolProvider:r}}function Nj(n,e,t,r){if(t.kind==="file")return Ij(n,e,t.filePath,t.ext),t.filePath;if(t.kind==="dir")return Aj(n,e,t.dirPath,r);if(t.kind==="none")return null;throw new me("errorCode",`Unexpected output target kind: ${t.kind}`)}async function Mj(n,e,t,r,i){let o=nj({text:"Running compatibility check...",color:"cyan"}).start();try{await Tj(n.toolProvider,t);let s=wj(n.scriptPath,e,n.project,t);Pj(n.scriptPath,s);let a=await vj(n.toolProvider,s),c=mj(a,Qf.tmpdir());if(!c)throw new me("errorCode","Scanner output format unexpected: missing report path.");m(Ae(`[compat:check] tmp csv: "${c}"`));let l=pj(c),d=Nj(c,l,n.target,t.format);Cj(c),o.stop(),Ej(l,d,t.format,t.limit,n.target.kind),await jo(r,!0,null,i)}catch(s){o.fail("Compatibility check failed");let a=eh(s);throw await jo(r,!1,a,i),s}}async function xP(n,e){let t=Date.now(),r=["check","compat"];try{let i=await Oj(n,e);await Mj(i,n,e,t,r)}catch(i){let o=eh(i);throw await jo(t,!1,o,r),i}}function _j(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new Lj(`--limit must be a positive integer (got "${n}")`);return e}var th=new IP("compat").description("Compatibility checking utilities.");th.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)",_j,100).action(async(n,e)=>{await xP(n,e)});th.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 DP(t)});var $j=new IP("check").description("Run DevEco project checks").addCommand(th).addCommand(zf()).addCommand(Zf()),AP=$j;import{Command as kU}from"commander";import{green as Ch,red as DU,yellow as fC}from"colorette";import ki from"fs";import kh from"path";import hC from"json5";import{readFileSync as pH}from"fs";import{join as Fj}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:Fj(".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"},Yt={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 Bd(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function rh(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 Ho(n,e,t){if(n===Yt.FORBIDDEN)return e===Te.OPENPROXY_BLOCKED_URL?new Error(k.ERR_CERT_NETWORK_ERROR):new Error(k.ERR_FORBIDDEN);if(n===Yt.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=jj(t);return new Error(r??k.ERR_DOWNLOAD_CER)}function jj(n){let e=TP(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?TP(t):t;if(r&&typeof r=="object"){let i=r.msg;if(typeof i=="string"&&i.trim()!=="")return i}return null}function TP(n){try{return JSON.parse(n)}catch{return null}}function nh(n){return JSON.parse(n)}async function OP(n){let e=`${fe.BASE_URL}${fe.CERT_LIST_PATH}`,t=await $.postAllowFailure(e,{headers:Bd(n)});if(t.statusCode!==200)throw Ho(t.statusCode,t.statusText,t.data);return nh(t.data)?.certList??[]}async function Wd(n,e){return(await OP(n)).find(r=>r.certName===e)??null}async function ih(n,e){let t=`${fe.BASE_URL}${fe.CERT_DELETE_PATH}`,r=await $.deleteAllowFailure(t,{headers:Bd(n),params:{certIds:[e]}});if(r.statusCode!==200)throw Ho(r.statusCode,r.statusText,r.data);return nh(r.data)?.ret?.code===0}async function oh(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:Bd(n),params:o});if(s.statusCode!==200)throw Ho(s.statusCode,s.statusText,s.data);if(!s.data.includes(Te.SUCCESS_MARKER))throw Ho(void 0,s.statusText,s.data)}async function sh(n,e){let t=`${fe.BASE_URL}${fe.CERT_DOWNLOAD_URL_PATH}`,r=await $.postAllowFailure(t,{headers:Bd(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw Ho(r.statusCode,r.statusText,r.data);return nh(r.data)?.urlsInfo?.[0]??null}import{mkdirSync as Hj,writeFileSync as Uj,existsSync as Bj}from"fs";import{dirname as Wj}from"path";import{createHash as Vj}from"crypto";function Gj(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 Pa(n,e,t){Gj(n);let{statusCode:r,statusText:i,buffer:o}=await $.getBinaryAllowFailure(n,{timeout:Re.DOWNLOAD_CONNECT_TIMEOUT_MS});if(r!==200)throw r===Yt.FORBIDDEN&&i===Te.OPENPROXY_BLOCKED_URL?new Error(k.ERR_CERT_NETWORK_ERROR):new Error(k.ERR_DOWNLOAD_CER);if(t){let a=Vj("sha256").update(o).digest("hex");if(a!==t.toLowerCase())throw new Error(`SHA-256 mismatch for ${e}: expected ${t.toLowerCase()}, got ${a}`)}let s=Wj(e);Bj(s)||Hj(s,{recursive:!0}),Uj(e,o)}import lH from"fs/promises";import{readFileSync as dH}from"fs";import Vd from"path";import LP from"crypto";import qj from"os";import Ca from"fs/promises";var _P={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},NP=["ECC","RSA"],MP=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],zj={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},Jj=8,ah=64,Yj=/[\\/:*?"<>|=-]/g,zr={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function Kj(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>ah)throw new Error(`The length of keyAlias cannot exceed ${ah}`);if(!NP.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${NP.join(" / ")}`);let e=zj[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function Xj(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(!MP.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${MP.join(" / ")}`)}function Zj(n){return LP.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function Qj(n){let e=n?.trim()??"";return e&&e.replace(Yj,"_").replace(/\.+/g,"_").slice(0,ah)||zr.productName}async function $P(){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=Vd.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");try{await Ca.access(r)}catch(i){throw new Error(`Sign tool jar not found: ${r}`,{cause:i})}return{javaPath:e,jarPath:r}}async function eH(n){let{javaPath:e,jarPath:t}=await $P(),r=["-jar",t,_P.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 tH(n){let{javaPath:e,jarPath:t}=await $P(),r=["-jar",t,_P.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 rH(n){f.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),Kj(n);let e=await eH(n),t=await us(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 nH(n){f.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),Xj(n);let e=await tH(n),t=await us(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 iH(n=Jj){return LP.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function oH(){let n=qj.homedir();try{await Ca.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=Vd.join(n,".ohos","config");try{await Ca.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 je(n,e,t,r){let i=Qj(n),o=Vd.basename(e),s=Zj(e),c=`${i}_${o}_${s}${r==="release"?"_release":""}=.${t}`,l=await oH();return Vd.join(l,c)}function sH(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 aH(n){try{await Ca.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function cH(n){try{await Ca.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function ch(n,e,t,r){let i=process.cwd(),o=sH(i);await aH(o),f.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${o}`);let s=iH(),a=r==="release",c=a?"releaseKey":zr.keyAlias,l=a?"CN=ReleaseKey":zr.csrSubject,d=await je(n??"",o,"p12",r),h=await je(n??"",o,"csr",r);return console.log("Start generating p12"),await rH({keyAlias:e?.keyAlias??c,keyPwd:s,keyAlg:e?.keyAlg??zr.keyAlg,keySize:e?.keySize??zr.keySize,keystoreFile:d,keystorePwd:s}),await cH(d),console.log("Start generating csr"),await nH({subject:t?.subject??l,outFile:h,keyAlias:e?.keyAlias??c,keyPwd:s,signAlg:t?.signAlg??zr.signAlg,keystoreFile:d,keystorePwd:s}),{p12FilePath:d,csrFilePath:h,keyPwd:s,keyAlias:e?.keyAlias??c}}var uH=["p12","cer","csr","p7b"];async function lh(n,e,t){for(let r of uH){let i=await je(n,e,r,t);await lH.rm(i,{force:!0})}}function dh(n){let e;try{e=dH(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 Gd(n,e,t){return{certPath:await je(n,e,"cer",t),csrPath:await je(n,e,"csr",t),p12Path:await je(n,e,"p12",t),profilePath:await je(n,e,"p7b",t)}}async function uh(n,e,t){let r=e??"",i=B.discover(process.cwd()).rootDir;await lh(r,i,t);let o=rh(n.teamId,t==="release"),s=await Wd(n,o);if(s&&!await ih(n,s.id))throw new Error(k.ERR_DOWNLOAD_CER);let a=await ch(e,void 0,void 0,t),c;try{c=pH(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 oh(n,c,o,l);let d=await Wd(n,o);if(!d)throw new Error(k.ERR_DOWNLOAD_CER);let h=await sh(n,d.certObjectId);if(!h)throw new Error(k.ERR_DOWNLOAD_CER);let w=await je(r,i,"cer",t);await Pa(h.newUrl,w,h.sha256),dh(w);let D=await je(r,i,"p7b",t);return{p12FilePath:a.p12FilePath,csrFilePath:a.csrFilePath,cerFilePath:w,profileFilePath:D,certId:d.id,keyAlias:a.keyAlias,keyPwd:a.keyPwd,storePassword:a.keyPwd}}import tu from"crypto";import Mn from"fs";import*as ZP from"path";import MH from"json5";import{execa as YP}from"execa";import KP from"node-forge";import{createCipheriv as mH,createDecipheriv as fH,pbkdf2Sync as hH,randomBytes as hh}from"crypto";import{promises as Si}from"fs";import{dirname as gH,join as Kt}from"path";var qd=3,ka=16,yH=1e4,FP="material",wH=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),BP="aes-128-gcm",bi=12,zd=16,Tn=4;function ph(n){return new Uint8Array(hh(n))}function vH(n){return hh(n).toString("hex")}function bH(...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 jP(n,e,t=yH,r=ka){let i=[...n,wH],o=bH(...i),s=Buffer.from(o).toString("utf8"),a=Buffer.from(s,"utf8"),c=hH(a,e,t,r,"sha256");return new Uint8Array(c)}function HP(n,e){let t=hh(bi),r=mH(BP,n,t),i=Buffer.concat([r.update(e),r.final()]),o=r.getAuthTag(),s=Buffer.concat([i,o]),a=s.length,c=Buffer.alloc(Tn+bi+s.length);return c.writeUInt32BE(a,0),t.copy(c,Tn),s.copy(c,Tn+bi),c}function UP(n,e){if(e.length<Tn+bi+zd)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(Tn,Tn+bi),i=e.subarray(Tn+bi,Tn+bi+t);if(i.length<zd)throw new Error("Ciphertext too short for auth tag");let o=i.subarray(0,i.length-zd),s=i.subarray(i.length-zd),a=fH(BP,n,r);return a.setAuthTag(s),Buffer.concat([a.update(o),a.final()])}async function SH(n){try{await Si.rm(n,{recursive:!0,force:!0})}catch{}}async function mh(n){let e=await Si.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 Si.readFile(Kt(n,t[0]))}async function fh(n,e){let t=vH(ka),r=Kt(n,t);return await Si.writeFile(r,e,{mode:384}),t}var On=class{static keyChain=Promise.resolve();static async generateMaterial(e){let t=Kt(e,FP);await SH(t);let r=Kt(t,"ac"),i=Kt(t,"ce");await Si.mkdir(r,{recursive:!0,mode:448}),await Si.mkdir(i,{recursive:!0,mode:448});for(let d=0;d<qd;d++)await Si.mkdir(Kt(t,"fd",String(d)),{recursive:!0,mode:448});let o=ph(ka),s=[];for(let d=0;d<qd;d++)s.push(ph(ka));let a=ph(ka),c=jP(s,o),l=HP(c,a);await fh(r,o),await fh(i,l);for(let d=0;d<qd;d++){let h=Kt(t,"fd",String(d));await fh(h,s[d])}return a}static async readMaterial(e){let t=Kt(e,FP),r=Kt(t,"ac"),i=new Uint8Array(await mh(r)),o=[];for(let d=0;d<qd;d++){let h=Kt(t,"fd",String(d)),w=await mh(h);o.push(new Uint8Array(w))}let s=Kt(t,"ce"),a=await mh(s),c=jP(o,i),l=UP(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=gH(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 HP(r,i).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),i=Buffer.from(e,"hex");return UP(r,i).toString("utf8")}};import zP from"fs";import Qd from"path";import RH from"json5";import*as Jd from"fs";import*as WP from"path";function Yd(n){let e=WP.resolve(n);if(!Jd.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=Jd.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 Bo from"fs";import*as lt from"path";import{debuglog as Uo}from"util";var VP={"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 EH(n){return Object.prototype.hasOwnProperty.call(VP,n)}function Kd(n){if(EH(n))return VP[n]}var GP={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as PH}from"url";var Zd=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 Xd(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function qP(n){return n==null||n.length===0}function CH(n){return!qP(n)}function gh(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function kH(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 DH(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 Nn=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=lt.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=lt.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=lt.join(t.sdkPath,"default","sdk-pkg.json"),a=Yd(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=lt.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=PH(e);if(t.includes("dist")){let s=lt.dirname(t),a=lt.dirname(s);return lt.join(a,"src","resources")}let r=lt.dirname(t),i=lt.dirname(r),o=lt.dirname(i);return lt.join(o,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{Uo("read builtin acl permission failed.");return}if(r!==void 0)try{let i=JSON.parse(r),s=(Array.isArray(i)?i:Xd(i)?Object.values(i):[]).filter(Xd).map(a=>new Zd(a));s.forEach(a=>{let c=a.permissionInsteadName;CH(c)&&(a.permissionInsteadName=Kd(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(i){Uo(`failed to parse aclPermissionsInfo.json: ${i}`)}}static initAclPermissionFromSDK(e,t,r){let i=this.parsePermissionDefinitionFile(e);i&&i.forEach(o=>{if(!Xd(o))return;let s=o,a=gh(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(qP(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||gh(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||gh(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:kH(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let i=new Zd;i.permissionName=t;let o=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;i.permissionDisplayName=o;let s=DH(r,this.ACL_SINCE_KEY);i.minSupportApiLevel=String(s),this.handleInsteadName(i,o),e.add(i)}static parsePermissionDefinitionFile(e){let t=lt.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!Bo.existsSync(t))return;let r;try{r=Bo.readFileSync(t,"utf-8")}catch(s){Uo(`failed to load permissionDefinitions.json: ${s}`);return}let i;try{let s=JSON.parse(r);if(!Xd(s)){Uo("json object is null");return}i=s}catch(s){Uo(`failed to parse permissionDefinitions.json: ${s}`);return}let o=i[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(o)){Uo("definePermissions is not an array");return}return o}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=Kd(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=Kd(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function eu(n,e){let t=new Set,r=new Set;Nn.handleSpecificAclPermissions(),Nn.initAclPermission(n,e);for(let i of n.profile.modules){let o=JP(i,n,e,r,Qd.join("src","main"));for(let a of o)t.add(a);let s=JP(i,n,e,r,Qd.join("src","ohosTest"));for(let a of s)t.add(a)}return xH(r),t}function xH(n){if(n.size>0)throw new Error(GP.DUPLICATE_PERMISSION)}function JP(n,e,t,r,i){let o=AH(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 D=IH(w,"name");D&&s.push(D)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=Qd.join(t.sdkPath,"default","sdk-pkg.json"),l=Yd(c),d=Nn.getAclPermissionInfos(e),h=new Set(Array.from(d).filter(w=>{let D=Number(w.minSupportApiLevel);return Number.isFinite(D)&&D<=l}).map(w=>w.permissionName));for(let w of Array.from(a))h.has(w)||a.delete(w);return a}function IH(n,e){let t=n[e];return typeof t=="string"?t:""}function AH(n,e,t){let r=Qd.join(n,e.srcPath,t,"module.json5"),i=TH(r);if(i==null)return null;let o=OH(i,"module");return o==null?null:NH(o,"requestPermissions")}function TH(n){try{if(!zP.existsSync(n))return null;let e=zP.readFileSync(n,"utf-8");return RH.parse(e)}catch{return null}}function OH(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 NH(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var wh=class{verifyStorePassword(e,t){try{let r=Mn.readFileSync(e),i=KP.asn1.fromDer(r.toString("binary"));return KP.pkcs12.pkcs12FromAsn1(i,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=Mn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(i=>this.formatFp(new tu.X509Certificate(i).fingerprint256));try{return[this.formatFp(new tu.X509Certificate(Mn.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let i=Mn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let o of i)try{let s=new tu.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 LH(n,e){let t=Mn.readFileSync(n,"utf-8"),r=_H(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:yh(o["bundle-name"]),expiryDate:$H(i?.validity?.["not-after"]),cerFingerprintInProfile:FH(yh(o[s])),deviceUdidsInProfile:jH(i?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:HH(i?.acls?.["allowed-acls"]),teamIdInProfile:yh(o["developer-id"])}}function _H(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 $H(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function FH(n){if(!n)return null;try{let t=new tu.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function jH(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 HH(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 yh(n){return typeof n=="string"?n:null}var Da=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([UH(o,c,s),s==="release"?Promise.resolve([]):WH(t.hdcPath)]),h=null;if(XP(l).allExist)try{h=LH(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 BH(c,o,l.storeFile,s),localAclPermissions:[...eu(a,t)].sort(),hapSignTool:new wh,profileInfo:h}}static#t(e){return e.force?(m("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:vt({force:!0})}):null}static#r(e){let t=XP(e.materialPaths);return t.allExist?null:(m(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:vt({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:vt({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:vt({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:vt({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:vt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=GH(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:vt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return qH(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(m("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:vt({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:vt({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:vt({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:vt({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:vt({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:vt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function UH(n,e,t){let[r,i,o,s]=await Promise.all([je(n,e,"p12",t),je(n,e,"csr",t),je(n,e,"cer",t),je(n,e,"p7b",t)]);return{storeFile:r,csrFile:i,cerFile:o,profileFile:s}}async function BH(n,e,t,r){let i=ZP.join(n,"build-profile.json5");if(!Mn.existsSync(i))return;let o;try{o=MH.parse(Mn.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 On.decryptPassword(l,t)}catch{return}}async function WH(n){m(`Executing: ${n} list targets`);let{stdout:e}=await YP(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
1374
+ `),console.log(Ie("[compat:check] === end stdout ===")));let o=new pe("errorCode",`Compatibility scan failed: ${i.message}`+(i.stderr?`
1375
+ ${i.stderr}`:""));throw i.stdout&&(o.stdout=i.stdout),o}}function bj(n,e){if(!ij.includes(e.format))throw new ZF(`--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 pe("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 pe("errorCode","--source-version is required.");if(!e.targetVersion)throw new pe("errorCode","--target-version is required.");if(!e.outputPath&&e.format==="csv")throw new pe("errorCode","--format csv requires --output-path. For console output, use --format json or --format default (or omit the flag).")}function Sj(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 pe("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 pe("errorCode",`--target-version "${n.targetVersion}" must be later than --source-version "${n.sourceVersion}". Run \`devecocli compat versions\` to see the available order.`)}}function Ej(n,e,t,r,i){i==="none"&&(t==="json"?gj(n,r):hj(n,r)),fj(n,e)}function Pj(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 Cj(n){try{tj(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 kj=[".csv",".json"];function Dj(n){return kj.includes(n.toLowerCase())}function Rj(n,e){if(!n)return{kind:"none"};let t=ne.extname(n).toLowerCase();if(!Dj(t))return{kind:"dir",dirPath:ne.resolve(n)};if(t===".csv"&&!(e==="default"||e==="csv")||t===".json"&&e!=="json")throw new pe("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 xj(n){if(n.kind==="file"){if(Bd(n.filePath))throw new pe("errorCode",`Target file "${n.filePath}" already exists. Remove it first, or choose a different --output-path.`);let e=ne.dirname(n.filePath);if(!Bd(e))throw new pe("errorCode",`Target directory "${e}" does not exist. Create it first, or choose a different --output-path.`)}else if(n.kind==="dir"&&!Bd(n.dirPath))throw new pe("errorCode",`Target directory "${n.dirPath}" does not exist. Create it first, or choose a different --output-path.`)}function RP(n){return JSON.stringify({records:n,count:n.length},null,2)+`
1377
+ `}function Aj(n,e,t,r){r===".csv"?EP(n,t):PP(t,RP(e),"utf8"),m(Ie(`[compat:check] saved report: "${t}"`))}function Ij(n,e,t,r){if(r==="json"){let o=ne.basename(n,".csv"),s=ne.join(t,`${o}.json`);return PP(s,RP(e),"utf8"),m(Ie(`[compat:check] saved report: "${s}"`)),s}let i=ne.join(t,ne.basename(n));return EP(n,i),m(Ie(`[compat:check] saved report: "${i}"`)),i}async function Tj(n,e){let t=new ft(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 pe("errorCode",`hvigorw compileNative failed (module=${r??"<project>"}): `+i.message,{cause:i})}}async function Oj(n,e){bj(n,e);let t=B.discover(process.cwd());await tt.warnInvalidBundledLinks(t.rootDir),e.modules&&e.modules.length>0&&sj(t,e.modules),n.length>0&&aj(n);let r=await P.new(),{apiChangeDir:i,scriptPath:o}=r.getApiscanPaths();m(Ie(`[compat:check] script: "${o}"`));let s=kP(i);Sj(e,s),e.outputPath&&m(Ie(`[compat:check] outputPath: "${e.outputPath}"`));let a=Rj(e.outputPath,e.format);return m(Ie(`[compat:check] outputTarget: ${a.kind}`)),xj(a),{project:t,scriptPath:o,target:a,toolProvider:r}}function Nj(n,e,t,r){if(t.kind==="file")return Aj(n,e,t.filePath,t.ext),t.filePath;if(t.kind==="dir")return Ij(n,e,t.dirPath,r);if(t.kind==="none")return null;throw new pe("errorCode",`Unexpected output target kind: ${t.kind}`)}async function Mj(n,e,t,r,i){let o=nj({text:"Running compatibility check...",color:"cyan"}).start();try{await Tj(n.toolProvider,t);let s=wj(n.scriptPath,e,n.project,t);Pj(n.scriptPath,s);let a=await vj(n.toolProvider,s),c=mj(a,Qf.tmpdir());if(!c)throw new pe("errorCode","Scanner output format unexpected: missing report path.");m(Ie(`[compat:check] tmp csv: "${c}"`));let l=pj(c),d=Nj(c,l,n.target,t.format);Cj(c),o.stop(),Ej(l,d,t.format,t.limit,n.target.kind),await Ho(r,!0,null,i)}catch(s){o.fail("Compatibility check failed");let a=eh(s);throw await Ho(r,!1,a,i),s}}async function xP(n,e){let t=Date.now(),r=["check","compat"];try{let i=await Oj(n,e);await Mj(i,n,e,t,r)}catch(i){let o=eh(i);throw await Ho(t,!1,o,r),i}}function _j(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new Lj(`--limit must be a positive integer (got "${n}")`);return e}var th=new AP("compat").description("Compatibility checking utilities.");th.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)",_j,100).action(async(n,e)=>{await xP(n,e)});th.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 DP(t)});var $j=new AP("check").description("Run DevEco project checks").addCommand(th).addCommand(zf()).addCommand(Zf()),IP=$j;import{Command as kU}from"commander";import{green as Ch,red as DU,yellow as fC}from"colorette";import Di from"fs";import kh from"path";import hC from"json5";import{readFileSync as pH}from"fs";import{join as Fj}from"path";var me={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:Fj(".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"},Kt={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 rh(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 Uo(n,e,t){if(n===Kt.FORBIDDEN)return e===Te.OPENPROXY_BLOCKED_URL?new Error(k.ERR_CERT_NETWORK_ERROR):new Error(k.ERR_FORBIDDEN);if(n===Kt.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=jj(t);return new Error(r??k.ERR_DOWNLOAD_CER)}function jj(n){let e=TP(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?TP(t):t;if(r&&typeof r=="object"){let i=r.msg;if(typeof i=="string"&&i.trim()!=="")return i}return null}function TP(n){try{return JSON.parse(n)}catch{return null}}function nh(n){return JSON.parse(n)}async function OP(n){let e=`${me.BASE_URL}${me.CERT_LIST_PATH}`,t=await $.postAllowFailure(e,{headers:Wd(n)});if(t.statusCode!==200)throw Uo(t.statusCode,t.statusText,t.data);return nh(t.data)?.certList??[]}async function Vd(n,e){return(await OP(n)).find(r=>r.certName===e)??null}async function ih(n,e){let t=`${me.BASE_URL}${me.CERT_DELETE_PATH}`,r=await $.deleteAllowFailure(t,{headers:Wd(n),params:{certIds:[e]}});if(r.statusCode!==200)throw Uo(r.statusCode,r.statusText,r.data);return nh(r.data)?.ret?.code===0}async function oh(n,e,t,r=Re.CERT_TYPE_DEBUG){let i=`${me.BASE_URL}${me.CERT_ADD_PATH}`,o={csr:e,certName:t,certType:r},s=await $.postAllowFailure(i,{headers:Wd(n),params:o});if(s.statusCode!==200)throw Uo(s.statusCode,s.statusText,s.data);if(!s.data.includes(Te.SUCCESS_MARKER))throw Uo(void 0,s.statusText,s.data)}async function sh(n,e){let t=`${me.BASE_URL}${me.CERT_DOWNLOAD_URL_PATH}`,r=await $.postAllowFailure(t,{headers:Wd(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw Uo(r.statusCode,r.statusText,r.data);return nh(r.data)?.urlsInfo?.[0]??null}import{mkdirSync as Hj,writeFileSync as Uj,existsSync as Bj}from"fs";import{dirname as Wj}from"path";import{createHash as Vj}from"crypto";function Gj(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 ka(n,e,t){Gj(n);let{statusCode:r,statusText:i,buffer:o}=await $.getBinaryAllowFailure(n,{timeout:Re.DOWNLOAD_CONNECT_TIMEOUT_MS});if(r!==200)throw r===Kt.FORBIDDEN&&i===Te.OPENPROXY_BLOCKED_URL?new Error(k.ERR_CERT_NETWORK_ERROR):new Error(k.ERR_DOWNLOAD_CER);if(t){let a=Vj("sha256").update(o).digest("hex");if(a!==t.toLowerCase())throw new Error(`SHA-256 mismatch for ${e}: expected ${t.toLowerCase()}, got ${a}`)}let s=Wj(e);Bj(s)||Hj(s,{recursive:!0}),Uj(e,o)}import lH from"fs/promises";import{readFileSync as dH}from"fs";import Gd from"path";import LP from"crypto";import qj from"os";import Da from"fs/promises";var _P={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},NP=["ECC","RSA"],MP=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],zj={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},Jj=8,ah=64,Yj=/[\\/:*?"<>|=-]/g,Yr={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function Kj(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>ah)throw new Error(`The length of keyAlias cannot exceed ${ah}`);if(!NP.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${NP.join(" / ")}`);let e=zj[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function Xj(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(!MP.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${MP.join(" / ")}`)}function Zj(n){return LP.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function Qj(n){let e=n?.trim()??"";return e&&e.replace(Yj,"_").replace(/\.+/g,"_").slice(0,ah)||Yr.productName}async function $P(){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=Gd.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");try{await Da.access(r)}catch(i){throw new Error(`Sign tool jar not found: ${r}`,{cause:i})}return{javaPath:e,jarPath:r}}async function eH(n){let{javaPath:e,jarPath:t}=await $P(),r=["-jar",t,_P.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 tH(n){let{javaPath:e,jarPath:t}=await $P(),r=["-jar",t,_P.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 rH(n){f.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),Kj(n);let e=await eH(n),t=await ms(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 nH(n){f.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),Xj(n);let e=await tH(n),t=await ms(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 iH(n=Jj){return LP.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function oH(){let n=qj.homedir();try{await Da.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=Gd.join(n,".ohos","config");try{await Da.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 je(n,e,t,r){let i=Qj(n),o=Gd.basename(e),s=Zj(e),c=`${i}_${o}_${s}${r==="release"?"_release":""}=.${t}`,l=await oH();return Gd.join(l,c)}function sH(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 aH(n){try{await Da.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function cH(n){try{await Da.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function ch(n,e,t,r){let i=process.cwd(),o=sH(i);await aH(o),f.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${o}`);let s=iH(),a=r==="release",c=a?"releaseKey":Yr.keyAlias,l=a?"CN=ReleaseKey":Yr.csrSubject,d=await je(n??"",o,"p12",r),h=await je(n??"",o,"csr",r);return console.log("Start generating p12"),await rH({keyAlias:e?.keyAlias??c,keyPwd:s,keyAlg:e?.keyAlg??Yr.keyAlg,keySize:e?.keySize??Yr.keySize,keystoreFile:d,keystorePwd:s}),await cH(d),console.log("Start generating csr"),await nH({subject:t?.subject??l,outFile:h,keyAlias:e?.keyAlias??c,keyPwd:s,signAlg:t?.signAlg??Yr.signAlg,keystoreFile:d,keystorePwd:s}),{p12FilePath:d,csrFilePath:h,keyPwd:s,keyAlias:e?.keyAlias??c}}var uH=["p12","cer","csr","p7b"];async function lh(n,e,t){for(let r of uH){let i=await je(n,e,r,t);await lH.rm(i,{force:!0})}}function dh(n){let e;try{e=dH(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 qd(n,e,t){return{certPath:await je(n,e,"cer",t),csrPath:await je(n,e,"csr",t),p12Path:await je(n,e,"p12",t),profilePath:await je(n,e,"p7b",t)}}async function uh(n,e,t){let r=e??"",i=B.discover(process.cwd()).rootDir;await lh(r,i,t);let o=rh(n.teamId,t==="release"),s=await Vd(n,o);if(s&&!await ih(n,s.id))throw new Error(k.ERR_DOWNLOAD_CER);let a=await ch(e,void 0,void 0,t),c;try{c=pH(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 oh(n,c,o,l);let d=await Vd(n,o);if(!d)throw new Error(k.ERR_DOWNLOAD_CER);let h=await sh(n,d.certObjectId);if(!h)throw new Error(k.ERR_DOWNLOAD_CER);let w=await je(r,i,"cer",t);await ka(h.newUrl,w,h.sha256),dh(w);let R=await je(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 ru from"crypto";import _n from"fs";import*as ZP from"path";import MH from"json5";import{execa as YP}from"execa";import KP from"node-forge";import{createCipheriv as mH,createDecipheriv as fH,pbkdf2Sync as hH,randomBytes as hh}from"crypto";import{promises as Ei}from"fs";import{dirname as gH,join as Xt}from"path";var zd=3,Ra=16,yH=1e4,FP="material",wH=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),BP="aes-128-gcm",Si=12,Jd=16,Nn=4;function ph(n){return new Uint8Array(hh(n))}function vH(n){return hh(n).toString("hex")}function bH(...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 jP(n,e,t=yH,r=Ra){let i=[...n,wH],o=bH(...i),s=Buffer.from(o).toString("utf8"),a=Buffer.from(s,"utf8"),c=hH(a,e,t,r,"sha256");return new Uint8Array(c)}function HP(n,e){let t=hh(Si),r=mH(BP,n,t),i=Buffer.concat([r.update(e),r.final()]),o=r.getAuthTag(),s=Buffer.concat([i,o]),a=s.length,c=Buffer.alloc(Nn+Si+s.length);return c.writeUInt32BE(a,0),t.copy(c,Nn),s.copy(c,Nn+Si),c}function UP(n,e){if(e.length<Nn+Si+Jd)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(Nn,Nn+Si),i=e.subarray(Nn+Si,Nn+Si+t);if(i.length<Jd)throw new Error("Ciphertext too short for auth tag");let o=i.subarray(0,i.length-Jd),s=i.subarray(i.length-Jd),a=fH(BP,n,r);return a.setAuthTag(s),Buffer.concat([a.update(o),a.final()])}async function SH(n){try{await Ei.rm(n,{recursive:!0,force:!0})}catch{}}async function mh(n){let e=await Ei.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 Ei.readFile(Xt(n,t[0]))}async function fh(n,e){let t=vH(Ra),r=Xt(n,t);return await Ei.writeFile(r,e,{mode:384}),t}var Mn=class{static keyChain=Promise.resolve();static async generateMaterial(e){let t=Xt(e,FP);await SH(t);let r=Xt(t,"ac"),i=Xt(t,"ce");await Ei.mkdir(r,{recursive:!0,mode:448}),await Ei.mkdir(i,{recursive:!0,mode:448});for(let d=0;d<zd;d++)await Ei.mkdir(Xt(t,"fd",String(d)),{recursive:!0,mode:448});let o=ph(Ra),s=[];for(let d=0;d<zd;d++)s.push(ph(Ra));let a=ph(Ra),c=jP(s,o),l=HP(c,a);await fh(r,o),await fh(i,l);for(let d=0;d<zd;d++){let h=Xt(t,"fd",String(d));await fh(h,s[d])}return a}static async readMaterial(e){let t=Xt(e,FP),r=Xt(t,"ac"),i=new Uint8Array(await mh(r)),o=[];for(let d=0;d<zd;d++){let h=Xt(t,"fd",String(d)),w=await mh(h);o.push(new Uint8Array(w))}let s=Xt(t,"ce"),a=await mh(s),c=jP(o,i),l=UP(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=gH(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 HP(r,i).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),i=Buffer.from(e,"hex");return UP(r,i).toString("utf8")}};import zP from"fs";import eu from"path";import RH from"json5";import*as Yd from"fs";import*as WP from"path";function Kd(n){let e=WP.resolve(n);if(!Yd.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=Yd.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 Wo from"fs";import*as lt from"path";import{debuglog as Bo}from"util";var VP={"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 EH(n){return Object.prototype.hasOwnProperty.call(VP,n)}function Xd(n){if(EH(n))return VP[n]}var GP={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as PH}from"url";var Qd=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 Zd(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function qP(n){return n==null||n.length===0}function CH(n){return!qP(n)}function gh(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function kH(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 DH(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 Ln=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=lt.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=lt.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=lt.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=lt.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(Wo.existsSync(e))return Wo.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=PH(e);if(t.includes("dist")){let s=lt.dirname(t),a=lt.dirname(s);return lt.join(a,"src","resources")}let r=lt.dirname(t),i=lt.dirname(r),o=lt.dirname(i);return lt.join(o,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{Bo("read builtin acl permission failed.");return}if(r!==void 0)try{let i=JSON.parse(r),s=(Array.isArray(i)?i:Zd(i)?Object.values(i):[]).filter(Zd).map(a=>new Qd(a));s.forEach(a=>{let c=a.permissionInsteadName;CH(c)&&(a.permissionInsteadName=Xd(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(i){Bo(`failed to parse aclPermissionsInfo.json: ${i}`)}}static initAclPermissionFromSDK(e,t,r){let i=this.parsePermissionDefinitionFile(e);i&&i.forEach(o=>{if(!Zd(o))return;let s=o,a=gh(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(qP(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||gh(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||gh(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:kH(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let i=new Qd;i.permissionName=t;let o=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;i.permissionDisplayName=o;let s=DH(r,this.ACL_SINCE_KEY);i.minSupportApiLevel=String(s),this.handleInsteadName(i,o),e.add(i)}static parsePermissionDefinitionFile(e){let t=lt.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!Wo.existsSync(t))return;let r;try{r=Wo.readFileSync(t,"utf-8")}catch(s){Bo(`failed to load permissionDefinitions.json: ${s}`);return}let i;try{let s=JSON.parse(r);if(!Zd(s)){Bo("json object is null");return}i=s}catch(s){Bo(`failed to parse permissionDefinitions.json: ${s}`);return}let o=i[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(o)){Bo("definePermissions is not an array");return}return o}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=Xd(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=Xd(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function tu(n,e){let t=new Set,r=new Set;Ln.handleSpecificAclPermissions(),Ln.initAclPermission(n,e);for(let i of n.profile.modules){let o=JP(i,n,e,r,eu.join("src","main"));for(let a of o)t.add(a);let s=JP(i,n,e,r,eu.join("src","ohosTest"));for(let a of s)t.add(a)}return xH(r),t}function xH(n){if(n.size>0)throw new Error(GP.DUPLICATE_PERMISSION)}function JP(n,e,t,r,i){let o=IH(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=AH(w,"name");R&&s.push(R)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=eu.join(t.sdkPath,"default","sdk-pkg.json"),l=Kd(c),d=Ln.getAclPermissionInfos(e),h=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))h.has(w)||a.delete(w);return a}function AH(n,e){let t=n[e];return typeof t=="string"?t:""}function IH(n,e,t){let r=eu.join(n,e.srcPath,t,"module.json5"),i=TH(r);if(i==null)return null;let o=OH(i,"module");return o==null?null:NH(o,"requestPermissions")}function TH(n){try{if(!zP.existsSync(n))return null;let e=zP.readFileSync(n,"utf-8");return RH.parse(e)}catch{return null}}function OH(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 NH(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var wh=class{verifyStorePassword(e,t){try{let r=_n.readFileSync(e),i=KP.asn1.fromDer(r.toString("binary"));return KP.pkcs12.pkcs12FromAsn1(i,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=_n.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(i=>this.formatFp(new ru.X509Certificate(i).fingerprint256));try{return[this.formatFp(new ru.X509Certificate(_n.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let i=_n.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let o of i)try{let s=new ru.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 LH(n,e){let t=_n.readFileSync(n,"utf-8"),r=_H(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:yh(o["bundle-name"]),expiryDate:$H(i?.validity?.["not-after"]),cerFingerprintInProfile:FH(yh(o[s])),deviceUdidsInProfile:jH(i?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:HH(i?.acls?.["allowed-acls"]),teamIdInProfile:yh(o["developer-id"])}}function _H(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 $H(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function FH(n){if(!n)return null;try{let t=new ru.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function jH(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 HH(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 yh(n){return typeof n=="string"?n:null}var xa=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([UH(o,c,s),s==="release"?Promise.resolve([]):WH(t.hdcPath)]),h=null;if(XP(l).allExist)try{h=LH(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 BH(c,o,l.storeFile,s),localAclPermissions:[...tu(a,t)].sort(),hapSignTool:new wh,profileInfo:h}}static#t(e){return e.force?(m("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:vt({force:!0})}):null}static#r(e){let t=XP(e.materialPaths);return t.allExist?null:(m(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:vt({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:vt({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:vt({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:vt({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:vt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=GH(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:vt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return qH(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(m("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:vt({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:vt({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:vt({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:vt({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:vt({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:vt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function UH(n,e,t){let[r,i,o,s]=await Promise.all([je(n,e,"p12",t),je(n,e,"csr",t),je(n,e,"cer",t),je(n,e,"p7b",t)]);return{storeFile:r,csrFile:i,cerFile:o,profileFile:s}}async function BH(n,e,t,r){let i=ZP.join(n,"build-profile.json5");if(!_n.existsSync(i))return;let o;try{o=MH.parse(_n.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 Mn.decryptPassword(l,t)}catch{return}}async function WH(n){m(`Executing: ${n} list targets`);let{stdout:e}=await YP(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
1378
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 YP(n,["-t",i,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),s=VH(o);s&&r.push(s)}catch{m(`[reGenerateSign] Failed to get UDID for ${i}, skipping`)}return r}function VH(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 XP(n){let e=[n.storeFile,n.csrFile,n.cerFile,n.profileFile],t=[];for(let r of e)Mn.existsSync(r)||t.push(r);return{allExist:t.length===0,missing:t}}function GH(n,e){let t=[];for(let r of e)n.includes(r)||t.push(r);return{allPresent:t.length===0,missing:t}}function qH(n,e){let t=[...n].sort(),r=[...e].sort();return t.length!==r.length?!1:t.every((i,o)=>i===r[o])}function vt(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 vh}from"util";import{execa as bh}from"execa";async function eC(n,e){let t=await ru(n);if(!t)throw new Error(k.DEVICE_LIST_EMPTY);let r=await YH(e);if(t.length===0)for(let s of r)await zH(n,s.udid,s.deviceName);else for(let s of r)await JH(n,t,s.udid,s.deviceName);let o=(await ru(n)).map(s=>s.id);if(o.length===0)throw new Error(k.DEVICE_LIST_EMPTY);return o}async function zH(n,e,t){await nC(n,e,tC(t))}async function JH(n,e,t,r){for(let i=0;i<e.length;i++){if(t===e[i].udid)return;if(i===e.length-1){await nC(n,t,tC(r));return}}}function tC(n){switch(n){case"liteWearable":return"1";case"wearable":return"2";case"tv":return"3";default:return"4"}}async function QP(n,e=1,t=100){let r=`${fe.BASE_URL}${fe.DEVICE_LIST_PATH}?encodeFlag=0&start=${e}&pageSize=${t}`,i=iC(n),o=await $.get(r,{headers:i});if(!o)throw vh("query devices failed: response is null"),new Error(k.ERROR_WHILE_ADD_DEVICE);if(o.statusCode!==200)throw rC(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.list)throw vh("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 rC(n,e,t){return n===Yt.FORBIDDEN?e===Te.OPENPROXY_BLOCKED_URL?new Error(k.ERR_CERT_NETWORK_ERROR):new Error(k.ERR_FORBIDDEN):n===Yt.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 ru(n){let t=await QP(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 QP(n,s,100);if(!a||!a.deviceList||a.deviceList.length===0)break;r.push(...a.deviceList)}return r}async function nC(n,e,t){let r=`${fe.BASE_URL}${fe.DEVICE_ADD_PATH}`,i=iC(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 vh("add device failed: response is null"),new Error(k.ERROR_WHILE_ADD_DEVICE);if(a.statusCode!==200)throw rC(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 iC(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}async function YH(n){let{stdout:e}=await bh(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of 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 XP(n){let e=[n.storeFile,n.csrFile,n.cerFile,n.profileFile],t=[];for(let r of e)_n.existsSync(r)||t.push(r);return{allExist:t.length===0,missing:t}}function GH(n,e){let t=[];for(let r of e)n.includes(r)||t.push(r);return{allPresent:t.length===0,missing:t}}function qH(n,e){let t=[...n].sort(),r=[...e].sort();return t.length!==r.length?!1:t.every((i,o)=>i===r[o])}function vt(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 vh}from"util";import{execa as bh}from"execa";async function eC(n,e){let t=await nu(n);if(!t)throw new Error(k.DEVICE_LIST_EMPTY);let r=await YH(e);if(t.length===0)for(let s of r)await zH(n,s.udid,s.deviceName);else for(let s of r)await JH(n,t,s.udid,s.deviceName);let o=(await nu(n)).map(s=>s.id);if(o.length===0)throw new Error(k.DEVICE_LIST_EMPTY);return o}async function zH(n,e,t){await nC(n,e,tC(t))}async function JH(n,e,t,r){for(let i=0;i<e.length;i++){if(t===e[i].udid)return;if(i===e.length-1){await nC(n,t,tC(r));return}}}function tC(n){switch(n){case"liteWearable":return"1";case"wearable":return"2";case"tv":return"3";default:return"4"}}async function QP(n,e=1,t=100){let r=`${me.BASE_URL}${me.DEVICE_LIST_PATH}?encodeFlag=0&start=${e}&pageSize=${t}`,i=iC(n),o=await $.get(r,{headers:i});if(!o)throw vh("query devices failed: response is null"),new Error(k.ERROR_WHILE_ADD_DEVICE);if(o.statusCode!==200)throw rC(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.list)throw vh("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 rC(n,e,t){return n===Kt.FORBIDDEN?e===Te.OPENPROXY_BLOCKED_URL?new Error(k.ERR_CERT_NETWORK_ERROR):new Error(k.ERR_FORBIDDEN):n===Kt.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 nu(n){let t=await QP(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 QP(n,s,100);if(!a||!a.deviceList||a.deviceList.length===0)break;r.push(...a.deviceList)}return r}async function nC(n,e,t){let r=`${me.BASE_URL}${me.DEVICE_ADD_PATH}`,i=iC(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 vh("add device failed: response is null"),new Error(k.ERROR_WHILE_ADD_DEVICE);if(a.statusCode!==200)throw rC(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 iC(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}async function YH(n){let{stdout:e}=await bh(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
1380
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 KH(i,n),s=await XH(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 KH(n,e){let{stdout:t}=await bh(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 XH(n,e){let{stdout:t}=await bh(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return ZH(t)}function ZH(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 Ei from"fs";import{createHash as QH}from"crypto";import{debuglog as Ci}from"util";import{Buffer as sC}from"buffer";import{createPublicKey as eU,X509Certificate as Sh}from"crypto";import{readFileSync as tU}from"fs";import Pi from"node-forge";async function aC(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 h=d?fe.PROVISION_ADD_REAL_PATH:fe.PROVISION_ADD_TEST_PATH,w=`${fe.BASE_URL}${h}`,D=rU(t,r),z=await iU(n,w,a||[],r,s??[],D,o||[]);if(!z||!z.profileInfo||!z.profileInfo.provisionFileUrl)throw Ci("add provision failed, the provision file url is null"),new Error(k.ADD_PROFILE_FAIL);let ie=z.profileInfo,Xt=(await cU(n,ie.provisionFileUrl)).urlList,_n=z.profileInfo.id;if(Xt&&Xt.length>0){let $n=await Gd(t,i,e.type),Fn=$n.profilePath;if(!await lU(Xt,Fn))throw await oC(n,_n),new Error(k.ERROR_WHILE_DOWNLOAD_PROFILE);if(await oC(n,_n),Ei.existsSync($n.certPath)&&Ei.existsSync(Fn)&&Ei.existsSync($n.p12Path)){let DC=Ei.readFileSync($n.certPath,"utf8"),RC=Ei.readFileSync(Fn,"utf8");return dU(RC,DC,$n.p12Path,c,l)||aU(Fn),Fn}}throw new Error(k.ADD_PROFILE_FAIL)}function rU(n,e){let t=n?`${n}_`:"";return`${nU(`${t}${e}_${e}`)}`}function nU(n){return QH("sha256").update(n).digest("hex").substring(0,16)}async function iU(n,e,t,r,i,o,s){oU(r);let a=Ph(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}`),Eh(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}`),sU(l.data,o),new Error(d.ret?.msg||k.ADD_PROFILE_FAIL);let h=d.provisionFileUrl;return{profileInfo:{id:d.id,name:o,provisionFileUrl:h}}}function Eh(n,e,t){return n===Yt.FORBIDDEN?e===Te.OPENPROXY_BLOCKED_URL?new Error(k.ERR_CERT_NETWORK_ERROR):new Error(k.ERR_FORBIDDEN):n===Yt.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 oU(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 sU(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 oC(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:Ph(n)});if(r.statusCode!==200)throw Eh(r.statusCode,r.statusText,r.data);let i=JSON.parse(r.data);(!i||!i.ret||i.ret.code!==0)&&Ci(`delete provision failed: ${r.data}`)}function aU(...n){for(let e of n)try{Ei.existsSync(e)&&Ei.unlinkSync(e)}catch(t){Ci(`delete local sign file error: ${t.message}`)}}async function cU(n,e){let t=`${fe.BASE_URL}${fe.CERT_DOWNLOAD_URL_PATH}`,r=Ph(n),i={sourceUrls:e},o=await $.postAllowFailure(t,{headers:r,params:i});if(!o)throw Ci("get download list failed: response is null"),new Error(k.ADD_PROFILE_FAIL);if(o.statusCode!==200)throw Eh(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw Ci("download: The application does not exist"),new Error(s.ret?.msg||k.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function lU(n,e){if(!n||n.length===0)return!1;let t=n[0];return await Pa(t.newUrl,e,t.sha256),!0}function dU(n,e,t,r,i){return uU(n,e),r=r||Re.TARGET_FRIENDLY_NAME,i=i||"",pU(e,t,r,i),!0}function uU(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 pU(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=mU(l),h=new Date(d.validFrom),w=new Date(d.validTo);if(s<h||s>w){let D=`Certificate is not valid, Valid from ${h} to ${w}`;throw console.warn(`checkCertificateInValidityPeriod: ${D}`),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(!hU(e,t,r,o))throw new Error(k.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function mU(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new Sh(t);let r=sC.from(t,"base64");return new Sh(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function fU(n){if(n.cert){let e=Pi.pki.publicKeyToPem(n.cert.publicKey);return eU(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=Pi.asn1.toDer(n.asn1).getBytes(),t=sC.from(e,"binary");return new Sh(t).publicKey.export({type:"spki",format:"der"})}catch(e){return Ci(`Failed to parse cert from asn1: ${e}`),null}return null}function hU(n,e,t,r){try{let i=tU(n),o=Pi.asn1.fromDer(Pi.util.createBuffer(i)),c=Pi.pkcs12.pkcs12FromAsn1(o,t).getBags({bagType:Pi.pki.oids.certBag})[Pi.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let h=fU(l);if(!h)continue;if(r.some(D=>{let z=D.publicKey.export({type:"spki",format:"der"});return h.equals(z)}))return!0}return!1}catch(i){let o=i instanceof Error?i.message:String(i);return Ci(`Failed to process P12 file: ${n}, error: ${o}`),!1}}function Ph(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var lC="https://developer.huawei.com",gU={"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"},yU="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function wU(n){let e=gU[n];return e?`${lC}${e}`:void 0}function vU(){return`${lC}${yU}`}var bU={"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 cC(n,e){return(bU[n]??n).replace(/\{(\d+)\}/g,(r,i)=>String(e[Number(i)]??""))}function SU(n){return Array.from(n).join(", ")}function dC(n,e){if(n.size===0)return;let t=Nn.getAclPermissionInfos(e),r=new Set;for(let h of t)n.has(h.permissionName)&&r.add(h);for(let h of r){let w=wU(h.permissionName);w!=null&&(h.permissionHelpUrlKey=w)}let i=new Set;for(let h of r)i.add(h.permissionDisplayName);let o=new Set;for(let h of r)if(h.permissionHelpUrlKey!=null){let w=h.permissionInsteadName??h.permissionDisplayName;o.add(`${w} (${h.permissionHelpUrlKey})`)}let s=vU(),a=cC("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=o.size>0?Array.from(o).join(", ")+".":"",d=cC("acl.permissions.warn",[SU(i),l,c]);console.log(d)}var nu=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 EU from"fs";import uC from"path";var iu=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=uC.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");if(!EU.existsSync(r)){let i=uC.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 ou=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await Je.getUserInfo()}catch(e){return m(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await Je.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 wn()).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 wn();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 PU(n){try{let{teamList:e}=await wn();if(e.length>0)return e[0].id}catch(e){m(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function CU(n){let e=await Je.getUserInfo(),t=await Je.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await PU(e.userId);if(!r)throw new Error("No team found");let i={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await ru(i)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var su=class{constructor(e){this.toolProvider=e}async checkDevice(e,t){try{let r=await CU(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=>sr(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 au=class{projectChecker=new nu;toolchainChecker=null;authChecker=new ou;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 iu(e),this.deviceChecker=new su(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 pC=5*1024*1024;function RU(n){try{let e=ki.statSync(n);if(e.size>pC)throw new Error(`Profile file too large: ${e.size} bytes (max ${pC} bytes): ${n}`);let t=ki.readFileSync(n,"utf-8");return hC.parse(t)}catch(e){if(e.code==="ENOENT")return{app:{signingConfigs:[],products:[]}};throw new Error(`Failed to read profile: ${n}`,{cause:e})}}function xU(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function IU(n){if(n.keyPwd===n.storePassword){let r=await On.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await On.encryptedPassword(n.keyPwd,n.p12FilePath),t=await On.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function gC(n,e,t,r){let i=kh.join(n,"build-profile.json5"),o=RU(i);xU(o);let s=r==="release"?`${t??"default"}_release`:t??"default",{keyPassword:a,storePassword:c}=await IU(e),l={name:s,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:a,profile:e.profileFilePath,signAlg:zr.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 h=o.app?.products?.findIndex(w=>w.name===t);h!==void 0&&h>=0?o.app.products[h].signingConfig=s:o.app.products.push({name:t,signingConfig:s}),ki.writeFileSync(i,hC.stringify(o,null,2),"utf-8")}async function AU(n){let e=await Je.getUserInfo(),t=await Je.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 mC=["debug","release"];async function TU(n){let e=n.product||"default";if(n.type&&!mC.includes(n.type))throw new Error(`Invalid signing type '${n.type}'. Valid types: ${mC.join(", ")}`);await new au().preflight({productName:e,teamId:n.teamId,type:n.type}),await tt.warnInvalidBundledLinks(B.discover(process.cwd()).rootDir),console.log("Executing signature generate command");let r=await AU(n),i=await P.new(),{shouldRegenerate:o}=await Da.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product,type:n.type},i);if(!o){console.log(Ch("Signature generation completed successfully."));return}await OU(n,r,i)||(process.exitCode=1)}async function OU(n,e,t){if(n.type==="release"&&await MU(n))return!1;let r=await uh(e,n.product,n.type),i=LU(n,e,r,t);n.type!=="release"&&(i.allDeviceIds=await eC(e,t.hdcPath));try{await aC(e,i)}catch(s){if(n.type==="release")return NU(n,r);throw s}let o=B.discover(process.cwd()).rootDir;return await gC(o,r,n.product??"default",n.type),console.log(Ch(`Signing config written to ${kh.join(o,"build-profile.json5")}`)),console.log(Ch("Signature generation completed successfully.")),!0}async function NU(n,e){let t=n.product||"default",r=B.discover(process.cwd()).rootDir;return await gC(r,e,t,n.type),console.warn(fC(`
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 XH(n,e){let{stdout:t}=await bh(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return ZH(t)}function ZH(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 Pi from"fs";import{createHash as QH}from"crypto";import{debuglog as ki}from"util";import{Buffer as sC}from"buffer";import{createPublicKey as eU,X509Certificate as Sh}from"crypto";import{readFileSync as tU}from"fs";import Ci from"node-forge";async function aC(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 h=d?me.PROVISION_ADD_REAL_PATH:me.PROVISION_ADD_TEST_PATH,w=`${me.BASE_URL}${h}`,R=rU(t,r),J=await iU(n,w,a||[],r,s??[],R,o||[]);if(!J||!J.profileInfo||!J.profileInfo.provisionFileUrl)throw ki("add provision failed, the provision file url is null"),new Error(k.ADD_PROFILE_FAIL);let ye=J.profileInfo,Zt=(await cU(n,ye.provisionFileUrl)).urlList,Fn=J.profileInfo.id;if(Zt&&Zt.length>0){let jn=await qd(t,i,e.type),Hn=jn.profilePath;if(!await lU(Zt,Hn))throw await oC(n,Fn),new Error(k.ERROR_WHILE_DOWNLOAD_PROFILE);if(await oC(n,Fn),Pi.existsSync(jn.certPath)&&Pi.existsSync(Hn)&&Pi.existsSync(jn.p12Path)){let DC=Pi.readFileSync(jn.certPath,"utf8"),RC=Pi.readFileSync(Hn,"utf8");return dU(RC,DC,jn.p12Path,c,l)||aU(Hn),Hn}}throw new Error(k.ADD_PROFILE_FAIL)}function rU(n,e){let t=n?`${n}_`:"";return`${nU(`${t}${e}_${e}`)}`}function nU(n){return QH("sha256").update(n).digest("hex").substring(0,16)}async function iU(n,e,t,r,i,o,s){oU(r);let a=Ph(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}`),Eh(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}`),sU(l.data,o),new Error(d.ret?.msg||k.ADD_PROFILE_FAIL);let h=d.provisionFileUrl;return{profileInfo:{id:d.id,name:o,provisionFileUrl:h}}}function Eh(n,e,t){return n===Kt.FORBIDDEN?e===Te.OPENPROXY_BLOCKED_URL?new Error(k.ERR_CERT_NETWORK_ERROR):new Error(k.ERR_FORBIDDEN):n===Kt.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 oU(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 sU(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 oC(n,e){if(!e||e.trim().length===0)return;let t=`${me.BASE_URL}${me.PROVISION_DELETE_PATH}?id=${e}`,r=await $.deleteAllowFailure(t,{headers:Ph(n)});if(r.statusCode!==200)throw Eh(r.statusCode,r.statusText,r.data);let i=JSON.parse(r.data);(!i||!i.ret||i.ret.code!==0)&&ki(`delete provision failed: ${r.data}`)}function aU(...n){for(let e of n)try{Pi.existsSync(e)&&Pi.unlinkSync(e)}catch(t){ki(`delete local sign file error: ${t.message}`)}}async function cU(n,e){let t=`${me.BASE_URL}${me.CERT_DOWNLOAD_URL_PATH}`,r=Ph(n),i={sourceUrls:e},o=await $.postAllowFailure(t,{headers:r,params:i});if(!o)throw ki("get download list failed: response is null"),new Error(k.ADD_PROFILE_FAIL);if(o.statusCode!==200)throw Eh(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw ki("download: The application does not exist"),new Error(s.ret?.msg||k.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function lU(n,e){if(!n||n.length===0)return!1;let t=n[0];return await ka(t.newUrl,e,t.sha256),!0}function dU(n,e,t,r,i){return uU(n,e),r=r||Re.TARGET_FRIENDLY_NAME,i=i||"",pU(e,t,r,i),!0}function uU(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 pU(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=mU(l),h=new Date(d.validFrom),w=new Date(d.validTo);if(s<h||s>w){let R=`Certificate is not valid, Valid from ${h} 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(!hU(e,t,r,o))throw new Error(k.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function mU(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new Sh(t);let r=sC.from(t,"base64");return new Sh(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function fU(n){if(n.cert){let e=Ci.pki.publicKeyToPem(n.cert.publicKey);return eU(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=Ci.asn1.toDer(n.asn1).getBytes(),t=sC.from(e,"binary");return new Sh(t).publicKey.export({type:"spki",format:"der"})}catch(e){return ki(`Failed to parse cert from asn1: ${e}`),null}return null}function hU(n,e,t,r){try{let i=tU(n),o=Ci.asn1.fromDer(Ci.util.createBuffer(i)),c=Ci.pkcs12.pkcs12FromAsn1(o,t).getBags({bagType:Ci.pki.oids.certBag})[Ci.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let h=fU(l);if(!h)continue;if(r.some(R=>{let J=R.publicKey.export({type:"spki",format:"der"});return h.equals(J)}))return!0}return!1}catch(i){let o=i instanceof Error?i.message:String(i);return ki(`Failed to process P12 file: ${n}, error: ${o}`),!1}}function Ph(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var lC="https://developer.huawei.com",gU={"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"},yU="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function wU(n){let e=gU[n];return e?`${lC}${e}`:void 0}function vU(){return`${lC}${yU}`}var bU={"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 cC(n,e){return(bU[n]??n).replace(/\{(\d+)\}/g,(r,i)=>String(e[Number(i)]??""))}function SU(n){return Array.from(n).join(", ")}function dC(n,e){if(n.size===0)return;let t=Ln.getAclPermissionInfos(e),r=new Set;for(let h of t)n.has(h.permissionName)&&r.add(h);for(let h of r){let w=wU(h.permissionName);w!=null&&(h.permissionHelpUrlKey=w)}let i=new Set;for(let h of r)i.add(h.permissionDisplayName);let o=new Set;for(let h of r)if(h.permissionHelpUrlKey!=null){let w=h.permissionInsteadName??h.permissionDisplayName;o.add(`${w} (${h.permissionHelpUrlKey})`)}let s=vU(),a=cC("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=o.size>0?Array.from(o).join(", ")+".":"",d=cC("acl.permissions.warn",[SU(i),l,c]);console.log(d)}var iu=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 EU from"fs";import uC from"path";var ou=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=uC.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");if(!EU.existsSync(r)){let i=uC.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 su=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await Je.getUserInfo()}catch(e){return m(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await Je.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 bn()).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 bn();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 PU(n){try{let{teamList:e}=await bn();if(e.length>0)return e[0].id}catch(e){m(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function CU(n){let e=await Je.getUserInfo(),t=await Je.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await PU(e.userId);if(!r)throw new Error("No team found");let i={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await nu(i)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var au=class{constructor(e){this.toolProvider=e}async checkDevice(e,t){try{let r=await CU(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 ce.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=>cr(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 cu=class{projectChecker=new iu;toolchainChecker=null;authChecker=new su;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 ou(e),this.deviceChecker=new au(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 pC=5*1024*1024;function RU(n){try{let e=Di.statSync(n);if(e.size>pC)throw new Error(`Profile file too large: ${e.size} bytes (max ${pC} bytes): ${n}`);let t=Di.readFileSync(n,"utf-8");return hC.parse(t)}catch(e){if(e.code==="ENOENT")return{app:{signingConfigs:[],products:[]}};throw new Error(`Failed to read profile: ${n}`,{cause:e})}}function xU(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function AU(n){if(n.keyPwd===n.storePassword){let r=await Mn.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await Mn.encryptedPassword(n.keyPwd,n.p12FilePath),t=await Mn.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function gC(n,e,t,r){let i=kh.join(n,"build-profile.json5"),o=RU(i);xU(o);let s=r==="release"?`${t??"default"}_release`:t??"default",{keyPassword:a,storePassword:c}=await AU(e),l={name:s,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:a,profile:e.profileFilePath,signAlg:Yr.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 h=o.app?.products?.findIndex(w=>w.name===t);h!==void 0&&h>=0?o.app.products[h].signingConfig=s:o.app.products.push({name:t,signingConfig:s}),Di.writeFileSync(i,hC.stringify(o,null,2),"utf-8")}async function IU(n){let e=await Je.getUserInfo(),t=await Je.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 mC=["debug","release"];async function TU(n){let e=n.product||"default";if(n.type&&!mC.includes(n.type))throw new Error(`Invalid signing type '${n.type}'. Valid types: ${mC.join(", ")}`);await new cu().preflight({productName:e,teamId:n.teamId,type:n.type}),await tt.warnInvalidBundledLinks(B.discover(process.cwd()).rootDir),console.log("Executing signature generate command");let r=await IU(n),i=await P.new(),{shouldRegenerate:o}=await xa.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product,type:n.type},i);if(!o){console.log(Ch("Signature generation completed successfully."));return}await OU(n,r,i)||(process.exitCode=1)}async function OU(n,e,t){if(n.type==="release"&&await MU(n))return!1;let r=await uh(e,n.product,n.type),i=LU(n,e,r,t);n.type!=="release"&&(i.allDeviceIds=await eC(e,t.hdcPath));try{await aC(e,i)}catch(s){if(n.type==="release")return NU(n,r);throw s}let o=B.discover(process.cwd()).rootDir;return await gC(o,r,n.product??"default",n.type),console.log(Ch(`Signing config written to ${kh.join(o,"build-profile.json5")}`)),console.log(Ch("Signature generation completed successfully.")),!0}async function NU(n,e){let t=n.product||"default",r=B.discover(process.cwd()).rootDir;return await gC(r,e,t,n.type),console.warn(fC(`
1382
1382
  Release certificate materials generated successfully, but the release Profile (.p7b) cannot be auto-generated.
1383
1383
  Signing config (with encrypted p12 password) has been written to build-profile.json5.
1384
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:
@@ -1393,7 +1393,7 @@ Generated files:
1393
1393
  cer: ${e.cerFilePath}
1394
1394
 
1395
1395
  Signing config '${t}_release' written to ${kh.join(r,"build-profile.json5")}
1396
- `)),!1}async function MU(n){let e=B.discover(process.cwd()).rootDir,t=n.product||"default",r=await Gd(t,e,n.type),i=ki.existsSync(r.p12Path)&&ki.existsSync(r.csrPath)&&ki.existsSync(r.certPath),o=ki.existsSync(r.profilePath);return!i||o?!1:(console.warn(fC(`
1396
+ `)),!1}async function MU(n){let e=B.discover(process.cwd()).rootDir,t=n.product||"default",r=await qd(t,e,n.type),i=Di.existsSync(r.p12Path)&&Di.existsSync(r.csrPath)&&Di.existsSync(r.certPath),o=Di.existsSync(r.profilePath);return!i||o?!1:(console.warn(fC(`
1397
1397
  Release certificate materials already exist. Profile (.p7b) is still missing.
1398
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
1399
  1. Use the generated .csr file to apply for a release certificate
@@ -1405,17 +1405,17 @@ Existing files:
1405
1405
  p12: ${r.p12Path}
1406
1406
  csr: ${r.csrPath}
1407
1407
  cer: ${r.certPath}
1408
- `)),!0)}function LU(n,e,t,r){let i=process.cwd(),o=B.discover(i),s=eu(o,r);return dC(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 yC=new kU("signature").description("Generate application signature.");yC.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 TU(n)}catch(o){r=!1,i=X(o),console.error(DU(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await R.track(e,o)}});var wC=yC;import{Command as GU}from"commander";import{green as qU,red as Mh}from"colorette";import Wo from"fs";import du from"path";import zU from"ora";import cu from"fs";import Dh from"path";import{homedir as _U}from"os";function vC(){let n=process.env.DEVECO_CLI_DATA_DIR?F():Dh.join(_U(),be.CONFIG_DIR_NAME,be.APP_NAME);return Dh.join(n,"ui_verification_config.json")}function bC(){let n=vC();if(!cu.existsSync(n))return{};try{let e=JSON.parse(cu.readFileSync(n,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Rh(){let n=bC();if(Object.keys(n).length===0)return null;let e;if(cf(n.encryptedApiKey))try{e=af(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 xh(n){let e=vC();cu.mkdirSync(Dh.dirname(e),{recursive:!0,mode:448});let t=bC();return n.baseUrl!==void 0&&(t.baseUrl=n.baseUrl),n.modelName!==void 0&&(t.modelName=n.modelName),n.apiKey!==void 0&&(t.encryptedApiKey=sf(n.apiKey),delete t.apiKey),cu.writeFileSync(e,JSON.stringify(t,null,2),{encoding:"utf8",mode:384}),e}import lu from"fs";import $U from"os";import SC from"path";var Di=SC.join($U.tmpdir(),"ui-verification","cache"),FU=15;function Ih(n=Di,e=FU){if(!lu.existsSync(n))return;let t=lu.readdirSync(n,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>{let i=SC.join(n,r.name);return{entryPath:i,mtime:lu.statSync(i).mtimeMs}}).sort((r,i)=>r.mtime-i.mtime);for(let r of t.slice(0,Math.max(0,t.length-e)))lu.rmSync(r.entryPath,{recursive:!0,force:!0})}import{execFile as jU,spawn as HU}from"child_process";import UU from"fs";import Ah from"path";import{fileURLToPath as BU}from"url";function WU(){let n=Ah.dirname(BU(import.meta.url));for(;;){let e=Ah.join(n,"node_modules","ui-verification-mcp","bin","ui-verification-mcp.cjs");if(UU.existsSync(e))return e;let t=Ah.dirname(n);if(t===n)break;n=t}throw new Error("ui-verification-mcp is not installed. Run `npm install` and try again.")}var Ra=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(`
1408
+ `)),!0)}function LU(n,e,t,r){let i=process.cwd(),o=B.discover(i),s=tu(o,r);return dC(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 yC=new kU("signature").description("Generate application signature.");yC.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 TU(n)}catch(o){r=!1,i=X(o),console.error(DU(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await D.track(e,o)}});var wC=yC;import{Command as GU}from"commander";import{green as qU,red as Mh}from"colorette";import Vo from"fs";import uu from"path";import zU from"ora";import lu from"fs";import Dh from"path";import{homedir as _U}from"os";function vC(){let n=process.env.DEVECO_CLI_DATA_DIR?F():Dh.join(_U(),be.CONFIG_DIR_NAME,be.APP_NAME);return Dh.join(n,"ui_verification_config.json")}function bC(){let n=vC();if(!lu.existsSync(n))return{};try{let e=JSON.parse(lu.readFileSync(n,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Rh(){let n=bC();if(Object.keys(n).length===0)return null;let e;if(cf(n.encryptedApiKey))try{e=af(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 xh(n){let e=vC();lu.mkdirSync(Dh.dirname(e),{recursive:!0,mode:448});let t=bC();return n.baseUrl!==void 0&&(t.baseUrl=n.baseUrl),n.modelName!==void 0&&(t.modelName=n.modelName),n.apiKey!==void 0&&(t.encryptedApiKey=sf(n.apiKey),delete t.apiKey),lu.writeFileSync(e,JSON.stringify(t,null,2),{encoding:"utf8",mode:384}),e}import du from"fs";import $U from"os";import SC from"path";var Ri=SC.join($U.tmpdir(),"ui-verification","cache"),FU=15;function Ah(n=Ri,e=FU){if(!du.existsSync(n))return;let t=du.readdirSync(n,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>{let i=SC.join(n,r.name);return{entryPath:i,mtime:du.statSync(i).mtimeMs}}).sort((r,i)=>r.mtime-i.mtime);for(let r of t.slice(0,Math.max(0,t.length-e)))du.rmSync(r.entryPath,{recursive:!0,force:!0})}import{execFile as jU,spawn as HU}from"child_process";import UU from"fs";import Ih from"path";import{fileURLToPath as BU}from"url";function WU(){let n=Ih.dirname(BU(import.meta.url));for(;;){let e=Ih.join(n,"node_modules","ui-verification-mcp","bin","ui-verification-mcp.cjs");if(UU.existsSync(e))return e;let t=Ih.dirname(n);if(t===n)break;n=t}throw new Error("ui-verification-mcp is not installed. Run `npm install` and try again.")}var Aa=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
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=WU();m(`Executing: ${process.execPath} ${r}`);let i=HU(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=>jU("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 EC from"fs";import Nh from"path";async function Oh(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:
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=WU();m(`Executing: ${process.execPath} ${r}`);let i=HU(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=>jU("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 EC from"fs";import Nh from"path";async function Oh(n,e){let t=await new le(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
1411
  ${Th(i)}`):new Error(`Device '${e}' not found.
1412
1412
  Available devices:
1413
1413
  ${Th(t)}`)}if(t.length===1)return t[0].id;throw new Error(`Multiple devices connected. Use --device <name|serial> to specify one.
1414
1414
  Available devices:
1415
1415
  ${Th(t)}`)}function Th(n){return n.map(e=>` - ${e.name} (${e.id})`).join(`
1416
- `)}var Ln=class extends Error{exitCode;constructor(e){super("Verification cancelled by user"),this.exitCode=e==="SIGINT"?130:143}};var VU=600*1e3,xa=class{async verifyUi(e,t,r){let i=this.resolveBundleName(e.bundleName),o=await P.new(),s=await Oh(o,e.device),a=new AbortController,c=()=>a.abort(new Ln("SIGINT")),l=()=>a.abort(new Ln("SIGTERM"));process.on("SIGINT",c),process.on("SIGTERM",l);let d;try{d=await this.startSession(t,o.hdcPath,a.signal);let h=await d.callTool("verifyUI",{testPlan:e.testPlan,bundleName:i,freshStart:e.freshStart,device:s},r,VU),w=this.parseVerifyResult(h);return await this.cacheArtifacts(d,w.id,a.signal),a.signal.throwIfAborted(),Ih(),w}finally{try{await d?.close()}finally{process.off("SIGINT",c),process.off("SIGTERM",l)}}}startSession(e,t,r){return Ra.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=Nh.join(Di,t),o=Nh.join(i,"screenshots");EC.mkdirSync(o,{recursive:!0});try{let s=await e.callTool("getLog",{id:t,maxLogSize:-1});EC.writeFileSync(Nh.join(i,"verify.log"),String(s),"utf8")}catch{r.throwIfAborted()}try{await e.callTool("saveScreenshot",{id:t,dirname:o})}catch{r.throwIfAborted()}}};var PC=3e3;function JU(){let n=Rh();return!n?.baseUrl||!n.modelName||!n.apiKey?null:{baseUrl:n.baseUrl,modelName:n.modelName,apiKey:n.apiKey}}function YU(){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(Mh(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 KU(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>PC)throw new Error(`--test-plan must not exceed ${PC} characters`);return r}async function XU(n,e){let t=KU(n,e),r=JU();if(!r){YU();return}let i=zU({text:"Verifying UI\u2026",color:"cyan",discardStdin:!1}).start();try{let o=await new xa().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(qU("Verification passed")):(i.fail(Mh("Verification failed")),process.exitCode=1),console.log(JSON.stringify(o,null,2))}catch(o){i.fail(Mh(o instanceof Error?o.message:String(o))),process.exitCode=o instanceof Ln?o.exitCode:1}}function ZU(n){let e=du.join(Di,n.id,"verify.log");if(!Wo.existsSync(e))throw new Error(`No log found for ID: ${n.id}`);let t=Wo.readFileSync(e,"utf8");if(n.searchKeywords&&(t=t.split(`
1416
+ `)}var $n=class extends Error{exitCode;constructor(e){super("Verification cancelled by user"),this.exitCode=e==="SIGINT"?130:143}};var VU=600*1e3,Ia=class{async verifyUi(e,t,r){let i=this.resolveBundleName(e.bundleName),o=await P.new(),s=await Oh(o,e.device),a=new AbortController,c=()=>a.abort(new $n("SIGINT")),l=()=>a.abort(new $n("SIGTERM"));process.on("SIGINT",c),process.on("SIGTERM",l);let d;try{d=await this.startSession(t,o.hdcPath,a.signal);let h=await d.callTool("verifyUI",{testPlan:e.testPlan,bundleName:i,freshStart:e.freshStart,device:s},r,VU),w=this.parseVerifyResult(h);return await this.cacheArtifacts(d,w.id,a.signal),a.signal.throwIfAborted(),Ah(),w}finally{try{await d?.close()}finally{process.off("SIGINT",c),process.off("SIGTERM",l)}}}startSession(e,t,r){return Aa.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=Nh.join(Ri,t),o=Nh.join(i,"screenshots");EC.mkdirSync(o,{recursive:!0});try{let s=await e.callTool("getLog",{id:t,maxLogSize:-1});EC.writeFileSync(Nh.join(i,"verify.log"),String(s),"utf8")}catch{r.throwIfAborted()}try{await e.callTool("saveScreenshot",{id:t,dirname:o})}catch{r.throwIfAborted()}}};var PC=3e3;function JU(){let n=Rh();return!n?.baseUrl||!n.modelName||!n.apiKey?null:{baseUrl:n.baseUrl,modelName:n.modelName,apiKey:n.apiKey}}function YU(){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(Mh(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 KU(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>PC)throw new Error(`--test-plan must not exceed ${PC} characters`);return r}async function XU(n,e){let t=KU(n,e),r=JU();if(!r){YU();return}let i=zU({text:"Verifying UI\u2026",color:"cyan",discardStdin:!1}).start();try{let o=await new Ia().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(qU("Verification passed")):(i.fail(Mh("Verification failed")),process.exitCode=1),console.log(JSON.stringify(o,null,2))}catch(o){i.fail(Mh(o instanceof Error?o.message:String(o))),process.exitCode=o instanceof $n?o.exitCode:1}}function ZU(n){let e=uu.join(Ri,n.id,"verify.log");if(!Vo.existsSync(e))throw new Error(`No log found for ID: ${n.id}`);let t=Vo.readFileSync(e,"utf8");if(n.searchKeywords&&(t=t.split(`
1417
1417
  `).filter(i=>i.includes(n.searchKeywords)).map(i=>`${i}
1418
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 QU(n){let e=du.join(Di,n.id,"screenshots");if(!Wo.existsSync(e))throw new Error(`No screenshots found for ID: ${n.id}`);Wo.mkdirSync(n.savePath,{recursive:!0});let t=Wo.readdirSync(e).map(r=>{let i=du.join(n.savePath,r);return Wo.copyFileSync(du.join(e,r),i),i});console.log(JSON.stringify({filenames:t,message:"Screenshots saved successfully"},null,2))}var uu=new GU("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(XU);uu.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=xh(n);console.log(`UI verification config saved to ${e}`)});uu.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(ZU);uu.command("screenshot").description("Save verification screenshots by ID").requiredOption("--id <id>","Verification task ID").requiredOption("--save-path <path>","Absolute path to save screenshots").action(QU);var CC=uu;if(!Xe())try{R.init(pu.join(F(),"TraceLogData")),R.startScheduler()}catch(n){g.error(`[telemetry] init failed: ${n instanceof Error?n.message:String(n)}`)}(async()=>{if(!Xe())try{let n=await P.new();R.setSourceType(n.sourceType);let e=n.readVersion();e&&(n.sourceType==="clt"?R.setCltVersion(e):R.setStudioVersion(e))}catch(n){g.error(`[telemetry] toolchain info failed: ${n instanceof Error?n.message:String(n)}`)}})();se.name("devecocli").description(`HarmonyOS application development command line tool
1419
+ ${t.slice(-r)}`),console.log(t)}function QU(n){let e=uu.join(Ri,n.id,"screenshots");if(!Vo.existsSync(e))throw new Error(`No screenshots found for ID: ${n.id}`);Vo.mkdirSync(n.savePath,{recursive:!0});let t=Vo.readdirSync(e).map(r=>{let i=uu.join(n.savePath,r);return Vo.copyFileSync(uu.join(e,r),i),i});console.log(JSON.stringify({filenames:t,message:"Screenshots saved successfully"},null,2))}var pu=new GU("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(XU);pu.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=xh(n);console.log(`UI verification config saved to ${e}`)});pu.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(ZU);pu.command("screenshot").description("Save verification screenshots by ID").requiredOption("--id <id>","Verification task ID").requiredOption("--save-path <path>","Absolute path to save screenshots").action(QU);var CC=pu;if(!Xe())try{D.init(mu.join(F(),"TraceLogData")),D.startScheduler()}catch(n){g.error(`[telemetry] init failed: ${n instanceof Error?n.message:String(n)}`)}(async()=>{if(!Xe())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){g.error(`[telemetry] toolchain info failed: ${n instanceof Error?n.message:String(n)}`)}})();oe.name("devecocli").description(`HarmonyOS application development command line tool
1420
1420
 
1421
- Privacy: ${Go.PRIVACY_URL}`).version("1.3.7");var kC=se.options.find(n=>n.long==="--version");kC&&(kC.flags="-V, -v, --version");se.addCommand(By);se.addCommand(Rv);se.addCommand(Ov);se.addCommand(Eb);se.addCommand(Jb);se.addCommand(yS);se.addCommand(ES);se.addCommand(kS);se.addCommand($S);se.addCommand(US);se.addCommand(wE);se.addCommand(CE);se.addCommand(JE);se.addCommand(AP);se.addCommand(wC);se.addCommand(CC);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 Lh=process.argv.slice(2);Lh.length>=2&&Lh[Lh.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);function t1(n){let e=n;for(;e.parent&&e.parent!==se;)e=e.parent;return e}var r1=new Set(["update","auth","serve"]);se.hook("preAction",async(n,e)=>{await ey().catch(()=>{});let t=t1(e),r=Ni();if(t.name()==="update"||t.name()==="docs"&&e.name()==="update")return;let i=new en(pu.join(F(),"update")),o=ir();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||r1.has(t.name())||await P.checkVersion()});function n1(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"||n1(e))return;await new os(e).checkAndNotify()});se.parseAsync(process.argv).finally(()=>{R.stopScheduler();try{Ru(pu.join(F(),"TraceLogData"))}catch(n){g.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(e1(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
1421
+ Privacy: ${qo.PRIVACY_URL}`).version("1.3.9");var kC=oe.options.find(n=>n.long==="--version");kC&&(kC.flags="-V, -v, --version");oe.addCommand(Vy);oe.addCommand(Rv);oe.addCommand(Ov);oe.addCommand(Eb);oe.addCommand(Jb);oe.addCommand(yS);oe.addCommand(ES);oe.addCommand(kS);oe.addCommand($S);oe.addCommand(US);oe.addCommand(wE);oe.addCommand(CE);oe.addCommand(JE);oe.addCommand(IP);oe.addCommand(wC);oe.addCommand(CC);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 Lh=process.argv.slice(2);Lh.length>=2&&Lh[Lh.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);function t1(n){let e=n;for(;e.parent&&e.parent!==oe;)e=e.parent;return e}var r1=new Set(["update","auth","serve"]);oe.hook("preAction",async(n,e)=>{await ey().catch(()=>{});let t=t1(e),r=Mi();if(t.name()==="update"||t.name()==="docs"&&e.name()==="update")return;let i=new rn(mu.join(F(),"update")),o=or();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||r1.has(t.name())||await P.checkVersion()});function n1(n){if(n.name()!=="status"||n.opts().format!=="json")return!1;let t=n.parent;for(;t&&t!==oe;){if(t.name()==="screenrecord")return!0;t=t.parent}return!1}oe.hook("postAction",async(n,e)=>{if(process.exitCode||Mi()!=="off"||n1(e))return;await new ss(e).checkAndNotify()});oe.parseAsync(process.argv).finally(()=>{D.stopScheduler();try{xu(mu.join(F(),"TraceLogData"))}catch(n){g.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(e1(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});