@yinsen/deveco-cli 1.3.1 → 1.3.3-Test.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,72 +1,95 @@
1
1
  #!/usr/bin/env node
2
- var Dg=Object.defineProperty;var Rg=(n,e)=>{for(var t in e)Dg(n,t,{get:e[t],enumerable:!0})};import*as ma from"path";import{program as ae}from"commander";import{red as MR}from"colorette";var Vr={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},Gi={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 ve={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"},G={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"},kn={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},qr={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"},Gr={baseUrl:G.LOGIN_URL,authUrl:G.AUTH_APPLY_PATH,tempTokenCheckUrl:G.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:G.JWT_TOKEN_CHECK_PATH,successRedirectUrl:G.LOGIN_SUCCESS_PATH,failedRedirectUrl:G.LOGIN_FAILED_PATH,logoutUrl:G.LOGOUT_PATH,agcTeamListUrl:G.AGC_TEAM_LIST_URL,appId:ve.APP_ID,timeout:Vr.LOGIN_TIMEOUT_MS,countryCode:"CN"};import{Command as mv}from"commander";import{green as Ha,red as iu,yellow as Ua}from"colorette";import J from"fs";import*as j from"path";import ht from"json5";import*as ha from"fs";import*as we from"path";function p(n){if(process.env.DEVECO_CLI_DEBUG){let e=typeof n=="function"?n():n;console.log(`[DEBUG] ${e}`)}}var S=class n{static ASCII_CONTROL_MAX=31;static ASCII_DELETE=127;static parsePositiveInteger(e,t="value"){let r=e.trim();if(!/^\d+$/.test(r))throw new Error(`${t} must be a positive integer`);let i=Number.parseInt(r,10);if(!Number.isInteger(i)||i<=0)throw new Error(`${t} must be a positive integer`);return i}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
3
- `)}static parseDurationToSeconds(e,t="value"){let i=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!i)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported).`);let o=i[1];if((i[2]??"s")==="s")return n.parsePositiveInteger(o,t);if(!/^\d+(?:\.\d)?$/.test(o))throw new Error(`${t} supports a maximum of 1 decimal place for minutes (e.g. 2.5m).`);let a=Number.parseFloat(o);if(!Number.isFinite(a)||a<=0)throw new Error(`${t} must be a positive duration.`);return Math.round(a*60)}static filterLogsByRelativeWindow(e,t,r,i=new Date){if(!t&&!r)return e;let[o,s]=n.resolveTimeBounds(t,r,i),a=e.split(/\r?\n/),c=[],l=!1;for(let d of a){let g=n.extractTimestampFromLogLine(d,i);g&&(l=n.isWithinBounds(g,o,s)),l&&c.push(d)}return c.join(`
4
- `)}static resolveTimeBounds(e,t,r){let i=e?new Date(r.getTime()-e*1e3):null,o=t?new Date(r.getTime()-t*1e3):null;return i&&o?i<o?[i,o]:[o,i]:i?[i,r]:o?[null,o]:[null,null]}static isWithinBounds(e,t,r){let i=e.getTime(),o=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(o!==null&&i<o||s!==null&&i>s)}static extractTimestampFromLogLine(e,t){let r=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!r)return null;let i=t.getFullYear(),o=Number.parseInt(r[1],10)-1,s=Number.parseInt(r[2],10),a=Number.parseInt(r[3],10),c=Number.parseInt(r[4],10),l=Number.parseInt(r[5],10),d=r[6]??"0",g=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),v=new Date(i,o,s,a,c,l,g);return v.getTime()>t.getTime()+1440*60*1e3&&v.setFullYear(i-1),v}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 p(`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(we.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=we.resolve(we.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=we.normalize(e),i=we.relative(r,t);if(i.split(we.sep)[0]===".."||we.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||we.isAbsolute(e)}static isPathContained(e,t){let r=we.resolve(t,e),i=we.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=ha.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=we.resolve(i,e),s;try{s=ha.realpathSync(o)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${o}`}}return n.isPathContained(s,i)}};import Cd from"crypto";import Ye from"fs";import Aa from"os";import Tn from"path";import xg from"https";var Zl={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var zi=class n{static ENDPOINT=Zl.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=xg.request({protocol:o.protocol,hostname:o.hostname,port:o.port||(o.protocol==="https:"?443:80),path:o.pathname+o.search,method:"POST",headers:t,timeout:i},l=>{let d=[];l.on("data",g=>d.push(g)),l.on("end",()=>{s({code:l.statusCode??0,body:Buffer.concat(d).toString("utf8")})})});c.on("timeout",()=>{c.destroy(new Error("request timeout"))}),c.on("error",a),c.write(r),c.end()})}};var Ql={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()},ga=class{constructor(e={}){this.config=e}config;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??Ql.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}},ed=new ga({namingStrategy:Ql.snakeCase,fieldNames:{}});import zr from"crypto";import Ji from"fs";import Lg from"path";var Yi="aes-256-gcm",Ng=12,Og="deveco-cli-trace-file",Mg="trace-file-secret",nd=32;function td(n){try{let e=Ji.readFileSync(n,"utf8").trim();return e&&Buffer.from(e,"base64").length===nd?e:null}catch{return null}}function rd(n){let e=Lg.join(n,Mg),t=td(e);if(t)return ya(t);let r=zr.randomBytes(nd).toString("base64");try{Ji.mkdirSync(n,{recursive:!0});try{Ji.writeFileSync(e,r,{flag:"wx"})}catch{let i=td(e);if(i)return ya(i);Ji.writeFileSync(e,r)}}catch{}return ya(r)}function ya(n){return zr.createHash("sha256").update(Og).update(n).digest()}function va(n,e){let t=zr.randomBytes(Ng),r=zr.createCipheriv(Yi,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o={version:1,algorithm:Yi,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:r.getAuthTag().toString("base64")};return JSON.stringify(o)}function id(n,e){let t;try{t=JSON.parse(n)}catch{return null}if(!_g(t))return n;try{let r=zr.createDecipheriv(Yi,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 _g(n){if(!n||typeof n!="object")return!1;let e=n;return e.version===1&&e.algorithm===Yi&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as F from"fs";import*as no from"path";import z from"fs";import*as Ki from"os";import*as M from"path";import jg from"json5";var wa="Huawei";var ad=3;function Xi(n){if(!z.existsSync(n)||!z.statSync(n).isDirectory())return!1;let e=z.existsSync(M.join(n,"build-profile.json5")),t=z.existsSync(M.join(n,"hvigorfile.js"))||z.existsSync(M.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=z.readFileSync(M.join(n,"build-profile.json5"),"utf-8");return jg.parse(r).app!==void 0}catch{return!1}}function ba(n,e,t){if(e>=t)return null;let r=Fg(n),i=$g(r);if(i)return i;for(let o of r){let s=ba(o,e+1,t);if(s)return s}return null}function Fg(n){try{let e=z.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(M.join(n,r.name));return t}catch{return[]}}function $g(n){for(let e of n)if(Xi(e))return e;return null}function Ct(n){if(!n||n.trim()==="")return null;let e=M.resolve(n),t;try{t=z.realpathSync(e)}catch{t=e}if(!z.existsSync(t))return null;if(Xi(t))return t;let r=t;for(let i=1;i<=3;i++){let o=M.dirname(r);if(o===r)break;if(Xi(o))return o;r=o}if(z.statSync(t).isDirectory()){let i=ba(t,0,ad);if(i)return i}return null}function Zi(n){if(!n||n.trim()==="")return null;let e=M.resolve(n),t;try{t=z.realpathSync(e)}catch{t=e}return!z.existsSync(t)||!z.statSync(t).isDirectory()?null:Xi(t)?t:ba(t,0,ad)}var od="DevEco Studio";function cd(){if(process.platform==="win32"){let n=[M.join("C:\\Program Files",wa,od),M.join("C:\\Program Files (x86)",wa,od)];return sd(n)}if(process.platform==="darwin"){let n=["/Applications/DevEco Studio.app",M.join(process.env.HOME??"","Applications","DevEco Studio.app")];return sd(n)}return null}function sd(n){for(let e of n)if(z.existsSync(e))return e;return null}function Jr(n,e){let t=e?M.join("standardIndex","index.js"):"index.js";return z.existsSync(M.join(n,"ace-server"))?M.join(n,"ace-server","out",t):M.join(n,"out",t)}function Qi(n){return z.existsSync(Jr(n,!0))}var Hg=[".idea",".deveco","cxx","compile_commands.json"];function In(n){return M.join(n,...Hg)}function ld(n){return new Promise(e=>setTimeout(e,n))}var Ug=new Set(["c","cc","cpp","cxx","h","hh","hpp","hxx"]);function An(n){let e=M.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&Ug.has(e)}function eo(n){return M.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function fe(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function Wg(n){return fe(n)}function Dn(n){let e=Wg(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function Wt(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??M.join(Ki.homedir(),"AppData","Local");return M.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?M.join(Ki.homedir(),"Library","Logs","devecocli-mcp-server"):M.join(Ki.homedir(),".local","share","devecocli-mcp-server","logs")}function dd(n,e){let t=Bg(e),r=Vg(t,n);if(r!==null)return r;let i=Date.now(),s=`${n.replace(/:/g,"\\:")}=${i}`,a=qg(t,n,s);return Gg(e,a),i}function Bg(n){let e;try{e=z.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function Vg(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 qg(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 Gg(n,e){try{z.mkdirSync(M.dirname(n),{recursive:!0})}catch{}try{z.writeFileSync(n,e.join(`
2
+ var ky=Object.defineProperty;var Iy=(n,e)=>{for(var t in e)ky(n,t,{get:e[t],enumerable:!0})};import*as Na from"path";import{program as le}from"commander";import{red as ix}from"colorette";var Zn={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},li={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"},Y={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"},xr={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},Qn={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"},eo={baseUrl:Y.LOGIN_URL,authUrl:Y.AUTH_APPLY_PATH,tempTokenCheckUrl:Y.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:Y.JWT_TOKEN_CHECK_PATH,successRedirectUrl:Y.LOGIN_SUCCESS_PATH,failedRedirectUrl:Y.LOGIN_FAILED_PATH,logoutUrl:Y.LOGOUT_PATH,agcTeamListUrl:Y.AGC_TEAM_LIST_URL,appId:be.APP_ID,timeout:Zn.LOGIN_TIMEOUT_MS,countryCode:"CN"};import{Command as dw}from"commander";import{green as cc,red as _u,yellow as lc}from"colorette";import X from"fs";import*as j from"path";import Pt from"json5";import*as _a from"fs";import*as Se from"path";function u(n){if(process.env.DEVECO_CLI_DEBUG){let e=typeof n=="function"?n():n;console.log(`[DEBUG] ${e}`)}}var S=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 o=Number.parseInt(r,10);if(!Number.isInteger(o)||o<=0)throw new Error(`${t} must be a positive integer`);return o}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
3
+ `)}static parseDurationToSeconds(e,t="value"){let o=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!o)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported).`);let i=o[1];if((o[2]??"s")==="s")return n.parsePositiveInteger(i,t);if(!/^\d+(?:\.\d)?$/.test(i))throw new Error(`${t} supports a maximum of 1 decimal place for minutes (e.g. 2.5m).`);let a=Number.parseFloat(i);if(!Number.isFinite(a)||a<=0)throw new Error(`${t} must be a positive duration.`);return Math.round(a*60)}static filterLogsByRelativeWindow(e,t,r,o=new Date){if(!t&&!r)return e;let[i,s]=n.resolveTimeBounds(t,r,o),a=e.split(/\r?\n/),c=[],l=!1;for(let d of a){let g=n.extractTimestampFromLogLine(d,o);g&&(l=n.isWithinBounds(g,i,s)),l&&c.push(d)}return c.join(`
4
+ `)}static resolveTimeBounds(e,t,r){let o=e?new Date(r.getTime()-e*1e3):null,i=t?new Date(r.getTime()-t*1e3):null;return o&&i?o<i?[o,i]:[i,o]:o?[o,r]:i?[null,i]:[null,null]}static isWithinBounds(e,t,r){let o=e.getTime(),i=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(i!==null&&o<i||s!==null&&o>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 o=t.getFullYear(),i=Number.parseInt(r[1],10)-1,s=Number.parseInt(r[2],10),a=Number.parseInt(r[3],10),c=Number.parseInt(r[4],10),l=Number.parseInt(r[5],10),d=r[6]??"0",g=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),v=new Date(o,i,s,a,c,l,g);return v.getTime()>t.getTime()+1440*60*1e3&&v.setFullYear(o-1),v}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 o=0;o<t.length;o++){let i=t[o];if(!r.test(i))throw new Error(`Segment "${i}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(o===0){if(!/^[a-zA-Z]/.test(i))throw new Error(`First segment "${i}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(i))throw new Error(`Segment "${i}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(i))throw new Error(`Segment "${i}" must end with a letter or digit.`)}}static assertModuleName(e){this.assertSafeName(e,"module name")}static assertAbilityName(e){this.assertSafeName(e,"ability name")}static assertSafeName(e,t){if(!/^[A-Za-z0-9_.]+$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(r=>{let o=r.charCodeAt(0);return o<=n.ASCII_CONTROL_MAX||o===n.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let r=`'${e.replace(/'/g,"'\\''")}'`;return u(`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(Se.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=Se.resolve(Se.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=Se.normalize(e),o=Se.relative(r,t);if(o.split(Se.sep)[0]===".."||Se.isAbsolute(o))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||Se.isAbsolute(e)}static isPathContained(e,t){let r=Se.resolve(t,e),o=Se.relative(t,r);return n.isPathEscaping(o)?{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 o;try{o=_a.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let i=Se.resolve(o,e),s;try{s=_a.realpathSync(i)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${i}`}}return n.isPathContained(s,o)}};import ru from"crypto";import tt from"fs";import Ja from"os";import _r from"path";import Dy from"https";var Td={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var di=class n{static ENDPOINT=Td.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:o}=await this.httpPost(n.ENDPOINT,r,Buffer.from(e,"utf8"),6e4);return n.isSuccess(o)}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,o){let i=new URL(e);return new Promise((s,a)=>{let c=Dy.request({protocol:i.protocol,hostname:i.hostname,port:i.port||(i.protocol==="https:"?443:80),path:i.pathname+i.search,method:"POST",headers:t,timeout:o},l=>{let d=[];l.on("data",g=>d.push(g)),l.on("end",()=>{s({code:l.statusCode??0,body:Buffer.concat(d).toString("utf8")})})});c.on("timeout",()=>{c.destroy(new Error("request timeout"))}),c.on("error",a),c.write(r),c.end()})}};var xd={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()},ja=class{constructor(e={}){this.config=e}config;serialize(e){let t=this.transform(e);return this.config.pretty?JSON.stringify(t,null,2):JSON.stringify(t)}toObject(e){return this.transform(e)}transform(e){if(e==null)return e;if(Array.isArray(e))return e.map(i=>this.transform(i));if(typeof e!="object")return e;let t=this.config.namingStrategy??xd.identity,r=this.config.fieldNames??{},o={};for(let[i,s]of Object.entries(e)){let a=r[i]??t(i);o[a]=this.transform(s)}return o}},Ld=new ja({namingStrategy:xd.snakeCase,fieldNames:{}});import to from"crypto";import ui from"fs";import Ry from"path";var pi="aes-256-gcm",Ty=12,xy="deveco-cli-trace-file",Ly="trace-file-secret",Md=32;function Nd(n){try{let e=ui.readFileSync(n,"utf8").trim();return e&&Buffer.from(e,"base64").length===Md?e:null}catch{return null}}function Od(n){let e=Ry.join(n,Ly),t=Nd(e);if(t)return Fa(t);let r=to.randomBytes(Md).toString("base64");try{ui.mkdirSync(n,{recursive:!0});try{ui.writeFileSync(e,r,{flag:"wx"})}catch{let o=Nd(e);if(o)return Fa(o);ui.writeFileSync(e,r)}}catch{}return Fa(r)}function Fa(n){return to.createHash("sha256").update(xy).update(n).digest()}function $a(n,e){let t=to.randomBytes(Ty),r=to.createCipheriv(pi,e,t),o=Buffer.concat([r.update(n,"utf8"),r.final()]),i={version:1,algorithm:pi,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:r.getAuthTag().toString("base64")};return JSON.stringify(i)}function _d(n,e){let t;try{t=JSON.parse(n)}catch{return null}if(!Ny(t))return n;try{let r=to.createDecipheriv(pi,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 Ny(n){if(!n||typeof n!="object")return!1;let e=n;return e.version===1&&e.algorithm===pi&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as F from"fs";import*as wi from"path";import K from"fs";import*as mi from"os";import*as O from"path";import My from"json5";var Ha="Huawei";var $d=3;function fi(n){if(!K.existsSync(n)||!K.statSync(n).isDirectory())return!1;let e=K.existsSync(O.join(n,"build-profile.json5")),t=K.existsSync(O.join(n,"hvigorfile.js"))||K.existsSync(O.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=K.readFileSync(O.join(n,"build-profile.json5"),"utf-8");return My.parse(r).app!==void 0}catch{return!1}}function Ua(n,e,t){if(e>=t)return null;let r=Oy(n),o=_y(r);if(o)return o;for(let i of r){let s=Ua(i,e+1,t);if(s)return s}return null}function Oy(n){try{let e=K.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(O.join(n,r.name));return t}catch{return[]}}function _y(n){for(let e of n)if(fi(e))return e;return null}function Lt(n){if(!n||n.trim()==="")return null;let e=O.resolve(n),t;try{t=K.realpathSync(e)}catch{t=e}if(!K.existsSync(t))return null;if(fi(t))return t;let r=t;for(let o=1;o<=3;o++){let i=O.dirname(r);if(i===r)break;if(fi(i))return i;r=i}if(K.statSync(t).isDirectory()){let o=Ua(t,0,$d);if(o)return o}return null}function hi(n){if(!n||n.trim()==="")return null;let e=O.resolve(n),t;try{t=K.realpathSync(e)}catch{t=e}return!K.existsSync(t)||!K.statSync(t).isDirectory()?null:fi(t)?t:Ua(t,0,$d)}var jd="DevEco Studio";function Hd(){if(process.platform==="win32"){let n=[O.join("C:\\Program Files",Ha,jd),O.join("C:\\Program Files (x86)",Ha,jd)];return Fd(n)}if(process.platform==="darwin"){let n=["/Applications/DevEco Studio.app",O.join(process.env.HOME??"","Applications","DevEco Studio.app")];return Fd(n)}return null}function Fd(n){for(let e of n)if(K.existsSync(e))return e;return null}function ro(n,e){let t=e?O.join("standardIndex","index.js"):"index.js";return K.existsSync(O.join(n,"ace-server"))?O.join(n,"ace-server","out",t):O.join(n,"out",t)}function gi(n){return K.existsSync(ro(n,!0))}var jy=[".idea",".deveco","cxx","compile_commands.json"];function Lr(n){return O.join(n,...jy)}function Ud(n){return new Promise(e=>setTimeout(e,n))}var Fy=new Set(["c","cc","cpp","cxx","h","hh","hpp","hxx"]);function Nr(n){let e=O.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&Fy.has(e)}function yi(n){return O.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function ge(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function $y(n){return ge(n)}function Mr(n){let e=$y(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function Kt(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??O.join(mi.homedir(),"AppData","Local");return O.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?O.join(mi.homedir(),"Library","Logs","devecocli-mcp-server"):O.join(mi.homedir(),".local","share","devecocli-mcp-server","logs")}function Bd(n,e){let t=Hy(e),r=Uy(t,n);if(r!==null)return r;let o=Date.now(),s=`${n.replace(/:/g,"\\:")}=${o}`,a=By(t,n,s);return Wy(e,a),o}function Hy(n){let e;try{e=K.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function Uy(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let i=parseInt(t.slice(r+1),10);return Number.isFinite(i)&&i>0?i:null}return null}function By(n,e,t){let r=!1,o=n.map(i=>{if(r)return i;let s=i.indexOf("=");return s<=0?i:i.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):i});return r||o.push(t),o}function Wy(n,e){try{K.mkdirSync(O.dirname(n),{recursive:!0})}catch{}try{K.writeFileSync(n,e.join(`
5
5
  `)+`
6
- `,"utf8")}catch{}}function Sa(n,e,t="[Cleanup]"){try{let r=M.dirname(n);if(!z.existsSync(r))return;let i=Date.now();for(let o of z.readdirSync(r,{withFileTypes:!0}))o.isDirectory()&&zg(M.join(r,o.name),i,e,t)}catch{}}function zg(n,e,t,r){try{let{mtimeMs:i}=z.statSync(n);if(e-i<=t)return;z.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 ud="mcp-server.log",Jg="mcp-server",Yg={maxSize:10*1024*1024,maxFiles:4},Ea=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={...Yg,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Wt(),this.currentLogFile=no.join(this.logDir,ud),F.existsSync(this.logDir)||F.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 no.join(this.logDir,`${Jg}-${e}.log.${t}`)}fileExists(e){try{return F.accessSync(e,F.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=F.readdirSync(this.logDir),t=[];for(let i of e)if(i===ud||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=no.join(this.logDir,i),s=F.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{F.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)&&F.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)&&F.renameSync(o,s)}let r=this.getRotatedFileName(e,1);F.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=F.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=F.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{F.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...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()}] ${o}
7
- `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);F.writeSync(this.fd,c),this.checkRotation(c.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{F.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},Je=null;function Rn(n=!1){Je&&Je.dispose(),Je=new Ea(n)}function pd(){Je&&(Je.dispose(),Je=null)}function fd(){Je&&Je.flush()}function md(){return Je?.getLogFilePath()??null}function hd(){return Je?.getLogDirectory()??null}function to(){return Je||Rn(!1),Je}var h={debug:(n,...e)=>to().debug(n,...e),info:(n,...e)=>to().info(n,...e),warn:(n,...e)=>to().warn(n,...e),error:(n,...e)=>to().error(n,...e)};import Pa from"fs";import gd from"path";var Yr=300*1e3,Kr=3600*1e3,Ca=10080*60*1e3;function Bt(){let n=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return n==="1"||n==="true"}var Kg="upload-state.json";function yd(n){return gd.join(n,Kg)}function Xg(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function ro(n){try{let e=Pa.readFileSync(yd(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 Xg()}}function ka(n,e){try{Pa.writeFileSync(yd(n),JSON.stringify(e),"utf8")}catch{}}function vd(n){let e=ro(n);e.firstEventAt===null&&(e.firstEventAt=Date.now(),ka(n,e))}function wd(n){let e=ro(n);e.lastUploadAt=Date.now(),e.firstEventAt=null,ka(n,e)}function bd(n){let e=ro(n);e.lastRetryAt=Date.now(),ka(n,e)}function Ia(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 Zg(n,e=Date.now()){let t=gd.join(n,"failed"),r;try{r=Pa.readdirSync(t)}catch{return!1}for(let i of r){if(!i.startsWith("telemetry-")||!i.endsWith(".txt"))continue;let o=Ia(i);if(o!==null&&e-o<=Ca)return!0}return!1}function Sd(n,e=Date.now()){let t=ro(n);return!!(t.firstEventAt!==null&&e-t.firstEventAt>=Yr||Zg(n,e)&&(t.lastRetryAt===null||e-t.lastRetryAt>=Kr))}import Qg from"crypto";import io from"fs";import ey from"path";var ty="install-id";function ny(n){return ey.join(n,ty)}function Ed(n){try{let e=io.readFileSync(n,"utf8").trim();return ry(e)?e:null}catch{return null}}function ry(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 Pd(n){let e=ny(n),t=Ed(e);if(t)return t;let r=Qg.randomUUID();try{io.mkdirSync(n,{recursive:!0});try{io.writeFileSync(e,r,{flag:"wx"})}catch{let i=Ed(e);if(i)return i;io.writeFileSync(e,r)}}catch{}return r}var Xr=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 zi;storageDir="";failedDir="";installId="";disabled=Bt();traceFileKey=Buffer.alloc(0);sessionId=Cd.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){h.info(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=Tn.join(e,"failed"),this.cliVersion="1.3.1",this.nodeVersion=process.version,this.installId=Pd(e).replace(/-/g,""),this.traceFileKey=rd(e),Ye.mkdirSync(e,{recursive:!0}),Ye.mkdirSync(this.failedDir,{recursive:!0}),h.info(`[telemetry] init: dir=${e}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(e){this.devecoStudioVersion=e,h.info(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,h.info(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,h.info(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");if(!t){await this.record(e,0,!0,null);return}if(typeof t!="function"){let 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=va(JSON.stringify(o),this.traceFileKey);await Ye.promises.appendFile(this.currentFile(),s+`
8
- `,"utf8"),vd(this.storageDir)}catch{}}buildTraceEvent(e,t,r,i){let o=`${n.EVENT_PREFIX}${e.event}`,s=ed.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:Cd.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,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=Aa.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=Aa.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 Aa.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}formatVersion(e){return e?`${e}_${this.resolveOsSuffix()}`:""}dateString(){let e=new Date,t=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return`${e.getFullYear()}-${t}-${r}`}currentFile(){return Tn.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){h.info("[telemetry] scheduler not started (telemetry disabled)");return}h.info(`[telemetry] scheduler started (flush every ${Yr/1e3}s, retry failed every ${Kr/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},Yr)},Yr),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},Kr)},Kr)}stopScheduler(){this.initialTimer&&(clearTimeout(this.initialTimer),this.initialTimer=null),this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null),this.retryInitialTimer&&(clearTimeout(this.retryInitialTimer),this.retryInitialTimer=null),this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),h.info("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");let e=await this.listPendingFiles(),t=!0;for(let r of e)await this.flushFile(r)||(t=!1);return wd(this.storageDir),t}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");let e=Date.now(),t;try{t=await Ye.promises.readdir(this.failedDir)}catch{return!0}let r=t.filter(o=>o.startsWith("telemetry-")&&o.endsWith(".txt")).map(o=>Tn.join(this.failedDir,o)),i=!0;for(let o of r){let s=Tn.basename(o),a=Ia(s);if(a!==null){if(e-a>Ca){try{await Ye.promises.unlink(o)}catch{}continue}await this.flushFile(o)||(i=!1)}}return i||h.warn("[telemetry] retry failed"),bd(this.storageDir),i}runExclusive(e){let t=()=>e(),r=this.flushChain.then(t,t);return this.flushChain=r.then(()=>{},()=>{}),r}async listPendingFiles(){let e;try{e=await Ye.promises.readdir(this.storageDir)}catch{return[]}return e.filter(t=>t.startsWith("telemetry-")&&t.endsWith(".txt")).map(t=>Tn.join(this.storageDir,t)).sort()}async flushFile(e){let t=e+".pending";try{await Ye.promises.rename(e,t)}catch{return!1}let r;try{r=await Ye.promises.readFile(t,"utf8")}catch{return!1}let i=r.split(`
9
- `).map(s=>s.trim()).filter(Boolean),o=[];for(let s of i){let a=id(s,this.traceFileKey);a!==null&&o.push(a)}if(o.length===0){try{await Ye.promises.unlink(t)}catch{}return!0}return this.uploadInBatches(t,o)}async uploadInBatches(e,t){let r=0;for(;r<t.length;){let i=r,o=[],s=16;for(;r<t.length&&o.length<n.MAX_BATCH;){let d=t[r],g=Buffer.byteLength(d,"utf8")+1;if(o.length>0&&s+g>n.MAX_PAYLOAD_BYTES)break;o.push(d),s+=g,r++}let a=this.buildPayloadItems(o),c=JSON.stringify(a),l=!1;try{l=await this.uploader.upload(c,this.installId)}catch{}if(!l){h.warn("[telemetry] upload failed");let d=t.slice(i).join(`
6
+ `,"utf8")}catch{}}function Ba(n,e,t="[Cleanup]"){try{let r=O.dirname(n);if(!K.existsSync(r))return;let o=Date.now();for(let i of K.readdirSync(r,{withFileTypes:!0}))i.isDirectory()&&Vy(O.join(r,i.name),o,e,t)}catch{}}function Vy(n,e,t,r){try{let{mtimeMs:o}=K.statSync(n);if(e-o<=t)return;K.rmSync(n,{recursive:!0,force:!0});let i=Math.floor((e-o)/1e3);console.error(`${r} Removed expired dir (age ${Math.floor(i/86400)}d ${Math.floor(i%86400/3600)}h): ${n}`)}catch(o){console.error(`${r} Failed to remove expired dir ${n}: ${o}`)}}var Wd="mcp-server.log",qy="mcp-server",Gy={maxSize:10*1024*1024,maxFiles:4},Wa=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={...Gy,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Kt(),this.currentLogFile=wi.join(this.logDir,Wd),F.existsSync(this.logDir)||F.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"),o=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${o}`}getRotatedFileName(e,t){return wi.join(this.logDir,`${qy}-${e}.log.${t}`)}fileExists(e){try{return F.accessSync(e,F.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=F.readdirSync(this.logDir),t=[];for(let o of e)if(o===Wd||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(o)){let i=wi.join(this.logDir,o),s=F.statSync(i);t.push({name:o,mtime:s.mtime,path:i})}t.sort((o,i)=>i.mtime.getTime()-o.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let o=r;o<t.length;o++)try{F.unlinkSync(t[o].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&F.unlinkSync(t);for(let o=this.rotationOptions.maxFiles-1;o>=1;o--){let i=this.getRotatedFileName(e,o),s=this.getRotatedFileName(e,o+1);this.fileExists(i)&&F.renameSync(i,s)}let r=this.getRotatedFileName(e,1);F.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=F.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=F.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{F.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...r){if(this.mode==="silent"||n.LEVEL_ORDER[e]<n.LEVEL_ORDER[this.minLevel])return;let o=r.map(c=>c instanceof Error?`${c.name}: ${c.message}`:typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),i=o?`${t} ${o}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] ${i}
7
+ `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);F.writeSync(this.fd,c),this.checkRotation(c.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{F.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},et=null;function Or(n=!1){et&&et.dispose(),et=new Wa(n)}function Vd(){et&&(et.dispose(),et=null)}function qd(){et&&et.flush()}function Gd(){return et?.getLogFilePath()??null}function zd(){return et?.getLogDirectory()??null}function vi(){return et||Or(!1),et}var h={debug:(n,...e)=>vi().debug(n,...e),info:(n,...e)=>vi().info(n,...e),warn:(n,...e)=>vi().warn(n,...e),error:(n,...e)=>vi().error(n,...e)};import Va from"fs";import Jd from"path";var no=300*1e3,oo=3600*1e3,qa=10080*60*1e3;function Et(){let n=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return n==="1"||n==="true"}var zy="upload-state.json";function Yd(n){return Jd.join(n,zy)}function Jy(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function bi(n){try{let e=Va.readFileSync(Yd(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 Jy()}}function Ga(n,e){try{Va.writeFileSync(Yd(n),JSON.stringify(e),"utf8")}catch{}}function Kd(n){let e=bi(n);e.firstEventAt===null&&(e.firstEventAt=Date.now(),Ga(n,e))}function Xd(n){let e=bi(n);e.lastUploadAt=Date.now(),e.firstEventAt=null,Ga(n,e)}function Zd(n){let e=bi(n);e.lastRetryAt=Date.now(),Ga(n,e)}function za(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 Yy(n,e=Date.now()){let t=Jd.join(n,"failed"),r;try{r=Va.readdirSync(t)}catch{return!1}for(let o of r){if(!o.startsWith("telemetry-")||!o.endsWith(".txt"))continue;let i=za(o);if(i!==null&&e-i<=qa)return!0}return!1}function Qd(n,e=Date.now()){let t=bi(n);return!!(t.firstEventAt!==null&&e-t.firstEventAt>=no||Yy(n,e)&&(t.lastRetryAt===null||e-t.lastRetryAt>=oo))}import Ky from"crypto";import Si from"fs";import Xy from"path";var Zy="install-id";function Qy(n){return Xy.join(n,Zy)}function eu(n){try{let e=Si.readFileSync(n,"utf8").trim();return ev(e)?e:null}catch{return null}}function ev(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 tu(n){let e=Qy(n),t=eu(e);if(t)return t;let r=Ky.randomUUID();try{Si.mkdirSync(n,{recursive:!0});try{Si.writeFileSync(e,r,{flag:"wx"})}catch{let o=eu(e);if(o)return o;Si.writeFileSync(e,r)}}catch{}return r}var io=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 di;storageDir="";failedDir="";installId="";disabled=Et();traceFileKey=Buffer.alloc(0);sessionId=ru.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){h.info(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=_r.join(e,"failed"),this.cliVersion="1.3.3-Test.2",this.nodeVersion=process.version,this.installId=tu(e).replace(/-/g,""),this.traceFileKey=Od(e),tt.mkdirSync(e,{recursive:!0}),tt.mkdirSync(this.failedDir,{recursive:!0}),h.info(`[telemetry] init: dir=${e}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(e){this.devecoStudioVersion=e,h.info(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,h.info(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,h.info(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");if(!t){await this.record(e,0,!0,null);return}if(typeof t!="function"){let i=t;await this.record(e,i.duration_ms,i.success,i.error_code);return}let r=t,o=Date.now();try{let i=await r(),s=Date.now()-o;return await this.record(e,s,!0,null),i}catch(i){let s=Date.now()-o,a=this.toErrorCode(i);throw await this.record(e,s,!1,a),i}}async record(e,t,r,o){let i=this.buildTraceEvent(e,t,r,o);try{let s=$a(JSON.stringify(i),this.traceFileKey);await tt.promises.appendFile(this.currentFile(),s+`
8
+ `,"utf8"),Kd(this.storageDir)}catch{}}buildTraceEvent(e,t,r,o){let i=`${n.EVENT_PREFIX}${e.event}`,s=Ld.toObject(e);return s&&typeof s=="object"&&delete s.event,{countryCode:n.COUNTRY_CODE,event:i,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:ru.randomUUID(),trace_os_version:n.TRACE_OS_VERSION,os_arch:this.resolveOsArch(),action:i,trace_os_name:this.resolveOsName(),version:`${this.cliVersion}_${this.resolveOsSuffix()}`,deveco_studio_version:this.formatVersion(this.devecoStudioVersion),command_line_version:this.formatVersion(this.cltVersion),source_type:this.sourceType,session_id:this.sessionId,node_version:this.nodeVersion,duration_ms:t,success:r,error_code:o,event_detail:s}}}toErrorCode(e){return e instanceof Error?e.code??e.name:"UnknownError"}resolveOsArch(){let e=Ja.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=Ja.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 Ja.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}formatVersion(e){return e?`${e}_${this.resolveOsSuffix()}`:""}dateString(){let e=new Date,t=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return`${e.getFullYear()}-${t}-${r}`}currentFile(){return _r.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){h.info("[telemetry] scheduler not started (telemetry disabled)");return}h.info(`[telemetry] scheduler started (flush every ${no/1e3}s, retry failed every ${oo/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},no)},no),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},oo)},oo)}stopScheduler(){this.initialTimer&&(clearTimeout(this.initialTimer),this.initialTimer=null),this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null),this.retryInitialTimer&&(clearTimeout(this.retryInitialTimer),this.retryInitialTimer=null),this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),h.info("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");let e=await this.listPendingFiles(),t=!0;for(let r of e)await this.flushFile(r)||(t=!1);return Xd(this.storageDir),t}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");let e=Date.now(),t;try{t=await tt.promises.readdir(this.failedDir)}catch{return!0}let r=t.filter(i=>i.startsWith("telemetry-")&&i.endsWith(".txt")).map(i=>_r.join(this.failedDir,i)),o=!0;for(let i of r){let s=_r.basename(i),a=za(s);if(a!==null){if(e-a>qa){try{await tt.promises.unlink(i)}catch{}continue}await this.flushFile(i)||(o=!1)}}return o||h.warn("[telemetry] retry failed"),Zd(this.storageDir),o}runExclusive(e){let t=()=>e(),r=this.flushChain.then(t,t);return this.flushChain=r.then(()=>{},()=>{}),r}async listPendingFiles(){let e;try{e=await tt.promises.readdir(this.storageDir)}catch{return[]}return e.filter(t=>t.startsWith("telemetry-")&&t.endsWith(".txt")).map(t=>_r.join(this.storageDir,t)).sort()}async flushFile(e){let t=e+".pending";try{await tt.promises.rename(e,t)}catch{return!1}let r;try{r=await tt.promises.readFile(t,"utf8")}catch{return!1}let o=r.split(`
9
+ `).map(s=>s.trim()).filter(Boolean),i=[];for(let s of o){let a=_d(s,this.traceFileKey);a!==null&&i.push(a)}if(i.length===0){try{await tt.promises.unlink(t)}catch{}return!0}return this.uploadInBatches(t,i)}async uploadInBatches(e,t){let r=0;for(;r<t.length;){let o=r,i=[],s=16;for(;r<t.length&&i.length<n.MAX_BATCH;){let d=t[r],g=Buffer.byteLength(d,"utf8")+1;if(i.length>0&&s+g>n.MAX_PAYLOAD_BYTES)break;i.push(d),s+=g,r++}let a=this.buildPayloadItems(i),c=JSON.stringify(a),l=!1;try{l=await this.uploader.upload(c,this.installId)}catch{}if(!l){h.warn("[telemetry] upload failed");let d=t.slice(o).join(`
10
10
  `)+`
11
- `;return await this.moveToFailed(e,d),!1}}try{await Ye.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=Tn.basename(e,".pending"),i=Tn.join(this.failedDir,r);try{let o=t.split(`
12
- `).filter(Boolean).map(s=>va(s,this.traceFileKey)).join(`
11
+ `;return await this.moveToFailed(e,d),!1}}try{await tt.promises.unlink(e)}catch{}return!0}buildPayloadItems(e){let t=[];for(let r of e)try{let o=JSON.parse(r);t.push({action:o.event,detail:JSON.stringify(o.properties),timestamp:Number(o.eventtime)||Date.now()})}catch{}return t}async moveToFailed(e,t){let r=_r.basename(e,".pending"),o=_r.join(this.failedDir,r);try{let i=t.split(`
12
+ `).filter(Boolean).map(s=>$a(s,this.traceFileKey)).join(`
13
13
  `)+`
14
- `;await Ye.promises.appendFile(i,o,"utf8")}catch{return}try{await Ye.promises.unlink(e)}catch{}}};var I=new Xr;import{spawn as iy}from"child_process";import{existsSync as oy}from"fs";import{dirname as sy,join as ay}from"path";import{fileURLToPath as cy}from"url";function ly(){let n=sy(cy(import.meta.url)),e=ay(n,"internal","telemetry-upload-background.js");return oy(e)?e:null}function Da(n){if(Bt()||!Sd(n))return;let e=ly();if(!e){h.warn("[telemetry] background upload script not found, skipping spawn");return}try{iy(process.execPath,[e],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1",DEVECO_CLI_TELEMETRY_UPLOAD:"1"}}).unref()}catch(t){h.warn("[telemetry] failed to spawn background upload:",t)}}var w=class extends Error{traceMessage;constructor(e,t,r){super(e,r),this.name="TraceError",this.traceMessage=t??e}};function B(n){if(n instanceof w)return n.traceMessage;if(n instanceof Error){let e=n.code;return typeof e=="string"&&e!==""?e:n.name}return"UnknownError"}var b={CommandExecuted:"Command_executed",McpToolCall:"serve_mcp",SkillOperation:"skills",Init:"mcp_config_operation",SkillConfigOperation:"skill_config_operation",DocOperation:"docs",ServeLsp:"serve_lsp",CheckCommand:"check"};var Ce={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json",LOCK_JSON5_PATH:"oh_modules/.ohpm/lock.json5"};var Y=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(!J.existsSync(t))return null;try{let r=J.readFileSync(t,"utf-8"),i=ht.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 w(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=S.resolvePathWithinRoot(this.rootDir,t.srcPath),i=j.join(r,"src","main","module.json5");if(!J.existsSync(i))return"entry";try{let o=J.readFileSync(i,"utf-8");return ht.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 w(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=S.resolvePathWithinRoot(this.rootDir,t.srcPath),i=j.join(r,"build-profile.json5");if(!J.existsSync(i))throw new w(`Build profile for module '${e}' not found at ${i}.`,"Build profile for module not found at ${profilePath}.");try{let o=J.readFileSync(i,"utf-8");return ht.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(J.existsSync(t))try{let r=J.readFileSync(t,"utf-8"),i=ht.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(!J.existsSync(e))return!1;try{let t=J.readFileSync(e,"utf-8");return ht.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=S.resolvePathWithinRoot(this.rootDir,r.srcPath),o=j.join(i,"src","main","module.json5");if(!J.existsSync(o))return"EntryAbility";try{let s=J.readFileSync(o,"utf-8"),c=ht.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 w(`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 w(`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,Ce.LOCK_JSON5_PATH);if(!J.existsSync(t))return null;let r;try{r=ht.parse(J.readFileSync(t,"utf-8"))}catch(d){return p(`Failed to parse lock.json5: ${d instanceof Error?d.message:String(d)}`),null}let i=r,o=i?.modules;if(!o||typeof o!="object")return null;let s=Object.values(o).find(d=>typeof d=="object"&&d!==null&&d.name===e);if(!s)return null;let a=this.buildOverrideMap(i.overrides),c=[],l=new Set;for(let d of["dependencies","dynamicDependencies"]){let g=s[d];!g||typeof g!="object"||this.collectLocalDeps(g,a,v=>this.resolveLockDepByVersion(v),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=S.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(S.resolvePathWithinRoot(this.rootDir,e.srcPath),Ce.OH_PACKAGE_JSON5);if(!J.existsSync(t))return[];let r=this.readRootOverrideMap(),i=[],o=new Set;try{let s=ht.parse(J.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){p(`Failed to get module dependencies: ${s instanceof Error?s.message:String(s)}`)}return i}readRootOverrideMap(){let e=j.join(this.rootDir,Ce.OH_PACKAGE_JSON5);if(!J.existsSync(e))return null;try{let t=ht.parse(J.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=S.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 w(`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(!J.existsSync(a))throw new w(`Build metadata not found for module '${e}' at ${a}. Build the project first.`,"Build metadata not found for module. Build the project first.");let c=this.parseOutputMetadata(a,s);return{moduleNode: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 g=s?"-signed.hsp":"-signed.hap";if(!r&&!d.endsWith(g))throw new w(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`,"Target device is a real device, but the artifact is not signed.");let v=this.buildOutputPath(o.srcPath,i,["outputs",t,d]);if(!J.existsSync(v))throw new w(`Generated package file not found in ${v}.`,"Generated package file not found.");return v}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(!J.existsSync(l))throw new w(`Remote HSP dependency not found: ${l}`,"Remote HSP dependency not found.");s.push(l)}return s}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 J.existsSync(s)?o:null}buildOutputPath(e,t,r){let i=S.resolvePathWithinRoot(this.rootDir,e),o=j.resolve(i,"build",t,...r);return S.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=J.readFileSync(e,"utf-8");r=ht.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 w(`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 w(`Invalid traversal name: '${e}'. It must contain path characters.`,"Invalid traversal name.");if(!t.endsWith(".hap")&&!t.endsWith(".hsp"))throw new w(`Invalid package name '${t}'.It must be a .hap or .hsp file.`,"Invalid package name.")}};import ke from"fs";import*as We from"os";import*as P from"path";import so from"fs";import*as ao from"os";import*as Zr from"path";import fy from"regedit";import{execFileSync as uy}from"child_process";import Id from"fs";import*as Ad from"os";import*as Ra from"path";import{compare as dy}from"semver";function kd(n,e){return dy(n,e)}function Zn(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 oo(n,e){let t=Ra.join(n,"Contents","Info.plist");if(!Id.existsSync(t)){p(`[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=uy(r,i,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(o&&!o.includes("Does Not Exist"))return o}catch{}}function py(n){let e=oo(n,"CFBundleShortVersionString");if(!e)return oo(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[oo(n,"CFBundleVersion"),oo(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 Vt(n){if(Ad.platform()==="darwin")return py(n);let e=Ra.join(n,"product-info.json");try{let t=JSON.parse(Id.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}var my="DevEco Studio",hy=["Contents","Resources","product-info.json"],gy="name";function yy(n){return n.filter(e=>{try{return so.statSync(e).isDirectory()}catch{return!1}})}function vy(n){let e=Zr.join(n,...hy);if(so.existsSync(e))try{let r=JSON.parse(so.readFileSync(e,"utf8"))[gy];return typeof r=="string"&&r.trim()?r.trim():void 0}catch{return}}function wy(n){return vy(n)===my}function by(){let n=[];for(let e of[Zr.join(ao.homedir(),"Applications"),"/Applications"])try{n.push(...so.readdirSync(e).filter(t=>t.endsWith(".app")).map(t=>Zr.join(e,t)).filter(wy))}catch{}return n}function Dd(n){return new Promise((e,t)=>fy.list(n,(r,i)=>r?t(r):e(i)))}async function Rd(n,e,t){let i=((await Dd([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(i.length===0)return[];let o=await Dd(i);return i.flatMap(s=>{let a=o[s]?.values?.[t]?.value;return a?[a]:[]})}async function Sy(){let n=[Zr.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 Rd(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 Rd(e,()=>!0,""))}catch{}return n}async function Td(){let n=ao.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"?by():await Sy(),t=yy(e).flatMap(r=>{let i=Vt(r);return i?(p(`[ToolProvider] ${r} => version ${i}`),[{root:r,version:i}]):(p(`[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)=>Zn(i.version,r.version)>0?i:r)}import*as xd from"fs";import*as xe from"path";function Ey(n,e){let t=xe.relative(e,n);return t===""||!xe.isAbsolute(t)&&!t.startsWith(`..${xe.sep}`)&&t!==".."}function qt(n){let e=xe.resolve(n),t=[],r=e;for(;;)try{let i=xd.realpathSync(r);return t.length===0?i:xe.join(i,...t.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=xe.dirname(r);if(o===r)return e;t.push(xe.basename(r)),r=o}}function Ld(n,e){let t=qt(e),r=qt(n);return Ey(r,t)?r:null}function Ta(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function co(n){let e=Ta(n);if(!e)throw new Error("Path must not be empty.");return qt(e)}var xa="https://matrix.openharmony.cn",Ke={TAGS_API_URL:`${xa}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${xa}/api/registry/skill/skills`,SKILL_API_BASE:`${xa}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,DEFAULT_MAX_PAGES:100,SUCCESS_CODE:"20000"},ct={"trae-cn":{path:".trae-cn/skills",displayName:"trae-cn"},opencode:{path:".config/opencode/skills",displayName:"opencode"},deveco:{path:".config/deveco/skills",displayName:"deveco"},cursor:{path:".cursor/skills",displayName:"cursor"},codebuddy:{path:".codebuddy/skills",displayName:"codebuddy"},qoder:{path:".qoder/skills",displayName:"qoder"},"claude-code":{path:".claude/skills",projectPath:".claude/skills",displayName:"claude-code"},codex:{path:".codex/skills",displayName:"codex"},atomcode:{path:".atomcode/skills",displayName:"atomcode"}};import{homedir as kt}from"os";import Ue from"path";var gt="deveco-mcp";var Gt={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:Ue.join(kt(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:Ue.join(process.platform==="win32"?Ue.join(process.env.APPDATA??Ue.join(kt(),"AppData","Roaming"),"Trae CN","User"):Ue.join(kt(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:Ue.join(kt(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:Ue.join(kt(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:Ue.join(process.platform==="win32"?Ue.join(process.env.APPDATA??Ue.join(kt(),"AppData","Roaming"),"Qoder","SharedClientCache"):Ue.join(kt(),"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:Ue.join(kt(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:Ue.join(kt(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function Od(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function Nd(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Md(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function lo(n,e){return n.format==="opencode"?Od(e):n.format==="claude-code"||n.format==="codex"?Nd(e):Md(e)}var La="https://developer.huawei.com/consumer/cn/download/";var Py=/^#\s*Version:\s*(\S+)/,Cy="26.0.0.810";function ky(n){try{let e=JSON.parse(ke.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch(e){p(`[ToolProvider] Failed to parse API level from ${n}: ${e instanceof Error?e.message:String(e)}`);return}}function Iy(n){let e=P.join(n,"default","openharmony");return[P.join(n,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>P.join(e,t,"oh-uni-package.json"))]}var A=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}_sourceType;_toolchainRoot;_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;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(ke.existsSync(t.marker))return t.root;return null}get clangdPath(){let e=n.buildToolPaths(this._toolchainRoot,this._sourceType).clangdPath;return ke.existsSync(e)?e:null}get javaPath(){return this._javaPath??""}get sdkPath(){return this._sdkPath}get hdcPath(){return this._hdcPath}get emulatorPath(){return this._emulatorPath}get emulatorLauncherPath(){return this.emulatorPath}assertJava(){if(this._sourceType==="clt"&&!this._javaPath&&(this._javaPath=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 Zn(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 getStudioVersion(){try{let e=await n.resolveInstallSource();return Vt(e.toolchainRoot)}catch{return}}static async getCltVersion(){try{let e=await n.resolveInstallSource();return n.readCltVersion(e.toolchainRoot)}catch{return}}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()}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(Vt(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 w(`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 w(`Invalid ${t} version "${e}" from ${r} at ${o}`,`Invalid ${t} version "${e}" from ${r}`);if(Zn(e,i)<0)throw new Error(`The detected ${t} version is ${e}, which is below the minimum required version ${i}. Upgrade before using deveco-cli:
15
- ${La}`)}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 w(`${a}
14
+ `;await tt.promises.appendFile(o,i,"utf8")}catch{return}try{await tt.promises.unlink(e)}catch{}}};var I=new io;import{spawn as tv}from"child_process";import{existsSync as rv}from"fs";import{dirname as nv,join as ov}from"path";import{fileURLToPath as iv}from"url";function sv(){let n=nv(iv(import.meta.url)),e=ov(n,"internal","telemetry-upload-background.js");return rv(e)?e:null}function Ya(n){if(Et()||!Qd(n))return;let e=sv();if(!e){h.warn("[telemetry] background upload script not found, skipping spawn");return}try{tv(process.execPath,[e],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1",DEVECO_CLI_TELEMETRY_UPLOAD:"1"}}).unref()}catch(t){h.warn("[telemetry] failed to spawn background upload:",t)}}var w=class extends Error{traceMessage;constructor(e,t,r){super(e,r),this.name="TraceError",this.traceMessage=t??e}};function G(n){if(n instanceof w)return n.traceMessage;if(n instanceof Error){let e=n.code;return typeof e=="string"&&e!==""?e:n.name}return"UnknownError"}var b={CommandExecuted:"Command_executed",McpToolCall:"serve_mcp",SkillOperation:"skills",Init:"mcp_config_operation",SkillConfigOperation:"skill_config_operation",DocOperation:"docs",ServeLsp:"serve_lsp",CheckCommand:"check"};var De={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json",LOCK_JSON5_PATH:"oh_modules/.ohpm/lock.json5"};var W=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 o=j.dirname(t);if(o===t)break;t=o}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=j.join(e,"build-profile.json5");if(!X.existsSync(t))return null;try{let r=X.readFileSync(t,"utf-8"),o=Pt.parse(r);return o.app?o: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(i=>i.name===e);if(!t)throw new w(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=S.resolvePathWithinRoot(this.rootDir,t.srcPath),o=j.join(r,"src","main","module.json5");if(!X.existsSync(o))return"entry";try{let i=X.readFileSync(o,"utf-8");return Pt.parse(i)?.module?.type||"entry"}catch(i){return console.warn(`Warning: Failed to parse ${o}:`,i),"entry"}}findOwningModule(e){let t=j.normalize(e);for(let r of this.profile.modules){let o=j.normalize(j.join(this.rootDir,r.srcPath)),i=o+j.sep;if(t.startsWith(i)||t===o)return r.name}return null}getModuleProfile(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)throw new w(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=S.resolvePathWithinRoot(this.rootDir,t.srcPath),o=j.join(r,"build-profile.json5");if(!X.existsSync(o))throw new w(`Build profile for module '${e}' not found at ${o}.`,"Build profile for module not found at ${profilePath}.");try{let i=X.readFileSync(o,"utf-8");return Pt.parse(i)}catch(i){throw new Error(`Failed to parse module build profile at ${o}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}getBundleName(e){if(e){let r=this.profile.app.products?.find(o=>o.name===e);if(r?.bundleName)return r.bundleName}let t=j.join(this.rootDir,"AppScope","app.json5");if(X.existsSync(t))try{let r=X.readFileSync(t,"utf-8"),o=Pt.parse(r);if(o?.app?.bundleName)return o.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(!X.existsSync(e))return!1;try{let t=X.readFileSync(e,"utf-8");return Pt.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 o=S.resolvePathWithinRoot(this.rootDir,r.srcPath),i=j.join(o,"src","main","module.json5");if(!X.existsSync(i))return"EntryAbility";try{let s=X.readFileSync(i,"utf-8"),c=Pt.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let l=c.find(d=>d.name==="EntryAbility");return l?l.name:c[0].name}catch(s){return console.warn(`Warning: Failed to parse ${i}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new w(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`,"Invalid product name.");if(!this.profile.app.products?.some(r=>r.name===e)){let r=this.profile.app.products?.map(o=>o.name).join(", ")||"none";throw new w(`Product '${e}' not found in project configuration. Available products: ${r}`,"Productnot found in project configuration.")}}getModuleDependencies(e){let t=this.profile.modules.find(o=>o.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,De.LOCK_JSON5_PATH);if(!X.existsSync(t))return null;let r;try{r=Pt.parse(X.readFileSync(t,"utf-8"))}catch(d){return u(`Failed to parse lock.json5: ${d instanceof Error?d.message:String(d)}`),null}let o=r,i=o?.modules;if(!i||typeof i!="object")return null;let s=Object.values(i).find(d=>typeof d=="object"&&d!==null&&d.name===e);if(!s)return null;let a=this.buildOverrideMap(o.overrides),c=[],l=new Set;for(let d of["dependencies","dynamicDependencies"]){let g=s[d];!g||typeof g!="object"||this.collectLocalDeps(g,a,v=>this.resolveLockDepByVersion(v),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 o=t.get(e);if(o){let i=this.resolveLocalDepToModule(o);if(i)return i}}return r()}buildOverrideMap(e){if(!e||typeof e!="object")return null;let t=new Map;for(let[r,o]of Object.entries(e))typeof o=="string"&&t.set(r,o);return t.size>0?t:null}resolveLocalDepToModule(e){let t=n.stripLocalDep(e);if(!t)return null;let r=j.resolve(this.rootDir,t),o;try{o=S.ensurePathWithinRoot(this.rootDir,r)}catch{return null}let i=this.profile.modules.find(s=>j.resolve(this.rootDir,s.srcPath)===o);return i?i.name:null}static stripLocalDep(e){return!e.startsWith("file:")&&!e.startsWith(".")&&!e.startsWith("..")?null:e.startsWith("file:")?e.substring(5):e}readOhPackageLocalModuleDeps(e){let t=j.join(S.resolvePathWithinRoot(this.rootDir,e.srcPath),De.OH_PACKAGE_JSON5);if(!X.existsSync(t))return[];let r=this.readRootOverrideMap(),o=[],i=new Set;try{let s=Pt.parse(X.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),o,i)}}catch(s){u(`Failed to get module dependencies: ${s instanceof Error?s.message:String(s)}`)}return o}readRootOverrideMap(){let e=j.join(this.rootDir,De.OH_PACKAGE_JSON5);if(!X.existsSync(e))return null;try{let t=Pt.parse(X.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,o,i){for(let[s,a]of Object.entries(e)){let c=this.resolveDepModule(s,t,()=>r(a));c&&!i.has(c)&&(i.add(c),o.push(c))}}resolveLocalDepModuleName(e,t){let r=n.stripLocalDep(e);if(!r)return null;let o=j.join(t.srcPath,r),i=S.resolvePathWithinRoot(this.rootDir,o),s=this.profile.modules.find(a=>j.resolve(this.rootDir,a.srcPath)===i);return s?s.name:null}collectNonHarDependentModuleList(e){let t=[],r=[],o=new Set;for(r.push(e),o.add(e);r.length>0;){let i=r.shift();this.getModuleType(i)!=="har"&&t.push(i);let a=this.getModuleDependencies(i);for(let c of a)o.has(c)||(r.push(c),o.add(c))}return t}resolveModuleMetadata(e,t,r){this.validateProduct(r);let o=this.profile.modules.find(l=>l.name===e);if(!o){let l=this.getRunnableModuleNames();throw new w(`Module '${e}' not found. Available modules: ${l}`,"Module not found.")}let i=this.getModuleType(e)==="shared",s=i?"hspName":"hapName",a=this.buildOutputPath(o.srcPath,r,["intermediates",i?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!X.existsSync(a))throw new w(`Build metadata not found for module '${e}' at ${a}. Build the project first.`,"Build metadata not found for module. Build the project first.");let c=this.parseOutputMetadata(a,s);return{moduleNode:o,isShared:i,metadataPath:a,metadata:c}}findArtifactPath(e,t,r,o="default"){let{moduleNode:i,isShared:s,metadata:a}=this.resolveModuleMetadata(e,t,o),{packageName:c,isSigned:l}=a,d=c;if(!l){let P=this.getSignedHapName(c,i.srcPath,o,t);P&&(d=P)}let g=s?"-signed.hsp":"-signed.hap";if(!r&&!d.endsWith(g))throw new w(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`,"Target device is a real device, but the artifact is not signed.");let v=this.buildOutputPath(i.srcPath,o,["outputs",t,d]);if(!X.existsSync(v))throw new w(`Generated package file not found in ${v}.`,"Generated package file not found.");return v}findRemoteHspPaths(e,t,r="default"){let{moduleNode:o,metadata:i}=this.resolveModuleMetadata(e,t,r),s=[],a=new Set;for(let{hspPath:c}of i.dependRemoteHsps){if(a.has(c))continue;a.add(c);let l=j.isAbsolute(c)?c:this.buildOutputPath(o.srcPath,r,["outputs",t,c]);if(!X.existsSync(l))throw new w(`Remote HSP dependency not found: ${l}`,"Remote HSP dependency not found.");s.push(l)}return s}getSignedHapName(e,t,r,o){let i=null;if(e.endsWith("-unsigned.hap")?i=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(i=e.replace("-unsigned.hsp","-signed.hsp")),!i)return null;let s=this.buildOutputPath(t,r,["outputs",o,i]);return X.existsSync(s)?i:null}buildOutputPath(e,t,r){let o=S.resolvePathWithinRoot(this.rootDir,e),i=j.resolve(o,"build",t,...r);return S.ensurePathWithinRoot(this.rootDir,i)}collectRemoteHsps(e){return e.flatMap(t=>{let r=t.dependRemoteHsps;return Array.isArray(r)?r.filter(o=>!!(o.hspName&&o.hspPath)).map(o=>({hspName:o.hspName,hspPath:o.hspPath})):[]})}parseOutputMetadata(e,t){let r;try{let c=X.readFileSync(e,"utf-8");r=Pt.parse(c)}catch(c){throw new Error(`Failed to parse output metadata at ${e}: ${c instanceof Error?c.message:String(c)}`,{cause:c})}let o,i=!1,s=Array.isArray(r)?r:[r];for(let c of s)o||(o=c[t]),i||(i=c.isSigned===!0);if(!o)throw new w(`Could not find ${t} in output_metadata.json at ${e}`,"Could not find metadataKey in output_metadata.json at metadataPath.");this.validatePackageName(o);let a=this.collectRemoteHsps(s);return{packageName:o,isSigned:i,dependRemoteHsps:a}}validatePackageName(e){let t=j.basename(e);if(t!==e)throw new w(`Invalid traversal name: '${e}'. It must contain path characters.`,"Invalid traversal name.");if(!t.endsWith(".hap")&&!t.endsWith(".hsp"))throw new w(`Invalid package name '${t}'.It must be a .hap or .hsp file.`,"Invalid package name.")}};import Re from"fs";import*as Ge from"os";import*as C from"path";import Pi from"fs";import*as Ci from"os";import*as so from"path";import dv from"regedit";import{execFileSync as cv}from"child_process";import ou from"fs";import*as iu from"os";import*as Ka from"path";import{compare as av}from"semver";function nu(n,e){return av(n,e)}function an(n,e){let t=Math.max(n.split(".").length,e.split(".").length);for(let r=0;r<t;r++){let o=Number(n.split(".")[r]??0)-Number(e.split(".")[r]??0);if(o)return o}return 0}function Ei(n,e){let t=Ka.join(n,"Contents","Info.plist");if(!ou.existsSync(t)){u(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[r,o]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let i=cv(r,o,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(i&&!i.includes("Does Not Exist"))return i}catch{}}function lv(n){let e=Ei(n,"CFBundleShortVersionString");if(!e)return Ei(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[Ei(n,"CFBundleVersion"),Ei(n,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let o of r){let i=o?.split(".").at(-1)?.replace(new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`),"");if(i&&/^\d+$/.test(i))return`${e}.${i}`}return e}function Xt(n){if(iu.platform()==="darwin")return lv(n);let e=Ka.join(n,"product-info.json");try{let t=JSON.parse(ou.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}var uv="DevEco Studio",pv=["Contents","Resources","product-info.json"],mv="name";function fv(n){return n.filter(e=>{try{return Pi.statSync(e).isDirectory()}catch{return!1}})}function hv(n){let e=so.join(n,...pv);if(Pi.existsSync(e))try{let r=JSON.parse(Pi.readFileSync(e,"utf8"))[mv];return typeof r=="string"&&r.trim()?r.trim():void 0}catch{return}}function gv(n){return hv(n)===uv}function yv(){let n=[];for(let e of[so.join(Ci.homedir(),"Applications"),"/Applications"])try{n.push(...Pi.readdirSync(e).filter(t=>t.endsWith(".app")).map(t=>so.join(e,t)).filter(gv))}catch{}return n}function su(n){return new Promise((e,t)=>dv.list(n,(r,o)=>r?t(r):e(o)))}async function au(n,e,t){let o=((await su([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(o.length===0)return[];let i=await su(o);return o.flatMap(s=>{let a=i[s]?.values?.[t]?.value;return a?[a]:[]})}async function vv(){let n=[so.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 au(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 au(e,()=>!0,""))}catch{}return n}async function cu(){let n=Ci.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"?yv():await vv(),t=fv(e).flatMap(r=>{let o=Xt(r);return o?(u(`[ToolProvider] ${r} => version ${o}`),[{root:r,version:o}]):(u(`[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,o)=>an(o.version,r.version)>0?o:r)}import*as lu from"fs";import*as Oe from"path";function Xa(n,e){let t=Oe.relative(e,n);return t===""||!Oe.isAbsolute(t)&&!t.startsWith(`..${Oe.sep}`)&&t!==".."}function Zt(n){let e=Oe.resolve(n),t=[],r=e;for(;;)try{let o=lu.realpathSync(r);return t.length===0?o:Oe.join(o,...t.reverse())}catch(o){if(o.code!=="ENOENT")throw o;let i=Oe.dirname(r);if(i===r)return e;t.push(Oe.basename(r)),r=i}}function du(n,e){let t=Zt(e),r=Zt(n);return Xa(r,t)?r:null}function Za(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function ki(n){let e=Za(n);if(!e)throw new Error("Path must not be empty.");return Zt(e)}var Qa="https://matrix.openharmony.cn",rt={TAGS_API_URL:`${Qa}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${Qa}/api/registry/skill/skills`,SKILL_API_BASE:`${Qa}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,DEFAULT_MAX_PAGES:100,SUCCESS_CODE:"20000"},mt={"trae-cn":{path:".trae-cn/skills",displayName:"trae-cn"},opencode:{path:".config/opencode/skills",displayName:"opencode"},pi:{path:".pi/agent/skills",displayName:"pi"},deveco:{path:".config/deveco/skills",displayName:"deveco"},cursor:{path:".cursor/skills",displayName:"cursor"},codebuddy:{path:".codebuddy/skills",displayName:"codebuddy"},qoder:{path:".qoder/skills",displayName:"qoder"},"claude-code":{path:".claude/skills",projectPath:".claude/skills",displayName:"claude-code"},codex:{path:".codex/skills",displayName:"codex"},atomcode:{path:".atomcode/skills",displayName:"atomcode"},dsh:{path:".dsh/skills",projectPath:".dsh/skills",displayName:"deepseek harness"}};import{homedir as Ct}from"os";import _e from"path";var kt="deveco-mcp";var Qt={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:_e.join(Ct(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},pi:{name:"pi",displayName:"Pi Coding Agent",supportsGlobal:!0,globalConfigPath:_e.join(Ct(),".pi","agent","mcp.json"),projectConfigPath:".pi/mcp.json",mcpServersKey:"mcpServers",format:"standard"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:_e.join(process.platform==="win32"?_e.join(process.env.APPDATA??_e.join(Ct(),"AppData","Roaming"),"Trae CN","User"):_e.join(Ct(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:_e.join(Ct(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:_e.join(Ct(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:_e.join(process.platform==="win32"?_e.join(process.env.APPDATA??_e.join(Ct(),"AppData","Roaming"),"Qoder","SharedClientCache"):_e.join(Ct(),"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:_e.join(Ct(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:_e.join(Ct(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function pu(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function uu(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function mu(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function Ii(n,e){return n.format==="opencode"?pu(e):n.format==="claude-code"||n.format==="codex"?uu(e):mu(e)}var ec="https://developer.huawei.com/consumer/cn/download/";var wv=/^#\s*Version:\s*(\S+)/,bv="26.0.0.810";function Sv(n){try{let e=JSON.parse(Re.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch(e){u(`[ToolProvider] Failed to parse API level from ${n}: ${e instanceof Error?e.message:String(e)}`);return}}function Ev(n){let e=C.join(n,"default","openharmony");return[C.join(n,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>C.join(e,t,"oh-uni-package.json"))]}var A=class n{constructor(e,t,r,o,i,s,a,c,l,d){this._sourceType=e;this._toolchainRoot=t;this._devecoStudioPath=r;this._nodePath=o;this._ohpmJsPath=i;this._hvigorJsPath=s;this._javaPath=a;this._sdkPath=c;this._hdcPath=l;this._emulatorPath=d}_sourceType;_toolchainRoot;_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;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(Re.existsSync(t.marker))return t.root;return null}get clangdPath(){let e=n.buildToolPaths(this._toolchainRoot,this._sourceType).clangdPath;return Re.existsSync(e)?e:null}get javaPath(){return this._javaPath??""}get sdkPath(){return this._sdkPath}get hdcPath(){return this._hdcPath}get emulatorPath(){return this._emulatorPath}get emulatorLauncherPath(){return this.emulatorPath}assertJava(){if(this._sourceType==="clt"&&!this._javaPath&&(this._javaPath=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 an(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 getStudioVersion(){try{let e=await n.resolveInstallSource();return Xt(e.toolchainRoot)}catch{return}}static async getCltVersion(){try{let e=await n.resolveInstallSource();return n.readCltVersion(e.toolchainRoot)}catch{return}}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()}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(Xt(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,o,i){if(!e)throw new w(`Failed to determine ${t} version from ${r} at ${i}`,`Failed to determine ${t} version from ${r}`);if(!/^\d+(?:\.\d+){1,3}$/.test(e))throw new w(`Invalid ${t} version "${e}" from ${r} at ${i}`,`Invalid ${t} version "${e}" from ${r}`);if(an(e,o)<0)throw new Error(`The detected ${t} version is ${e}, which is below the minimum required version ${o}. Upgrade before using deveco-cli:
15
+ ${ec}`)}static resolveCodelinterPath(e,t){let r=n.buildToolPaths(e,t).codelinterCandidates,o=r.find(n.isFile);if(!o){let a=t==="studio"?"Code Linter not found in DevEco Studio.":"Code Linter not found in DevEco Command Line Tools.";throw new w(`${a}
16
16
  Searched paths:
17
17
  ${r.join(`
18
- `)}`,a)}let o=qt(e),s=qt(i);return n.assertInsideRoot(s,o,"codelinter"),s}static isValidRoot(e,t){if(!n.isDirectory(e))return!1;if(t==="clt")return ke.existsSync(P.join(e,"version.txt"));let r=We.platform()==="darwin"?P.join(e,"Contents"):e,i=We.platform()==="darwin"?P.join(r,"Info.plist"):P.join(r,"product-info.json");if(!ke.existsSync(i))return!1;let o=n.buildToolPaths(e,"studio");return[o.nodePath,o.ohpmJsPath,o.hvigorJsPath].every(ke.existsSync)}static buildToolPaths(e,t){return t==="clt"?n.buildCltToolPaths(e):n.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=We.platform()==="win32",r=t?".exe":"",i=P.join(e,"sdk");return{nodePath:t?P.join(e,"tool","node","node.exe"):P.join(e,"tool","node","bin","node"),ohpmJsPath:P.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:P.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:i,hdcPath:P.join(i,"default","openharmony","toolchains",`hdc${r}`),emulatorPath:P.join(e,"emulator",t?"Emulator.exe":"Emulator"),clangdPath:n.clangdPathFor(i),arktsLangServerCandidates:[{root:P.join(e,"arkts-lsp","lib"),marker:P.join(e,"arkts-lsp","lib","out","index.js")}],codelinterCandidates:n.codelinterCandidatesFor(e,"clt")}}static buildStudioToolPaths(e){let t=We.platform()==="darwin",r=We.platform()==="win32",i=t?P.join(e,"Contents"):e,o=P.join(i,"tools"),s=P.join(i,"sdk"),a=r?".exe":"";return{nodePath:r?P.join(o,"node","node.exe"):P.join(o,"node","bin","node"),ohpmJsPath:P.join(o,"ohpm","bin","pm-cli.js"),hvigorJsPath:P.join(o,"hvigor","bin","hvigorw.js"),javaPath:r?P.join(e,"jbr","bin","java.exe"):t?P.join(i,"jbr","Contents","Home","bin","java"):P.join(i,"jbr","bin","java"),sdkPath:s,hdcPath:P.join(s,"default","openharmony","toolchains",`hdc${a}`),emulatorPath:P.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[P.join(e,"codelinter","index.js"),P.join(e,"codelinter","run","index.js"),P.join(e,"tool","codelinter","bin","codelinter.js"),P.join(e,"tool","codelinter","codelinter.js")];let r=We.platform()==="darwin"?["Contents"]:[];return[P.join(e,...r,"plugins","codelinter","run","index.js"),P.join(e,...r,"plugins","codelinter","index.js"),P.join(e,...r,"tools","codelinter","bin","codelinter.js"),P.join(e,...r,"tools","codelinter","codelinter.js")]}static studioArktsLangServerCandidates(e){if(We.platform()==="linux")return[];let t=We.platform()==="darwin"?["Contents"]:[],r=P.join(e,...t,"plugins","openharmony");return[{root:r,marker:P.join(r,"ace-server","out","index.js")}]}static clangdPathFor(e){return P.join(e,"default","openharmony","native","llvm","bin",We.platform()==="win32"?"clangd.exe":"clangd")}static isFile(e){try{return ke.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return ke.existsSync(e)&&ke.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 p(`[ToolProvider] Using ${r} \u2192 ${a}`),{sourceType:o,toolchainRoot:a}}}let t=await Td();return p(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,r){let i;try{i=co(e)}catch(o){throw new Error(`Invalid ${r}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}return t==="studio"&&We.platform()==="darwin"&&(i=n.normalizeMacStudioRoot(i)),n.isValidRoot(i,t)?i:n.throwInvalidSource(i,t,r,e)}static assertBuiltPathsInsideRoot(e,t,r){let i=qt(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(Ld(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=`${P.sep}Contents`,r=P.normalize(e);return r.endsWith(t)?r.slice(0,-t.length):r}static readCltVersion(e){try{return ke.readFileSync(P.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(Py)?.[1]?.trim()).find(Boolean)}catch{return}}static resolveCltJava(e){let t=process.env.JAVA_HOME?.trim(),r=t&&(n.javaIn(P.join(t,"bin"))??n.javaIn(t)),i=(process.env.Path??process.env.PATH??"").split(P.delimiter).map(s=>n.javaIn(s.trim())).find(Boolean),o=r??i;if(o)return ke.realpathSync(o);if(e)throw new Error("No Java runtime found in CLT mode. Set JAVA_HOME to a JDK/JBR installation directory (or point JAVA_HOME at the JDK bin directory), or add the JDK bin directory to PATH.");return""}static javaIn(e){return(We.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(r=>P.join(e,r)).find(ke.existsSync)}getMaxApiLevel(){for(let e of Iy(this.sdkPath)){let t=ky(e);if(t!==void 0)return t}return 23}getSdkPlatformVersion(){let e=P.join(this.sdkPath,"default","sdk-pkg.json"),t;try{t=JSON.parse(ke.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=We.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=P.join(this._devecoStudioPath,t,"plugins","harmony","arkanalyzer-apiscan"),i=P.join(r,"resources","apiChange"),o=P.join(r,"api-change-scan.js");if(!ke.existsSync(i)||!ke.existsSync(o)){let s=Vt(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${Cy}. Upgrade before using 'check compat' at ${La}`)}return this._apiscanPaths={apiChangeDir:i,scriptPath:o},this._apiscanPaths}};import{execa as Ly}from"execa";import*as Hd from"net";import*as zt from"path";import*as po from"fs";import*as Ud from"os";import{execFile as jd}from"child_process";import{existsSync as Ay}from"fs";var Fd="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",Na;function Dy(){return Na===void 0&&(Na=Ay(Fd)),Na}function Xe(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)];p(`Executing: ${r} ${i.join(" ")}`),jd(r,i,{timeout:5e3,windowsHide:!0},(o,s)=>{if(o){e(null);return}e(t?xy(s):Ty(s))})})}async function Ry(n){return new Promise(e=>{let t=process.platform==="win32",r,i;if(t){if(!Dy()){e([]);return}r=Fd,i=["-NoProfile","-Command",`Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq ${n} } | Select-Object -ExpandProperty ProcessId`]}else r="ps",i=["-o","pid=","--ppid",String(n)];jd(r,i,{timeout:5e3,windowsHide:!0},(o,s)=>{if(o){e([]);return}let a=[],c=s.trim().split(`
19
- `);for(let l of c){let d=l.trim();d&&/^\d+$/.test(d)&&a.push(Number(d))}e(a)})})}async function $d(n){let e=0,t=await Xe(n);t&&(e+=Number(t)*1024);let r=await Ry(n);for(let i of r)e+=await $d(i);return e}function ce(n){return`${(n/1024/1024).toFixed(2)}MB`}async function _d(n,e){if(!n)return process.memoryUsage().rss;if(e)return $d(n);let t=await Xe(n);return t?Number(t)*1024:0}function uo(n,e=500,t=!1){let r=0,i=!1,o=setInterval(async()=>{if(i)return;let s=await _d(n,t);s>r&&(r=s)},e);return{stop:async()=>{i=!0,clearInterval(o);let s=await _d(n,t);return Math.max(r,s)}}}function Ty(n){let e=n.trim().match(/^(\d+)$/);return e?e[1]:null}function xy(n){let e=n.match(/"([^"]+?)\s*K"/i);return e&&e[1].replace(/\D/g,"")||null}var Be=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let i=zt.dirname(e.javaPath),o=`${i}${zt.delimiter}${process.env.PATH||""}`,s={...process.env,PATH:o,DEVECO_SDK_HOME:e.sdkPath};e.sourceType==="clt"&&e.javaPath&&(s.JAVA_HOME=zt.dirname(i)),this.env=s}async sync(e,t){let r=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(r)}async buildProduct(e,t){let r=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];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}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(o)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];return this.runHvigor(e)}async stopDaemon(){return this.runHvigor(["--stop-daemon"])}async ensureDaemonRunning(){if(this.findProjectDaemon()){p("[HvigorAdapter] Daemon already running.");return}p("[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 Hd.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(!po.existsSync(t))return null;try{let r=po.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||zt.join(Ud.homedir(),".hvigor");return zt.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","--analyze=normal"),this.runHvigor(r)}async runHvigor(e){let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];p(`Executing: ${t} ${r.join(" ")}`);let i=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit",o=Ly(t,r,{cwd:this.projectRoot,env:this.env,stdout:i,stderr:i}),s=uo(o.pid,500,!0),a="";try{await o}finally{let c=await s.stop();c>0&&(a=ce(c),p(`Hvigor peak memory: ${a}`))}return a}};import{execa as Ny}from"execa";var Qn=class{toolProvider;projectRoot;peakMemoryMb="";constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=[this.toolProvider.ohpmJsPath,"install","--all"];p(`Executing: ${e} ${t.join(" ")}`);let r=Ny(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"}),i=uo(r.pid);try{await r}finally{let o=await i.stop();o>0&&(this.peakMemoryMb=ce(o))}}};import{mkdir as Oy}from"fs/promises";import{dirname as My,resolve as _y}from"path";import{execa as jy}from"execa";import{lock as Oa,check as TL}from"proper-lockfile";function Ma(n){return _y(n,".hvigor",".build-lock")}function Fy(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function Wd(n){let e=My(Ma(n));if(await Oy(e,{recursive:!0}),process.platform==="win32")try{await jy("attrib",["+h",e])}catch{}}async function $y(n,e){let t=new AbortController,r=Fy(e);await Wd(n);let i={lockfilePath:Ma(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await Oa(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 Oa(n,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function xn(n,e,t){let{release:r,signal:i}=await $y(n,t);try{return await e(i)}finally{await r()}}async function fo(n,e){let t=new AbortController;await Wd(n);let r={lockfilePath:Ma(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await Oa(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 Jt from"fs";import*as Ln from"path";import Hy from"json5";var Uy=1e3;function ho(n){p(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=Ln.join(n,Ce.SYNC_OUTPUT_PATH);if(!Jt.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return p(`[ProjectCheck] ${l.reason}`),l}let t=Jt.statSync(e).mtimeMs;p(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Wy(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return p(`[ProjectCheck] ${l.reason}`),l}let i=Ln.join(n,Ce.OH_PACKAGE_JSON5),o=mo(i,t,"root");if(o.required)return p(`[ProjectCheck] Root check: ${o.reason}`),o;let s=Ln.join(n,Ce.BUILD_PROFILE_JSON5),a=mo(s,t,"build-profile");if(a.required)return p(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let d=Ln.join(n,l.srcPath,Ce.OH_PACKAGE_JSON5),g=mo(d,t,l.name);if(g.required)return p(`[ProjectCheck] Module '${l.name}' check: ${g.reason}`),g;let v=Ln.join(n,l.srcPath,Ce.BUILD_PROFILE_JSON5),D=mo(v,t,l.name);if(D.required)return p(`[ProjectCheck] Module '${l.name}' build-profile check: ${D.reason}`),D}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return p(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function mo(n,e,t){if(!Jt.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=Jt.statSync(n).mtimeMs;return r-e>Uy?{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 Wy(n){let e=Ln.join(n,Ce.BUILD_PROFILE_JSON5);try{let t=Jt.readFileSync(e,"utf-8");if(!t.trim())return null;let r=Hy.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 K from"fs";import*as te from"path";import*as Bd from"util";var _a="";function yo(n){if(!n||n==="auto"||n==="stdout"||n==="none"){_a="";return}_a=n}function Vd(){return _a||(hd()??"")}function go(n,...e){if(e.length===0)return n;try{return Bd.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var u={info(n,...e){h.info(`[lsp] ${go(n,...e)}`)},warn(n,...e){h.warn(`[lsp] ${go(n,...e)}`)},error(n,...e){h.error(`[lsp] ${go(n,...e)}`)},debug(n,...e){h.debug(`[lsp] ${go(n,...e)}`)}};import*as Qr from"fs";import*as ei from"os";import*as er from"path";import By from"json5";var y={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"},T="2.0";var qd=8192,ja=100,Gd=.03,zd=.7,Ze=900*1e3;function Ve(n){if(!Qr.existsSync(n))return null;try{let e=Qr.readFileSync(n,"utf-8");return e.trim()?By.parse(e):null}catch{return null}}function vo(n,e){let t=Math.floor(ei.totalmem()/1048576),r=Math.floor(t*zd),i,o;e!==void 0&&Number.isFinite(e)&&e>0?(i=e,o=`override(${e})`):(i=qd,n>ja&&(i+=(n-ja)*Gd*1024),o=`formula(moduleCount=${n})`);let s=r>0&&i>r;s&&(i=r);let a=Math.round(i);return u.info(`[computeLspServerMaxSize] source=${o}, physicalTotal=${t}MB, physicalCap(70%)=${r}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function lt(n){if(n.startsWith("file:"))return n;try{let e=er.resolve(n),t=new URL(`file://${e}`).toString();if(ei.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 tr(n){return n&&n.replace(/\\/g,"/")}function V(n){let e=er.normalize(n).replace(/\\/g,"/");if(ei.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function Jd(n){return er.join(n,"build-profile.json5")}var It=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=Jd(this.projectRoot);try{let t=Ve(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 u.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};import{spawn as Vy}from"child_process";import*as bo from"fs";var qy=600*1e3;function Gy(n,e,t){let r=t.split(/\s+/).filter(i=>i.length>0);return[n,[e,...r]]}function zy(n){let e=[],t=[];return n.stdout?.on("data",r=>{e.push(r.toString())}),n.stderr?.on("data",r=>{let i=r.toString();t.push(i),i.split(/\r?\n/).filter(Boolean).forEach(o=>u.info("[hvigor:err] %s",o))}),{stdout:e,stderr:t}}function wo(n){return n.join("")}function Jy(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
18
+ `)}`,a)}let i=Zt(e),s=Zt(o);return n.assertInsideRoot(s,i,"codelinter"),s}static isValidRoot(e,t){if(!n.isDirectory(e))return!1;if(t==="clt")return Re.existsSync(C.join(e,"version.txt"));let r=Ge.platform()==="darwin"?C.join(e,"Contents"):e,o=Ge.platform()==="darwin"?C.join(r,"Info.plist"):C.join(r,"product-info.json");if(!Re.existsSync(o))return!1;let i=n.buildToolPaths(e,"studio");return[i.nodePath,i.ohpmJsPath,i.hvigorJsPath].every(Re.existsSync)}static buildToolPaths(e,t){return t==="clt"?n.buildCltToolPaths(e):n.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=Ge.platform()==="win32",r=t?".exe":"",o=C.join(e,"sdk");return{nodePath:t?C.join(e,"tool","node","node.exe"):C.join(e,"tool","node","bin","node"),ohpmJsPath:C.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:C.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:o,hdcPath:C.join(o,"default","openharmony","toolchains",`hdc${r}`),emulatorPath:C.join(e,"emulator",t?"Emulator.exe":"Emulator"),clangdPath:n.clangdPathFor(o),arktsLangServerCandidates:[{root:C.join(e,"arkts-lsp","lib"),marker:C.join(e,"arkts-lsp","lib","out","index.js")}],codelinterCandidates:n.codelinterCandidatesFor(e,"clt")}}static buildStudioToolPaths(e){let t=Ge.platform()==="darwin",r=Ge.platform()==="win32",o=t?C.join(e,"Contents"):e,i=C.join(o,"tools"),s=C.join(o,"sdk"),a=r?".exe":"";return{nodePath:r?C.join(i,"node","node.exe"):C.join(i,"node","bin","node"),ohpmJsPath:C.join(i,"ohpm","bin","pm-cli.js"),hvigorJsPath:C.join(i,"hvigor","bin","hvigorw.js"),javaPath:r?C.join(e,"jbr","bin","java.exe"):t?C.join(o,"jbr","Contents","Home","bin","java"):C.join(o,"jbr","bin","java"),sdkPath:s,hdcPath:C.join(s,"default","openharmony","toolchains",`hdc${a}`),emulatorPath:C.join(i,"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[C.join(e,"codelinter","index.js"),C.join(e,"codelinter","run","index.js"),C.join(e,"tool","codelinter","bin","codelinter.js"),C.join(e,"tool","codelinter","codelinter.js")];let r=Ge.platform()==="darwin"?["Contents"]:[];return[C.join(e,...r,"plugins","codelinter","run","index.js"),C.join(e,...r,"plugins","codelinter","index.js"),C.join(e,...r,"tools","codelinter","bin","codelinter.js"),C.join(e,...r,"tools","codelinter","codelinter.js")]}static studioArktsLangServerCandidates(e){if(Ge.platform()==="linux")return[];let t=Ge.platform()==="darwin"?["Contents"]:[],r=C.join(e,...t,"plugins","openharmony");return[{root:r,marker:C.join(r,"ace-server","out","index.js")}]}static clangdPathFor(e){return C.join(e,"default","openharmony","native","llvm","bin",Ge.platform()==="win32"?"clangd.exe":"clangd")}static isFile(e){try{return Re.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return Re.existsSync(e)&&Re.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,o,i]of e){let s=process.env[r]?.trim();if(s){let a=n.resolveExplicitRoot(s,o,r);return u(`[ToolProvider] Using ${r} \u2192 ${a}`),{sourceType:i,toolchainRoot:a}}}let t=await cu();return u(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,r){let o;try{o=ki(e)}catch(i){throw new Error(`Invalid ${r}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return t==="studio"&&Ge.platform()==="darwin"&&(o=n.normalizeMacStudioRoot(o)),n.isValidRoot(o,t)?o:n.throwInvalidSource(o,t,r,e)}static assertBuiltPathsInsideRoot(e,t,r){let o=Zt(e),i=[["node",t.nodePath],["ohpm",t.ohpmJsPath],["hvigor",t.hvigorJsPath],["sdk",t.sdkPath],["hdc",t.hdcPath],["emulator",t.emulatorPath]];r&&t.javaPath&&i.push(["java",t.javaPath]);for(let[s,a]of i)n.assertInsideRoot(a,o,s)}static assertInsideRoot(e,t,r){if(du(e,t)===null)throw new Error(`Unsafe toolchain path: ${r} resolves outside the toolchain root`)}static throwInvalidSource(e,t,r,o){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}: ${o}`)}static normalizeMacStudioRoot(e){let t=`${C.sep}Contents`,r=C.normalize(e);return r.endsWith(t)?r.slice(0,-t.length):r}static readCltVersion(e){try{return Re.readFileSync(C.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(wv)?.[1]?.trim()).find(Boolean)}catch{return}}static resolveCltJava(e){let t=process.env.JAVA_HOME?.trim(),r=t&&(n.javaIn(C.join(t,"bin"))??n.javaIn(t)),o=(process.env.Path??process.env.PATH??"").split(C.delimiter).map(s=>n.javaIn(s.trim())).find(Boolean),i=r??o;if(i)return Re.realpathSync(i);if(e)throw new Error("No Java runtime found in CLT mode. Set JAVA_HOME to a JDK/JBR installation directory (or point JAVA_HOME at the JDK bin directory), or add the JDK bin directory to PATH.");return""}static javaIn(e){return(Ge.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(r=>C.join(e,r)).find(Re.existsSync)}getMaxApiLevel(){for(let e of Ev(this.sdkPath)){let t=Sv(e);if(t!==void 0)return t}return 23}getSdkPlatformVersion(){let e=C.join(this.sdkPath,"default","sdk-pkg.json"),t;try{t=JSON.parse(Re.readFileSync(e,"utf8"))}catch(i){throw new Error(`Failed to read SDK metadata: ${e}`,{cause:i})}let r=t.data?.platformVersion,o=typeof r=="string"?r.trim():"";if(!o)throw new Error(`Missing data.platformVersion in SDK metadata: ${e}`);return o}detectApiLevel(){return this.getMaxApiLevel()}_apiscanPaths;getApiscanPaths(){if(this._apiscanPaths)return this._apiscanPaths;let e=Ge.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=C.join(this._devecoStudioPath,t,"plugins","harmony","arkanalyzer-apiscan"),o=C.join(r,"resources","apiChange"),i=C.join(r,"api-change-scan.js");if(!Re.existsSync(o)||!Re.existsSync(i)){let s=Xt(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${bv}. Upgrade before using 'check compat' at ${ec}`)}return this._apiscanPaths={apiChangeDir:o,scriptPath:i},this._apiscanPaths}};import{execa as Dv}from"execa";import*as vu from"net";import*as er from"path";import*as Ai from"fs";import*as wu from"os";import{execFile as hu}from"child_process";import{existsSync as Pv}from"fs";var gu="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",tc;function Cv(){return tc===void 0&&(tc=Pv(gu)),tc}function je(n){return new Promise(e=>{let t=process.platform==="win32",r=t?"tasklist":"ps",o=t?["/fi",`PID eq ${n}`,"/fo","csv","/nh"]:["-o","rss=","-p",String(n)];u(`Executing: ${r} ${o.join(" ")}`),hu(r,o,{timeout:5e3,windowsHide:!0},(i,s)=>{if(i){e(null);return}e(t?Av(s):Iv(s))})})}async function kv(n){return new Promise(e=>{let t=process.platform==="win32",r,o;if(t){if(!Cv()){e([]);return}r=gu,o=["-NoProfile","-Command",`Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq ${n} } | Select-Object -ExpandProperty ProcessId`]}else r="ps",o=["-o","pid=","--ppid",String(n)];hu(r,o,{timeout:5e3,windowsHide:!0},(i,s)=>{if(i){e([]);return}let a=[],c=s.trim().split(`
19
+ `);for(let l of c){let d=l.trim();d&&/^\d+$/.test(d)&&a.push(Number(d))}e(a)})})}async function yu(n){let e=0,t=await je(n);t&&(e+=Number(t)*1024);let r=await kv(n);for(let o of r)e+=await yu(o);return e}function Q(n){return`${(n/1024/1024).toFixed(2)}MB`}async function fu(n,e){if(!n)return process.memoryUsage().rss;if(e)return yu(n);let t=await je(n);return t?Number(t)*1024:0}function cn(n,e=500,t=!1){let r=0,o=!1,i=setInterval(async()=>{if(o)return;let s=await fu(n,t);s>r&&(r=s)},e);return{stop:async()=>{o=!0,clearInterval(i);let s=await fu(n,t);return Math.max(r,s)}}}function Iv(n){let e=n.trim().match(/^(\d+)$/);return e?e[1]:null}function Av(n){let e=n.match(/"([^"]+?)\s*K"/i);return e&&e[1].replace(/\D/g,"")||null}var ze=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let o=er.dirname(e.javaPath),i=`${o}${er.delimiter}${process.env.PATH||""}`,s={...process.env,PATH:i,DEVECO_SDK_HOME:e.sdkPath};e.sourceType==="clt"&&e.javaPath&&(s.JAVA_HOME=er.dirname(o)),this.env=s}async sync(e,t){let r=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(r)}async buildProduct(e,t){let r=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(r)}async buildModules(e,t,r,o){let i=[...Array.from(o),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(i)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];return this.runHvigor(e)}async stopDaemon(){return this.runHvigor(["--stop-daemon"])}async ensureDaemonRunning(){if(this.findProjectDaemon()){u("[HvigorAdapter] Daemon already running.");return}u("[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 vu.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(!Ai.existsSync(t))return null;try{let r=Ai.readFileSync(t,"utf-8"),o=JSON.parse(r),i=e??this.projectRoot,s=Object.values(o).filter(a=>a.cwdPath===i&&(a.state==="idle"||a.state==="half_busy"||a.state==="busy")&&this.isProcessAlive(a.pid));return s.length>0?s[s.length-1]:null}catch{return null}}getDaemonRegistryPath(){let e=process.env.HVIGOR_USER_HOME||er.join(wu.homedir(),".hvigor");return er.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","--analyze=normal"),this.runHvigor(r)}async runHvigor(e){let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];u(`Executing: ${t} ${r.join(" ")}`);let o=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit",i=Dv(t,r,{cwd:this.projectRoot,env:this.env,stdout:o,stderr:o}),s=cn(i.pid,500,!0),a="";try{await i}finally{let c=await s.stop();c>0&&(a=Q(c),u(`Hvigor peak memory: ${a}`))}return a}};import{execa as Rv}from"execa";var ln=class{toolProvider;projectRoot;peakMemoryMb="";constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=[this.toolProvider.ohpmJsPath,"install","--all"];u(`Executing: ${e} ${t.join(" ")}`);let r=Rv(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"}),o=cn(r.pid);try{await r}finally{let i=await o.stop();i>0&&(this.peakMemoryMb=Q(i))}}};import{mkdir as Tv}from"fs/promises";import{dirname as xv,resolve as Lv}from"path";import{execa as Nv}from"execa";import{lock as rc,check as QN}from"proper-lockfile";function nc(n){return Lv(n,".hvigor",".build-lock")}function Mv(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function bu(n){let e=xv(nc(n));if(await Tv(e,{recursive:!0}),process.platform==="win32")try{await Nv("attrib",["+h",e])}catch{}}async function Ov(n,e){let t=new AbortController,r=Mv(e);await bu(n);let o={lockfilePath:nc(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await rc(n,{...o,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return r(),{release:await rc(n,{...o,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function jr(n,e,t){let{release:r,signal:o}=await Ov(n,t);try{return await e(o)}finally{await r()}}async function Di(n,e){let t=new AbortController;await bu(n);let r={lockfilePath:nc(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},o;try{o=await rc(n,{...r,retries:0})}catch(i){if(i&&typeof i=="object"&&"code"in i&&i.code==="ELOCKED")return{acquired:!1};throw i}try{return{acquired:!0,result:await e(t.signal)}}finally{await o()}}import*as tr from"fs";import*as Fr from"path";import _v from"json5";var jv=1e3;function Ti(n){u(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=Fr.join(n,De.SYNC_OUTPUT_PATH);if(!tr.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return u(`[ProjectCheck] ${l.reason}`),l}let t=tr.statSync(e).mtimeMs;u(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Fv(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return u(`[ProjectCheck] ${l.reason}`),l}let o=Fr.join(n,De.OH_PACKAGE_JSON5),i=Ri(o,t,"root");if(i.required)return u(`[ProjectCheck] Root check: ${i.reason}`),i;let s=Fr.join(n,De.BUILD_PROFILE_JSON5),a=Ri(s,t,"build-profile");if(a.required)return u(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let d=Fr.join(n,l.srcPath,De.OH_PACKAGE_JSON5),g=Ri(d,t,l.name);if(g.required)return u(`[ProjectCheck] Module '${l.name}' check: ${g.reason}`),g;let v=Fr.join(n,l.srcPath,De.BUILD_PROFILE_JSON5),P=Ri(v,t,l.name);if(P.required)return u(`[ProjectCheck] Module '${l.name}' build-profile check: ${P.reason}`),P}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return u(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function Ri(n,e,t){if(!tr.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=tr.statSync(n).mtimeMs;return r-e>jv?{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 Fv(n){let e=Fr.join(n,De.BUILD_PROFILE_JSON5);try{let t=tr.readFileSync(e,"utf-8");if(!t.trim())return null;let r=_v.parse(t);if(typeof r!="object"||r===null)return null;let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}import*as Z from"fs";import*as se from"path";import*as Su from"util";var oc="";function Li(n){if(!n||n==="auto"||n==="stdout"||n==="none"){oc="";return}oc=n}function Eu(){return oc||(zd()??"")}function xi(n,...e){if(e.length===0)return n;try{return Su.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var f={info(n,...e){h.info(`[lsp] ${xi(n,...e)}`)},warn(n,...e){h.warn(`[lsp] ${xi(n,...e)}`)},error(n,...e){h.error(`[lsp] ${xi(n,...e)}`)},debug(n,...e){h.debug(`[lsp] ${xi(n,...e)}`)}};import*as ao from"fs";import*as co from"os";import*as dn from"path";import $v from"json5";var y={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"},T="2.0";var Pu=8192,ic=100,Cu=.03,ku=.7,nt=900*1e3;function Je(n){if(!ao.existsSync(n))return null;try{let e=ao.readFileSync(n,"utf-8");return e.trim()?$v.parse(e):null}catch{return null}}function Ni(n,e){let t=Math.floor(co.totalmem()/1048576),r=Math.floor(t*ku),o,i;e!==void 0&&Number.isFinite(e)&&e>0?(o=e,i=`override(${e})`):(o=Pu,n>ic&&(o+=(n-ic)*Cu*1024),i=`formula(moduleCount=${n})`);let s=r>0&&o>r;s&&(o=r);let a=Math.round(o);return f.info(`[computeLspServerMaxSize] source=${i}, 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=dn.resolve(n),t=new URL(`file://${e}`).toString();if(co.platform()==="win32"){let r=t.match(/^file:\/\/\/([A-Za-z]):/);if(r){let o=r[1].toUpperCase(),i=t.substring(`file:///${r[1]}:`.length);t=`file:///${o}%3A${i}`}}return t}catch{return n}}function un(n){return n&&n.replace(/\\/g,"/")}function z(n){let e=dn.normalize(n).replace(/\\/g,"/");if(co.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function Iu(n){return dn.join(n,"build-profile.json5")}var Nt=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=Iu(this.projectRoot);try{let t=Je(e);if(typeof t!="object"||t===null)return[];let r=t.modules;return Array.isArray(r)?r.filter(o=>{if(typeof o!="object"||o===null)return!1;let i=o;return typeof i.name=="string"&&typeof i.srcPath=="string"}):[]}catch(t){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};import{spawn as Hv}from"child_process";import*as Oi from"fs";var Uv=600*1e3;function Bv(n,e,t){let r=t.split(/\s+/).filter(o=>o.length>0);return[n,[e,...r]]}function Wv(n){let e=[],t=[];return n.stdout?.on("data",r=>{e.push(r.toString())}),n.stderr?.on("data",r=>{let o=r.toString();t.push(o),o.split(/\r?\n/).filter(Boolean).forEach(i=>f.info("[hvigor:err] %s",i))}),{stdout:e,stderr:t}}function Mi(n){return n.join("")}function Vv(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
20
20
  Output so far:
21
- `+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function Yy(n,e,t){return new Promise(r=>{let i=Vy(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:o,stderr:s}=zy(i),a=setTimeout(()=>{i.kill();let c=[wo(o),wo(s)].filter(Boolean).join(`
21
+ `+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function qv(n,e,t){return new Promise(r=>{let o=Hv(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:i,stderr:s}=Wv(o),a=setTimeout(()=>{o.kill();let c=[Mi(i),Mi(s)].filter(Boolean).join(`
22
22
  `).trim();r({success:!1,output:`Build process timeout after 10 minutes.
23
23
  Output so far:
24
- `+c,exitCode:-1})},qy);i.on("close",(c,l)=>{clearTimeout(a);let d=[wo(o),wo(s)].filter(Boolean).join(`
25
- `).trim()||"";r(Jy(c,l,d))}),i.on("error",c=>{clearTimeout(a),r({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function Fa(n,e,t,r,i){let o={...process.env,DEVECO_SDK_HOME:r},s=Gy(e,t,i);return await Yy(s,n,o)}function Ky(n,e,t){return{node_path:e,hvigor_path:t,sdk_path:n}}function Xy(n){return!n.node_path||!bo.existsSync(n.node_path)?`Node path not found or invalid: ${n.node_path}`:!n.hvigor_path||!bo.existsSync(n.hvigor_path)?`Hvigor path not found or invalid: ${n.hvigor_path}`:!n.sdk_path||!bo.existsSync(n.sdk_path)?`SDK path not found or invalid: ${n.sdk_path}`:null}var Zy="--sync -p product=default --analyze=normal --parallel --incremental --no-daemon";async function Yd(n,e,t,r){try{let i=Ky(e,t,r),o=Xy(i);if(o!=null)return u.info(`Config validation failed: ${o}`),!1;let s=await Fa(n,i.node_path,i.hvigor_path,e,Zy);return u.info(`[hvigor] sync finished: success=${s.success}, exitCode=${s.exitCode}`),s.success}catch(i){return u.info(`syncProject failed: ${JSON.stringify(i)}`),!1}}function Qy(n){let e=te.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh"].includes(e)}function ev(n,e){let t=te.join(n,e.name);return e.isDirectory()?e.name===".cxx"||Xd(t):Qy(t)}function Xd(n){if(!K.existsSync(n))return!1;try{return K.readdirSync(n,{withFileTypes:!0}).some(t=>ev(n,t))}catch{}return!1}function Yt(n){try{let t=new It(n).getAllModuleInfo(),r=[];for(let i of t){let o=te.resolve(n,i.srcPath);Xd(o)&&r.push(i)}return r}catch(e){throw h.error(`[CppCompile] findCppModules threw: ${e instanceof Error?e.message:String(e)}`),e}}function tv(n){let e=[],r=new It(n).getAllModuleInfo();for(let i of r){let o=te.resolve(n,i.srcPath),s=te.join(o,".cxx");K.existsSync(s)&&Zd(s,e)}return e}function Zd(n,e){try{let t=K.readdirSync(n,{withFileTypes:!0});for(let r of t){let i=te.join(n,r.name);r.isDirectory()?Zd(i,e):r.name==="compile_commands.json"&&e.push(i)}}catch{}}function nv(n){let e=[];for(let t of n)try{let r=K.readFileSync(t,"utf8"),i=JSON.parse(r);e.push(...i)}catch{}return e}function rv(n,e){let t=te.join(n,...iv.slice(0,-1));K.mkdirSync(t,{recursive:!0});let r=te.join(t,"compile_commands.json");K.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function $a(n){let e=tv(n);if(e.length>0){let t=nv(e);rv(n,t),h.info(`[CppCompile] compile_commands.json generated, ${t.length} compile commands`)}else h.warn("[CppCompile] No compile_commands.json files found")}var iv=[".idea",".deveco","cxx","compile_commands.json"];async function ov(n,e,t,r,i){if(!r){h.warn(`[CppCompile] hvigorw.js path not injected (sdk '${e}')`);return}h.info(`[CppCompile] sdkPath: ${e}, hvigorPath: ${r}`);for(let o of i){let s=o.name;try{S.assertModuleName(s)}catch{h.warn(`[CppCompile] Skipping module with invalid name: ${s}`);continue}let a=["--mode","module","-p",`module=${o.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"].join(" ");h.info(`[CppCompile] Running compileNative for module: ${o.name}`);let c=await Fa(n,t,r,e,a);c.success?h.info(`[CppCompile] compileNative ${o.name} succeeded`):h.warn(`[CppCompile] compileNative ${o.name} failed: ${c.output}`)}}async function Qd(n,e,t,r){let i=Yt(n);if(i.length===0){h.info("[CppCompile] No C++ modules found, skipping initialization");return}h.info(`[CppCompile] Found ${i.length} C++ module(s): ${i.map(o=>o.name).join(", ")}`),await ov(n,e,t,r,i),$a(n),pv(n,i)}var sv=1e3,av=["src","main","cpp","CMakeLists.txt"],cv=new Set([".cxx","build","node_modules",".preview",".hvigor",".idea"]),lv=new Set(["c","cpp","cxx","cc"]),dv="cpp-source-manifest.json";function uv(n){let e=te.extname(n).replace(/^\./,"").toLowerCase();return lv.has(e)}function Kd(n,e){return K.existsSync(n)?K.statSync(n).mtimeMs-e>sv:!1}function eu(n){return te.join(te.dirname(In(n)),dv)}function tu(n,e,t){let r;try{r=K.readdirSync(n,{withFileTypes:!0})}catch{return}for(let i of r){let o=te.join(n,i.name);if(i.isDirectory()){if(cv.has(i.name))continue;tu(o,e,t)}else uv(i.name)&&t.push(te.relative(e,o).replace(/\\/g,"/"))}}function nu(n,e){let t=[];for(let r of e){let i=S.resolvePathWithinRoot(n,r.srcPath);tu(i,n,t)}return t.sort()}function pv(n,e){let t=nu(n,e),r={files:t,updatedAt:Date.now()},i=eu(n);try{K.mkdirSync(te.dirname(i),{recursive:!0}),K.writeFileSync(i,JSON.stringify(r,null,2),"utf8"),h.info(`[CppCompile] C++ source manifest written, ${t.length} files`)}catch(o){h.warn(`[CppCompile] Failed to write C++ source manifest: ${o}`)}}function fv(n,e){let t=eu(n);if(!K.existsSync(t))return{required:!0,reason:"C++ source manifest not found, needs initialization"};let r;try{let o=JSON.parse(K.readFileSync(t,"utf8"));r=Array.isArray(o.files)?o.files:[]}catch{return{required:!0,reason:"C++ source manifest corrupted, needs initialization"}}let i=nu(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 ru(n){let e=In(n);if(!K.existsSync(e))return{required:!0,reason:"C++ baseline (compile_commands.json) not found, needs initialization"};let t=K.statSync(e).mtimeMs,r=Yt(n);if(r.length===0)return{required:!1,reason:"no C++ modules, skip compileNative"};for(let o of r){let s=S.resolvePathWithinRoot(n,o.srcPath);if(Kd(te.join(s,"build-profile.json5"),t))return{required:!0,reason:`module '${o.name}': build-profile.json5 newer than baseline`};let a=te.join(s,...av);if(Kd(a,t))return{required:!0,reason:`module '${o.name}': CMakeLists.txt newer than baseline`}}let i=fv(n,r);return i||{required:!1,reason:`C++ project up-to-date (baseline: ${new Date(t).toISOString()})`}}function hv(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(", ")}`)}}function gv(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 yv(n,e){let t;if(e.modules&&e.modules.length>0)t=e.modules,gv(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 w(`Multiple entry modules found (${o.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`,"Multiple entry modules found."):new w(`No entry module found and multiple modules available (${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 Wa(n,e){let t=new Set;for(let r of e){let i=r.indexOf("@"),o=i!==-1?r.substring(0,i):r,s=n.getModuleType(o);s==="shared"?t.add("assembleHsp"):s==="har"?t.add("assembleHar"):t.add("assembleHap")}return t}function ti(n,e){let t=e,r=`${n} failed`;console.error(iu(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 Ba(n,e,t,r,i,o){let s=ho(o);console.log(`
26
- [ohpm install] Running...`);try{await n.installAll()}catch(l){ti("ohpm install",l)}let a="";if(s.required){console.log(`
27
- [hvigor sync] Running...`);try{a=await e.sync(t,r)}catch(l){ti("hvigor sync",l)}}else console.log(`
24
+ `+c,exitCode:-1})},Uv);o.on("close",(c,l)=>{clearTimeout(a);let d=[Mi(i),Mi(s)].filter(Boolean).join(`
25
+ `).trim()||"";r(Vv(c,l,d))}),o.on("error",c=>{clearTimeout(a),r({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function sc(n,e,t,r,o){let i={...process.env,DEVECO_SDK_HOME:r},s=Bv(e,t,o);return await qv(s,n,i)}function Gv(n,e,t){return{node_path:e,hvigor_path:t,sdk_path:n}}function zv(n){return!n.node_path||!Oi.existsSync(n.node_path)?`Node path not found or invalid: ${n.node_path}`:!n.hvigor_path||!Oi.existsSync(n.hvigor_path)?`Hvigor path not found or invalid: ${n.hvigor_path}`:!n.sdk_path||!Oi.existsSync(n.sdk_path)?`SDK path not found or invalid: ${n.sdk_path}`:null}var Jv="--sync -p product=default --analyze=normal --parallel --incremental --no-daemon";async function Au(n,e,t,r){try{let o=Gv(e,t,r),i=zv(o);if(i!=null)return f.info(`Config validation failed: ${i}`),!1;let s=await sc(n,o.node_path,o.hvigor_path,e,Jv);return f.info(`[hvigor] sync finished: success=${s.success}, exitCode=${s.exitCode}`),s.success}catch(o){return f.info(`syncProject failed: ${JSON.stringify(o)}`),!1}}function Yv(n){let e=se.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh"].includes(e)}function Kv(n,e){let t=se.join(n,e.name);return e.isDirectory()?e.name===".cxx"||Ru(t):Yv(t)}function Ru(n){if(!Z.existsSync(n))return!1;try{return Z.readdirSync(n,{withFileTypes:!0}).some(t=>Kv(n,t))}catch{}return!1}function rr(n){try{let t=new Nt(n).getAllModuleInfo(),r=[];for(let o of t){let i=se.resolve(n,o.srcPath);Ru(i)&&r.push(o)}return r}catch(e){throw h.error(`[CppCompile] findCppModules threw: ${e instanceof Error?e.message:String(e)}`),e}}function Xv(n){let e=[],r=new Nt(n).getAllModuleInfo();for(let o of r){let i=se.resolve(n,o.srcPath),s=se.join(i,".cxx");Z.existsSync(s)&&Tu(s,e)}return e}function Tu(n,e){try{let t=Z.readdirSync(n,{withFileTypes:!0});for(let r of t){let o=se.join(n,r.name);r.isDirectory()?Tu(o,e):r.name==="compile_commands.json"&&e.push(o)}}catch{}}function Zv(n){let e=[];for(let t of n)try{let r=Z.readFileSync(t,"utf8"),o=JSON.parse(r);e.push(...o)}catch{}return e}function Qv(n,e){let t=se.join(n,...ew.slice(0,-1));Z.mkdirSync(t,{recursive:!0});let r=se.join(t,"compile_commands.json");Z.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function ac(n){let e=Xv(n);if(e.length>0){let t=Zv(e);Qv(n,t),h.info(`[CppCompile] compile_commands.json generated, ${t.length} compile commands`)}else h.warn("[CppCompile] No compile_commands.json files found")}var ew=[".idea",".deveco","cxx","compile_commands.json"];async function tw(n,e,t,r,o){if(!r){h.warn(`[CppCompile] hvigorw.js path not injected (sdk '${e}')`);return}h.info(`[CppCompile] sdkPath: ${e}, hvigorPath: ${r}`);for(let i of o){let s=i.name;try{S.assertModuleName(s)}catch{h.warn(`[CppCompile] Skipping module with invalid name: ${s}`);continue}let a=["--mode","module","-p",`module=${i.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"].join(" ");h.info(`[CppCompile] Running compileNative for module: ${i.name}`);let c=await sc(n,t,r,e,a);c.success?h.info(`[CppCompile] compileNative ${i.name} succeeded`):h.warn(`[CppCompile] compileNative ${i.name} failed: ${c.output}`)}}async function xu(n,e,t,r){let o=rr(n);if(o.length===0){h.info("[CppCompile] No C++ modules found, skipping initialization");return}h.info(`[CppCompile] Found ${o.length} C++ module(s): ${o.map(i=>i.name).join(", ")}`),await tw(n,e,t,r,o),ac(n),cw(n,o)}var rw=1e3,nw=["src","main","cpp","CMakeLists.txt"],ow=new Set([".cxx","build","node_modules",".preview",".hvigor",".idea"]),iw=new Set(["c","cpp","cxx","cc"]),sw="cpp-source-manifest.json";function aw(n){let e=se.extname(n).replace(/^\./,"").toLowerCase();return iw.has(e)}function Du(n,e){return Z.existsSync(n)?Z.statSync(n).mtimeMs-e>rw:!1}function Lu(n){return se.join(se.dirname(Lr(n)),sw)}function Nu(n,e,t){let r;try{r=Z.readdirSync(n,{withFileTypes:!0})}catch{return}for(let o of r){let i=se.join(n,o.name);if(o.isDirectory()){if(ow.has(o.name))continue;Nu(i,e,t)}else aw(o.name)&&t.push(se.relative(e,i).replace(/\\/g,"/"))}}function Mu(n,e){let t=[];for(let r of e){let o=S.resolvePathWithinRoot(n,r.srcPath);Nu(o,n,t)}return t.sort()}function cw(n,e){let t=Mu(n,e),r={files:t,updatedAt:Date.now()},o=Lu(n);try{Z.mkdirSync(se.dirname(o),{recursive:!0}),Z.writeFileSync(o,JSON.stringify(r,null,2),"utf8"),h.info(`[CppCompile] C++ source manifest written, ${t.length} files`)}catch(i){h.warn(`[CppCompile] Failed to write C++ source manifest: ${i}`)}}function lw(n,e){let t=Lu(n);if(!Z.existsSync(t))return{required:!0,reason:"C++ source manifest not found, needs initialization"};let r;try{let i=JSON.parse(Z.readFileSync(t,"utf8"));r=Array.isArray(i.files)?i.files:[]}catch{return{required:!0,reason:"C++ source manifest corrupted, needs initialization"}}let o=Mu(n,e);return o.length!==r.length||o.some((i,s)=>i!==r[s])?{required:!0,reason:`C++ source file set changed (recorded=${r.length}, actual=${o.length})`}:null}function Ou(n){let e=Lr(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=rr(n);if(r.length===0)return{required:!1,reason:"no C++ modules, skip compileNative"};for(let i of r){let s=S.resolvePathWithinRoot(n,i.srcPath);if(Du(se.join(s,"build-profile.json5"),t))return{required:!0,reason:`module '${i.name}': build-profile.json5 newer than baseline`};let a=se.join(s,...nw);if(Du(a,t))return{required:!0,reason:`module '${i.name}': CMakeLists.txt newer than baseline`}}let o=lw(n,r);return o||{required:!1,reason:`C++ project up-to-date (baseline: ${new Date(t).toISOString()})`}}function uw(n,e){if(e.product&&n.validateProduct(e.product),e.buildMode){let t=["debug","release"],r=(n.profile.app.buildModeSet?.map(i=>i.name)??[]).filter(i=>!t.includes(i)),o=[...t,...r];if(!o.includes(e.buildMode))throw new Error(`Build mode '${e.buildMode}' not found. Available modes: ${o.join(", ")}`)}}function pw(n,e){let t=n.profile.modules.map(o=>o.name),r=new Set(t);for(let o of e){let i=o.split("@",1)[0];if(!r.has(i))throw new Error(`Module '${i}' not found in project-level build-profile.json5. Available modules: ${t.join(", ")||"none"}`)}}function mw(n,e){let t;if(e.modules&&e.modules.length>0)t=e.modules,pw(n,t);else{let o=n.profile.modules,i=o.filter(s=>n.getModuleType(s.name)==="entry");if(o.length===1)t=[o[0].name];else if(i.length===1)t=[i[0].name];else throw i.length>1?new w(`Multiple entry modules found (${i.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`,"Multiple entry modules found."):new w(`No entry module found and multiple modules available (${o.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`,"No entry module found and multiple modules available.")}let r=new Set;for(let o of t){let i=o.indexOf("@"),s=i!==-1?o.substring(0,i):o,a=i!==-1?o.substring(i+1):"default";r.add(`${s}@${a}`)}return Array.from(r)}function dc(n,e){let t=new Set;for(let r of e){let o=r.indexOf("@"),i=o!==-1?r.substring(0,o):r,s=n.getModuleType(i);s==="shared"?t.add("assembleHsp"):s==="har"?t.add("assembleHar"):t.add("assembleHap")}return t}function lo(n,e){let t=e,r=`${n} failed`;console.error(_u(r));let o=t.stdout||t.message;throw o&&console.error(o),t.stderr&&console.error(t.stderr),new Error(r,{cause:e})}async function uc(n,e,t,r,o,i){let s=Ti(i);console.log(`
26
+ [ohpm install] Running...`);try{await n.installAll()}catch(l){lo("ohpm install",l)}let a="";if(s.required){console.log(`
27
+ [hvigor sync] Running...`);try{a=await e.sync(t,r)}catch(l){lo("hvigor sync",l)}}else console.log(`
28
28
  [hvigor sync] Skipped (configurations unchanged)`);console.log(`
29
- [hvigor build] Running...`);let c="";try{i.type==="product"?c=await e.buildProduct(t,r):c=await e.buildModules(t,r,i.modulesToBuild,i.moduleTasks)}catch(l){ti("hvigor build",l)}return vv(o),{ohpmMemoryMb:n.peakMemoryMb,syncMemoryMb:a,buildMemoryMb:c}}function vv(n){try{if(Yt(n).length===0)return;$a(n),console.log(Ha(`
30
- Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(Ua(`
31
- Failed to merge compile_commands.json: ${e.message}`))}}async function ou(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=B(o),console.error(iu(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(n,o)}}function wv(n){let e={event:b.CommandExecuted,args:["build",...n.product?["--product"]:[],...n.modules?["--modules"]:[],...n.buildMode?["--build-mode"]:[]]};return n.buildMode&&(e.build_mode=n.buildMode),n.modules&&(e.module_count=n.modules.length),e}function bv(){return{event:b.CommandExecuted,args:["build","clean"]}}async function Sv(n){let e=process.cwd(),t=Y.discover(e);console.warn(Ua("Ensure the project source is trustworthy before proceeding."));let r=await A.new();r.assertJava(),hv(t,n);let i=n.product||"default",o=n.buildMode||"debug",s;if(n.product&&!n.modules)s={type:"product"};else{let d=yv(t,n),g=Wa(t,d);s={type:"modules",modulesToBuild:d,moduleTasks:g}}let a=new Qn(r,t.rootDir),c=new Be(r,t.rootDir),l=await xn(t.rootDir,async()=>Ba(a,c,i,o,s,t.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")});return console.log(`
32
- `+Ha("Build completed successfully")),{bundleName:t.getBundleName(),ohpmMemoryMb:l.ohpmMemoryMb,syncMemoryMb:l.syncMemoryMb,buildMemoryMb:l.buildMemoryMb}}async function Ev(){let n=process.cwd(),e=Y.discover(n);console.warn(Ua("Ensure the project source is trusted before proceeding."));let t=await A.new();t.assertJava();let r=new Be(t,e.rootDir);return await xn(e.rootDir,async()=>{console.log(`
33
- [1/2] Running hvigor clean...`);try{await r.clean()}catch(i){ti("hvigor clean",i)}console.log(`
34
- [2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(i){ti("hvigor --stop-daemon",i)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
35
- `+Ha("Clean completed successfully.")),e.getBundleName()}var su=new mv("build").description("Build HarmonyOS project").option("--product <product>","Product name defined in build-profile.json5 (default: default)").option("--modules <modules...>","Modules to build (format: module or module@target)").option("--build-mode <mode>","Build mode (buildModeSet in build-profile.json5; e.g. debug, release; default: debug)").action(async n=>{let e=wv(n);await ou(e,async()=>{let t=await Sv(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)})});su.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{let n=bv();await ou(n,async()=>{n.bundle_name=await Ev()})});var au=su;import{Command as aw}from"commander";import{green as oi,red as cw,yellow as Ro}from"colorette";import*as si from"path";import{randomUUID as Mv}from"crypto";import{execa as _v}from"execa";import{execa as Ov}from"execa";import{execFile as Pv,spawn as Cv}from"child_process";import{promisify as kv}from"util";var Iv=kv(Pv);function cu(n,e,t){let i=n.replace(/\r\n/g,`
29
+ [hvigor build] Running...`);let c="";try{o.type==="product"?c=await e.buildProduct(t,r):c=await e.buildModules(t,r,o.modulesToBuild,o.moduleTasks)}catch(l){lo("hvigor build",l)}return fw(i),{ohpmMemoryMb:n.peakMemoryMb,syncMemoryMb:a,buildMemoryMb:c}}function fw(n){try{if(rr(n).length===0)return;ac(n),console.log(cc(`
30
+ Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(lc(`
31
+ Failed to merge compile_commands.json: ${e.message}`))}}async function ju(n,e){let t=Date.now(),r=!0,o=null;try{await e()}catch(i){r=!1,o=G(i),console.error(_u(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await I.track(n,i)}}function hw(n){let e={event:b.CommandExecuted,args:["build",...n.product?["--product"]:[],...n.modules?["--modules"]:[],...n.buildMode?["--build-mode"]:[]]};return n.buildMode&&(e.build_mode=n.buildMode),n.modules&&(e.module_count=n.modules.length),e}function gw(){return{event:b.CommandExecuted,args:["build","clean"]}}async function yw(n){let e=process.cwd(),t=W.discover(e);console.warn(lc("Ensure the project source is trustworthy before proceeding."));let r=await A.new();r.assertJava(),uw(t,n);let o=n.product||"default",i=n.buildMode||"debug",s;if(n.product&&!n.modules)s={type:"product"};else{let d=mw(t,n),g=dc(t,d);s={type:"modules",modulesToBuild:d,moduleTasks:g}}let a=new ln(r,t.rootDir),c=new ze(r,t.rootDir),l=await jr(t.rootDir,async()=>uc(a,c,o,i,s,t.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")});return console.log(`
32
+ `+cc("Build completed successfully")),{bundleName:t.getBundleName(),ohpmMemoryMb:l.ohpmMemoryMb,syncMemoryMb:l.syncMemoryMb,buildMemoryMb:l.buildMemoryMb}}async function vw(){let n=process.cwd(),e=W.discover(n);console.warn(lc("Ensure the project source is trusted before proceeding."));let t=await A.new();t.assertJava();let r=new ze(t,e.rootDir);return await jr(e.rootDir,async()=>{console.log(`
33
+ [1/2] Running hvigor clean...`);try{await r.clean()}catch(o){lo("hvigor clean",o)}console.log(`
34
+ [2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(o){lo("hvigor --stop-daemon",o)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
35
+ `+cc("Clean completed successfully.")),e.getBundleName()}var Fu=new dw("build").description("Build HarmonyOS project").option("--product <product>","Product name defined in build-profile.json5 (default: default)").option("--modules <modules...>","Modules to build (format: module or module@target)").option("--build-mode <mode>","Build mode (buildModeSet in build-profile.json5; e.g. debug, release; default: debug)").action(async n=>{let e=hw(n);await ju(e,async()=>{let t=await yw(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)})});Fu.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{let n=gw();await ju(n,async()=>{n.bundle_name=await vw()})});var $u=Fu;import{Command as Ob}from"commander";import{green as wo,red as _b,yellow as es}from"colorette";import*as bo from"path";import{randomUUID as Lw}from"crypto";import{execa as zu}from"execa";import{execa as xw}from"execa";import{execFile as ww,spawn as bw}from"child_process";import{promisify as Sw}from"util";var Ew=Sw(ww);function Hu(n,e,t){let o=n.replace(/\r\n/g,`
36
36
  `).split(`
37
- `),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 lu(n,e,t){let r=n.endsWith("\r")?n.slice(0,-1):n;r.length>0&&t.onData([r],e)}function Av(n,e){return{stdout:n.stdoutChunks.join(""),stderr:n.stderrChunks.join(""),exitCode:e??-1}}function Dv(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function Rv(n,e,t,r,i){n.stdout?.on("data",o=>{let s=o.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=cu(e.stdoutLineBuffer+s,"stdout",t)}),n.stderr?.on("data",o=>{let s=o.toString();e.stderrChunks.push(s),e.stderrLineBuffer=cu(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,lu(e.stdoutLineBuffer,"stdout",t),lu(e.stderrLineBuffer,"stderr",t),t.onClose(o);let s=Av(e,o);r(s)})}async function ni(n,e=[],t={}){try{let{stdout:r,stderr:i}=await Iv(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 du(n,e,t){return await new Promise((r,i)=>{let o=Cv(n,e,{stdio:["inherit","pipe","pipe"]}),s=Dv();Rv(o,s,t,r,i)})}function uu(n){let e=n.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var Tv=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],xv=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function nr(n){return n?Tv.some(e=>e.test(n))?"transient":xv.some(e=>e.test(n))?"fatal":"ok":"ok"}var Va=[800,1500,2500];function Lv(n){return new Promise(e=>setTimeout(e,n))}async function ie(n,e){let t=1+Va.length,r={stdout:"",stderr:"",exitCode:-1};for(let i=0;i<t;i++){if(r=await ni(n,e),r.exitCode===0||nr(r.stderr)!=="transient"||i>=t-1)return r;p(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${Va[i]}ms`),await Lv(Va[i])}return r}var pu=/^[\w.-]+$/;async function So(n,e,t){if(!pu.test(t)){p(`Skipping invalid param key: ${JSON.stringify(t)}`);return}let r=["-t",e,"shell","param","get",t];p(`Executing: ${n} ${r.join(" ")}`);let i=await ie(n,r);if(i.exitCode!==0)return;let o=i.stdout.trim();if(!(!o||nr(o)!=="ok"))return uu(o)}var qa="__DEVECO_PARAM_DELIM__";function Nv(n,e){let t=new Map,r=n.split(qa);for(let i=0;i<e.length;i++){let o=(r[i]??"").trim();if(!o||nr(o)!=="ok")continue;let s=uu(o);s&&t.set(e[i],s)}return t}async function rr(n,e,t){let r=t.filter(a=>pu.test(a)?!0:(p(`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 So(n,e,r[0]);return c&&a.set(r[0],c),a}let i=r.map(a=>`param get ${a}`).join(`; echo ${qa}; `)+`; echo ${qa}`,o=await ie(n,["-t",e,"shell",i]);if(o.exitCode===0){let a=Nv(o.stdout,r);if(a.size>0)return a}p(`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 So(n,e,a);c&&s.set(a,c)}return s}function yt(n){return n.startsWith("127.0.0.1:")}var fu=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],oe=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 p(`Executing: ${this.hdcPath} ${e.join(" ")}`),Ov(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let r of e.split(`
38
- `)){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"){p(`[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 rr(this.hdcPath,e,[...fu]);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 w(`Multiple devices match "${t}". Use a serial instead:
39
- `+o.map(s=>` - ${s.name} (${s.device.serial})`).join(`
40
- `),"Multiple devices match."):new w(`Device "${t}" not found. Use \`devecocli device list\` to see available targets.`,"Device not found.")}return e[0]}async getDeviceDetail(e){let t={serial:e,status:"device"};try{let r=await rr(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=yt(e),r,i;try{let o=await rr(this.hdcPath,e,[...fu]);r=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:i}}};var Kt=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=oe.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;p(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await _v(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){S.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){if(t.length===0)return;let i=`/data/local/tmp/${Mv()}`;try{await this.runHdc(["-t",e,"shell","mkdir",i]);for(let s of t){let a=await this.runHdc(["-t",e,"file","send",s,i+"/"]);if(!a.startsWith("FileTransfer finish"))throw new Error(a)}let o=await this.runHdc(["-t",e,"shell","bm","install","-p",i]);if(!o.includes("install bundle successfully."))throw new Error(o);console.log("App installed successfully")}finally{await this.runHdc(["-t",e,"shell","rm","-rf",i],!1)}}async launchApp(e,t,r){S.assertBundleNameStrict(t),S.assertAbilityName(r);let i=["-t",e,"shell","aa","start","-a",r,"-b",t];return await this.runHdc(i)}async forceStopApp(e,t){S.assertBundleNameStrict(t);let r=["-t",e,"shell","aa","force-stop",t];return await this.runHdc(r,!1)}};import Ga from"fs";import*as Nn from"path";function ri(n,e){if(!Ga.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=Ga.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=Nn.resolve(e),o=new Set,s=[];for(let a of r){let c=Nn.resolve(i,a),l=Nn.isAbsolute(a)?Nn.relative(i,a):a;if(l.startsWith(".."))throw new Error(`File path is outside the project directory: ${a}`);let d=S.isPathContainedWithSymlink(l,i);if(!d.contained){if(!Ga.existsSync(c))throw new Error(`File not found: ${a}`);let g=d.reason?`; ${d.reason}`:"";throw new Error(`File path is outside the project directory: ${a}${g}`)}o.has(c)||(o.add(c),s.push(c))}return s}import za from"fs";import ii from"path";import{execa as $v}from"execa";import mu from"fs";import*as hu from"path";import jv from"json5";function Fv(n,e){try{let r=jv.parse(mu.readFileSync(n,"utf-8")).modules?.find(i=>i.name===e);return r?.srcPath?r.srcPath.replace(/^\.\//,""):null}catch(t){return p(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function vt(n,e){let t=hu.join(n,"build-profile.json5");return mu.existsSync(t)?Fv(t,e)??e:e}async function gu(n,e,t,r){let i=ii.dirname(n.javaPath),o={...process.env,PATH:`${i}${ii.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","--analyze=normal","--parallel","--incremental","--no-daemon"];p(`[buildSignedHqf] ${n.nodePath} ${s.join(" ")}`);let a=await $v(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=>Uv(e,l,r))}function yu(n,e,t){let r=vt(n,e);return ii.join(n,r,"build",t,"outputs")}function Hv(n,e,t){return ii.join(yu(n,e,t),`${e}-${t}-signed.hqf`)}function Uv(n,e,t){let r=yu(n,e,t),i=Hv(n,e,t);if(za.existsSync(i))return i;let o=Ja(r,"-signed.hqf")??Ja(r,".hqf");if(!o)throw new Error(`Signed hqf not found at ${i} (and no *.hqf under ${r})`);return p(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${o}`),o}function Ja(n,e){if(!za.existsSync(n))return null;for(let t of za.readdirSync(n,{withFileTypes:!0})){let r=ii.join(n,t.name);if(t.isDirectory()){let i=Ja(r,e);if(i)return i}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import X from"fs";import*as N from"path";import Ya from"json5";var vu="default",ir=class n{static writeChangedFileLists(e,t,r,i){let o=t||vu,s=n.loadBuildProfile(e);if(!s)return{writtenModules:[],skippedFiles:r};let a=s.modules,c=n.filterRunnableModules(e,a);if(c.length===0)return{writtenModules:[],skippedFiles:r};let l=n.buildReverseDependencyMap(e,a),d=n.createCollectors(c),g=n.collectChanges(r,e,a,l,d);return{writtenModules:n.flushCollectors(e,o,c,d,i),skippedFiles:g}}static initEmptyChangedFileLists(e,t,r){let i=t||vu,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=N.normalize(a),l=n.classifyFile(c,t,r);if(l.fileClass==="unknown"){s.push(c);continue}let d=n.findModuleByFilePath(c,t,r);if(!d){s.push(c);continue}let g=n.resolveTargetModules(d,t,r,i);if(g.length===0){s.push(c);continue}n.dispatchToCollectors(g,o,c,l,d.srcPath,t)}return s}static resolveTargetModules(e,t,r,i){let o=n.getModuleType(t,e.srcPath);return o==="entry"||o==="shared"?[e.name]:Array.from(n.findTopLevelConsumers(e.name,i,t,r))}static dispatchToCollectors(e,t,r,i,o,s){for(let a of e){let c=t.get(a);c&&n.addFileToCollector(c,r,i.fileClass,o,s)}}static flushCollectors(e,t,r,i,o){let s=[];for(let a of r){let c=i.get(a.name);if(!c||!n.hasAnyChange(c))continue;(!o||a.name===o)&&c.hotReloadEntries.length>0&&n.writeApplyFile(e,a.srcPath,t,c.hotReloadEntries),n.writePatchFile(e,a.srcPath,t,c.patchEtsFiles,c.patchRawFiles,c.patchResFiles),s.push(a.name)}return s}static hasAnyChange(e){return e.hotReloadEntries.length>0||e.patchEtsFiles.length>0||e.patchRawFiles.length>0||e.patchResFiles.length>0||e.nativeFiles.length>0}static initEmptyForModule(e,t,r,i){let o=N.join(e,r,"build",t,"intermediates","patch","default"),s=N.join(o,"changedFileList.json");if(X.existsSync(s)||(X.mkdirSync(o,{recursive:!0}),X.writeFileSync(s,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!i)return;let a=N.join(e,r,"build",t,"intermediates","hotReload"),c=N.join(a,"changedFileList.json");X.existsSync(c)||(X.mkdirSync(a,{recursive:!0}),X.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=N.join(e,"build-profile.json5");if(!X.existsSync(t))return null;try{let r=X.readFileSync(t,"utf-8");return Ya.parse(r)}catch{return null}}static classifyFile(e,t,r){let i=N.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=N.normalize(e);for(let o of r){let s=N.normalize(N.join(t,o.srcPath)),a=s+N.sep;if(i.startsWith(a)||i===s)return o}return null}static getModuleType(e,t){let r=N.join(e,t,"src","main","module.json5");if(!X.existsSync(r))return"entry";try{let i=X.readFileSync(r,"utf-8");return Ya.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=N.join(e,t,"oh-package.json5");if(!X.existsSync(r))return[];try{let i=X.readFileSync(r,"utf-8"),o=Ya.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=N.resolve(e,t,o);return i.find(l=>N.resolve(e,l.srcPath)===a)?.name??null}static findTopLevelConsumers(e,t,r,i){let o=new Set,s=new Set,a=[e];for(;a.length>0;){let c=a.shift();s.has(c)||(s.add(c),n.processDependents(c,t,r,i,o,a))}return o}static processDependents(e,t,r,i,o,s){let a=t.get(e)||[];for(let c of a){let l=i.find(g=>g.name===c);if(!l)continue;let d=n.getModuleType(r,l.srcPath);(d==="entry"||d==="shared")&&o.add(c),d==="har"&&s.push(c)}}static addFileToCollector(e,t,r,i,o){let s=N.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=N.join(e,o,"build",r,"intermediates","hotReload","changedFileList.json"),a=n.readExistingApply(s),c=n.mergeApplyEntries(a,i),l=N.dirname(s);X.existsSync(l)||X.mkdirSync(l,{recursive:!0}),X.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),p(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!X.existsSync(e))return[];try{let t=X.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,r,i,o,s){let a=t.replace(/^\.\//,""),c=N.join(e,a,"build",r,"intermediates","patch","default","changedFileList.json"),l=n.readExistingPatch(c),d=N.join(e,a,"src","main","ets"),g=i.map(ze=>n.resolveRelativePathForPatch(ze,d)),v=n.mergeStrings(l.modifiedFiles,g),D=n.mergePatchResources(l.rawFile,o),He=n.mergePatchResources(l.resFile,s),ye=N.dirname(c);X.existsSync(ye)||X.mkdirSync(ye,{recursive:!0}),X.writeFileSync(c,JSON.stringify({resources:{resFile:He,rawFile:D},modifiedFiles:v}),"utf-8"),p(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!X.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=X.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 N.relative(N.normalize(t),N.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 Wv from"fs";import{randomUUID as Bv}from"crypto";import{execa as Vv}from"execa";var or=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!Wv.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}S.assertBundleName(r);let o=`/data/local/tmp/${Bv()}`,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(p(`[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;p(`[InstallHqf] Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await Vv(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}};var qv="6.1.1",Eo=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}toolProvider;projectRoot;async execute(e){await xn(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(qv);let t=ri(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=ir.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 p(`[Apply] hvigor assembleDevHqf --no-daemon (modules=${t.join(",")})`),await gu(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 or(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 Kt(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 Kt(this.toolProvider);try{await t.launchApp(e.targetDeviceId,e.bundleName,e.abilityName),console.log("[Apply] app launched")}catch(r){console.warn(`[Apply] launch app failed: ${r.message}`)}}};import Ka from"fs";import*as $ from"path";var Po=class n{static generate(e,t,r,i){let o=vt(e,t),s=$.join(e,o),a=$.join(s,"build","config"),c=n.buildConfig(e,s,r,i);Ka.mkdirSync(a,{recursive:!0}),Ka.writeFileSync($.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),p(`[BuildConfigManager] buildConfig.json written to ${a}`);let l=$.join(s,"build",r,"intermediates","loader_out",r,"ets");Ka.mkdirSync(l,{recursive:!0})}static buildConfig(e,t,r,i){let o=$.dirname(i.nodePath)+$.sep,s=$.join(t,"build",r),a=$.join(s,"intermediates"),c=$.join(a,"loader_out",r),l=$.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:$.join(e,"build-profile.json5"),localPropertiesPath:$.join(e,"local.properties"),appResource:$.join(l,"ResourceTable.txt"),cachePath:$.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:$.join(a,"loader",r,"loader.json"),aceModuleJsonPath:$.join(l,"module.json"),aceSoPath:$.join(c,"nativeDependencies.txt"),aceModuleRoot:$.join(t,"src","main","ets"),aceModuleBuild:$.join(c,"ets"),aceProfilePath:$.join(l,"resources","base","profile"),aceSuperVisualPath:$.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"false",mode:"hotReload",oldMapFilePath:$.join(c,"ets"),changedFileList:$.join(a,"patch",r,"changedFileList.json"),patchAbcPath:$.join(a,"patch",r,"ets"),removeChangedFileListInSdk:"true"}}}};import wu from"fs";import*as U from"path";var Co=class n{static generate(e,t,r,i){let o=vt(e,t),s=U.join(e,o),a=U.join(s,"build","config"),c=n.buildConfig(e,s,r,i);wu.mkdirSync(a,{recursive:!0}),wu.writeFileSync(U.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),p(`[HotReloadBuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,i){let o=U.dirname(i.nodePath)+U.sep,s=U.join(t,"build",r),a=U.join(s,"intermediates"),c=U.join(a,"loader_out",r),l=U.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:U.join(e,"build-profile.json5"),localPropertiesPath:U.join(e,"local.properties"),appResource:U.join(l,"ResourceTable.txt"),cachePath:U.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:U.join(a,"loader",r,"loader.json"),aceModuleJsonPath:U.join(l,"module.json"),aceSoPath:U.join(c,"nativeDependencies.txt"),aceModuleRoot:U.join(t,"src","main","ets"),aceModuleBuild:U.join(c,"ets"),aceProfilePath:U.join(l,"resources","base","profile"),aceSuperVisualPath:U.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:U.join(c,"ets"),changedFileList:U.join(a,"hotReload","changedFileList.json"),patchAbcPath:U.join(a,"hotReload","patchAbcPath","ets"),removeChangedFileListInSdk:"true"}}}};import bu from"crypto";import Qe from"fs";import et from"path";import Su from"os";import{io as Gv}from"socket.io-client";var zv=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),sr=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;Qe.mkdirSync(et.dirname(i),{recursive:!0}),Qe.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(`
37
+ `),i=o.pop()??"",s=o.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),i}function Uu(n,e,t){let r=n.endsWith("\r")?n.slice(0,-1):n;r.length>0&&t.onData([r],e)}function Pw(n,e){return{stdout:n.stdoutChunks.join(""),stderr:n.stderrChunks.join(""),exitCode:e??-1}}function Cw(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function kw(n,e,t,r,o){n.stdout?.on("data",i=>{let s=i.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=Hu(e.stdoutLineBuffer+s,"stdout",t)}),n.stderr?.on("data",i=>{let s=i.toString();e.stderrChunks.push(s),e.stderrLineBuffer=Hu(e.stderrLineBuffer+s,"stderr",t)}),n.on("error",i=>{e.settled||(e.settled=!0,t.onError(i),o(i))}),n.on("close",i=>{if(e.settled)return;e.settled=!0,Uu(e.stdoutLineBuffer,"stdout",t),Uu(e.stderrLineBuffer,"stderr",t),t.onClose(i);let s=Pw(e,i);r(s)})}async function uo(n,e=[],t={}){try{let{stdout:r,stderr:o}=await Ew(n,e,t);return{stdout:typeof r=="string"?r.trim():"",stderr:typeof o=="string"?o.trim():"",exitCode:0}}catch(r){let o=r;return{stdout:o.stdout?.trim()||"",stderr:o.stderr?.trim()??o.message,exitCode:typeof o.code=="number"?o.code:1}}}async function Bu(n,e,t){return await new Promise((r,o)=>{let i=bw(n,e,{stdio:["inherit","pipe","pipe"]}),s=Cw();kw(i,s,t,r,o)})}function Wu(n){let e=n.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var Iw=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],Aw=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function nr(n){return n?Iw.some(e=>e.test(n))?"transient":Aw.some(e=>e.test(n))?"fatal":"ok":"ok"}var Dw=/(?:^|\s)(\d{2,})(?:\s|$)/;function Vu(n){let e=n.stdout.trim(),t=n.stderr.trim();return nr(e)!=="ok"||nr(t)!=="ok"?"query-failed":n.exitCode===0?e&&Dw.test(e)?"alive":"dead":n.exitCode===1&&!e&&!t?"dead":"query-failed"}var pc=[800,1500,2500];function Rw(n){return new Promise(e=>setTimeout(e,n))}async function ee(n,e){let t=1+pc.length,r={stdout:"",stderr:"",exitCode:-1};for(let o=0;o<t;o++){if(r=await uo(n,e),r.exitCode===0||nr(r.stderr)!=="transient"||o>=t-1)return r;u(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${pc[o]}ms`),await Rw(pc[o])}return r}var qu=/^[\w.-]+$/;async function _i(n,e,t){if(!qu.test(t)){u(`Skipping invalid param key: ${JSON.stringify(t)}`);return}let r=["-t",e,"shell","param","get",t];u(`Executing: ${n} ${r.join(" ")}`);let o=await ee(n,r);if(o.exitCode!==0)return;let i=o.stdout.trim();if(!(!i||nr(i)!=="ok"))return Wu(i)}var mc="__DEVECO_PARAM_DELIM__";function Tw(n,e){let t=new Map,r=n.split(mc);for(let o=0;o<e.length;o++){let i=(r[o]??"").trim();if(!i||nr(i)!=="ok")continue;let s=Wu(i);s&&t.set(e[o],s)}return t}async function pn(n,e,t){let r=t.filter(a=>qu.test(a)?!0:(u(`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 _i(n,e,r[0]);return c&&a.set(r[0],c),a}let o=r.map(a=>`param get ${a}`).join(`; echo ${mc}; `)+`; echo ${mc}`,i=await ee(n,["-t",e,"shell",o]);if(i.exitCode===0){let a=Tw(i.stdout,r);if(a.size>0)return a}u(`Batched param fetch failed (exit=${i.exitCode}), falling back to individual calls for ${e}`);let s=new Map;for(let a of r){let c=await _i(n,e,a);c&&s.set(a,c)}return s}function It(n){return n.startsWith("127.0.0.1:")}var Gu=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],de=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(),o=t?.trim();if(!r||!o)return r;let i=new RegExp(`^${this.escapeRegExp(o)}(\\s+|[-_]+)?`,"i");return r.replace(i,"").trim()||r}async executeHdc(e){return u(`Executing: ${this.hdcPath} ${e.join(" ")}`),xw(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let r of e.split(`
38
+ `)){let o=r.trim();if(!o||o.startsWith("[Empty]"))continue;let i=o.split(/\s+/),s=i[0];if(!s||s.startsWith("[Empty]"))continue;let a=i.length>=2?i[1]:"device";if(a.toLowerCase()==="unauthorized"){u(`[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 o=e.get("const.product.model");if(o&&o!=="emulator"){let s=e.get("const.product.brand");return this.stripBrandPrefix(o,s)}let i=e.get("const.build.product");if(i&&i!=="emulator")return i}async getDeviceName(e){let t=await pn(this.hdcPath,e,[...Gu]);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 o=t.toLowerCase(),i=[];for(let s of e){let a=await this.getDeviceName(s.serial);a.toLowerCase()===o&&i.push({device:s,name:a})}if(i.length===1)return i[0].device;throw i.length>1?new w(`Multiple devices match "${t}". Use a serial instead:
39
+ `+i.map(s=>` - ${s.name} (${s.device.serial})`).join(`
40
+ `),"Multiple devices match."):new w(`Device "${t}" not found. Use \`devecocli device list\` to see available targets.`,"Device not found.")}return e[0]}async getDeviceDetail(e){let t={serial:e,status:"device"};try{let r=await pn(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=r.get("const.product.devicetype");let o=r.get("const.ohos.apiversion"),i=r.get("const.ohos.releasetype");o&&(t.osVersion=i?`API ${o} (${i})`:`API ${o}`)}catch{}return t}async listDevicesWithName(){let e=await this.listDevices();return Promise.all(e.map(async t=>({serial:t.serial,name:await this.getDeviceName(t.serial)})))}async getConnectedEntries(){let e=await this.listDevices();return Promise.all(e.map(t=>this.buildConnectedEntry(t.serial)))}async buildConnectedEntry(e){let t=It(e),r,o;try{let i=await pn(this.hdcPath,e,[...Gu]);r=this.extractDisplayName(i),o=i.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:o}}};var Ye=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=de.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;u(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:o}=await zu(r,e,{env:{...process.env}});return o}catch(o){if(t)throw o;return o.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){S.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){if(t.length===0)return;let o=`/data/local/tmp/${Lw()}`;try{await this.runHdc(["-t",e,"shell","mkdir",o]);for(let s of t){let a=await this.runHdc(["-t",e,"file","send",s,o+"/"]);if(!a.startsWith("FileTransfer finish"))throw new Error(a)}let i=await this.runHdc(["-t",e,"shell","bm","install","-p",o]);if(!i.includes("install bundle successfully."))throw new Error(i);console.log("App installed successfully")}finally{await this.runHdc(["-t",e,"shell","rm","-rf",o],!1)}}async launchApp(e,t,r){S.assertBundleNameStrict(t),S.assertAbilityName(r);let o=["-t",e,"shell","aa","start","-a",r,"-b",t];return await this.runHdc(o)}async pidofBundle(e,t){S.assertBundleNameStrict(t);let r=["-t",e,"shell","pidof",t],o=this.toolProvider.hdcPath;u(`Executing: ${o} ${r.join(" ")}`);let i=await ee(o,r),s=Vu(i);if(s==="query-failed"){let a=[i.stdout,i.stderr].map(c=>c.trim()).filter(Boolean).join(" ");throw new Error(`pidof query failed for '${t}': ${a||`exit ${i.exitCode}`}`)}return s==="alive"}async forceStopApp(e,t){S.assertBundleNameStrict(t);let r=["-t",e,"shell","aa","force-stop",t];return await this.runHdc(r,!1)}async transferFile(e,t,r,o){let i=["-t",e,"file",t,r,o],s=await this.runHdc(i,!1);if(!s.includes("FileTransfer finish"))throw new Error(`File ${t} failed: ${s.trim()||"hdc returned no output"}`);return s.trim()}async runSqlite3(e,t,r=[]){let o=["-t",e,"shell","sqlite3",t,...r];await zu(this.toolProvider.hdcPath,o,{stdio:"inherit",env:{...process.env}})}};import fc from"fs";import*as $r from"path";function po(n,e){if(!fc.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=fc.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 o=$r.resolve(e),i=new Set,s=[];for(let a of r){let c=$r.resolve(o,a),l=$r.isAbsolute(a)?$r.relative(o,a):a;if(l.startsWith(".."))throw new Error(`File path is outside the project directory: ${a}`);let d=S.isPathContainedWithSymlink(l,o);if(!d.contained){if(!fc.existsSync(c))throw new Error(`File not found: ${a}`);let g=d.reason?`; ${d.reason}`:"";throw new Error(`File path is outside the project directory: ${a}${g}`)}i.has(c)||(i.add(c),s.push(c))}return s}import hc from"fs";import mo from"path";import{execa as Ow}from"execa";import Ju from"fs";import*as Yu from"path";import Nw from"json5";function Mw(n,e){try{let r=Nw.parse(Ju.readFileSync(n,"utf-8")).modules?.find(o=>o.name===e);return r?.srcPath?r.srcPath.replace(/^\.\//,""):null}catch(t){return u(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function At(n,e){let t=Yu.join(n,"build-profile.json5");return Ju.existsSync(t)?Mw(t,e)??e:e}async function Ku(n,e,t,r){let o=mo.dirname(n.javaPath),i={...process.env,PATH:`${o}${mo.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","--analyze=normal","--parallel","--incremental","--no-daemon"];u(`[buildSignedHqf] ${n.nodePath} ${s.join(" ")}`);let a=await Ow(n.nodePath,s,{cwd:e,env:i,stdout:"inherit",stderr:"inherit",reject:!1}),c=(a.exitCode??0)|0;if(c===-1)throw new Error("hvigor hot compile produced invalid abc (exit code -1)");if(c!==0)throw new Error(`hvigor assembleDevHqf failed with exit code ${a.exitCode}`);return t.map(l=>jw(e,l,r))}function Xu(n,e,t){let r=At(n,e);return mo.join(n,r,"build",t,"outputs")}function _w(n,e,t){return mo.join(Xu(n,e,t),`${e}-${t}-signed.hqf`)}function jw(n,e,t){let r=Xu(n,e,t),o=_w(n,e,t);if(hc.existsSync(o))return o;let i=gc(r,"-signed.hqf")??gc(r,".hqf");if(!i)throw new Error(`Signed hqf not found at ${o} (and no *.hqf under ${r})`);return u(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${i}`),i}function gc(n,e){if(!hc.existsSync(n))return null;for(let t of hc.readdirSync(n,{withFileTypes:!0})){let r=mo.join(n,t.name);if(t.isDirectory()){let o=gc(r,e);if(o)return o}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import te from"fs";import*as N from"path";import yc from"json5";var Zu="default",mn=class n{static writeChangedFileLists(e,t,r,o){let i=t||Zu,s=n.loadBuildProfile(e);if(!s)return{writtenModules:[],skippedFiles:r};let a=s.modules,c=n.filterRunnableModules(e,a);if(c.length===0)return{writtenModules:[],skippedFiles:r};let l=n.buildReverseDependencyMap(e,a),d=n.createCollectors(c),g=n.collectChanges(r,e,a,l,d);return{writtenModules:n.flushCollectors(e,i,c,d,o),skippedFiles:g}}static initEmptyChangedFileLists(e,t,r){let o=t||Zu,i=n.loadBuildProfile(e);if(!i)return[];let s=i.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,o,c.srcPath,d),a.push(c.name)}return a}static filterRunnableModules(e,t){return t.filter(r=>{let o=n.getModuleType(e,r.srcPath);return o==="entry"||o==="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,o,i){let s=[];for(let a of e){let c=N.normalize(a),l=n.classifyFile(c,t,r);if(l.fileClass==="unknown"){s.push(c);continue}let d=n.findModuleByFilePath(c,t,r);if(!d){s.push(c);continue}let g=n.resolveTargetModules(d,t,r,o);if(g.length===0){s.push(c);continue}n.dispatchToCollectors(g,i,c,l,d.srcPath,t)}return s}static resolveTargetModules(e,t,r,o){let i=n.getModuleType(t,e.srcPath);return i==="entry"||i==="shared"?[e.name]:Array.from(n.findTopLevelConsumers(e.name,o,t,r))}static dispatchToCollectors(e,t,r,o,i,s){for(let a of e){let c=t.get(a);c&&n.addFileToCollector(c,r,o.fileClass,i,s)}}static flushCollectors(e,t,r,o,i){let s=[];for(let a of r){let c=o.get(a.name);if(!c||!n.hasAnyChange(c))continue;(!i||a.name===i)&&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,o){let i=N.join(e,r,"build",t,"intermediates","patch","default"),s=N.join(i,"changedFileList.json");if(te.existsSync(s)||(te.mkdirSync(i,{recursive:!0}),te.writeFileSync(s,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!o)return;let a=N.join(e,r,"build",t,"intermediates","hotReload"),c=N.join(a,"changedFileList.json");te.existsSync(c)||(te.mkdirSync(a,{recursive:!0}),te.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=N.join(e,"build-profile.json5");if(!te.existsSync(t))return null;try{let r=te.readFileSync(t,"utf-8");return yc.parse(r)}catch{return null}}static classifyFile(e,t,r){let o=N.extname(e).toLowerCase();if(o===".ets"||o===".ts")return{fileClass:"ets_ts",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};if(o===".cpp"||o===".cc"||o===".c"||o===".h"||o===".hpp")return{fileClass:"native",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};let i=e.replace(/\\/g,"/");return i.includes("/resources/rawfile/")?{fileClass:"raw_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:i.includes("/resources/resfile/")?{fileClass:"res_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:{fileClass:"unknown",moduleSrcPath:""}}static findModuleByFilePath(e,t,r){let o=N.normalize(e);for(let i of r){let s=N.normalize(N.join(t,i.srcPath)),a=s+N.sep;if(o.startsWith(a)||o===s)return i}return null}static getModuleType(e,t){let r=N.join(e,t,"src","main","module.json5");if(!te.existsSync(r))return"entry";try{let o=te.readFileSync(r,"utf-8");return yc.parse(o)?.module?.type||"entry"}catch{return"entry"}}static buildReverseDependencyMap(e,t){let r=new Map;for(let o of t){let i=n.readLocalDependencies(e,o.srcPath);for(let s of i){let a=r.get(s)||[];a.includes(o.name)||a.push(o.name),r.set(s,a)}}return r}static readLocalDependencies(e,t){let r=N.join(e,t,"oh-package.json5");if(!te.existsSync(r))return[];try{let o=te.readFileSync(r,"utf-8"),i=yc.parse(o);return n.resolveDepModuleNames(e,t,i.dependencies||{})}catch{return[]}}static resolveDepModuleNames(e,t,r){let o=n.loadBuildProfile(e);if(!o)return[];let i=o.modules,s=[];for(let a of Object.values(r)){if(typeof a!="string")continue;let c=n.tryResolveDepModule(e,t,a,i);c&&s.push(c)}return s}static tryResolveDepModule(e,t,r,o){let i=r;if(!(i.startsWith("file:")||i.startsWith(".")||i.startsWith("..")))return null;i.startsWith("file:")&&(i=i.substring(5));let a=N.resolve(e,t,i);return o.find(l=>N.resolve(e,l.srcPath)===a)?.name??null}static findTopLevelConsumers(e,t,r,o){let i=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,o,i,a))}return i}static processDependents(e,t,r,o,i,s){let a=t.get(e)||[];for(let c of a){let l=o.find(g=>g.name===c);if(!l)continue;let d=n.getModuleType(r,l.srcPath);(d==="entry"||d==="shared")&&i.add(c),d==="har"&&s.push(c)}}static addFileToCollector(e,t,r,o,i){let s=N.join(i,o,"src","main","resources");r==="ets_ts"?(e.hotReloadEntries.push({filePath:t,belongProjectPath:i}),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,o){let i=t.replace(/^\.\//,""),s=N.join(e,i,"build",r,"intermediates","hotReload","changedFileList.json"),a=n.readExistingApply(s),c=n.mergeApplyEntries(a,o),l=N.dirname(s);te.existsSync(l)||te.mkdirSync(l,{recursive:!0}),te.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),u(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!te.existsSync(e))return[];try{let t=te.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,r,o,i,s){let a=t.replace(/^\.\//,""),c=N.join(e,a,"build",r,"intermediates","patch","default","changedFileList.json"),l=n.readExistingPatch(c),d=N.join(e,a,"src","main","ets"),g=o.map(Ae=>n.resolveRelativePathForPatch(Ae,d)),v=n.mergeStrings(l.modifiedFiles,g),P=n.mergePatchResources(l.rawFile,i),ie=n.mergePatchResources(l.resFile,s),B=N.dirname(c);te.existsSync(B)||te.mkdirSync(B,{recursive:!0}),te.writeFileSync(c,JSON.stringify({resources:{resFile:ie,rawFile:P},modifiedFiles:v}),"utf-8"),u(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!te.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=te.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 N.relative(N.normalize(t),N.normalize(e)).replace(/\\/g,"/")}static mergeApplyEntries(e,t){let r=new Set,o=[];for(let i of[...e,...t])r.has(i.filePath)||(r.add(i.filePath),o.push(i));return o}static mergeStrings(e,t){let r=new Set,o=[];for(let i of[...e,...t])r.has(i)||(r.add(i),o.push(i));return o}static mergePatchResources(e,t){let r=new Set,o=[];for(let i of[...e,...t])r.has(i.filePath)||(r.add(i.filePath),o.push(i));return o}};import Fw from"fs";import{randomUUID as $w}from"crypto";import{execa as Hw}from"execa";var fn=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!Fw.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}S.assertBundleName(r);let i=`/data/local/tmp/${$w()}`,s=[];try{for(let a=0;a<t.length;a++){let c=`${i}/${r}_${a}.hqf`;s.push(c),await this.pushHqf(e,t[a],i,c)}return await this.executeQuickfix(e,s)}catch(a){let c=`hqf install error: ${a.message}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}finally{await this.runHdc(["-t",e,"shell","rm","-rf",i],!1)}}async pushHqf(e,t,r,o){console.log(`[Apply] Pushing hqf to device ${e}: ${t}`),await this.runHdc(["-t",e,"shell","mkdir","-p",r]);let i=await this.runHdc(["-t",e,"file","send",t,o]);if(!i.startsWith("FileTransfer finish"))throw new Error(`Failed to send hqf: ${i}`)}async executeQuickfix(e,t){console.log(`[Apply] Installing ${t.length} hqf patch(es) via quickfix...`);let r=["-t",e,"shell","bm","quickfix","-a","-f",...t,"-d"];await this.getApiVersion(e)>17&&r.push("-o");let i=await this.runHdc(r,!1);if(u(`[InstallHqf] quickfix output: ${i}`),/succe(?:ed|ss)/i.test(i))return console.log("[Apply] hqf installed successfully."),{success:!0,message:"hqf quickfix installed successfully."};let s=`hqf quickfix install failed. Device response: ${i||"(empty)"}. Please try reinstalling the application.`;return console.error(`[Apply] ${s}`),{success:!1,message:s}}async getApiVersion(e){try{let t=await this.runHdc(["-t",e,"shell","param","get","const.ohos.apiversion"],!1),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;u(`[InstallHqf] Executing: ${r} ${e.join(" ")}`);try{let{stdout:o}=await Hw(r,e,{env:{...process.env}});return o}catch(o){if(t)throw o;return o.stdout||""}}};var Uw="6.1.1",ji=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}toolProvider;projectRoot;async execute(e){await jr(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(Uw);let t=po(e.applyFile,this.projectRoot);console.log(`[Apply] Parsed ${t.length} changed file(s)`);let r=this.writeChangeFileList(e,t);await this.stopApp(e);let o=await this.buildHqf(e,r);await this.installHqf(e,o),await this.launchApp(e),console.log("[Apply] Apply complete")}writeChangeFileList(e,t){let r=mn.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 u(`[Apply] hvigor assembleDevHqf --no-daemon (modules=${t.join(",")})`),await Ku(this.toolProvider,this.projectRoot,t,e.productName)}async installHqf(e,t){console.log(`[Apply] Installing ${t.length} hqf(s) to ${e.targetDeviceId}`);let o=await new fn(this.toolProvider).install(e.targetDeviceId,t,e.bundleName);if(!o.success)throw new Error(`hqf install failed: ${o.message}`);console.log("[Apply] hqf installed")}async stopApp(e){let t=new Ye(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 Ye(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 vc from"fs";import*as $ from"path";var Fi=class n{static generate(e,t,r,o){let i=At(e,t),s=$.join(e,i),a=$.join(s,"build","config"),c=n.buildConfig(e,s,r,o);vc.mkdirSync(a,{recursive:!0}),vc.writeFileSync($.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),u(`[BuildConfigManager] buildConfig.json written to ${a}`);let l=$.join(s,"build",r,"intermediates","loader_out",r,"ets");vc.mkdirSync(l,{recursive:!0})}static buildConfig(e,t,r,o){let i=$.dirname(o.nodePath)+$.sep,s=$.join(t,"build",r),a=$.join(s,"intermediates"),c=$.join(a,"loader_out",r),l=$.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:i,projectProfilePath:$.join(e,"build-profile.json5"),localPropertiesPath:$.join(e,"local.properties"),appResource:$.join(l,"ResourceTable.txt"),cachePath:$.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:$.join(a,"loader",r,"loader.json"),aceModuleJsonPath:$.join(l,"module.json"),aceSoPath:$.join(c,"nativeDependencies.txt"),aceModuleRoot:$.join(t,"src","main","ets"),aceModuleBuild:$.join(c,"ets"),aceProfilePath:$.join(l,"resources","base","profile"),aceSuperVisualPath:$.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"false",mode:"hotReload",oldMapFilePath:$.join(c,"ets"),changedFileList:$.join(a,"patch",r,"changedFileList.json"),patchAbcPath:$.join(a,"patch",r,"ets"),removeChangedFileListInSdk:"true"}}}};import Qu from"fs";import*as U from"path";var $i=class n{static generate(e,t,r,o){let i=At(e,t),s=U.join(e,i),a=U.join(s,"build","config"),c=n.buildConfig(e,s,r,o);Qu.mkdirSync(a,{recursive:!0}),Qu.writeFileSync(U.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),u(`[HotReloadBuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,o){let i=U.dirname(o.nodePath)+U.sep,s=U.join(t,"build",r),a=U.join(s,"intermediates"),c=U.join(a,"loader_out",r),l=U.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:i,projectProfilePath:U.join(e,"build-profile.json5"),localPropertiesPath:U.join(e,"local.properties"),appResource:U.join(l,"ResourceTable.txt"),cachePath:U.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:U.join(a,"loader",r,"loader.json"),aceModuleJsonPath:U.join(l,"module.json"),aceSoPath:U.join(c,"nativeDependencies.txt"),aceModuleRoot:U.join(t,"src","main","ets"),aceModuleBuild:U.join(c,"ets"),aceProfilePath:U.join(l,"resources","base","profile"),aceSuperVisualPath:U.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:U.join(c,"ets"),changedFileList:U.join(a,"hotReload","changedFileList.json"),patchAbcPath:U.join(a,"hotReload","patchAbcPath","ets"),removeChangedFileListInSdk:"true"}}}};import ep from"crypto";import ot from"fs";import it from"path";import tp from"os";import{io as Bw}from"socket.io-client";var Ww=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),hn=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),o=this.watchLogPath;ot.mkdirSync(it.dirname(o),{recursive:!0}),ot.writeFileSync(o,"");let i=this.createWatchLogBuffer(o);r.on("WatchLog",i.onWatchLog),r.on("WatchResult",i.onWatchResult),await this.awaitInitialBuild(r,e)}createWatchLogBuffer(e){let r=[];return{onWatchLog:s=>{let a=n.extractText(s);a.trim()&&(r.push(a.endsWith(`
41
41
  `)?a:a+`
42
- `),r.length>100&&r.shift())},onWatchResult:s=>{let a=n.extractText(s);if(!a.trim())return;let c=`[WatchResult] ${a}`;console.log(c),Qe.writeFileSync(e,[...r,c+`
43
- `].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 et.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=Gv(`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=v=>{t()||(r(!0),g(),this.invalidateSocket(),i(new Error(`Socket disconnected: ${v}`)))},s=this.createOutputHandler(),{onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d}=this.getDataHandler(),g=()=>{e.off("disconnect",o),e.off("Output",s),e.off("WatchLog",a),e.off("WatchResult",c),e.off("WatchCompileResult",l),e.off("WatchCompileData",d)};return{onDisconnect:o,onOutput:s,onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d,detach:g}}getDataHandler(){let e=n.extractText;return{onWatchLog:s=>{let a=e(s);a.trim()&&process.stdout.write(a+(a.endsWith(`
42
+ `),r.length>100&&r.shift())},onWatchResult:s=>{let a=n.extractText(s);if(!a.trim())return;let c=`[WatchResult] ${a}`;console.log(c),ot.writeFileSync(e,[...r,c+`
43
+ `].join("")),r.length=0}}}awaitInitialBuild(e,t){return new Promise((r,o)=>{let i=!1,s=this.createOutputHandler(),a=l=>{!l?.status||i||(l.status==="finish"?(i=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),r()):(l.status==="reject"||l.status==="close")&&(i=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),this.invalidateSocket(),o(new Error(l.reason||`Watch-session build ${l.status}`))))},c=l=>{i||(i=!0,o(new Error(`Socket disconnected: ${l}`)))};e.on("disconnect",c),e.on("Output",s),e.on("BuildStatus",a),e.emit("CommonBuild",this.buildStartOptions(t)),console.log("[DaemonClient] Compiling, waiting for build to finish...")})}getWatchLogPath(){return this.watchLogPath}get watchLogPath(){return it.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=Bw(`ws://127.0.0.1:${e.port}`,{transports:["websocket"],path:`/${t}`});return await new Promise((o,i)=>{let s=setTimeout(()=>{i(new Error("Socket connect timeout (10s)"))},1e4);r.once("connect",()=>{clearTimeout(s),o()}),r.once("connect_error",a=>{clearTimeout(s),i(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((o,i)=>{let s=!1,a=Date.now(),c=this.createHotCompileHandlers(r,()=>s,d=>s=d,i),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`),o(d.exitCode??0)):(d.status==="reject"||d.status==="close")&&(s=!0,c.detach(),r.off("BuildStatus",l),this.invalidateSocket(),i(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,o){let i=v=>{t()||(r(!0),g(),this.invalidateSocket(),o(new Error(`Socket disconnected: ${v}`)))},s=this.createOutputHandler(),{onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d}=this.getDataHandler(),g=()=>{e.off("disconnect",i),e.off("Output",s),e.off("WatchLog",a),e.off("WatchResult",c),e.off("WatchCompileResult",l),e.off("WatchCompileData",d)};return{onDisconnect:i,onOutput:s,onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d,detach:g}}getDataHandler(){let e=n.extractText;return{onWatchLog:s=>{let a=e(s);a.trim()&&process.stdout.write(a+(a.endsWith(`
44
44
  `)?"":`
45
- `))},onWatchResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchResult] ${a}`)},onWatchCompileResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileResult] ${a}`)},onWatchCompileData:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileData] ${a}`)}}}createOutputHandler(){return e=>{let t=typeof e.text=="string"?e.text:Buffer.from(e.text).toString(e.encoding??"utf-8");t.trim()&&(e.type==="stderr"?process.stderr.write(t):process.stdout.write(t))}}buildCompileOptions(e){let t={_:["assembleDevHqf"],daemon:!0,hotCompile:!0,mode:"module",prop:[`module=${e.moduleSpecs.join(",")}`,`product=${e.productName}`,"debuggable=true","hotReload=true","requiredDeviceType=phone"],parallel:!0,incremental:!0,analyze:"normal",env:{DEVECO_SDK_HOME:this.toolProvider.sdkPath}};return console.log("[DaemonClient] buildCompileOptions:",JSON.stringify(t,null,2)),t}async waitForDaemonReady(){let 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(!Qe.existsSync(e))return null;try{let t=Qe.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=et.join(t,"fd"),i=et.join(t,"ac"),o=et.join(t,"ce"),s=this.readComponents(r),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(zv)]),c=this.readSingleFile(i),l=bu.pbkdf2Sync(Buffer.from(a).toString(),c,1e4,16,"sha256"),d=this.readSingleFile(o),g=this.aesGcmDecrypt(l,d),v=Buffer.from(e,"hex");return this.aesGcmDecrypt(g,v).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=bu.createDecipheriv("aes-128-gcm",e,o);return l.setAuthTag(c),Buffer.concat([l.update(a),l.final()])}readComponents(e){let t=Qe.readdirSync(e).map(r=>et.join(e,r)).filter(r=>Qe.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=Qe.readdirSync(r);if(i.length===0)throw new Error(`No file in ${r}`);return Qe.readFileSync(et.join(r,i[0]))})}readSingleFile(e){let t=Qe.readdirSync(e).map(r=>et.join(e,r)).filter(r=>Qe.statSync(r).isFile());if(t.length===0)throw new Error(`No file in ${e}`);return Qe.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||et.join(Su.homedir(),".hvigor");return et.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||et.join(Su.homedir(),".hvigor");return et.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import Cu from"fs";import*as At from"path";import{green as Do,yellow as Xa}from"colorette";import On from"fs";import*as Mn from"path";import Jv from"json5";var Yv=2e6,Kv=1e6,Xv="hotreload",ko=class n{static generateOrUpdate(e,t,r){let i=n.readAppConfig(e),o=Mn.resolve(e,t),s=Mn.join(o,"patch.json"),a;return On.existsSync(s)?(p(`[PatchManager] patch.json found at ${s}, incrementing patchVersionCode`),a=n.readExistingPatch(s),a.app.patchVersionCode+=1):(p(`[PatchManager] patch.json not found, generating new one at ${s}`),a={app:{bundleName:i.bundleName,patchVersionCode:Yv,versionCode:i.versionCode},module:{name:r,type:Xv}}),n.writePatchJson(s,a),a}static readAppConfig(e){let t=Mn.join(e,"AppScope","app.json5");if(!On.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let r=On.readFileSync(t,"utf-8"),i=Jv.parse(r),o=i?.app?.bundleName;if(!o)throw new Error("bundleName is missing in AppScope/app.json5");let s=i?.app?.versionCode??Kv;return{bundleName:o,versionCode:s}}static readExistingPatch(e){let t=On.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=Mn.dirname(e);On.existsSync(r)||On.mkdirSync(r,{recursive:!0});let i=JSON.stringify(t,null,2);On.writeFileSync(e,i,"utf-8"),p(`[PatchManager] patch.json written to ${e}`),p(`[PatchManager] Content: ${i}`)}};import me from"fs";import*as W from"path";import Eu from"crypto";import Zv from"json5";import{execa as Pu}from"execa";var Io=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}`);p(`[DecipherUtil] Decrypting ${r}, encrypted length: ${t.length}`);let i=W.resolve(e,"material"),o=n.getKey(i,r),s=new Int8Array(Buffer.from(t,"hex"));return p(`[DecipherUtil] Data length: ${s.length}, key length: ${o.length}`),n.decrypt(o,s).toString("utf-8")}static getKey(e,t){let r=W.resolve(e,n.DIRS[0]),i=n.readFd(r,t),o=n.readDirBytes(W.resolve(e,n.DIRS[1]),t),s=n.getRootKey(i,o,t),a=n.readDirBytes(W.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=Eu.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=Eu.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=me.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=W.join(e,o);i.push(n.readDirBytes(s,t))}return i}static readDirBytes(e,t){if(me.statSync(e).isDirectory()){let i=me.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(me.readFileSync(W.join(e,i[0])))}return new Int8Array(me.readFileSync(e))}},Ao=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let i=`${W.dirname(e.javaPath)}${W.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=W.join(e,"ets","modules.abc");if(me.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(!me.existsSync(e))return null;let t=me.readdirSync(e,{withFileTypes:!0});for(let r of t){let i=W.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=vt(this.projectRoot,e),i=W.join(this.projectRoot,r,"build",t,"outputs","default");return me.existsSync(i)||me.mkdirSync(i,{recursive:!0}),{unsignedHqfPath:W.join(i,`${e}-default-unsigned.hqf`),signedHqfPath:W.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=W.dirname(t),s=this.toolProvider.javaPath,a=["-jar",i,"--mode","hqf","--json-path",e,"--ets-path",o,"--out-path",r,"--force","true"];p(`[GenSignHqf] Packing: ${s} ${a.join(" ")}`);try{let c=Date.now(),l=await Pu(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):me.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);p(`[GenSignHqf] Signing: ${o} ${s.join(" ")}`);try{let a=Date.now(),c=await Pu(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}`):me.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=Io.decryptPwd(r,t.storePassword,"storePassword"),o=Io.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=W.resolve(e.storeFile,".."),r=W.join(t,"material");return me.existsSync(r)?t:null}readSigningConfig(e){let t=W.join(this.projectRoot,"build-profile.json5");if(!me.existsSync(t))return null;try{let r=me.readFileSync(t,"utf-8"),i=Zv.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=[W.join(e,"default","openharmony","toolchains","lib","hap-sign-tool.jar"),W.join(e,"toolchains","lib","hap-sign-tool.jar")];for(let r of t)if(me.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=[W.join(e,"default","openharmony","toolchains","lib","app_packing_tool.jar"),W.join(e,"toolchains","lib","app_packing_tool.jar")];for(let r of t)if(me.existsSync(r))return r;return null}};async function ku(n){let e=Date.now(),t=vt(n.projectPath,n.moduleName),r=Qv(n);console.log(Xa("[HotReload] Ensure the project source is trusted before proceeding."));let i=ew(n),o=ri(r,n.projectPath);console.log(`[HotReload] Parsed ${o.length} changed file(s) from ${n.applyFileName}`),tw(n,o),nw(n,t),await rw(n,i);let s=At.join(n.projectPath,t,"patch.json"),a=await ow(n,t,s);return await sw(n,a),console.log(Do("[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 Qv(n){if(At.basename(n.applyFileName)!==n.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n.applyFileName}`);return At.join(n.projectPath,".hvigor",n.applyFileName)}function ew(n){let{projectPath:e,toolProvider:t}=n,r=new sr(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 tw(n,e){let t=ir.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(Do(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn(Xa(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function nw(n,e){let t=ko.generateOrUpdate(n.projectPath,e,n.moduleName);console.log(Do(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function rw(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=iw(r);throw new Error(`Daemon hot compile exited with code ${i}`+(o?`
45
+ `))},onWatchResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchResult] ${a}`)},onWatchCompileResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileResult] ${a}`)},onWatchCompileData:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileData] ${a}`)}}}createOutputHandler(){return e=>{let t=typeof e.text=="string"?e.text:Buffer.from(e.text).toString(e.encoding??"utf-8");t.trim()&&(e.type==="stderr"?process.stderr.write(t):process.stdout.write(t))}}buildCompileOptions(e){let t={_:["assembleDevHqf"],daemon:!0,hotCompile:!0,mode:"module",prop:[`module=${e.moduleSpecs.join(",")}`,`product=${e.productName}`,"debuggable=true","hotReload=true","requiredDeviceType=phone"],parallel:!0,incremental:!0,analyze:"normal",env:{DEVECO_SDK_HOME:this.toolProvider.sdkPath}};return console.log("[DaemonClient] buildCompileOptions:",JSON.stringify(t,null,2)),t}async waitForDaemonReady(){let r=Date.now();for(;Date.now()-r<3e4;){let o=this.findProjectDaemon();if(o&&(o.state==="half_busy"||o.state==="idle"))return;await new Promise(i=>setTimeout(i,1e3))}throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first.")}findProjectDaemon(){let e=this.getRegistryPath();if(!ot.existsSync(e))return null;try{let t=ot.readFileSync(e,"utf-8"),r=JSON.parse(t),o=Object.values(r).filter(i=>i.cwdPath===this.projectRoot&&(i.state==="idle"||i.state==="half_busy"||i.state==="busy")&&this.isProcessAlive(i.pid));return o.length>0?o[o.length-1]:null}catch{return null}}decryptSessionId(e){let t=this.getMetaDir(),r=it.join(t,"fd"),o=it.join(t,"ac"),i=it.join(t,"ce"),s=this.readComponents(r),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(Ww)]),c=this.readSingleFile(o),l=ep.pbkdf2Sync(Buffer.from(a).toString(),c,1e4,16,"sha256"),d=this.readSingleFile(i),g=this.aesGcmDecrypt(l,d),v=Buffer.from(e,"hex");return this.aesGcmDecrypt(g,v).toString("utf-8")}aesGcmDecrypt(e,t){let r=0,o=t.readUInt32BE(r);r+=4;let i=t.subarray(r,r+12);r+=12;let s=o-16,a=t.subarray(r,r+s);r+=s;let c=t.subarray(r,r+16),l=ep.createDecipheriv("aes-128-gcm",e,i);return l.setAuthTag(c),Buffer.concat([l.update(a),l.final()])}readComponents(e){let t=ot.readdirSync(e).map(r=>it.join(e,r)).filter(r=>ot.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 o=ot.readdirSync(r);if(o.length===0)throw new Error(`No file in ${r}`);return ot.readFileSync(it.join(r,o[0]))})}readSingleFile(e){let t=ot.readdirSync(e).map(r=>it.join(e,r)).filter(r=>ot.statSync(r).isFile());if(t.length===0)throw new Error(`No file in ${e}`);return ot.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 o=Buffer.isBuffer(e[r])?e[r]:Buffer.from(e[r]);for(let i=0;i<t.length;i++)t[i]^=o[i]}return t}getRegistryPath(){let e=process.env.HVIGOR_USER_HOME||it.join(tp.homedir(),".hvigor");return it.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||it.join(tp.homedir(),".hvigor");return it.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import op from"fs";import*as Mt from"path";import{green as Wi,yellow as wc}from"colorette";import Hr from"fs";import*as Ur from"path";import Vw from"json5";var qw=2e6,Gw=1e6,zw="hotreload",Hi=class n{static generateOrUpdate(e,t,r){let o=n.readAppConfig(e),i=Ur.resolve(e,t),s=Ur.join(i,"patch.json"),a;return Hr.existsSync(s)?(u(`[PatchManager] patch.json found at ${s}, incrementing patchVersionCode`),a=n.readExistingPatch(s),a.app.patchVersionCode+=1):(u(`[PatchManager] patch.json not found, generating new one at ${s}`),a={app:{bundleName:o.bundleName,patchVersionCode:qw,versionCode:o.versionCode},module:{name:r,type:zw}}),n.writePatchJson(s,a),a}static readAppConfig(e){let t=Ur.join(e,"AppScope","app.json5");if(!Hr.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let r=Hr.readFileSync(t,"utf-8"),o=Vw.parse(r),i=o?.app?.bundleName;if(!i)throw new Error("bundleName is missing in AppScope/app.json5");let s=o?.app?.versionCode??Gw;return{bundleName:i,versionCode:s}}static readExistingPatch(e){let t=Hr.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=Ur.dirname(e);Hr.existsSync(r)||Hr.mkdirSync(r,{recursive:!0});let o=JSON.stringify(t,null,2);Hr.writeFileSync(e,o,"utf-8"),u(`[PatchManager] patch.json written to ${e}`),u(`[PatchManager] Content: ${o}`)}};import ye from"fs";import*as V from"path";import rp from"crypto";import Jw from"json5";import{execa as np}from"execa";var Ui=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}`);u(`[DecipherUtil] Decrypting ${r}, encrypted length: ${t.length}`);let o=V.resolve(e,"material"),i=n.getKey(o,r),s=new Int8Array(Buffer.from(t,"hex"));return u(`[DecipherUtil] Data length: ${s.length}, key length: ${i.length}`),n.decrypt(i,s).toString("utf-8")}static getKey(e,t){let r=V.resolve(e,n.DIRS[0]),o=n.readFd(r,t),i=n.readDirBytes(V.resolve(e,n.DIRS[1]),t),s=n.getRootKey(o,i,t),a=n.readDirBytes(V.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 o=[...e,n.COMPONENT],i=n.xor(o[0],o[1],r);for(let a=2;a<o.length;a++)i=n.xor(i,o[a],r);let s=rp.pbkdf2Sync(Buffer.from(i).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 o=new Int8Array(e.byteLength);for(let i=0;i<e.byteLength;i++)o[i]=e[i]^t[i];return o}static decrypt(e,t){let r=(255&t[0])<<24|(255&t[1])<<16|(255&t[2])<<8|255&t[3],o=t.length-4-r,i=t.slice(4,4+o),s=t.slice(t.length-16),a=rp.createDecipheriv("aes-128-gcm",Buffer.from(e),Buffer.from(i));a.setAuthTag(Buffer.from(s));let c=a.update(Buffer.from(t.subarray(4+o,t.length-16))),l=a.final();return Buffer.concat([c,l])}static readFd(e,t){let r=ye.readdirSync(e).filter(i=>i!==".DS_Store");if(r.length!==3)throw new Error(`fd directory must have 3 entries for ${t}`);let o=[];for(let i of r){let s=V.join(e,i);o.push(n.readDirBytes(s,t))}return o}static readDirBytes(e,t){if(ye.statSync(e).isDirectory()){let o=ye.readdirSync(e).filter(i=>i!==".DS_Store");if(o.length!==1)throw new Error(`Expected exactly 1 file in ${e} for ${t}`);return new Int8Array(ye.readFileSync(V.join(e,o[0])))}return new Int8Array(ye.readFileSync(e))}},Bi=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let o=`${V.dirname(e.javaPath)}${V.delimiter}${process.env.PATH||""}`;this.env={...process.env,PATH:o,DEVECO_SDK_HOME:e.sdkPath}}async generateAndSign(e,t,r,o,i=!1){let s=this.checkAbcExists(t);if(!s.exists)return{signedHqfPaths:[],message:s.message};let a=this.resolveHqfPaths(e,o);return await this.generateHqf(r,s.abcPath,a.unsignedHqfPath)?i?{success:!0,signedHqfPaths:[a.unsignedHqfPath],unsignedHqfPath:a.unsignedHqfPath,message:"Unsigned hqf generated (signing skipped for emulator)."}:this.signHqfDirect(a.unsignedHqfPath,a.signedHqfPath):{signedHqfPaths:[],unsignedHqfPath:a.unsignedHqfPath,message:"Failed to generate unsigned hqf."}}checkAbcExists(e){let t=V.join(e,"ets","modules.abc");if(ye.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(!ye.existsSync(e))return null;let t=ye.readdirSync(e,{withFileTypes:!0});for(let r of t){let o=V.join(e,r.name);if(r.isDirectory()){let i=this.findFirstAbc(o);if(i)return i}else if(r.isFile()&&r.name.endsWith(".abc"))return o}return null}resolveHqfPaths(e,t){let r=At(this.projectRoot,e),o=V.join(this.projectRoot,r,"build",t,"outputs","default");return ye.existsSync(o)||ye.mkdirSync(o,{recursive:!0}),{unsignedHqfPath:V.join(o,`${e}-default-unsigned.hqf`),signedHqfPath:V.join(o,`${e}-default-signed.hqf`)}}async generateHqf(e,t,r){let o=this.resolvePackingTool();if(!o)return console.error("[HotReload] app_packing_tool.jar not found in SDK."),!1;let i=V.dirname(t),s=this.toolProvider.javaPath,a=["-jar",o,"--mode","hqf","--json-path",e,"--ets-path",i,"--out-path",r,"--force","true"];u(`[GenSignHqf] Packing: ${s} ${a.join(" ")}`);try{let c=Date.now(),l=await np(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):ye.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 o=this.buildSignArgs(r,e,t),i=this.toolProvider.javaPath,s=o.map((a,c)=>c>0&&["-keyPwd","-keystorePwd"].includes(o[c-1])?"******":a);u(`[GenSignHqf] Signing: ${i} ${s.join(" ")}`);try{let a=Date.now(),c=await np(i,o,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] sign (JVM#2): ${Date.now()-a}ms`),c.stdout&&console.log(c.stdout),c.stderr&&console.error(c.stderr),c.exitCode!==0?this.signFailResult(e,`hqf signing failed with exit code ${c.exitCode}`):ye.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 o=Ui.decryptPwd(r,t.storePassword,"storePassword"),i=Ui.decryptPwd(r,t.keyPassword,"keyPassword");return{signToolPath:e,storePwd:o,keyPwd:i,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=V.resolve(e.storeFile,".."),r=V.join(t,"material");return ye.existsSync(r)?t:null}readSigningConfig(e){let t=V.join(this.projectRoot,"build-profile.json5");if(!ye.existsSync(t))return null;try{let r=ye.readFileSync(t,"utf-8"),o=Jw.parse(r),s=o.app?.products?.find(a=>a.name===e)?.signingConfig;return s?o.app?.signingConfigs?.find(a=>a.name===s)?.material??null:null}catch{return null}}resolveSignTool(){let e=this.toolProvider.sdkPath,t=[V.join(e,"default","openharmony","toolchains","lib","hap-sign-tool.jar"),V.join(e,"toolchains","lib","hap-sign-tool.jar")];for(let r of t)if(ye.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=[V.join(e,"default","openharmony","toolchains","lib","app_packing_tool.jar"),V.join(e,"toolchains","lib","app_packing_tool.jar")];for(let r of t)if(ye.existsSync(r))return r;return null}};async function ip(n){let e=Date.now(),t=At(n.projectPath,n.moduleName),r=Yw(n);console.log(wc("[HotReload] Ensure the project source is trusted before proceeding."));let o=Kw(n),i=po(r,n.projectPath);console.log(`[HotReload] Parsed ${i.length} changed file(s) from ${n.applyFileName}`),Xw(n,i),Zw(n,t),await Qw(n,o);let s=Mt.join(n.projectPath,t,"patch.json"),a=await tb(n,t,s);return await rb(n,a),console.log(Wi("[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 Yw(n){if(Mt.basename(n.applyFileName)!==n.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n.applyFileName}`);return Mt.join(n.projectPath,".hvigor",n.applyFileName)}function Kw(n){let{projectPath:e,toolProvider:t}=n,r=new hn(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 Xw(n,e){let t=mn.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(Wi(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn(wc(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function Zw(n,e){let t=Hi.generateOrUpdate(n.projectPath,e,n.moduleName);console.log(Wi(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function Qw(n,e){let t=Date.now(),r=e.getWatchLogPath();try{console.log("[HotReload] Daemon hot compile (socket short connection)...");let o=await e.sendHotCompile({moduleSpecs:n.moduleSpecs,productName:n.productName});if(o!==0){let i=eb(r);throw new Error(`Daemon hot compile exited with code ${o}`+(i?`
46
46
  --- compile output (from watch session) ---
47
- ${o}`:""))}}finally{e.disconnect()}console.log(`[Timing] daemon hot compile: ${Date.now()-t}ms`)}function iw(n){try{return Cu.existsSync(n)?Cu.readFileSync(n,"utf8").split(/\r?\n/).filter(t=>t.trim()).slice(-40).join(`
48
- `):""}catch{return""}}async function ow(n,e,t){let r=At.join(n.projectPath,e,"build",n.productName,"intermediates"),i=[At.join(r,"hotReload","patchAbcPath"),At.join(r,"patch","default")],o=Date.now(),s=new Ao(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 sw(n,e){let t=Date.now(),i=await new or(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 Za(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 Iu(n,e,t){let r=At.join(n.rootDir,".hvigor",t),i;try{i=ri(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(Xa(`[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 Au(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 Du(n,e){await new Be(n,e.rootDir).stopDaemon(),console.log(Do("Hvigor daemon stopped."))}function Qa(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 To(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 w("Multiple devices found. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+i.map(o=>` - ${o.name} (${o.serial})`).join(`
49
- `),"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 ec(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 w(`Specify module(s) using --module <name> [<name>...].
47
+ ${i}`:""))}}finally{e.disconnect()}console.log(`[Timing] daemon hot compile: ${Date.now()-t}ms`)}function eb(n){try{return op.existsSync(n)?op.readFileSync(n,"utf8").split(/\r?\n/).filter(t=>t.trim()).slice(-40).join(`
48
+ `):""}catch{return""}}async function tb(n,e,t){let r=Mt.join(n.projectPath,e,"build",n.productName,"intermediates"),o=[Mt.join(r,"hotReload","patchAbcPath"),Mt.join(r,"patch","default")],i=Date.now(),s=new Bi(n.toolProvider,n.projectPath),a=n.targetDeviceId.includes("127.0.0.1")||n.targetDeviceId.includes("localhost"),c=null;for(let l of o){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()-i}ms`),!c?.success||c.signedHqfPaths.length===0)throw new Error(`hqf generation/signing failed (no abc found in any candidate). Last: ${c?.message??"unknown"}`);return c.signedHqfPaths}async function rb(n,e){let t=Date.now(),o=await new fn(n.toolProvider).install(n.targetDeviceId,e,n.bundleName);if(console.log(`[Timing] quickfix install: ${Date.now()-t}ms`),!o.success)throw new Error(`hqf install failed: ${o.message}`)}function bc(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 sp(n,e,t){let r=Mt.join(n.rootDir,".hvigor",t),o;try{o=po(r,n.rootDir)}catch{return}let i=new Set;for(let s of o){let a=n.findOwningModule(s);if(!a||a===e)continue;let c=n.getModuleType(a);(c==="feature"||c==="shared")&&i.add(`${a} (${c})`)}i.size>0&&console.warn(wc(`[HotReload] Changed files belong to feature/hsp dependency module(s): ${[...i].join(", ")}. These are NOT hot-reloadable \u2014 run \`devecocli run\` (full redeploy) for them. Only the target module (+ har deps) will be hot-reloaded this time.`))}function ap(n,e,t,r,o){let i=new Set,s=n.collectNonHarDependentModuleList(e);for(let a of s)i.add(n.findArtifactPath(a,t,r,o));return i.add(n.findArtifactPath(e,t,r,o)),[...i]}async function cp(n,e){await new ze(n,e.rootDir).stopDaemon(),console.log(Wi("Hvigor daemon stopped."))}var Vi=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:o,evidence:i}=e,s=[`Smoke: ${r}`,`${o} (bundle=${t.bundleName}, device=${t.targetDeviceId}).`];return r==="FAIL_CRASH"&&i.crashLogPath&&s.push(`crash_log: ${i.crashLogPath}`),r==="FAIL_BLANK"&&i.screenshotPath&&s.push(`screenshot: ${i.screenshotPath}`),s.join(`
49
+ `)}toTraceError(e,t){return new w(this.formatFailure(e,t),e.status)}};import Ki from"fs";import Nb from"path";import{yellow as vo}from"colorette";import{cyan as qi}from"colorette";function Br(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=nr(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 Sc=[800,1500,2500];function ob(n){return new Promise(e=>setTimeout(e,n))}var or=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=de.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(`
50
+ `)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let o=t[0];return u(qi(`Using device serial: ${o}`)),o}if(e&&t.includes(e))return u(qi(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let o=this.findDeviceByArg(r,e);if(o)return u(qi(`Using device: ${o.name} (${o.serial})`)),o.serial;let i=this.formatConnectedDeviceList(r);throw new w(`Device '${e}' not found.
51
+ Available devices:
52
+ ${i}`,"Device not found.")}if(r.length===1){let o=r[0];return u(qi(`Using device: ${o.name} (${o.serial})`)),o.serial}throw new w("Multiple devices found. Specify a target device using `--device <name>` or `--device <serial>`.\nAvailable devices:\n"+this.formatConnectedDeviceList(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){u(`Retrieving PID for bundle ${r}`),S.assertBundleNameStrict(r);let o=await ee(e,["-t",t,"shell","pidof",r]),i=Br(o,"Failed to look up PID");if(i)throw i;if(o.exitCode===0&&o.stdout.trim()){let s=o.stdout.trim(),a=s.split(/\s+/)[0]||s;return u(`Found PID for ${r}: ${a}`),a}return u(`No PID found for bundle: ${r}`),null}async resizeHilogBuffer(e,t,r){if(u(`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 o=await ee(e,["-t",t,"shell","hilog","-G",r]),i=Br(o,"Failed to resize hilog buffer");if(i)throw i;o.exitCode!==0&&console.error(`Failed to resize hilog buffer: ${o.stderr||o.stdout}`)}buildHilogCommand(e,t,r,o){let i=this.buildHilogShellCommand(r,o);return[e,["-t",t,"shell",i]]}buildHilogShellCommand(e,t){let r=["hilog"];return e.isFollow||r.push("-x"),e.tag&&(S.assertHilogToken(e.tag,"tag"),r.push("-T",e.tag)),e.level&&(S.assertHilogLevel(e.level),r.push("-L",e.level)),e.domain&&(S.assertHilogToken(e.domain,"domain"),r.push("-D",e.domain)),t&&r.push("-P",t),e.keyword&&(S.assertHilogKeyword(e.keyword),r.push("-e",S.quotePosixShellArg(e.keyword))),r.join(" ")}async followHilog(e,t,r,o,i){let a=await Bu(e,t,{onData:r,onError:o,onClose:i});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}async runHilogWithSpawnRetry(e,t,r,o,i){let s=1+Sc.length,a={stdout:"",stderr:"",exitCode:-1};for(let c=0;c<s;c++){if(a=await this.followHilog(e,t,r,o,i),a.exitCode===0||nr(a.stderr)!=="transient"||c>=s-1)return a;u(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${Sc[c]}ms`),await ob(Sc[c])}return a}async runHilogStreamingCollect(e,t,r){return this.runHilogWithSpawnRetry(e,t,()=>{},o=>{u(`Callback triggered when an error occurs during ${r}: ${o.message}`)},()=>{})}async printTailSnapshotIfNeeded(e,t,r,o){if(!r.tail&&!r.fromSeconds&&!r.toSeconds)return;let i={...r,isFollow:!1},[s,a]=this.buildHilogCommand(e,t,i,o);u(`Ready to run hilog snapshot command: ${s} ${a.join(" ")}`);let c=await this.runHilogStreamingCollect(s,a,"a hilog snapshot streaming read"),l=Br(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=S.filterLogsByRelativeWindow(c.stdout||c.stderr,r.fromSeconds,r.toSeconds);d=S.getLastLines(d,r.tail),d.trim()&&console.log(d)}async getHilogOnce(e,t,r,o){let[i,s]=this.buildHilogCommand(e,t,r,o);u(`Ready to run hilog command: ${i} ${s.join(" ")}`);let a=await this.runHilogStreamingCollect(i,s,"a single hilog streaming read"),c=Br(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=S.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return d=S.getLastLines(d,r.tail),d}async runHilogFollow(e,t,r,o){try{await this.printTailSnapshotIfNeeded(e,t,r,o)}catch(l){console.error(`Warning: Failed to fetch log snapshot, continuing with live stream: ${l.message}`)}let[i,s]=this.buildHilogCommand(e,t,r,o);u(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${i} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(i,s,this.createFollowLineHandler(),l=>{u(`Spawn error during hilog follow: ${l.message}`)},()=>{}),c=Br(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,o=t.bundleName?await this.getPidForBundle(r,e,t.bundleName):void 0;if(t.bundleName&&!o)throw new w(`No running process found for bundle '${t.bundleName}'. Ensure the app is launched on the device before fetching logs.`,"No running process found for bundle.");return t.logSize&&await this.resizeHilogBuffer(r,e,t.logSize),t.isFollow?await this.runHilogFollow(r,e,t,o||""):await this.getHilogOnce(r,e,t,o||"")}async getLatestCrashLog(e,t){u(`Fetching crash logs from device: ${e}`);let r=this.toolProvider.hdcPath,o=await this.listCrashLogs(r,e,t);if(o.length===0)return;let s=[...o].sort((c,l)=>{let d=c.split("-").pop()||"";return(l.split("-").pop()||"").localeCompare(d)})[0],a=await this.fetchCrashLogContent(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 o=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];u(`Running command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log list streaming read"),s=Br(i,"Failed to list crash logs");if(s)throw s;if(i.exitCode!==0)throw new Error(`Failed to list crash logs: ${i.stderr||i.stdout}`);return u(`Crash logs list output:
53
+ ${i.stdout}`),this.parseCrashLogFilenames(i.stdout,r)}parseCrashLogFilenames(e,t){return e.split(`
54
+ `).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return S.assertCrashFilename(r),!0}catch{return!1}}).filter(r=>t?r.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){u(`Fetching latest crash log file: ${r}`);let o=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];u(`Executing command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log streaming read"),s=Br(i,"Failed to fetch crash log content");if(s)throw s;return i.exitCode!==0&&i.stderr&&console.error(`Warning: Failed to fetch crash logs: ${i.stderr}`),i.stdout+i.stderr}};import{readFileSync as sb,unlinkSync as ab}from"fs";import{tmpdir as cb}from"os";import{join as lb}from"path";var Ot=class{constructor(e,t){this.hdcPath=e;this.serial=t}hdcPath;serial;async listWindows(e){let t=await this.fetchDump(),r=ib(t);return e?.all||(r=r.filter(o=>o.type===1)),r}async fetchDump(){let e=["-t",this.serial,"shell","hidumper","-s","WindowManagerService","-a","-a"];u(`Executing: ${this.hdcPath} ${e.join(" ")}`);let t=await ee(this.hdcPath,e);if(t.exitCode!==0)throw new Error(`Failed to query windows: ${(t.stderr||t.stdout).trim()}`);return t.stdout}};function ib(n){let e=n.split(`
55
+ `),t=e.findIndex(s=>s.trimStart().startsWith("WindowName"));if(t===-1)return[];let r=[];for(let s=t+1;s<e.length;s++){let a=e[s].trim();if(!a||/^-+$/.test(a)||a.startsWith("Focus window")||a.startsWith("total window"))break;let c=a.split(/\s+/);if(c.length<5)continue;let l=c[0],d=Number(c[1]),g=Number(c[2]),v=Number(c[3]),P=Number(c[4]);Number.isFinite(v)&&Number.isFinite(d)&&Number.isFinite(g)&&r.push({id:v,name:l,pid:g,displayId:d,type:P})}let o=e.find(s=>s.trim().startsWith("Focus window")),i=o?Number(o.replace(/.*:\s*/,"").trim()):NaN;return r.map(s=>({...s,focused:s.id===i}))}function lp(n){if(!(!n||n==="HitTestMode.Default"))return n.startsWith("HitTestMode.")?n.slice(12):n}function fo(n){if(!(n==null||n==="")){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1}}function dp(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 up(n){return n.originalText||void 0}function gn(n,e){let t=[],r=[...n].reverse();for(;r.length>0;){let o=r.pop();o.id===e&&t.push(o);for(let i=o.children.length-1;i>=0;i--)r.push(o.children[i])}return t}function pp(n,e){let t=[],r=[{current:n,parent:null,depth:0}];for(;r.length>0;){let{current:o,parent:i,depth:s}=r.pop(),a=i===null,c=!o.id&&!o.text&&!o.clickable&&!o.longClickable&&!o.scrollable&&!o.checkable,l=a||!c,d=i;if(l){let v={...o,children:[]};if(a?t.push(v):i.children.push(v),d=v,e>0&&s+1>=e)continue}if(process.env.DEVECO_CLI_DEBUG){let v=o.type?o.id?`${o.type}#${o.id}`:o.type:"#";u(`collapse ${v} depth=${s} -> ${a?"root":c?"collapsed":"emitted"}`)}let g=l?s+1:s;for(let v=o.children.length-1;v>=0;v--)r.push({current:o.children[v],parent:d,depth:g})}return t}function db(n){let e=sb(n,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function ub(n){return n.attributes??{}}function Gi(n,e,t){let r=ub(n),o={id:r.id||void 0,type:r.type||void 0,text:up(r),bounds:dp(r.bounds),clickable:fo(r.clickable)||void 0,longClickable:fo(r.longClickable)||void 0,scrollable:fo(r.scrollable)||void 0,checkable:fo(r.checkable)||void 0,hitTestBehavior:lp(r.hitTestBehavior),children:[]};return e>0&&t+1>=e||n.children&&(o.children=n.children.map(i=>Gi(i,e,t+1))),o}function pb(n,e){if(e){let r=n.find(o=>String(o.id)===e);if(!r){let o=n.map(i=>`${i.id} (${i.name})`).join(", ");throw new w(`Window '${e}' not found. Available windows: ${o||"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 Wr=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 o=this.buildRemoteDumpPath(),i=["-t",e,"shell","uitest","dumpLayout","-p",o];r!==void 0&&i.push("-d",String(r)),t&&i.push("-w",t),u(`Executing: ${this.hdcPath} ${i.join(" ")}`);let s=await ee(this.hdcPath,i);if(s.exitCode!==0)throw new Error(`Failed to dump layout: ${(s.stderr||s.stdout).trim()}`);return this.recvAndParseDump(e,o)}async recvAndParseDump(e,t){let r=lb(cb(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,r),db(r)}finally{await this.cleanupDumpArtifacts(e,r,t)}}async recvDumpFile(e,t,r){let o=["-t",e,"file","recv",t,r];u(`Executing: ${this.hdcPath} ${o.join(" ")}`);let i=await ee(this.hdcPath,o);if(i.exitCode!==0)throw new Error(`Failed to recv dump file: ${(i.stderr||i.stdout).trim()}`)}async cleanupDumpArtifacts(e,t,r){try{u(`Removing local dump file: ${t}`),ab(t)}catch(i){u(`Failed to clean local dump file ${t}: ${i.message}`)}let o=["-t",e,"shell","rm","-f",r];u(`Executing: ${this.hdcPath} ${o.join(" ")}`),await ee(this.hdcPath,o).catch(i=>{u(`Failed to clean remote dump file ${r}: ${i.message}`)})}async dumpRawNodes(e,t,r){let i=await new Ot(this.hdcPath,e).listWindows({all:!0});if(r){let a=[...new Set(i.map(l=>l.displayId))],c=[];for(let l of a)c.push(await this.fetchRawDump(e,void 0,l));return c}let s=pb(i,t);return[await this.fetchRawDump(e,String(s.id),s.displayId)]}async dumpFullTree(e,t,r,o){return(await this.dumpRawNodes(e,r,o)).map(s=>Gi(s,t,0))}async dumpFullTreeByDisplays(e,t,r){let o=[];for(let i of r){let s=await this.fetchRawDump(e,void 0,i);o.push({displayId:i,tree:Gi(s,t,0)})}return o}async dumpCollapsedTree(e,t,r,o){return(await this.dumpRawNodes(e,r,o)).flatMap(s=>pp(Gi(s,0,0),t))}};import Fe from"fs";import Ee from"path";import{randomUUID as mb}from"crypto";function mp(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 fp(n,e){return[n,e].filter(Boolean).join(`
56
+ `).trim()}function hp(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 gp(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 yp(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 fb(){return String(Date.now())}function Ec(n){let e;try{e=Fe.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{Fe.accessSync(n,Fe.constants.W_OK|Fe.constants.X_OK)}catch(t){throw new Error(`Screenshot directory is not writable: ${n}`,{cause:t})}}function Pc(n,e){try{throw Fe.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 vp(n){if(!Fe.existsSync(n))throw new Error(`Screenshot file was not created: ${n}`);let e=Fe.statSync(n);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${n}`);let t=Fe.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 wp(n){try{return vp(n),!0}catch{return!1}}function bp(n){let e=[];for(let t of Fe.readdirSync(n,{withFileTypes:!0})){let r=Ee.join(n,t.name);if(t.isDirectory()){e.push(...bp(r));continue}t.isFile()&&wp(r)&&e.push(r)}return e}function hb(n,e){let t=Ee.join(n,Ee.basename(e));if(wp(t))return t;let r=bp(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}function gb(n,e){try{Fe.copyFileSync(n,e,Fe.constants.COPYFILE_EXCL)}catch(t){throw t.code==="EEXIST"?new Error(`Screenshot file already exists: ${e}`,{cause:t}):t}vp(e)}var Vr=class{constructor(e){this.toolProvider=e}toolProvider;resolveDestinationPath(e){if(!e?.trim())throw new Error("--path is required.");let t=e.trim(),r=Ee.resolve(t);try{if(Fe.statSync(r).isDirectory()){Ec(r);let i=Ee.join(r,`screenshot-${fb()}.png`);return Pc(i,r),i}}catch(i){if(i.code!=="ENOENT")throw i}if(Ee.extname(r).toLowerCase()!==".png")throw new Error(`Screenshot path must be an existing directory or a PNG file: ${r}`);let o=Ee.dirname(r);return Ec(o),Pc(r,o),r}async captureToPath(e,t,r){let o=Ee.dirname(Ee.resolve(t));Ec(o),Pc(Ee.resolve(t),o);let i=`/data/local/tmp/devecocli-${mb()}.png`;await this.capture({hdcPath:this.toolProvider.hdcPath,serial:e,localPath:Ee.resolve(t),remotePath:i,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];u(`Executing: ${e.hdcPath} ${t.join(" ")}`);let r=await ee(e.hdcPath,t);return r.exitCode===0?yp(r.stdout):void 0}async tryCreateRemoteScreenshot(e,t){let r=mp(e,t);u(`Executing: ${e.hdcPath} ${r.join(" ")}`);let o=await ee(e.hdcPath,r),i=await this.getRemoteScreenshotSize(e);return{created:i!==void 0&&i>0,output:hp(fp(o.stdout,o.stderr))}}async createRemoteScreenshot(e){let t="";for(let r of[void 0,"png"]){let o=await this.tryCreateRemoteScreenshot(e,r);if(o.created)return;if(e.display!==void 0&&gp(o.output))throw new Error(`Screenshot was not created on device: ${e.remotePath}.
57
+ snapshot_display output:
58
+ ${o.output}`);o.output&&(t=o.output)}throw new Error(t?`Screenshot was not created on device: ${e.remotePath}.
59
+ snapshot_display output:
60
+ ${t}`:`Screenshot was not created on device: ${e.remotePath}.`)}async tryReceiveScreenshot(e,t,r){let o=["-t",e.serial,"file","recv",e.remotePath,r];u(`Executing: ${e.hdcPath} ${o.join(" ")}`);let i=await ee(e.hdcPath,o);return i.exitCode!==0&&u(`hdc file recv failed: ${i.stderr||i.stdout||`exit code ${i.exitCode}`}`),hb(t,e.remotePath)}async receiveScreenshotFile(e){let t=Fe.mkdtempSync(Ee.join(Ee.dirname(e.localPath),".devecocli-screenshot-"));try{let r=await this.tryReceiveScreenshot(e,t,Ee.join(t,Ee.basename(e.remotePath)))??await this.tryReceiveScreenshot(e,t,t)??await this.tryReceiveScreenshot(e,t,Ee.join(t,"screenshot.png"));if(!r)throw new Error(`Screenshot file was not created in ${t}.`);gb(r,e.localPath)}finally{Fe.rmSync(t,{recursive:!0,force:!0})}}async removeRemoteScreenshot(e){let t=["-t",e.serial,"shell","rm","-f",e.remotePath];u(`Executing: ${e.hdcPath} ${t.join(" ")}`),await ee(e.hdcPath,t)}};var zi={left:"0",right:"1",up:"2",down:"3"};function Te(n,e){let t=Number(n);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function Cc(n,e){n!==void 0&&Te(n,e)}function Sp(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function Ji(n,e){if(n!==void 0&&n.length===0)throw new Error(`${e} must not be empty`)}function ho(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 Ep(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function Pp(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 yn(n,e,t,r,o=!0){Sp(n,e),Ji(t,"--id"),Cc(n,"x"),Cc(e,"y"),Ep(r),Pp(n!==void 0,!!t,!!r,o)}async function ht(n,e){let r=await new or(n).selectDevice(e);if(!r)throw new Error("No device selected. Use `devecocli device list` to see targets.");return r}async function Dt(n){let e=await A.new(),t=await ht(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function vn(n,e,t,r,o,i){if(t!==void 0&&r!==void 0)return{x:t,y:r};if(o===void 0)throw new Error("Either provide x y coordinates or use --id");let a=await new Ot(n,e).listWindows({all:!0}),c=new Wr(n);return yb(c,e,a,o,i)}async function yb(n,e,t,r,o){if(o!==void 0){let i=t.find(a=>String(a.id)===o);if(i&&i.displayId!==0)throw new w(`Window "${o}" is on display ${i.displayId}. The current command only supports operations on the primary display.`,"The current command only supports operations on the primary display.");let s=await n.dumpFullTree(e,0,o,!1);return wb(s,r)}return vb(n,e,t,r)}async function vb(n,e,t,r){let o=[...new Set(t.map(a=>a.displayId))],i=await n.dumpFullTreeByDisplays(e,0,o),s=[];for(let{displayId:a,tree:c}of i)for(let l of gn([c],r))s.push({node:l,displayId:a});if(s.length===0)throw new w(`Node "${r}" not found.`,"Node not found.");if(s.length>1)throw new w(`Multiple nodes found with id "${r}".`,"Multiple nodes found");if(s[0].displayId!==0)throw new w(`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 Cp(s[0].node,r)}function wb(n,e){let t=gn(n,e);if(t.length===0)throw new w(`Node "${e}" not found.`,"Node not found.");if(t.length>1)throw new w(`Multiple nodes found with id "${e}".`,"Multiple nodes found");return Cp(t[0],e)}function Cp(n,e){let t=n.bounds;if(!t)throw new w(`Node "${e}" has no bounds.`,"Node has no bounds.");let[r,o,i,s]=t;return{x:Math.ceil((r+i)/2),y:Math.ceil((o+s)/2)}}async function st(n,e,t){let r=["-t",e,"shell",...t];u(`Executing: ${n} ${r.join(" ")}`);let o=await ee(n,r);if(o.exitCode!==0)throw new Error(o.stderr||o.stdout||`uitest exited with code ${o.exitCode}`);let i=o.stdout.toLowerCase();if(["illegal","fail","error","incorrect","please confirm that the coordinate values are correct"].some(a=>i.includes(a))&&!i.includes("no error"))throw new Error(o.stdout.trim()||"uitest command failed")}import{deflateSync as bb,inflateSync as Sb}from"zlib";import Eb from"fs";var kp=8,Ip=32,Pb=.06,Cb=.04,kc=10,Yi=class n{whiteBits=null;blackBits=null;analyzeRgb(e,t,r){if(e<8||t<8||r.length<e*t*3)return null;let o=this.cropChrome(e,t,r),i=this.hashBits(o.width,o.height,o.rgb),s=Math.min(this.hammingDistance(i,this.solidRefBits(255)),this.hammingDistance(i,this.solidRefBits(0)));return{phash:this.bitsToHex(i),hamming:s,isBlank:s<=kc}}analyzeFile(e){let t;try{t=Eb.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 o=n.pngCrcTable(),i=[Buffer.from(`\x89PNG\r
61
+ 
62
+ `,"binary")],s=Buffer.alloc(13);s.writeUInt32BE(e,0),s.writeUInt32BE(t,4),s[8]=8,s[9]=2,i.push(n.pngChunk("IHDR",s,o));let a=Buffer.alloc((e*3+1)*t);for(let c=0;c<t;c++)a[c*(e*3+1)]=0,Buffer.from(r.buffer,r.byteOffset+c*e*3,e*3).copy(a,c*(e*3+1)+1);return i.push(n.pngChunk("IDAT",bb(a),o)),i.push(n.pngChunk("IEND",Buffer.alloc(0),o)),Buffer.concat(i)}cropChrome(e,t,r){let o=Math.floor(t*Pb),i=Math.floor(t*(1-Cb));if(i<=o+8)return{width:e,height:t,rgb:r};let s=i-o,a=new Uint8Array(e*s*3);for(let c=0;c<s;c++){let l=(o+c)*e*3;a.set(r.subarray(l,l+e*3),c*e*3)}return{width:e,height:s,rgb:a}}hashBits(e,t,r){let o=this.toGray(e,t,r),i=this.resizeGray(o,Ip,Ip),s=this.dct2(i),a=[];for(let d=0;d<kp;d++)a.push(s[d].slice(0,kp));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 i=new Uint8Array(12288);for(let s=0;s<4096;s++)i[s*3]=e,i[s*3+1]=t,i[s*3+2]=r;return this.hashBits(64,64,i)}hammingDistance(e,t){let r=Math.min(e.length,t.length),o=Math.abs(e.length-t.length);for(let i=0;i<r;i++)e[i]!==t[i]&&o++;return o}bitsToHex(e){let t=0n;for(let o of e)t=t<<1n|(o?1n:0n);let r=Math.max(1,Math.ceil(e.length/4));return t.toString(16).padStart(r,"0")}toGray(e,t,r){let o=[];for(let i=0;i<t;i++){let s=[];for(let a=0;a<e;a++){let c=(i*e+a)*3;s.push(.299*r[c]+.587*r[c+1]+.114*r[c+2])}o.push(s)}return o}resizeGray(e,t,r){let o=e.length,i=e[0]?.length??0;if(i===t&&o===r)return e;let s=[];for(let a=0;a<r;a++){let c=(a+.5)*o/r-.5,l=Math.max(0,Math.min(o-1,Math.floor(c))),d=Math.max(0,Math.min(o-1,l+1)),g=c-l,v=[];for(let P=0;P<t;P++){let ie=(P+.5)*i/t-.5,B=Math.max(0,Math.min(i-1,Math.floor(ie))),Ae=Math.max(0,Math.min(i-1,B+1)),Qe=ie-B,St=e[l][B],Rd=e[l][Ae],Ma=e[d][B],Oa=e[d][Ae];v.push(St*(1-Qe)*(1-g)+Rd*Qe*(1-g)+Ma*(1-Qe)*g+Oa*Qe*g)}s.push(v)}return s}stabilizeDct(e){let t=e.flat(),r=Math.abs(t[0]??0),o=Math.max(.001,r*1e-8);return t.map(i=>Math.abs(i)<o?0:i)}median(e){if(e.length===0)return 0;let t=[...e].sort((o,i)=>o-i),r=Math.floor(t.length/2);return t.length%2?t[r]:.5*(t[r-1]+t[r])}dct2(e){let t=e.length,r=a=>{let c=new Array(t).fill(0);for(let l=0;l<t;l++){let d=0;for(let g=0;g<t;g++)d+=a[g]*Math.cos(Math.PI*(g+.5)*l/t);c[l]=d}return c},o=e.map(r),i=[];for(let a=0;a<t;a++)i.push(r(o.map(c=>c[a])));let s=[];for(let a=0;a<t;a++){let c=[];for(let l=0;l<t;l++)c.push(i[l][a]);s.push(c)}return s}decodePngRgb(e){let t=this.parsePngChunks(e);if(!t)return null;let r;try{r=Sb(Buffer.concat(t.idat))}catch{return null}let o=this.pngScanlinesToRgb(r,t.width,t.height,t.colorType);return{width:t.width,height:t.height,rgb:o}}parsePngChunks(e){if(e.length<8||e.subarray(0,8).toString("binary")!==`\x89PNG\r
63
+ 
64
+ `)return null;let t=8,r=0,o=0,i=0,s=0,a=[];for(;t+8<=e.length;){let c=e.readUInt32BE(t),l=e.subarray(t+4,t+8).toString("ascii"),d=e.subarray(t+8,t+8+c);if(t+=12+c,l==="IHDR")r=d.readUInt32BE(0),o=d.readUInt32BE(4),i=d[8],s=d[9];else if(l==="IDAT")a.push(d);else if(l==="IEND")break}return!r||!o||i!==8||s!==2&&s!==6?null:{width:r,height:o,colorType:s,idat:a}}pngScanlinesToRgb(e,t,r,o){let i=o===6?4:3,s=t*i,a=new Uint8Array(t*r*3),c=0,l=new Uint8Array(s),d=new Uint8Array(s);for(let g=0;g<r;g++){let v=e[c++];d.set(e.subarray(c,c+s)),c+=s,this.applyPngFilter(v,d,l,i);for(let P=0;P<t;P++){let ie=(g*t+P)*3,B=P*i;a[ie]=d[B],a[ie+1]=d[B+1],a[ie+2]=d[B+2]}l.set(d)}return a}applyPngFilter(e,t,r,o){for(let i=0;i<t.length;i++){let s=i>=o?t[i-o]:0,a=r[i],c=i>=o?r[i-o]:0;e===1?t[i]=t[i]+s&255:e===2?t[i]=t[i]+a&255:e===3?t[i]=t[i]+Math.floor((s+a)/2)&255:e===4&&(t[i]=t[i]+this.paeth(s,a,c)&255)}}paeth(e,t,r){let o=e+t-r,i=Math.abs(o-e),s=Math.abs(o-t),a=Math.abs(o-r);return i<=s&&i<=a?e:s<=a?t:r}static pngChunk(e,t,r){let o=Buffer.concat([Buffer.from(e,"ascii"),t]),i=Buffer.alloc(12+t.length);return i.writeUInt32BE(t.length,0),o.copy(i,4),i.writeUInt32BE(n.pngCrc(o,r),8+t.length),i}static pngCrcTable(){let e=new Uint32Array(256);for(let t=0;t<256;t++){let r=t;for(let o=0;o<8;o++)r=r&1?3988292384^r>>>1:r>>>1;e[t]=r>>>0}return e}static pngCrc(e,t){let r=4294967295;for(let o=0;o<e.length;o++)r=t[(r^e[o])&255]^r>>>8;return(r^4294967295)>>>0}};import _t from"fs";import gt from"path";import{randomUUID as Tb}from"crypto";var kb=/^smoke-screenshot-\d+\.png$/,Ib=/^smoke-crash-\d+\.log$/,Ab=/^run-\d+-\d+-[0-9a-f]{4}$/;function Ap(n){return`smoke-screenshot-${n}.png`}function Dp(n){return`smoke-crash-${n}.log`}function Rp(n){return kb.test(n)||Ib.test(n)}var go="RUNNING",Ic="ENDED",Db=1440*60*1e3,Rb=1440*60*1e3;function Tp(n,e,t){return`run-${n}-${e}-${t}`}function xp(n){return Ab.test(n)}function Lp(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 Np(n,e,t){return n===null?!0:n==="ended"?e?.endedAt===void 0?!0:t.now-e.endedAt>=Db:!e||!Number.isInteger(e.pid)||e.pid<=0||t.now-e.startedAt>=Rb?!0:!t.isPidAlive(e.pid)}var xb="smoke";function Lb(n){try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}var yo=class{constructor(e,t=Lb){this.baseDir=e;this.isPidAlive=t;this.runsRoot=gt.join(e,xb)}baseDir;isPidAlive;runsRoot;static resolveBaseDir(e,t){return t??gt.join(e,".hvigor")}createRun(){let e=gt.join(this.runsRoot,Tp(Date.now(),process.pid,Tb().slice(0,4)));_t.mkdirSync(e,{recursive:!0});let t={pid:process.pid,startedAt:Date.now()};return _t.writeFileSync(gt.join(e,go),JSON.stringify(t),"utf8"),e}prune(e,t=Date.now()){this.pruneLegacyFlatArtifacts(),this.pruneEndedRuns(e,t)}finalize(e){try{let t=this.readMarker(e,go),r={pid:t?.pid??process.pid,startedAt:t?.startedAt??Date.now(),endedAt:Date.now()};_t.writeFileSync(gt.join(e,Ic),JSON.stringify(r),"utf8"),_t.rmSync(gt.join(e,go),{force:!0})}catch(t){u(`Smoke: finalize run failed (${e}): ${t.message}`)}}discard(e){try{_t.rmSync(e,{recursive:!0,force:!0})}catch(t){u(`Smoke: discard run failed (${e}): ${t.message}`)}}pruneLegacyFlatArtifacts(){let e;try{e=_t.readdirSync(this.baseDir,{withFileTypes:!0})}catch{return}for(let t of e)!t.isFile()||!Rp(t.name)||this.removeQuietly(gt.join(this.baseDir,t.name))}pruneEndedRuns(e,t){let r;try{r=_t.readdirSync(this.runsRoot,{withFileTypes:!0})}catch{return}for(let o of r){if(!o.isDirectory()||!xp(o.name))continue;let i=gt.join(this.runsRoot,o.name);if(gt.resolve(i)===gt.resolve(e))continue;let s=this.readMarkerState(i);Np(s.kind,s.marker,{now:t,isPidAlive:this.isPidAlive})&&this.removeQuietly(i)}}readMarkerState(e){let t=this.readMarker(e,Ic);if(t!==void 0)return{kind:"ended",marker:t};let r=this.readMarker(e,go);return r!==void 0?{kind:"running",marker:r}:{kind:null,marker:null}}readMarker(e,t){try{return Lp(_t.readFileSync(gt.join(e,t),"utf8"))}catch(r){return r.code==="ENOENT"?void 0:null}}removeQuietly(e){try{_t.rmSync(e,{recursive:!0,force:!0})}catch(t){u(`Smoke: prune artifact failed (${e}): ${t.message}`)}}};var Mp=1e3;function Mb(){let n=process.env.DEVECO_CLI_SMOKE_WAIT_MS;if(n===void 0||n==="")return Mp;let e=Number(n);return Number.isFinite(e)&&e>=0?Math.floor(e):Mp}var Xi=class{constructor(e,t,r){this.hdc=t;this.projectRoot=r;this.hilog=new or(e),this.screenshots=new Vr(e)}hdc;projectRoot;phash=new Yi;hilog;screenshots;runDir;runStore;async collect(e){this.openRun(e);let t=Mb();t>0&&await new Promise(o=>setTimeout(o,t));let r;try{r=await this.hdc.pidofBundle(e.targetDeviceId,e.bundleName)}catch(o){return console.warn(vo(`Smoke: process check failed (${o.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 yo(yo.resolveBaseDir(this.projectRoot,e.screenshotDir)),r=t.createRun();t.prune(r),this.runStore=t,this.runDir=r}artifactPath(e){return Nb.join(this.runDir??"",e)}discardEvidence(e){for(let t of[e.screenshotPath,e.crashLogPath])if(t)try{Ki.rmSync(t,{force:!0})}catch(r){u(`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(Ap(Date.now()));try{await this.screenshots.captureToPath(e.targetDeviceId,t)}catch(o){return this.skipBlank(`screenshot failed (${o.message})`)}if(!Ki.existsSync(t)||Ki.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(vo(`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(vo(`Smoke: crash log query failed (${r.message}).`));return}if(!t?.trim()){console.warn(vo("Smoke: no crash log found on device."));return}try{let r=this.artifactPath(Dp(Date.now()));return Ki.writeFileSync(r,t,"utf8"),r}catch(r){console.warn(vo(`Smoke: failed to save crash log (${r.message}).`));return}}};var Zi=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 ${kc}, 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 Qi=class{inspector;judge=new Zi;formatter=new Vi;constructor(e,t,r){let o=r??new Ye(e);this.inspector=new Xi(e,o,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 Ac(n){await new Qi(n.toolProvider,n.projectRoot,n.hdcAdapter).execute(n)}function Dc(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 ts(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 o=await n.listDevicesWithName();throw new w("Multiple devices found. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+o.map(i=>` - ${i.name} (${i.serial})`).join(`
65
+ `),"Multiple devices found.")}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let o=await n.getDeviceName(r.serial);console.log(`Auto-selected device: ${o} (${r.serial})`)}return r.serial}function Rc(n,e){if(e&&e.length>0)return e;let t=n.profile.modules.filter(r=>{let o=n.getModuleType(r.name);return o==="entry"||o==="feature"||o==="shared"});if(t.length===1){let r=t[0].name;return console.log(`Auto-selected module: ${r}`),[r]}throw new w(`Specify module(s) using --module <name> [<name>...].
50
66
  Available runnable modules:
51
67
  `+t.map(r=>` - ${r.name}`).join(`
52
- `),"Specify module error.")}function Ru(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 Tu(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(`
53
- 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(oi(`
68
+ `),"Specify module error.")}function Op(n,e,t){if(t)return t;let r=e.find(({moduleName:i})=>n.getModuleType(i)==="entry");if(r)return n.getMainAbility(r.moduleName);let o=e.find(({moduleName:i})=>n.getModuleType(i)==="feature");if(o)return n.getMainAbility(o.moduleName)}async function _p(n,e,t,r,o,i){if(i&&(console.log(`Uninstalling ${t}...`),await n.uninstallApp(e,t)||console.log(`App ${t} not installed; skipping uninstallation.`)),console.log(`
69
+ Installing artifacts to device ${e}...`),await n.installApp(e,r),o){console.log(`Launching ${t}/${o}...`);let s=await n.launchApp(e,t,o);console.log(wo(`
54
70
  Application '${t}': ${s}`))}else console.log(`
55
- Application '${t}' installed successfully (no ability to launch).`)}function lw(n){let e={event:b.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 dw=new aw("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=lw(n),t=Date.now(),r=!0,i=null;try{let o=await pw(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=B(o),console.error(cw(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(e,o)}});async function uw(n,e,t,r,i){let o=new Qn(e,n.rootDir),s=new Be(e,n.rootDir),a=new Set,c=new Set;for(let{moduleName:D,targetName:He}of t)for(let ye of n.collectNonHarDependentModuleList(D))a.add(`${ye}@${He}`),c.add(ye);let l=[...a],d=Wa(n,l),g={type:"modules",modulesToBuild:l,moduleTasks:d};for(let D of c)Po.generate(n.rootDir,D,r,e);let v=await xn(n.rootDir,()=>Ba(o,s,r,i,g,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion..."));return console.log(`
56
- `+oi("Build completed successfully.")),v}async function pw(n,e){let t=Y.discover(process.cwd());console.warn(Ro("Ensure the project source is trusted before proceeding."));let r=await A.new();if(n.skipBuild||r.assertJava(),e.bundle_name=t.getBundleName(),n.hotreloadApply){await hw(n,t,r);return}if(n.hotreload){await mw(n,t,r);return}if(n.apply){await yw(n,t,r);return}return xu(n,t,r)}async function fw(n,e,t){n.onSocketDisconnect(()=>{console.log("Daemon disconnected (likely via --hotreload stop). Exiting watch session."),process.exit(0)});let r=new Be(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 mw(n,e,t){if(n.hotreload==="stop"){await Du(t,e);return}let i=ec(e,n.module).map(Qa),{moduleName:o,targetName:s}=i[0];Za(n.module,o);let a=new Kt(t),c=oe.from(t),l=await To(c,n.device),d=l.includes("127.0.0.1")||l.includes("localhost"),g=n.product||"default";e.validateProduct(g);let v=e.getBundleName(g),D=Ru(e,i,n.ability);Co.generate(e.rootDir,o,g,t);let He=new Be(t,e.rootDir);console.log(oi("Ensuring hvigor daemon is running (via --sync --daemon, no hap build)...")),await He.ensureDaemonRunning();let ye=[`${o}@${g}`];for(let Ut of e.collectNonHarDependentModuleList(o))ye.includes(`${Ut}@${g}`)||ye.push(`${Ut}@${g}`);console.log(oi("Building hap + starting watch session (socket -> CommonBuild assembleHap --hot-reload-build --watch, kept open)..."));let ze=new sr(e.rootDir,t);await ze.startWatchSession({moduleSpecs:ye,productName:g});let Cn=Au(e,o,s,d,g);await Tu(a,l,v,Cn,D,!!n.uninstall),console.log(oi("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 fw(ze,t,e)}async function hw(n,e,t){let r=n.hotreloadApply;if(!r)throw new Error("hotreload-apply requires --hotreload-apply <fileName> (under .hvigor/)");if(si.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let i=ec(e,n.module),{moduleName:o}=Qa(i[0]);Za(n.module,o);let s=oe.from(t),a=await To(s,n.device),c=n.product||"default";e.validateProduct(c);let l=e.getBundleName(c);Iu(e,o,r);let d=[`${o}@${c}`],g=await ku({applyFileName:r,projectPath:e.rootDir,moduleName:o,productName:c,bundleName:l,toolProvider:t,targetDeviceId:a,moduleSpecs:d});if(!g.success)throw new Error(g.message)}function gw(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 xu(n,e,t){let i=ec(e,n.module).map(Qa);for(let{moduleName:ye}of i){let ze=e.getModuleType(ye);if(ze!=="entry"&&ze!=="feature"&&ze!=="shared")throw new w(`Module '${ye}' '${ze}' is not runnable. Specify an entry or feature module.`,"Module is not runnable.")}let o=new Kt(t),s=oe.from(t),a=await To(s,n.device),c=a.includes("127.0.0.1")||a.includes("localhost"),l=n.product||"default";e.validateProduct(l);let d=n.buildMode||"debug",g;n.skipBuild||(g=await uw(e,t,i,l,d));let v=gw(e,i,c,l),D=e.getBundleName(l),He=Ru(e,i,n.ability);return await Tu(o,a,D,v,He,!!n.uninstall),g}async function yw(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(si.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let i=si.join(e.rootDir,".hvigor",r),o=oe.from(t),s=await To(o,n.device),a=n.product||"default";e.validateProduct(a);let c=e.getBundleName(a),l=e.profile.modules.find(v=>e.getModuleType(v.name)==="entry")?.name,d=l?e.getMainAbility(l,n.ability):n.ability||"EntryAbility",g=new Eo(t,e.rootDir);try{await g.execute({applyFile:i,productName:a,targetDeviceId:s,bundleName:c,abilityName:d}),console.log(Ro("[Apply] \u5B8C\u6210\u3002\u82E5\u6539\u52A8\u672A\u751F\u6548\uFF0C\u8BF7\u68C0\u67E5 <module>/build/config/buildConfig.json \u662F\u5426\u6709\u5185\u5BB9\uFF0C\u6216\u6267\u884C devecocli run \u5168\u91CF\u6784\u5EFA\u3002"));return}catch(v){console.warn(Ro(`[Apply] \u5931\u8D25\uFF1A${v.message}`)),console.warn(Ro("[Apply] \u81EA\u52A8\u56DE\u9000\u5230\u5168\u91CF devecocli run..."))}await xu(n,e,t)}var Lu=dw;import{Command as Nw}from"commander";import*as Bu from"path";import{green as Hu,red as Uu,cyan as rc}from"colorette";import{execa as oc}from"execa";import{spawn as Ew}from"child_process";import*as Mu from"fs";import*as Lo from"path";import{yellow as Pw}from"colorette";import Cw from"proper-lockfile";import*as ai from"fs";import*as Ou from"path";import{homedir as vw}from"os";var ww="deveco-cli",Nu,tc=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function bw(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":Ta(n))||Ou.join(vw(),".local","share",ww);try{return co(t)}catch(r){throw new tc(r instanceof Error?r.message:String(r))}}function be(){if(Nu!==void 0)return Nu;let n=bw();try{if(ai.existsSync(n))return ai.realpathSync(n)}catch{}return n}function xo(){return"@yinsen/deveco-cli"}function Xt(){return"1.3.1"}function ar(){return"latest"}function cr(){let n=process.env.DEVECO_CLI_DISABLE_UPDATE;return n==="check"||n==="all"?n:"off"}import*as ci from"fs";import*as li from"path";var Sw={lastCheckedTimestamp:null,latestVersion:null,blockedVersions:[],checkError:null},nc=new Map,Zt=class n{static CHECK_WINDOW_HOUR=21;static ONE_DAY_MS=1440*60*1e3;cacheFilePath;lockFilePath;constructor(e){this.cacheFilePath=li.join(e,"cache.json"),this.lockFilePath=li.join(e,"check.lock")}async writeSuccess(e,t=[],r,i){await this.write({lastCheckedTimestamp:Date.now(),latestVersion:e,blockedVersions:t,checkError:null,checkedAgainstVersion:r,checkedAgainstTag:i})}async writeError(e){let t=this.read();await this.write({...t,lastCheckedTimestamp:Date.now(),checkError:e})}getLatestVersion(){return this.read().latestVersion}getBlockedVersions(){return[...this.read().blockedVersions]}getCheckedAgainstVersion(){return this.read().checkedAgainstVersion}getCheckedAgainstTag(){return this.read().checkedAgainstTag}isCheckNeeded(){let{lastCheckedTimestamp:e}=this.read();if(!e||e>Date.now())return!0;let t=new Date().setHours(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=nc.get(this.cacheFilePath);if(e)return e;try{let t=ci.readFileSync(this.cacheFilePath,"utf-8"),r=JSON.parse(t);return nc.set(this.cacheFilePath,r),r}catch{return{...Sw}}}async write(e){p(()=>`Writing update cache: lastChecked=${e.lastCheckedTimestamp}, latest=${e.latestVersion}, blocked=[${e.blockedVersions.join(",")}], error=${e.checkError}`),await ci.promises.mkdir(li.dirname(this.cacheFilePath),{recursive:!0}),await ci.promises.writeFile(this.cacheFilePath,JSON.stringify(e,null,2),"utf-8"),nc.set(this.cacheFilePath,e)}};var di=class{constructor(e){this.actionCommand=e}actionCommand;cache=new Zt(Lo.join(be(),"update"));async checkAndNotify(){if(!this.shouldSkip())try{let e=Xt(),t=ar(),r=this.cache.getCheckedAgainstVersion(),i=this.cache.getCheckedAgainstTag(),o=i!=null&&i!==t,s=r!=null&&r!==e,a=o?null:this.cache.getLatestVersion();a&&kd(a,e)>0&&(console.log(),console.log(Pw(`New version ${a} available, run \`devecocli update\` to upgrade`))),(o||s||this.cache.isCheckNeeded())&&await this.spawnBackgroundCheck()}catch(e){p(`Update check failed: ${e instanceof Error?e.message:String(e)}`)}}shouldSkip(){let e=this.actionCommand;for(;e;){if(e.name()==="update")return!0;e=e.parent}return!1}async spawnBackgroundCheck(){if(!process.argv[1]?.endsWith(".ts"))try{await kw(this.cache.getLockPath(),()=>{let e=[process.argv[1],"update","_check"];p(`Executing: ${process.execPath} ${e.join(" ")}`),Ew(process.execPath,e,{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1"}}).unref()})}catch{p("Update check lock held by another process, skipping")}}};async function kw(n,e){await Mu.promises.mkdir(Lo.dirname(n),{recursive:!0});let t=await Cw.lock(n,{stale:6e4,retries:0,realpath:!1});try{await e()}finally{await t()}}import{Command as Iw}from"commander";import{green as _u,cyan as No}from"colorette";import{execa as ui}from"execa";import*as tt from"path";import*as Z from"fs/promises";import*as Fu from"crypto";var Qt="@yinsen/deveco-cli-docs-zh",ju=1;async function Aw(n,e){let t=`${n}.tmp.${process.pid}`;await Z.writeFile(t,JSON.stringify(e,null,2),"utf-8"),await Z.rename(t,n)}function Dw(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 Fu.createHash(r).update(n).digest().equals(o)}async function Rw(){p(`Executing: npm view ${Qt} --json`);let{stdout:n}=await ui("npm",["view",Qt,"--json"]),e=JSON.parse(n);if((e.apiVersion??0)<=ju)return e;p(`Executing: npm view ${Qt} versions --json`);let{stdout:t}=await ui("npm",["view",Qt,"versions","--json"]),r=JSON.parse(t);for(let i=r.length-1;i>=0;i--){let o=r[i];p(`Checking: npm view ${Qt}@${o} --json`);let{stdout:s}=await ui("npm",["view",`${Qt}@${o}`,"--json"]),a=JSON.parse(s);if((a.apiVersion??0)<=ju)return console.log(No(`\u6700\u65B0\u7248 v${e.version} \u4E0D\u517C\u5BB9\u5F53\u524D CLI\uFF0C\u4F7F\u7528\u517C\u5BB9\u7248 v${a.version}`)),a}throw new Error(`\u6587\u6863\u5305\u6700\u65B0\u7248 v${e.version} (apiVersion ${e.apiVersion??0}) \u4E0D\u517C\u5BB9\u5F53\u524D CLI\uFF0C\u4E14\u65E0\u517C\u5BB9\u5386\u53F2\u7248\u672C\uFF0C\u8BF7\u5347\u7EA7 CLI`)}async function Tw(n,e,t){p(`Executing: npm pack ${Qt}@${n}`);let{stdout:r}=await ui("npm",["pack",`${Qt}@${n}`],{cwd:t}),i=r.trim().split(`
57
- `).pop(),o=tt.join(t,i),s=await Z.readFile(o);if(!Dw(s,e))throw await Z.unlink(o).catch(()=>{}),new Error("\u6587\u6863\u5305\u5B8C\u6574\u6027\u6821\u9A8C\u5931\u8D25");return o}async function xw(n,e,t){let r=tt.join(t,e),i=tt.join(t,`.tmp-${e}-${process.pid}`);return await Z.rm(r,{recursive:!0,force:!0}),await Z.rm(i,{recursive:!0,force:!0}),await Z.mkdir(i,{recursive:!0}),p(`Executing: tar -xzf ${tt.basename(n)} -C ${i}`),await ui("tar",["-xzf",n,"-C",i]),await Z.rename(tt.join(i,"package"),r),await Z.rm(i,{recursive:!0,force:!0}),await Z.unlink(n).catch(()=>{}),await Z.access(tt.join(r,"dist","engine","index.js")),await Z.access(tt.join(r,"docs.zip")),await Z.access(tt.join(r,"index.zip")),r}var Lw=new Iw("docs").description("Update documentation to the latest compatible version").option("--lang <lang>","Language (zh, en)","zh").option("--force","Force re-download even if up to date").option("--check","Check for updates without installing").action(async n=>{if(n.lang==="en")throw new Error("\u82F1\u6587\u6587\u6863\u5C1A\u672A\u542F\u7528\u591A\u8BED\u8A00\u652F\u6301");let e=be(),t=tt.join(e,"doc-data");await Z.mkdir(t,{recursive:!0}),console.log(No("Checking for documentation updates..."));let r=await Rw(),i=r.version,o=r.apiVersion??0,s=tt.join(t,"current.json"),a=null;try{a=JSON.parse(await Z.readFile(s,"utf-8"))}catch{}if(!n.force&&a?.version===i){console.log(_u(`\u6587\u6863\u5DF2\u662F\u6700\u65B0\u7248\u672C v${i}`));return}if(n.check){console.log(No(`\u53D1\u73B0\u65B0\u7248\u672C v${i}\uFF08\u5F53\u524D v${a?.version??"\u65E0"}\uFF09`));return}console.log(No(`\u6B63\u5728\u4E0B\u8F7D\u6587\u6863\u5305 v${i}...`));let c=await Tw(i,r.dist.integrity,t);await xw(c,i,t),await Aw(s,{version:i,apiVersion:o,installedAt:Date.now(),installedBy:"update-docs"}),console.log(_u(`\u6587\u6863\u5DF2\u66F4\u65B0\u5230 v${i}`))}),$u=Lw;var Oo=new Nw("update").description("Update deveco-cli to latest");Oo.command("_check",{hidden:!0}).action(async()=>{let n=Date.now(),e=new Zt(Bu.join(be(),"update"));try{let t=ar(),r=xo();p(`Executing: npm view ${r}@${t} --json`);let{stdout:i}=await oc("npm",["view",`${r}@${t}`,"--json"]),o=JSON.parse(i),s=typeof o.version=="string"?o.version.trim():null,a=Array.isArray(o.blockedVersions)?o.blockedVersions:[];await e.writeSuccess(s,a,Xt(),t),await Wu(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 Wu(n,!1,i)}});var Ow={event:b.CommandExecuted,args:["update"]},Mw={event:b.CommandExecuted,args:["update","_check"]};async function ic(n,e,t){let r={duration_ms:Date.now()-n,success:e,error_code:t};await I.track(Ow,r).catch(()=>{})}async function Wu(n,e,t){let r={duration_ms:Date.now()-n,success:e,error_code:t};await I.track(Mw,r).catch(()=>{})}Oo.action(async()=>{if(cr()==="all")throw new Error("devecocli update is disabled (DEVECO_CLI_DISABLE_UPDATE=all).");let n=Date.now(),e=Xt(),t=ar();console.log(rc("Checking for updates..."));let r=xo();try{let{stdout:i}=await oc("npm",["view",r,`dist-tags.${t}`]),o=i.trim();if(!o||o===e){console.log(Hu(`
58
- ${r} is already up to date (v${e}, tag: ${t})`)),await ic(n,!0,null);return}console.log(rc(`
59
- New version found: ${o} (current: ${e})`)),console.log(rc(`Updating ${r}...`)),await oc("npm",["install","-g",`${r}@${t}`],{stdio:"inherit"}),console.log(`
60
- `+Hu(`${r} updated successfully to version ${o}.`)),await ic(n,!0,null)}catch(i){let o=i,s=o.code??o.name??"UnknownError";console.error(Uu(`Failed to update ${r}`)),o.message&&console.error(Uu(o.message)),await ic(n,!1,s),process.exit(1)}});Oo.addCommand($u);var Vu=Oo;import{Command as db,Option as op}from"commander";import{execa as Mo}from"execa";function Se(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}function qu(n){let e=n.normalize("NFKC").match(/\((\d+)(?:\.\d+)*\)/)?.[1];return e!==void 0&&Number(e)>=26}import{spawn as _w}from"child_process";var jw=2500;function Fw(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 $w(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,jw);n.once("error",d=>c(d.message)),Fw(n,l,s,a,c,o)}function Gu(n,e,t){return p(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,i)=>{let o=[],s=_w(n,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>o.push(a)),$w(s,o,r,i)})}import*as lr from"path";function Hw(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 Uw(n){let e=n.instancePath?.trim();if(e)return lr.dirname(lr.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?lr.dirname(lr.normalize(t)).replace(/\\/g,"/"):""}function Ww(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function zu(n,e){return e?[...n,"-bootmode",e]:n}function Bw(n,e,t){let r=[zu(["-start",n],t)],i=Uw(e);if(i)for(let o of Ww(e.imageRoot))r.push(zu(["-hvd",n,"-path",i,...o],t));return Hw(r)}async function Ju(n,e,t,r){let i=new Error("No start strategy ran"),o=Bw(n,e,r);for(let s of o)try{return await t(s),{ok:!0}}catch(a){i=a}return{ok:!1,lastError:i}}function Vw(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 sc(n){return(await oe.withHdcPath(n).listDevices()).map(t=>t.serial).filter(yt)}async function ac(n){let e=await sc(n);return e.length===0?[]:(await Promise.all(e.map(r=>So(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function Yu(n,e){return(await ac(n)).includes(e)}async function Ku(n,e){let t=await oe.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||!yt(i.serial))throw new Error(`Cannot resolve the running emulator serial for "${e}".`);let o=["-t",i.serial,"shell","hidumper","-s","3302","-a","-i"];p(`Executing: ${n} ${o.join(" ")}`);let s=await ie(n,o);if(s.exitCode===0){let a=Vw(s.stdout);if(a!==void 0)return a}throw new Error(`Cannot determine the battery charging state for emulator "${e}".`)}import*as ur from"path";import{existsSync as qw,statSync as Gw}from"fs";function dr(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function zw(n){let e=dr(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 Jw(n){return dr(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function Yw(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=ur.dirname(ur.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let i=S.ensurePathWithinRoot(t,ur.join(t,r.name));qw(i)&&Gw(i).isDirectory()&&(r.instancePath=i.replace(/\\/g,"/"))}}function Kw(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=Jw(t),i=dr(t,["deviceType","DeviceType","devicetype"]),o=dr(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:zw(t),path:dr(t,["path","Path","hvdPath","hvd_path"]),imageRoot:dr(t,["imageRoot","image_root","ImageRoot"]),uuid:r||void 0,deviceType:i||void 0,osVersion:o||void 0}}).filter(t=>t.name):null}catch{return null}}function Xw(n){let e=[],t=/^(name|isrunning|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==="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 Xu(n){let t=Kw(n)??Xw(n);return Yw(t),t}function cc(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function Zw(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function Qw(n){let e=cc(n,["osVersion","OsVersion","OSVersion"]),t=cc(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=cc(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function Zu(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=Qw(s);a&&i.push(a)}return i}catch{return[]}}function Qu(n){return Zu(n)}function lc(n){return Zu(n,Zw)}function ep(n){let t=lc(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var tp=/no images are available/i,eb=/Scenario simulation failed\s*[::]/i,tb="7.0.0";function Dt(n){return n.normalize("NFKC").trim().toLowerCase()}function nb(n){let e=n.message||"";return tp.test(e)}function rb(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function pi(n,e){return`${n} ${e.join(" ")}`.trim()}function ib(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 pr=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 p(`Executing: ${pi(this.emulatorPath,e)}`),Mo(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return Gu(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return Xu(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let r of t)r.name&&r.deviceType&&e.set(Se(r.name),r.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),r=Se(e),i=t.find(a=>Se(a.name)===r);if(!i)throw new w(`Emulator "${e}" not found.`,"Emulator not found.");let o=i.name;if(await this.isAlreadyRunning(o,i))return"already-running";let s=await Ju(o,i,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return"started";if(await this.isAlreadyRunning(o))return"already-running";throw new w(`Unable to start emulator "${e}". All methods failed.
71
+ Application '${t}' installed successfully (no ability to launch).`)}function jb(n){let e={event:b.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 Fb=new Ob("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=jb(n),t=Date.now(),r=!0,o=null;try{let i=await Hb(n,e);i&&(i.ohpmMemoryMb&&(e.ohpm_install_memory=i.ohpmMemoryMb),i.syncMemoryMb&&(e.hvigor_sync_memory=i.syncMemoryMb),i.buildMemoryMb&&(e.hvigor_build_memory=i.buildMemoryMb))}catch(i){r=!1,o=G(i),console.error(_b(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await I.track(e,i)}});async function $b(n,e,t,r,o){let i=new ln(e,n.rootDir),s=new ze(e,n.rootDir),a=new Set,c=new Set;for(let{moduleName:P,targetName:ie}of t)for(let B of n.collectNonHarDependentModuleList(P))a.add(`${B}@${ie}`),c.add(B);let l=[...a],d=dc(n,l),g={type:"modules",modulesToBuild:l,moduleTasks:d};for(let P of c)Fi.generate(n.rootDir,P,r,e);let v=await jr(n.rootDir,()=>uc(i,s,r,o,g,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion..."));return console.log(`
72
+ `+wo("Build completed successfully.")),v}async function Hb(n,e){let t=W.discover(process.cwd());console.warn(es("Ensure the project source is trusted before proceeding."));let r=await A.new();if(n.skipBuild||r.assertJava(),e.bundle_name=t.getBundleName(),n.hotreloadApply){await Wb(n,t,r);return}if(n.hotreload){await Bb(n,t,r);return}if(n.apply){await qb(n,t,r);return}return jp(n,t,r)}async function Ub(n,e,t){n.onSocketDisconnect(()=>{console.log("Daemon disconnected (likely via --hotreload stop). Exiting watch session."),process.exit(0)});let r=new ze(e,t.rootDir),o=setInterval(async()=>{await r.isDaemonAlive()||(clearInterval(o),console.log("Daemon stopped (via --hotreload stop). Exiting watch session."),process.exit(0))},3e3);await new Promise(()=>{})}async function Bb(n,e,t){if(n.hotreload==="stop"){await cp(t,e);return}let o=Rc(e,n.module).map(Dc),{moduleName:i,targetName:s}=o[0];bc(n.module,i);let a=new Ye(t),c=de.from(t),l=await ts(c,n.device),d=l.includes("127.0.0.1")||l.includes("localhost"),g=n.product||"default";e.validateProduct(g);let v=e.getBundleName(g),P=Op(e,o,n.ability);$i.generate(e.rootDir,i,g,t);let ie=new ze(t,e.rootDir);console.log(wo("Ensuring hvigor daemon is running (via --sync --daemon, no hap build)...")),await ie.ensureDaemonRunning();let B=[`${i}@${g}`];for(let St of e.collectNonHarDependentModuleList(i))B.includes(`${St}@${g}`)||B.push(`${St}@${g}`);console.log(wo("Building hap + starting watch session (socket -> CommonBuild assembleHap --hot-reload-build --watch, kept open)..."));let Ae=new hn(e.rootDir,t);await Ae.startWatchSession({moduleSpecs:B,productName:g});let Qe=ap(e,i,s,d,g);await _p(a,l,v,Qe,P,!!n.uninstall),console.log(wo("Hot-reload watch session active (socket persistent). Edit code, write .hvigor/<file>, then `devecocli run --hotreload-apply <file>` in another terminal. Ctrl+C here to stop.")),await Ub(Ae,t,e)}async function Wb(n,e,t){let r=n.hotreloadApply;if(!r)throw new Error("hotreload-apply requires --hotreload-apply <fileName> (under .hvigor/)");if(bo.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let o=Rc(e,n.module),{moduleName:i}=Dc(o[0]);bc(n.module,i);let s=de.from(t),a=await ts(s,n.device),c=n.product||"default";e.validateProduct(c);let l=e.getBundleName(c);sp(e,i,r);let d=[`${i}@${c}`],g=await ip({applyFileName:r,projectPath:e.rootDir,moduleName:i,productName:c,bundleName:l,toolProvider:t,targetDeviceId:a,moduleSpecs:d});if(!g.success)throw new Error(g.message)}function Vb(n,e,t,r){let o=new Set;for(let{moduleName:i,targetName:s}of e)for(let a of n.collectNonHarDependentModuleList(i)){o.add(n.findArtifactPath(a,s,t,r));for(let c of n.findRemoteHspPaths(a,s,r))o.add(c)}return[...o]}async function jp(n,e,t){let o=Rc(e,n.module).map(Dc);for(let{moduleName:B}of o){let Ae=e.getModuleType(B);if(Ae!=="entry"&&Ae!=="feature"&&Ae!=="shared")throw new w(`Module '${B}' '${Ae}' is not runnable. Specify an entry or feature module.`,"Module is not runnable.")}let i=new Ye(t),s=de.from(t),a=await ts(s,n.device),c=a.includes("127.0.0.1")||a.includes("localhost"),l=n.product||"default";e.validateProduct(l);let d=n.buildMode||"debug",g;n.skipBuild||(g=await $b(e,t,o,l,d));let v=Vb(e,o,c,l),P=e.getBundleName(l),ie=Op(e,o,n.ability);return await _p(i,a,P,v,ie,!!n.uninstall),ie&&await Ac({toolProvider:t,projectRoot:e.rootDir,hdcAdapter:i,targetDeviceId:a,bundleName:P}),g}async function qb(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(bo.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let o=bo.join(e.rootDir,".hvigor",r),i=de.from(t),s=await ts(i,n.device),a=n.product||"default";e.validateProduct(a);let c=e.getBundleName(a),l=e.profile.modules.find(v=>e.getModuleType(v.name)==="entry")?.name,d=l?e.getMainAbility(l,n.ability):n.ability||"EntryAbility",g=new ji(t,e.rootDir);try{await g.execute({applyFile:o,productName:a,targetDeviceId:s,bundleName:c,abilityName:d})}catch(v){console.warn(es(`[Apply] \u5931\u8D25\uFF1A${v.message}`)),console.warn(es("[Apply] \u81EA\u52A8\u56DE\u9000\u5230\u5168\u91CF devecocli run...")),await jp(n,e,t);return}console.log(es("[Apply] \u5B8C\u6210\u3002\u82E5\u6539\u52A8\u672A\u751F\u6548\uFF0C\u8BF7\u68C0\u67E5 <module>/build/config/buildConfig.json \u662F\u5426\u6709\u5185\u5BB9\uFF0C\u6216\u6267\u884C devecocli run \u5168\u91CF\u6784\u5EFA\u3002")),await Ac({toolProvider:t,projectRoot:e.rootDir,targetDeviceId:s,bundleName:c})}var Fp=Fb;import{Command as fS}from"commander";import*as Yp from"path";import{green as Gp,red as zp,cyan as Nc}from"colorette";import{execa as Oc}from"execa";import{spawn as Kb}from"child_process";import*as Up from"fs";import*as rs from"path";import{yellow as Xb}from"colorette";import Zb from"proper-lockfile";import*as So from"fs";import*as Hp from"path";import{homedir as Gb}from"os";var zb="deveco-cli",$p,Tc=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function Jb(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":Za(n))||Hp.join(Gb(),".local","share",zb);try{return ki(t)}catch(r){throw new Tc(r instanceof Error?r.message:String(r))}}function Pe(){if($p!==void 0)return $p;let n=Jb();try{if(So.existsSync(n))return So.realpathSync(n)}catch{}return n}function Eo(){return"@yinsen/deveco-cli"}function ir(){return"1.3.3-Test.2"}function wn(){return"test"}function bn(){let n=process.env.DEVECO_CLI_DISABLE_UPDATE;return n==="check"||n==="all"?n:"off"}import*as Po from"fs";import*as Co from"path";var Yb={lastCheckedTimestamp:null,latestVersion:null,blockedVersions:[],checkError:null},xc=new Map,sr=class n{static CHECK_WINDOW_HOUR=21;static ONE_DAY_MS=1440*60*1e3;cacheFilePath;lockFilePath;constructor(e){this.cacheFilePath=Co.join(e,"cache.json"),this.lockFilePath=Co.join(e,"check.lock")}async writeSuccess(e,t=[],r,o){await this.write({lastCheckedTimestamp:Date.now(),latestVersion:e,blockedVersions:t,checkError:null,checkedAgainstVersion:r,checkedAgainstTag:o})}async writeError(e){let t=this.read();await this.write({...t,lastCheckedTimestamp:Date.now(),checkError:e})}getLatestVersion(){return this.read().latestVersion}getBlockedVersions(){return[...this.read().blockedVersions]}getCheckedAgainstVersion(){return this.read().checkedAgainstVersion}getCheckedAgainstTag(){return this.read().checkedAgainstTag}isCheckNeeded(){let{lastCheckedTimestamp:e}=this.read();if(!e||e>Date.now())return!0;let t=new Date().setHours(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=xc.get(this.cacheFilePath);if(e)return e;try{let t=Po.readFileSync(this.cacheFilePath,"utf-8"),r=JSON.parse(t);return xc.set(this.cacheFilePath,r),r}catch{return{...Yb}}}async write(e){u(()=>`Writing update cache: lastChecked=${e.lastCheckedTimestamp}, latest=${e.latestVersion}, blocked=[${e.blockedVersions.join(",")}], error=${e.checkError}`),await Po.promises.mkdir(Co.dirname(this.cacheFilePath),{recursive:!0}),await Po.promises.writeFile(this.cacheFilePath,JSON.stringify(e,null,2),"utf-8"),xc.set(this.cacheFilePath,e)}};var ko=class{constructor(e){this.actionCommand=e}actionCommand;cache=new sr(rs.join(Pe(),"update"));async checkAndNotify(){if(!this.shouldSkip())try{let e=ir(),t=wn(),r=this.cache.getCheckedAgainstVersion(),o=this.cache.getCheckedAgainstTag(),i=o!=null&&o!==t,s=r!=null&&r!==e,a=i?null:this.cache.getLatestVersion();a&&nu(a,e)>0&&(console.log(),console.log(Xb(`New version ${a} available, run \`devecocli update\` to upgrade`))),(i||s||this.cache.isCheckNeeded())&&await this.spawnBackgroundCheck()}catch(e){u(`Update check failed: ${e instanceof Error?e.message:String(e)}`)}}shouldSkip(){let e=this.actionCommand;for(;e;){if(e.name()==="update")return!0;e=e.parent}return!1}async spawnBackgroundCheck(){if(!process.argv[1]?.endsWith(".ts"))try{await Qb(this.cache.getLockPath(),()=>{let e=[process.argv[1],"update","_check"];u(`Executing: ${process.execPath} ${e.join(" ")}`),Kb(process.execPath,e,{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1"}}).unref()})}catch{u("Update check lock held by another process, skipping")}}};async function Qb(n,e){await Up.promises.mkdir(rs.dirname(n),{recursive:!0});let t=await Zb.lock(n,{stale:6e4,retries:0,realpath:!1});try{await e()}finally{await t()}}import*as ns from"fs";import*as Sn from"path";import{execa as eS}from"execa";import{yellow as tS}from"colorette";function rS(n){return n?n.endsWith(".ts"):!0}function nS(n,e){let t=Sn.join(n,"package.json");try{return JSON.parse(ns.readFileSync(t,"utf8")).name===e}catch{return!1}}function oS(n,e){let t;try{t=Sn.dirname(ns.realpathSync(n))}catch{return null}for(let r=0;r<20&&t&&t!==Sn.dirname(t);r++){if(nS(t,e))return t;t=Sn.dirname(t)}return null}async function iS(){try{u("Executing: npm root -g");let{stdout:n}=await eS("npm",["root","-g"]);return n.trim()||null}catch(n){return u(`[install-check] npm root -g failed: ${n instanceof Error?n.message:String(n)}`),null}}function sS(n,e){return Xa(n,e)}async function Lc(n){if(process.env.DEVECO_CLI_SKIP_INSTALL_CHECK)return;let e=process.argv[1];if(rS(e))return;let t=await iS();if(!t)return;let r=oS(e,n);if(!r){u("[install-check] running package root not found, skipping");return}sS(r,t)||(console.log(),console.log(tS(`Warning: devecocli is running from
73
+ ${r}
74
+ but \`npm\` in PATH installs global packages to
75
+ ${t}
76
+ The devecocli binary in PATH does not match the npm that \`devecocli update\` uses.
77
+ The update would land in the wrong place and would not reach the binary you are running.
78
+ Continuing with update \u2014 abort if this is unexpected.
79
+ Fix: run \`which -a devecocli\` (Windows: \`where devecocli\`) to list all shims, remove the stale one, or reinstall with the matching npm: \`npm install -g ${n}@latest\`.`)))}import{Command as aS}from"commander";import{green as Bp,cyan as os}from"colorette";import{execa as Io}from"execa";import*as at from"path";import*as re from"fs/promises";import*as Vp from"crypto";var ar="@yinsen/deveco-cli-docs-zh",Wp=1;async function cS(n,e){let t=`${n}.tmp.${process.pid}`;await re.writeFile(t,JSON.stringify(e,null,2),"utf-8"),await re.rename(t,n)}function lS(n,e){let t=e.indexOf("-");if(t<0)return!1;let r=e.slice(0,t),o=e.slice(t+1);if(r!=="sha512")return!1;let i=Buffer.from(o,"base64");return Vp.createHash(r).update(n).digest().equals(i)}async function dS(){u(`Executing: npm view ${ar} --json`);let{stdout:n}=await Io("npm",["view",ar,"--json"]),e=JSON.parse(n);if((e.apiVersion??0)<=Wp)return e;u(`Executing: npm view ${ar} versions --json`);let{stdout:t}=await Io("npm",["view",ar,"versions","--json"]),r=JSON.parse(t);for(let o=r.length-1;o>=0;o--){let i=r[o];u(`Checking: npm view ${ar}@${i} --json`);let{stdout:s}=await Io("npm",["view",`${ar}@${i}`,"--json"]),a=JSON.parse(s);if((a.apiVersion??0)<=Wp)return console.log(os(`\u6700\u65B0\u7248 v${e.version} \u4E0D\u517C\u5BB9\u5F53\u524D CLI\uFF0C\u4F7F\u7528\u517C\u5BB9\u7248 v${a.version}`)),a}throw new Error(`\u6587\u6863\u5305\u6700\u65B0\u7248 v${e.version} (apiVersion ${e.apiVersion??0}) \u4E0D\u517C\u5BB9\u5F53\u524D CLI\uFF0C\u4E14\u65E0\u517C\u5BB9\u5386\u53F2\u7248\u672C\uFF0C\u8BF7\u5347\u7EA7 CLI`)}async function uS(n,e,t){u(`Executing: npm pack ${ar}@${n}`);let{stdout:r}=await Io("npm",["pack",`${ar}@${n}`],{cwd:t}),o=r.trim().split(`
80
+ `).pop(),i=at.join(t,o),s=await re.readFile(i);if(!lS(s,e))throw await re.unlink(i).catch(()=>{}),new Error("\u6587\u6863\u5305\u5B8C\u6574\u6027\u6821\u9A8C\u5931\u8D25");return i}async function pS(n,e,t){let r=at.join(t,e),o=at.join(t,`.tmp-${e}-${process.pid}`);return await re.rm(r,{recursive:!0,force:!0}),await re.rm(o,{recursive:!0,force:!0}),await re.mkdir(o,{recursive:!0}),u(`Executing: tar -xzf ${at.basename(n)} -C ${o}`),await Io("tar",["-xzf",n,"-C",o]),await re.rename(at.join(o,"package"),r),await re.rm(o,{recursive:!0,force:!0}),await re.unlink(n).catch(()=>{}),await re.access(at.join(r,"dist","engine","index.js")),await re.access(at.join(r,"docs.zip")),await re.access(at.join(r,"index.zip")),r}var mS=new aS("docs").description("Update documentation to the latest compatible version").option("--lang <lang>","Language (zh, en)","zh").option("--force","Force re-download even if up to date").option("--check","Check for updates without installing").action(async n=>{if(n.lang==="en")throw new Error("\u82F1\u6587\u6587\u6863\u5C1A\u672A\u542F\u7528\u591A\u8BED\u8A00\u652F\u6301");let e=Pe(),t=at.join(e,"doc-data");await re.mkdir(t,{recursive:!0}),console.log(os("Checking for documentation updates..."));let r=await dS(),o=r.version,i=r.apiVersion??0,s=at.join(t,"current.json"),a=null;try{a=JSON.parse(await re.readFile(s,"utf-8"))}catch{}if(!n.force&&a?.version===o){console.log(Bp(`\u6587\u6863\u5DF2\u662F\u6700\u65B0\u7248\u672C v${o}`));return}if(n.check){console.log(os(`\u53D1\u73B0\u65B0\u7248\u672C v${o}\uFF08\u5F53\u524D v${a?.version??"\u65E0"}\uFF09`));return}console.log(os(`\u6B63\u5728\u4E0B\u8F7D\u6587\u6863\u5305 v${o}...`));let c=await uS(o,r.dist.integrity,t);await pS(c,o,t),await cS(s,{version:o,apiVersion:i,installedAt:Date.now(),installedBy:"update-docs"}),console.log(Bp(`\u6587\u6863\u5DF2\u66F4\u65B0\u5230 v${o}`))}),qp=mS;var is=new fS("update").description("Update deveco-cli to latest");is.command("_check",{hidden:!0}).action(async()=>{let n=Date.now(),e=new sr(Yp.join(Pe(),"update"));try{let t=wn(),r=Eo();u(`Executing: npm view ${r}@${t} --json`);let{stdout:o}=await Oc("npm",["view",`${r}@${t}`,"--json"]),i=JSON.parse(o),s=typeof i.version=="string"?i.version.trim():null,a=Array.isArray(i.blockedVersions)?i.blockedVersions:[];await e.writeSuccess(s,a,ir(),t),await Jp(n,!0,null)}catch(t){await e.writeError(t instanceof Error?t.message:String(t));let r=t,o=r.code??r.name??"UnknownError";await Jp(n,!1,o)}});var hS={event:b.CommandExecuted,args:["update"]},gS={event:b.CommandExecuted,args:["update","_check"]};async function Mc(n,e,t){let r={duration_ms:Date.now()-n,success:e,error_code:t};await I.track(hS,r).catch(()=>{})}async function Jp(n,e,t){let r={duration_ms:Date.now()-n,success:e,error_code:t};await I.track(gS,r).catch(()=>{})}is.action(async()=>{if(bn()==="all")throw new Error("devecocli update is disabled (DEVECO_CLI_DISABLE_UPDATE=all).");await Lc(Eo());let n=Date.now(),e=ir(),t=wn();console.log(Nc("Checking for updates..."));let r=Eo();try{let{stdout:o}=await Oc("npm",["view",r,`dist-tags.${t}`]),i=o.trim();if(!i||i===e){console.log(Gp(`
81
+ ${r} is already up to date (v${e}, tag: ${t})`)),await Mc(n,!0,null);return}console.log(Nc(`
82
+ New version found: ${i} (current: ${e})`)),console.log(Nc(`Updating ${r}...`)),await Oc("npm",["install","-g",`${r}@${t}`],{stdio:"inherit"}),console.log(`
83
+ `+Gp(`${r} updated successfully to version ${i}.`)),await Mc(n,!0,null)}catch(o){let i=o,s=i.code??i.name??"UnknownError";console.error(zp(`Failed to update ${r}`)),i.message&&console.error(zp(i.message)),await Mc(n,!1,s),process.exit(1)}});is.addCommand(qp);var Kp=is;import{Command as qS,Option as um}from"commander";import{execa as ss}from"execa";function Ce(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}function Xp(n){let e=n.normalize("NFKC").match(/\((\d+)(?:\.\d+)*\)/)?.[1];return e!==void 0&&Number(e)>=26}import{spawn as yS}from"child_process";var vS=2500;function wS(n,e,t,r,o,i){n.once("exit",s=>{if(i())return;clearTimeout(e);let a=t();s===0||s===null?r():o(a||`Emulator process exited with code ${s}`)})}function bS(n,e,t,r){let o=!1,i=()=>o,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{o||(o=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners(),n.stderr?.destroy(),n.unref(),t())},c=d=>{if(!o){o=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners();try{n.kill()}catch{}r(new Error(d))}},l=setTimeout(a,vS);n.once("error",d=>c(d.message)),wS(n,l,s,a,c,i)}function Zp(n,e,t){u(`Spawning emulator: ${n} ${t.join(" ")}`);let r=[],o=yS(n,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});o.stderr?.on("data",a=>r.push(a));let i=o.pid!==void 0&&!Et()?cn(o.pid,500,!0):void 0,s=new Promise((a,c)=>{bS(o,r,a,c)});return{pid:o.pid,started:s,tracker:i}}import*as En from"path";function SS(n){let e=new Set,t=[];for(let r of n){let o=JSON.stringify(r);e.has(o)||(e.add(o),t.push(r))}return t}function ES(n){let e=n.instancePath?.trim();if(e)return En.dirname(En.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?En.dirname(En.normalize(t)).replace(/\\/g,"/"):""}function PS(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function Qp(n,e){return e?[...n,"-bootmode",e]:n}function CS(n,e,t){let r=[Qp(["-start",n],t)],o=ES(e);if(o)for(let i of PS(e.imageRoot))r.push(Qp(["-hvd",n,"-path",o,...i],t));return SS(r)}async function em(n,e,t,r){let o=new Error("No start strategy ran"),i=CS(n,e,r);for(let s of i){let a;try{return a=t(s),await a.started,{ok:!0,args:s,tracker:a.tracker}}catch(c){if(a?.tracker)try{await a.tracker.stop()}catch{}o=c}}return{ok:!1,lastError:o}}function kS(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 _c(n){return(await de.withHdcPath(n).listDevices()).map(t=>t.serial).filter(It)}async function jc(n){let e=await _c(n);return e.length===0?[]:(await Promise.all(e.map(r=>_i(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function tm(n,e){return(await jc(n)).includes(e)}async function rm(n,e){let t=await de.withHdcPath(n).listDevicesWithName(),r=e.normalize("NFKC").replace(/\s+/g," ").trim(),o=t.find(a=>a.name.normalize("NFKC").replace(/\s+/g," ").trim()===r);if(!o||!It(o.serial))throw new Error(`Cannot resolve the running emulator serial for "${e}".`);let i=["-t",o.serial,"shell","hidumper","-s","3302","-a","-i"];u(`Executing: ${n} ${i.join(" ")}`);let s=await ee(n,i);if(s.exitCode===0){let a=kS(s.stdout);if(a!==void 0)return a}throw new Error(`Cannot determine the battery charging state for emulator "${e}".`)}import*as Cn from"path";import{existsSync as IS,statSync as AS}from"fs";function Pn(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function DS(n){let e=Pn(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 o=t.toLowerCase();if(o.includes("instance")&&(o.includes("path")||o.includes("dir"))||o==="deployedpath")return r.trim()}return""}function RS(n){return Pn(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function TS(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=Cn.dirname(Cn.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let o=S.ensurePathWithinRoot(t,Cn.join(t,r.name));IS(o)&&AS(o).isDirectory()&&(r.instancePath=o.replace(/\\/g,"/"))}}function xS(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=RS(t),o=Pn(t,["deviceType","DeviceType","devicetype"]),i=Pn(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:DS(t),path:Pn(t,["path","Path","hvdPath","hvd_path"]),imageRoot:Pn(t,["imageRoot","image_root","ImageRoot"]),uuid:r||void 0,deviceType:o||void 0,osVersion:i||void 0}}).filter(t=>t.name):null}catch{return null}}function LS(n){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,r=null,o;for(;(o=t.exec(n))!==null;){let[,i,s]=o;if(i.toLowerCase()==="name")r&&e.push(r),r={name:s.trim()};else if(r){let a=i.toLowerCase();a==="isrunning"?r.isRunning=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 nm(n){let t=xS(n)??LS(n);return TS(t),t}function Fc(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function NS(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function MS(n){let e=Fc(n,["osVersion","OsVersion","OSVersion"]),t=Fc(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=Fc(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function om(n,e=()=>!0){let t=n.trim();if(!t)return[];try{let r=JSON.parse(t);if(!Array.isArray(r))return[];let o=[];for(let i of r){if(!i||typeof i!="object")continue;let s=i;if(!e(s))continue;let a=MS(s);a&&o.push(a)}return o}catch{return[]}}function im(n){return om(n)}function sm(n){return om(n,NS)}var am=/no images are available/i,OS=/Scenario simulation failed\s*[::]/i,_S="7.0.0";function jt(n){return n.normalize("NFKC").trim().toLowerCase()}function jS(n){let e=n.message||"";return am.test(e)}function FS(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function Ao(n,e){return`${n} ${e.join(" ")}`.trim()}function $S(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 kn=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 u(`Executing: ${Ao(this.emulatorPath,e)}`),ss(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return Zp(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 nm(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(Ce(r.name),r.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),r=Ce(e),o=t.find(a=>Ce(a.name)===r);if(!o)throw new w(`Emulator "${e}" not found.`,"Emulator not found.");let i=o.name;if(await this.isAlreadyRunning(i,o))return{status:"already-running"};let s=await em(i,o,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return{status:"started",args:s.args,tracker:s.tracker};if(await this.isAlreadyRunning(i))return{status:"already-running"};throw new w(`Unable to start emulator "${e}". All methods failed.
61
84
  Last error: ${s.lastError.message||"unknown"}`,`Unable to start emulator. All methods failed.
62
- Last error: ${s.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:Yu(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=Se(e),i=t.find(a=>Se(a.name)===r);if(!i)throw new w(`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 w(`Emulator "${e}" not found.`,"Emulator instance not found.");if(!await this.isAlreadyRunning(i.name,i))throw new w(`Emulator "${e}" is not running.`,"Emulator instance is not running.");if(t.type==="battery"&&!await Ku(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);p(`[EmulatorManager] control ${ib(t)} -> ${pi(this.emulatorPath,o)}`),await this.runEmulatorChecked(o,{extraReject:t.type==="folded-state"?[eb]:void 0,printOutputOnSuccess:!1})}async assertControlCommandSupported(){let e=this.emulatorPath;if(n.supportedControlPaths.has(e))return;let t=["-version"];p(`Executing: ${pi(this.emulatorPath,t)}`);let{stdout:r,stderr:i,exitCode:o}=await Mo(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(`
63
- `).trim(),a=rb(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(A.compareVersion(a,tb)<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){p(`Executing: ${pi(this.emulatorPath,e)}`);let{exitCode:t}=await Mo(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=Dt(e.deviceType),i=Dt(e.osVersion);return Qu(t).some(o=>Dt(o.deviceType)===r&&Dt(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(!nb(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 listDownloadedImageOsVersions(){let e=await this.listEmulatorImages({downloaded:!0});return ep(e)}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}
64
- `:"";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=lc(t),i=Dt(e.deviceType),o=Dt(e.osVersion);return r.filter(s=>Dt(s.deviceType)===i&&(Dt(s.osVersion)===o||Dt(s.softwareVersion)===o))}async runUninstallImageChecked(e,t){await this.runEmulatorChecked(["-uninstall","-deviceType",e,"-osVersion",t,"-force"],{printOutputOnSuccess:!0,extraReject:[tp]})}async runEmulatorChecked(e,t){p(`Executing: ${pi(this.emulatorPath,e)}`);let{stdout:r,stderr:i,exitCode:o}=await Mo(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(`
65
- `).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,t){let r=await this.listEmulators(),i=Se(e),o=r.find(s=>Se(s.name)===i);if(o)if(t)await this.deleteVirtualDevice(o.name);else throw new w(`Emulator "${e}" already exists. Use \`--force\` to overwrite.`,"Emulator already exists.");return i}async createVirtualDevice(e){let t=await this.checkExistingVirtualDevice(e.name,e.force),r=["-create",e.name,"-deviceType",e.deviceType,"-osVersion",e.osVersion];if(qu(e.osVersion)&&r.push("-hotBoot","true"),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(`
66
- `)}),!await this.waitForEmulatorPresenceByList(t))throw new w(`Emulator "${e.name}" was reported as created, but it did not appear in the emulator list within the waiting period. Open the device manager list in DevEco Studio, then run this command again.`,"Emulator was reported as created, but it did not appear in the emulator list within the waiting period.")}async waitForEmulatorPresenceByList(e,t=1e4,r=500){let i=Date.now()+t;for(;Date.now()<i;){if((await this.listEmulators()).some(a=>Se(a.name)===e))return!0;await new Promise(a=>setTimeout(a,r))}return!1}async deleteVirtualDevice(e){let t=await this.listEmulators(),r=Se(e),i=t.find(s=>Se(s.name)===r);if(!i)throw new w(`Emulator "${e}" not found.`,"Emulator not found.");let o=i.name;if(i.isRunning===!0||await this.isAlreadyRunning(o,i))throw new w(`Failed to delete device: ${o}
67
- The device may be running.`,"Failed to delete device, The device may be running.");return await this.runEmulatorChecked(["-delete",o,"-force"],{printOutputOnSuccess:!1}),o}};import{red as ub,yellow as pb,gray as fb}from"colorette";import mb from"ora";import{green as ob}from"colorette";var sb=[[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]],ab=[[0,31],[127,159],[768,879],[6832,6911],[7616,7679],[8203,8207],[8400,8447],[65024,65039],[65056,65071],[8205,8205]],cb=new RegExp("\x1B\\[([0-9;]*)[a-zA-Z]","g");function np(n,e){for(let[t,r]of e)if(n>=t&&n<=r)return!0;return!1}function dc(n){let e=n.replace(cb,""),t=0,r=0;for(;r<e.length;){let i=e.codePointAt(r);if(i===void 0)break;np(i,ab)||(np(i,sb)?t+=2:t+=1),r+=i>65535?2:1}return t}function rp(n,e){let t=dc(n);return n+" ".repeat(Math.max(0,e-t))}function lb(n,e){return n.map((t,r)=>{let i=dc(t);for(let o of e){let s=o.cells[r]??"";i=Math.max(i,dc(s))}return i})}function Rt(n,e){let t=lb(n,e),r=[];r.push(n.map((i,o)=>rp(i,t[o])).join(" ")),r.push(t.map(i=>"-".repeat(i)).join(" "));for(let i of e){let o=i.cells.map((s,a)=>rp(s??"",t[a])).join(" ").trimEnd();r.push(i.highlight?ob(o):o)}return r.join(`
68
- `)}async function sp(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=B(o),console.error(ub(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(n,o)}}function hb(n,e){if(e.size!==0)for(let t of n){if(!t.isEmulator||!t.name)continue;let r=e.get(Se(t.name));r&&(t.deviceType=r)}}var gb=["Name","Serial","Kind","Device Type"];function yb(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function ap(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function vb(){console.log(pb(" No active devices.")),console.log(fb(" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function wb(n){let t=[...n].sort(ap).map(yb);console.log(Rt(gb,t))}function bb(n){return{name:n.name??n.serial,serial:n.serial,kind:n.isEmulator?"emulator":"device",deviceType:n.deviceType}}function Sb(n){let e=[...n].sort(ap);console.log(JSON.stringify(e.map(bb),null,2))}async function Eb(n,e){if(!n.some(i=>i.isEmulator)||!e.emulatorPath)return;let r=await pr.from(e).getDeviceTypeByName();hb(n,r)}async function ip(n,e,t,r="table"){try{let i=await n.getConnectedEntries();if(await Eb(i,e),t?.stop(),r==="json"){Sb(i);return}i.length===0?vb():wb(i)}catch(i){throw new w(`Failed to list devices: ${i.message}`,"Failed to list devices.")}finally{t?.stop()}}async function Pb(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 w(r.join(`
69
- `),"Multiple devices connected.")}async function Cb(n,e,t="table"){e||await Pb(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 w("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:yt(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 cp(){try{let n=await A.new();return{manager:oe.from(n),toolProvider:n}}catch(n){throw new w(`Failed to initialize device manager: ${n.message}`,"Failed to initialize device manager.")}}var uc=new db("device").description("Manage connected devices");uc.command("list").description("List all connected devices").addOption(new op("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:b.CommandExecuted,args:["device","list",...n.format==="json"?["--format","json"]:[]]};await sp(e,async()=>{let{manager:t,toolProvider:r}=await cp();if(n.format==="json"){await ip(t,r,void 0,"json");return}let i=mb({text:"Querying connected devices\u2026",color:"cyan"}).start();await ip(t,r,i,"table")})});uc.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").addOption(new op("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:b.CommandExecuted,args:["device","view",...n.target?["--target"]:[],...n.format==="json"?["--format","json"]:[]]};await sp(e,async()=>{let{manager:t}=await cp();await Cb(t,n.target,n.format)})});var lp=uc;import{Argument as wc,Command as bc,Option as hr}from"commander";import{green as hi,cyan as mr,red as Fo,yellow as wt,gray as vc}from"colorette";import Hb from"ora";import kb from"readline/promises";import{execa as up}from"execa";import*as en from"fs/promises";import*as fc from"os";import*as _n from"path";var pc=`1/4:\r
85
+ Last error: ${s.lastError.message||"unknown"}`)}async isAlreadyRunning(e,t){return t?.isRunning===!0||t===void 0&&(await this.listEmulators()).find(o=>o.name===e)?.isRunning===!0?!0:tm(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=Ce(e),o=t.find(a=>Ce(a.name)===r);if(!o)throw new w(`Emulator "${e}" not found.`,"Emulator not found.");let i=o.name;return await this.isAlreadyRunning(i,o)?(await this.executeEmulator(["-stop",i]),"stopped"):"already-stopped"}async controlEmulator(e,t){await this.assertControlCommandSupported();let o=(await this.listEmulators()).find(s=>s.name===e);if(!o)throw new w(`Emulator "${e}" not found.`,"Emulator instance not found.");if(!await this.isAlreadyRunning(o.name,o))throw new w(`Emulator "${e}" is not running.`,"Emulator instance is not running.");if(t.type==="battery"&&!(t.assumedCharging?!0:await rm(this.hdcPath,o.name))&&t.level===0)throw new Error("Battery level must be an integer in [1, 100] while the emulator is not charging.");let i=this.buildControlArgs(o.name,t);u(`[EmulatorManager] control ${$S(t)} -> ${Ao(this.emulatorPath,i)}`),await this.runEmulatorChecked(i,{extraReject:t.type==="folded-state"?[OS]:void 0,printOutputOnSuccess:!1})}async assertControlCommandSupported(){let e=this.emulatorPath;if(n.supportedControlPaths.has(e))return;let t=["-version"];u(`Executing: ${Ao(this.emulatorPath,t)}`);let{stdout:r,stderr:o,exitCode:i}=await ss(this.emulatorPath,t,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:1024*1024}),s=[r,o].filter(Boolean).join(`
86
+ `).trim(),a=FS(s);if(i!==0||!a)throw new Error("Emulator scene control commands require Emulator 7.0 or later. Unable to determine the current Emulator version.");if(A.compareVersion(a,_S)<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){u(`Executing: ${Ao(this.emulatorPath,e)}`);let{exitCode:t}=await ss(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=jt(e.deviceType),o=jt(e.osVersion);return im(t).some(i=>jt(i.deviceType)===r&&jt(i.osVersion)===o)}async uninstallEmulatorImage(e){let t=await this.resolveSoftwareVersionsForUninstall(e);if(t.length===0)throw new Error(`No downloaded image matches --os-version "${e.osVersion}" for --device-type "${e.deviceType}".`);let r;try{await this.runUninstallImageChecked(e.deviceType,e.osVersion)}catch(i){if(!jS(i))throw i;r=i}(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 o of t)await this.runUninstallImageChecked(e.deviceType,o)}catch(o){let i=r!==void 0?`Primary uninstall failed: ${r.message}
87
+ `:"";throw new Error(`${i}Fallback uninstall failed: ${o.message}`,{cause:o})}if(await this.hasMatchingDownloadedImage(e))throw new Error(`Image for --device-type "${e.deviceType}" and --os-version "${e.osVersion}" remains listed as downloaded after uninstallation.`)}async resolveSoftwareVersionsForUninstall(e){let t=await this.findMatchingDownloadedImages(e);return[...new Set(t.map(r=>r.softwareVersion).filter(Boolean))]}async findMatchingDownloadedImages(e){let t=await this.listEmulatorImages({deviceType:e.deviceType,downloaded:!0}),r=sm(t),o=jt(e.deviceType),i=jt(e.osVersion);return r.filter(s=>jt(s.deviceType)===o&&(jt(s.osVersion)===i||jt(s.softwareVersion)===i))}async runUninstallImageChecked(e,t){await this.runEmulatorChecked(["-uninstall","-deviceType",e,"-osVersion",t,"-force"],{printOutputOnSuccess:!0,extraReject:[am]})}async runEmulatorChecked(e,t){u(`Executing: ${Ao(this.emulatorPath,e)}`);let{stdout:r,stderr:o,exitCode:i}=await ss(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:20*1024*1024}),s=[r,o].filter(Boolean).join(`
88
+ `).trim(),a=/Invalid command|无效命令|鏃犳晥鍛戒护/i.test(s)||/please attach the correct parameter/i.test(s),c=(t?.extraReject??[]).some(d=>d.test(s));if(i!==0||a||c)throw new Error(s||`emulator exited with code ${i===null?"null":i}`);if(t?.printOutputOnSuccess!==!1&&s){let d=(t?.transformOutput?t.transformOutput(s):s).trim();d&&console.log(d)}}async checkExistingVirtualDevice(e){let t=await this.listEmulators(e.instancePath),r=Ce(e.name),o=t.find(i=>Ce(i.name)===r);if(o)if(e.force)await this.deleteVirtualDevice(o.name,e.instancePath);else throw new w(`Emulator "${e.name}" already exists. Use \`--force\` to overwrite.`,"Emulator already exists.");return 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??(Xp(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:i=>i.split(/\r?\n/).map(s=>s.trim().startsWith("Device create success.")?"Device create success.":s).join(`
89
+ `)}),!await this.waitForEmulatorPresenceByList(t,e.instancePath))throw new w(`Emulator "${e.name}" was reported as created, but it did not appear in the emulator list within the waiting period. Open the device manager list in DevEco Studio, then run this command again.`,"Emulator was reported as created, but it did not appear in the emulator list within the waiting period.")}async waitForEmulatorPresenceByList(e,t,r=1e4,o=500){let i=Date.now()+r;for(;Date.now()<i;){if((await this.listEmulators(t)).some(c=>Ce(c.name)===e))return!0;await new Promise(c=>setTimeout(c,o))}return!1}async deleteVirtualDevice(e,t){let r=await this.listEmulators(t),o=Ce(e),i=r.find(c=>Ce(c.name)===o);if(!i)throw new w(`Emulator "${e}" not found.`,"Emulator not found.");let s=i.name;if(i.isRunning===!0||await this.isAlreadyRunning(s,i))throw new w(`Failed to delete device: ${s}
90
+ The device may be running.`,"Failed to delete device, The device may be running.");let a=["-delete",s];return t!==void 0&&a.push("-instancePath",t),a.push("-force"),await this.runEmulatorChecked(a,{printOutputOnSuccess:!1}),s}};import{red as GS,yellow as zS,gray as JS}from"colorette";import pm from"ora";import{green as HS}from"colorette";var US=[[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]],BS=[[0,31],[127,159],[768,879],[6832,6911],[7616,7679],[8203,8207],[8400,8447],[65024,65039],[65056,65071],[8205,8205]],WS=new RegExp("\x1B\\[([0-9;]*)[a-zA-Z]","g");function cm(n,e){for(let[t,r]of e)if(n>=t&&n<=r)return!0;return!1}function $c(n){let e=n.replace(WS,""),t=0,r=0;for(;r<e.length;){let o=e.codePointAt(r);if(o===void 0)break;cm(o,BS)||(cm(o,US)?t+=2:t+=1),r+=o>65535?2:1}return t}function lm(n,e){let t=$c(n);return n+" ".repeat(Math.max(0,e-t))}function VS(n,e){return n.map((t,r)=>{let o=$c(t);for(let i of e){let s=i.cells[r]??"";o=Math.max(o,$c(s))}return o})}function Ft(n,e){let t=VS(n,e),r=[];r.push(n.map((o,i)=>lm(o,t[i])).join(" ")),r.push(t.map(o=>"-".repeat(o)).join(" "));for(let o of e){let i=o.cells.map((s,a)=>lm(s??"",t[a])).join(" ").trimEnd();r.push(o.highlight?HS(i):i)}return r.join(`
91
+ `)}async function Do(n,e){let t=Date.now(),r=!0,o=null;try{await e()}catch(i){r=!1,o=G(i),console.error(GS(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await I.track(n,i)}}function YS(n,e){if(e.size!==0)for(let t of n){if(!t.isEmulator||!t.name)continue;let r=e.get(Ce(t.name));r&&(t.deviceType=r)}}var KS=["Name","Serial","Kind","Device Type"];function XS(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function mm(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function ZS(){console.log(zS(" No active devices.")),console.log(JS(" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function QS(n){let t=[...n].sort(mm).map(XS);console.log(Ft(KS,t))}function eE(n){return{name:n.name??n.serial,serial:n.serial,kind:n.isEmulator?"emulator":"device",deviceType:n.deviceType}}function tE(n){let e=[...n].sort(mm);console.log(JSON.stringify(e.map(eE),null,2))}async function rE(n,e){if(!n.some(o=>o.isEmulator)||!e.emulatorPath)return;let r=await kn.from(e).getDeviceTypeByName();YS(n,r)}async function dm(n,e,t,r="table"){try{let o=await n.getConnectedEntries();if(await rE(o,e),t?.stop(),r==="json"){tE(o);return}o.length===0?ZS():QS(o)}catch(o){throw new w(`Failed to list devices: ${o.message}`,"Failed to list devices.")}finally{t?.stop()}}async function nE(n,e){let t=await n.listDevices();if(t.length<2)return;let r=["Multiple devices connected. Specify a device with:"];for(let o of t){let i=await n.getDeviceName(o.serial);r.push(` ${e} -t ${o.serial} # ${i}`)}throw new w(r.join(`
92
+ `),"Multiple devices connected.")}async function oE(n,e,t="table"){e||await nE(n,"devecocli device view");let r=await n.listDevices(),o=await n.getDeviceInfo(r,e);if(!o){if(t==="json"){console.error("No connected device found."),process.exitCode=1;return}throw new w("No connected device found.")}let i=await n.getDeviceDetail(o.serial),s=await n.getDeviceName(o.serial);if(t==="json"){let a={name:s,serial:o.serial,kind:It(o.serial)?"emulator":"device",deviceType:i.deviceType,osVersion:i.osVersion};console.log(JSON.stringify(a,null,2));return}console.log(` Serial: ${o.serial}`),console.log(` Device Name: ${s}`),i.deviceType&&console.log(` Device Type: ${i.deviceType}`),i.osVersion&&console.log(` OS Version: ${i.osVersion}`)}async function fm(n,e,t,r,o){let i=await ht(n,o),s=new Ye(n),a=e==="send",c=pm({text:a?`Sending ${t} to ${r} on ${i}...`:`Receiving ${t} from ${i} to ${r}...`,color:"cyan"}).start();try{await s.transferFile(i,e,t,r),c.stop(),console.log(`${a?"Sent to device":"Received from device"} (${i}): ${t} -> ${r}`)}catch(l){c.stop();let d=a?"Send":"Recv";throw new w(`File ${d} failed: ${l.message}`,`File ${d} failed.`)}}async function iE(n,e,t,r){let o=await ht(n,r),i=new Ye(n);try{await i.runSqlite3(o,e,t)}catch(s){throw new w(`sqlite3 failed: ${s.message}`,"sqlite3 failed.")}}async function Ro(){try{let n=await A.new();return{manager:de.from(n),toolProvider:n}}catch(n){throw new w(`Failed to initialize device manager: ${n.message}`,"Failed to initialize device manager.")}}var To=new qS("device").description("Manage connected devices");To.command("list").description("List all connected devices").addOption(new um("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:b.CommandExecuted,args:["device","list",...n.format==="json"?["--format","json"]:[]]};await Do(e,async()=>{let{manager:t,toolProvider:r}=await Ro();if(n.format==="json"){await dm(t,r,void 0,"json");return}let o=pm({text:"Querying connected devices\u2026",color:"cyan"}).start();await dm(t,r,o,"table")})});To.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").addOption(new um("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:b.CommandExecuted,args:["device","view",...n.target?["--target"]:[],...n.format==="json"?["--format","json"]:[]]};await Do(e,async()=>{let{manager:t}=await Ro();await oE(t,n.target,n.format)})});var hm=To.command("file").description("Transfer files between the host and a connected device");hm.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,o={event:b.CommandExecuted,args:["device","file","send",...r?["--device"]:[]]};await Do(o,async()=>{let{toolProvider:i}=await Ro();await fm(i,"send",n,e,r)})});hm.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,o={event:b.CommandExecuted,args:["device","file","recv",...r?["--device"]:[]]};await Do(o,async()=>{let{toolProvider:i}=await Ro();await fm(i,"recv",n,e,r)})});To.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:b.CommandExecuted,args:["device","sqlite3",n,...t.device?["--device"]:[]]};await Do(r,async()=>{let{toolProvider:o}=await Ro();await iE(o,n,e,t.device)})});var gm=To;import{Argument as zc,Command as Jc,InvalidArgumentError as SE,Option as ct}from"commander";import{green as No,cyan as An,red as Yc,yellow as lr,gray as Gc}from"colorette";import EE from"ora";import sE from"readline/promises";import{execa as vm}from"execa";import*as cr from"fs/promises";import*as Uc from"os";import*as qr from"path";var Hc=`1/4:\r
70
93
  ---------------------------------------\r
71
94
  Statement About HarmonyOS and Privacy\r
72
95
  \r
@@ -1236,13 +1259,13 @@ Part I: Chinese mainland.\r
1236
1259
  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
1237
1260
  \r
1238
1261
  Part III: Other countries and regions.\r
1239
- ---------------------------------------\r`;var Ib=new Set,_o=new Map,mc="HarmonyOS_Software_Service_Agreement",pp=["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(`
1240
- `),fp=pp,hc="HarmonyOS_SDK_Agreement";function mp(n,e){return`${n}\0${e}`}function hp(){Ib.clear(),_o.clear()}var Ab=pp,Tt=class extends Error{constructor(e=Ab){super(e),this.name="EmulatorLicenseBlockedError"}};function gp(n,e){return[n??"",e??""].join(`
1241
- `)}function yp(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 Db(n){return`Emulator${n.trim()}`}function vp(n){let e=Db(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 _n.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return _n.join(fc.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||_n.join(fc.homedir(),".cache");return _n.join(t,"Huawei",e,".emu_config")}async function Rb(n,e,t){let r=mp(n,e),i=_o.get(r);if(i!==void 0)return i;let o=await up(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=gp(o.stdout,o.stderr).trim();if(o.exitCode!==0||!s)throw new Tt(t);return _o.set(r,s),s}function Tb(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function xb(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 Lb(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=Tb(e.slice(r+1).trim());return{key:i,entry:{value:o,delimiter:t}}}}function Nb(n){let e={};for(let t of n.split(/\r?\n/)){let r=Lb(t);r&&(e[r.key]=r.entry)}return e}function Ob(n){let e=n.trim();if(!e)return{};let t=xb(e);return t||Nb(n)}function Mb(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function wp(n,e,t,r){let i=await Rb(n,e,r),o=yp(i);if(!o)throw new Tt(r);let s=vp(o),a;try{a=await en.readFile(s,"utf8")}catch(d){throw d.code==="ENOENT"?new Tt(r):d}let l=Ob(a)[t];if(!l)throw new Tt(r);if(l.delimiter==="=")throw new Tt(r);if(!Mb(l.value))throw new Tt(r)}async function gc(n,e){await wp(n,e,mc,fp)}async function yc(n,e){await wp(n,e,hc,fp)}async function _b(n,e){let t=await up(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),r=gp(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=mp(n,e);return _o.set(i,r),r}async function bp(n,e){let t=await _b(n,e),r=yp(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
1242
- ${t}.`);return vp(r)}function dp(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function jb(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[mc]="agree",r[hc]="agree",await en.writeFile(n,`${JSON.stringify(r,null,2)}
1243
- `,"utf8"),!0}catch{}return!1}async function Fb(n,e){let t=mc,r=hc,i=[{k:t,re:new RegExp(`^\\s*${dp(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${dp(r)}\\s*[:=]`)}],o=e.length===0?[]:e.split(/\r?\n/),s=[],a=new Set;for(let c of o){let l=!1;for(let{k:d,re:g}of i)if(g.test(c)){s.push(`${d}:agree`),a.add(d),l=!0;break}l||s.push(c)}a.has(t)||s.push(`${t}:agree`),a.has(r)||s.push(`${r}:agree`),await en.writeFile(n,s.join(`
1262
+ ---------------------------------------\r`;var aE=new Set,as=new Map,Bc="HarmonyOS_Software_Service_Agreement",wm=["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(`
1263
+ `),bm=wm,Wc="HarmonyOS_SDK_Agreement";function Sm(n,e){return`${n}\0${e}`}function Em(){aE.clear(),as.clear()}var cE=wm,$t=class extends Error{constructor(e=cE){super(e),this.name="EmulatorLicenseBlockedError"}};function Pm(n,e){return[n??"",e??""].join(`
1264
+ `)}function Cm(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 lE(n){return`Emulator${n.trim()}`}function km(n){let e=lE(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 qr.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return qr.join(Uc.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||qr.join(Uc.homedir(),".cache");return qr.join(t,"Huawei",e,".emu_config")}async function dE(n,e,t){let r=Sm(n,e),o=as.get(r);if(o!==void 0)return o;let i=await vm(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=Pm(i.stdout,i.stderr).trim();if(i.exitCode!==0||!s)throw new $t(t);return as.set(r,s),s}function uE(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function pE(n){try{let e=JSON.parse(n);if(e&&typeof e=="object"&&!Array.isArray(e)){let t={};for(let[r,o]of Object.entries(e))t[r]={value:typeof o=="string"?o:String(o),delimiter:"json"};return t}}catch{return}}function mE(n){let e=n.trim();if(!(!e||e.startsWith("#")))for(let t of["=",":"]){let r=e.indexOf(t);if(r<=0)continue;let o=e.slice(0,r).trim();if(!o||t===":"&&o.includes("//"))continue;let i=uE(e.slice(r+1).trim());return{key:o,entry:{value:i,delimiter:t}}}}function fE(n){let e={};for(let t of n.split(/\r?\n/)){let r=mE(t);r&&(e[r.key]=r.entry)}return e}function hE(n){let e=n.trim();if(!e)return{};let t=pE(e);return t||fE(n)}function gE(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function Im(n,e,t,r){let o=await dE(n,e,r),i=Cm(o);if(!i)throw new $t(r);let s=km(i),a;try{a=await cr.readFile(s,"utf8")}catch(d){throw d.code==="ENOENT"?new $t(r):d}let l=hE(a)[t];if(!l)throw new $t(r);if(l.delimiter==="=")throw new $t(r);if(!gE(l.value))throw new $t(r)}async function Vc(n,e){await Im(n,e,Bc,bm)}async function qc(n,e){await Im(n,e,Wc,bm)}async function yE(n,e){let t=await vm(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),r=Pm(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 o=Sm(n,e);return as.set(o,r),r}async function Am(n,e){let t=await yE(n,e),r=Cm(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
1265
+ ${t}.`);return km(r)}function ym(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function vE(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[Bc]="agree",r[Wc]="agree",await cr.writeFile(n,`${JSON.stringify(r,null,2)}
1266
+ `,"utf8"),!0}catch{}return!1}async function wE(n,e){let t=Bc,r=Wc,o=[{k:t,re:new RegExp(`^\\s*${ym(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${ym(r)}\\s*[:=]`)}],i=e.length===0?[]:e.split(/\r?\n/),s=[],a=new Set;for(let c of i){let l=!1;for(let{k:d,re:g}of o)if(g.test(c)){s.push(`${d}:agree`),a.add(d),l=!0;break}l||s.push(c)}a.has(t)||s.push(`${t}:agree`),a.has(r)||s.push(`${r}:agree`),await cr.writeFile(n,s.join(`
1244
1267
  `)+(s.length>0?`
1245
- `:""),"utf8")}async function Sp(n){await en.mkdir(_n.dirname(n),{recursive:!0});let e="";try{e=await en.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await jb(n,e,t)||await Fb(n,e)}async function Ep(n,e){return console.log(pc),0}var $b="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function Pp(n,e){try{return await gc(n,e),await yc(n,e),!0}catch(t){if(t instanceof Tt)return!1;throw t}}async function Cp(n,e){if(await Pp(n,e))return console.log("Emulator license agreements are already accepted."),0;if(console.log(pc),!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=kb.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await r.question($b)}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 bp(n,e);await Sp(s),hp()}catch(s){return console.error(s.message),1}return console.log("Emulator license agreements accepted."),0}async function kp(n,e){if(await Pp(n,e))return console.log("Emulator license agreements are already accepted."),0;try{let t=await bp(n,e);await Sp(t),hp()}catch(t){return console.error(t.message),1}return console.log("Emulator license agreements accepted."),0}async function nt(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=B(o),console.error(Fo(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(n,o)}}var Ub=["ohos.qemu.hvd.name","const.product.name","const.product.model"],Ip=["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"],Wb=`
1268
+ `:""),"utf8")}async function Dm(n){await cr.mkdir(qr.dirname(n),{recursive:!0});let e="";try{e=await cr.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await vE(n,e,t)||await wE(n,e)}async function Rm(n,e){return console.log(Hc),0}var bE="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function Tm(n,e){try{return await Vc(n,e),await qc(n,e),!0}catch(t){if(t instanceof $t)return!1;throw t}}async function xm(n,e){if(await Tm(n,e))return console.log("Emulator license agreements are already accepted."),0;if(console.log(Hc),!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=sE.createInterface({input:process.stdin,output:process.stdout}),o;try{o=await r.question(bE)}finally{r.close()}let i=o.trim().toLowerCase();if(i!=="y"&&i!=="yes")return console.error("Agreements not accepted. Emulator features will remain blocked until accepted."),1;try{let s=await Am(n,e);await Dm(s),Em()}catch(s){return console.error(s.message),1}return console.log("Emulator license agreements accepted."),0}async function Lm(n,e){if(await Tm(n,e))return console.log("Emulator license agreements are already accepted."),0;try{let t=await Am(n,e);await Dm(t),Em()}catch(t){return console.error(t.message),1}return console.log("Emulator license agreements accepted."),0}async function lt(n,e){let t=Date.now(),r=!0,o=null;try{await e()}catch(i){r=!1,o=G(i),console.error(Yc(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await I.track(n,i)}}var PE=["ohos.qemu.hvd.name","const.product.name","const.product.model"],Nm=["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"],CE=`
1246
1269
  Folded state scene mappings:
1247
1270
  foldableFold (3):
1248
1271
  open Fully expanded state
@@ -1265,83 +1288,81 @@ Folded state scene mappings:
1265
1288
  left-half-folded-right-folded
1266
1289
  left-expanded-right-half-folded
1267
1290
  left-half-folded-right-half-folded
1268
- `,Bb="6.1.0";function Vb(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function qb(n){let e=n.trim();if(!Ip.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${Ip.join(", ")}`);return e}function Dp(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 Rp(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&&!Gb(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 Gb(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function zb(n,e,t,r,i){return Number(Rp(n,e,t,r,i))}function Jb(n){let e=n.trim();if(!e||!/^[A-Za-z0-9_ ]+$/.test(e))throw new Error("The virtual device name can only contain letters, spaces, numbers, and underscores (_).")}function Yb(n){let e=n.trim();if(!e)throw new Error("--os-version must not be empty.");if(/^\d+$/.test(e))throw new Error(`--os-version "${n}" is invalid. use the full image label, e.g. HarmonyOS 5.1.1(19).`);if(!/^HarmonyOS\s+/i.test(e))throw/^HarmonyOS$/i.test(e)?new Error('--os-version is incomplete (only "HarmonyOS"). On PowerShell/cmd, quote the full label, e.g. --os-version "HarmonyOS 6.0.1(21)".'):new Error(`Invalid --os-version "${n}". It must start with "HarmonyOS " (e.g. "HarmonyOS 5.1.1(19)").`)}function Kb(n,e){let t=i=>i.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(wt("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(wt("Run `devecocli emulator image download ...` followed by `devecocli emulator image list` and then copy an `osVersion` string exactly.")),new Error("No downloaded osVersion values parsed; cannot validate --os-version.");if(!e.some(i=>t(i)===r)){console.error(Fo("--os-version does not match any downloaded image (exact string required).")),console.log(wt("Use one of these --os-version values:"));for(let i of e)console.log(` ${i}`);throw new Error(`No downloaded image matches --os-version "${n}".`)}}var Xb=["Name","Status","Serial","Device Type","OS Version"];function Zb(n){return{cells:[n.name,n.status,n.serial??"-",n.deviceType??"-",n.osVersion??"-"],highlight:n.status==="running"}}async function Qb(n,e){let t=await Promise.all(e.map(async r=>{let i=await rr(n,r,Ub);return[r,i]}));return new Map(t)}async function eS(n){let e=await sc(n),t=await Qb(n,e);return{serials:e,params:t}}function tS(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 nS(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&&tS(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 rS(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 iS(n,e,t,r){try{let[i,o]=await Promise.all([n.listEmulators(),eS(e)]);if(i.length===0){r?.stop(),console.log(t==="json"?"[]":wt(" No emulator instances found."));return}let s=i.filter(g=>g.isRunning).map(g=>g.name),{productSerialMap:a,hvdSerialMap:c}=nS(o.serials,o.params,s);r?.stop();let l=rS(i,a,c);if(t==="json"){console.log(JSON.stringify(l,null,2));return}let d=l.map(Zb);console.log(Rt(Xb,d))}catch(i){throw r?.stop(),new Error(`Failed to list emulators: ${i.message}`,{cause:i})}}function Tp(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(Fo(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(vc(s.stdout)),s.stderr&&console.error(vc(s.stderr))}return r}var oS=2e3,sS=6e4;async function aS(n,e){let t=Se(e);return(await ac(n)).some(i=>Se(i)===t)}async function xp(n,e,t,r=sS,i=oS){let o=Date.now()+r;for(;Date.now()<o;){if(await aS(n,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}async function cS(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(wt(`Emulator "${t}" is already running.`));return}console.log(mr(`Starting emulator "${t}"...`));let i=await xp(e,t,!0);console.log(i?hi(`Emulator "${t}" started successfully.`):wt(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function lS(n,e,t){let r=await Promise.allSettled(t.map(i=>cS(n,e,i)));if(Tp(r,t,"start"))throw new w("One or more emulators failed to start.")}async function Lp(n,e){let t=e.trim();if(!yt(t))return t;let r=await oe.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 dS(n,e,t){let r=await Lp(e,t);if(console.log(mr(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(wt(`Emulator "${r}" is already stopped.`));return}let o=await xp(e,r,!1);console.log(o?hi(`Emulator "${r}" stopped successfully.`):wt(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function uS(n,e,t){let r=await Promise.allSettled(t.map(i=>dS(n,e,i)));Tp(r,t,"stop")}async function rt(){let n=await A.new();return{manager:pr.from(n),toolProvider:n}}async function xt(n,e,t){let r={event:b.CommandExecuted,args:["emulator",t,"--target"]};await nt(r,async()=>{let i=Vb(n.target),o=e(),{manager:s,toolProvider:a}=await rt(),c=await Lp(a.hdcPath,i);await s.controlEmulator(c,o),console.log(hi(`Emulator "${i}" operation completed.`))})}function pS(n){let e=[];return jo(e,"longitude",n.longitude,-180,180,8),jo(e,"latitude",n.latitude,-90,90,8),jo(e,"altitude",n.altitude,-1e4,1e4,2),jo(e,"bearing",n.direction,0,359.99,2,"--direction"),Sc(e,"Specify one geolocation option.")}function fS(n){let e=[];return fi(e,"light",n.lightIntensity,0,1e5,!1,"--light-intensity"),fi(e,"humidity",n.humidity,0,100,!1),fi(e,"temperature",n.temperature,-273.1,100,!1),fi(e,"steps",n.steps,0,1e4,!0),fi(e,"heartrate",n.heartrate,0,255,!0),Sc(e,"Specify one sensor option.")}function Sc(n,e){if(n.length===0)throw new Error(e);if(n.length>1)throw new Error("Only one operation option can be specified.");return n[0]}function jo(n,e,t,r,i,o,s=`--${e}`){t!==void 0&&n.push({type:"gps",key:e,value:Rp(s,t,r,i,o)})}function fi(n,e,t,r,i,o,s=`--${e}`){if(t===void 0)return;let a=o?Dp(s,t,r,i):zb(s,t,r,i,1);n.push({type:"sensor",key:e,value:a})}function mS(n){let e=[];return n.level!==void 0&&e.push({type:"battery",level:Dp("--level",n.level,0,100)}),n.status!==void 0&&e.push({type:"battery-status",status:n.status==="charging"?1:0}),Sc(e,"Specify --level or --status.")}var le=new bc("emulator").description("Manage emulator instances");le.hook("preAction",async()=>{(await A.new()).require({studio:Bb})});var hS=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function $o(n){let e=new hr("--device-type <type>","Emulator device type").choices([...hS]);return n?e.makeOptionMandatory():e}function fr(n,e){for(let t of e)if(t in n)return n[t]}function mi(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function Ap(n){let e=mi(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var gS=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],yS="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";async function vS(n,e,t){if(!await n.hasAvailableEmulatorImage({deviceType:e,osVersion:t}))throw new Error(`Invalid --os-version value "${t}".
1269
- Run \`devecocli emulator image list --all\` and use an exact OS Version value.`)}function Np(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function Op(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let i=r,o=mi(fr(i,["osVersion","OsVersion","OSVersion","os_version"])),s=mi(fr(i,["deviceType","DeviceType","device_type"])),a=Ap(fr(i,["downloaded","Downloaded","isDownloaded"])),c=mi(fr(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=mi(fr(i,["releaseType","ReleaseType","release_type"])),d=Ap(fr(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,l,d,a],highlight:e&&a==="true"})}return t}function wS(n){let e=n.trim();if(!e)return!0;let t=Np(e);return t===null?!1:t.length===0?!0:Op(t,!0).length===0}function bS(n,e){let t=n.trim();if(!t)return"";let r=Np(t);if(!r)return n.trimEnd();let i=Op(r,e);return Rt(gS,i)}var Ho=new bc("image").description("HarmonyOS emulator system images (download, list, remove)");Ho.command("download").description("Download system image").addOption($o(!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:b.CommandExecuted,args:["emulator","image","download",...n.deviceType?["--device-type"]:[],...n.osVersion?["--os-version"]:[],...n.force?["--force"]:[]]};await nt(e,async()=>{let{manager:t,toolProvider:r}=await rt();await yc(r.emulatorPath,r.sdkPath);let i=n.deviceType?.trim(),o=n.osVersion?.trim();if(!i)throw new w("Error: missing required option '--device-type <type>'","Missing required device type.");if(!o)throw new w("Error: misssing required option '--os-version <version>'","Missing required OS version.");await vS(t,i,o),await t.installEmulatorImage({deviceType:i,osVersion:o,force:n.force===!0})})});Ho.command("remove").description("Remove a downloaded system image").addOption($o(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let e={event:b.CommandExecuted,args:["emulator","image","remove","--device-type","--os-version"]};await nt(e,async()=>{let{manager:t}=await rt();await t.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})})});Ho.command("list").description("List system images").addOption($o(!1)).option("--all","List all images (local and remote)").addOption(new hr("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:b.CommandExecuted,args:["emulator","image","list",...n.deviceType?["--device-type"]:[],...n.all?["--all"]:[],...n.format!=="table"?["--format"]:[]]};await nt(e,async()=>{let{manager:t}=await rt(),r;n.all?r=void 0:r=!0;let i=await t.listEmulatorImages({deviceType:n.deviceType,downloaded:r});if(wS(i)){console.log(wt(yS));return}if(n.format==="json"){console.log(i.trimEnd());return}let o=bS(i,n.all===!0);console.log(o)})});le.addCommand(Ho);var Uo=new bc("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");Uo.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let n={event:b.CommandExecuted,args:["emulator","license","view"]};await nt(n,async()=>{let{toolProvider:e}=await rt(),t=await Ep(e.emulatorPath,e.sdkPath);process.exitCode=t})});Uo.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let n={event:b.CommandExecuted,args:["emulator","license","accept"]};await nt(n,async()=>{let{toolProvider:e}=await rt(),t=await kp(e.emulatorPath,e.sdkPath);process.exitCode=t})});Uo.action(async()=>{let n={event:b.CommandExecuted,args:["emulator","license"]};await nt(n,async()=>{let{toolProvider:e}=await rt(),t=await Cp(e.emulatorPath,e.sdkPath);process.exitCode=t})});le.addCommand(Uo);le.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>xt(n,()=>({type:"shake"}),"shake"));le.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>xt(n,()=>({type:"power"}),"power"));le.command("rotate").description("Rotate emulator").addOption(new hr("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new wc("<direction>").choices(["left","right"])).action((n,e)=>xt(e,()=>({type:"rotation",direction:n}),"rotate"));le.command("volume").description("Change volume").addOption(new hr("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new wc("<direction>").choices(["up","down"])).action((n,e)=>xt(e,()=>({type:"volume",direction:n}),"volume"));le.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",Wb).action((n,e)=>xt(e,()=>({type:"folded-state",state:qb(n)}),"fold"));le.command("battery").description("Set battery level 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 hr("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>xt(n,()=>mS(n),"battery"));le.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=>xt(n,()=>pS(n),"geolocation"));le.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new wc("<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 xt(e,()=>t[n],"scene")});le.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=>xt(n,()=>fS(n),"sensor"));le.command("list").description("List all emulator instances").addOption(new hr("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:b.CommandExecuted,args:["emulator","list"]};await nt(e,async()=>{let{manager:t,toolProvider:r}=await rt(),i=n.format==="table"?Hb({text:"Listing emulators\u2026",color:"cyan"}).start():void 0;await iS(t,r.hdcPath,n.format,i)})});le.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let e={event:b.CommandExecuted,args:["emulator","start"]};await nt(e,async()=>{let{manager:t,toolProvider:r}=await rt();if(await gc(r.emulatorPath,r.sdkPath),!n?.length)throw new w("Error: missing required argument 'names'","Missing required emulator name.");await lS(t,r.hdcPath,n)})});le.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:b.CommandExecuted,args:["emulator","stop"]};await nt(e,async()=>{let{manager:t,toolProvider:r}=await rt();if(!n?.length){console.error(Fo("Error: missing required argument 'names'")),process.exitCode=1;return}await uS(t,r.hdcPath,n)})});var Mp=le.command("create <name>").description("Create a local emulator instance.").addOption($o(!0)).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`').option("--force","Overwrite if supported");Mp.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
1270
- ${wt("Tip: ")}${vc("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
1271
- ${mr('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
1272
- ${mr('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
1273
- `)}});Mp.action(async(n,e)=>{let t={event:b.CommandExecuted,args:["emulator","create","--device-type","--os-version",...e.force?["--force"]:[]]};await nt(t,async()=>{Jb(n),Yb(e.osVersion);let{manager:r}=await rt(),i=await r.listDownloadedImageOsVersions();Kb(e.osVersion,i),console.log(mr(`Creating emulator "${n}"...`)),await r.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(hi(`Emulator "${n}" created successfully.`))})});le.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let e={event:b.CommandExecuted,args:["emulator","delete"]};await nt(e,async()=>{let{manager:t}=await rt();console.log(mr(`Deleting emulator "${n}"...`));let r=await t.deleteVirtualDevice(n);console.log(hi(`Emulator "${r}" deleted successfully.`))})});var _p=le;import{Command as HS}from"commander";import{red as Ac,cyan as bt}from"colorette";import*as of from"readline";import*as nf from"crypto";import*as jp from"http";import*as Fp from"crypto";import{URL as SS}from"url";var Wo=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=jp.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 SS(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&&Fp.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 Ne from"fs";import*as tn from"path";import{homedir as DS}from"os";var Lt={};Rg(Lt,{LocalCrypto:()=>Lt,decryptForLocalStorage:()=>kS,decryptForLocalStorageFromDirectory:()=>IS,encryptForLocalStorage:()=>CS,isEncryptedBlob:()=>AS});import*as Q from"fs";import*as Ae from"path";import*as Le from"crypto";import*as Hp from"os";import{homedir as Up}from"os";var Ie=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var gi=kn.ALGORITHM,Wp=kn.IV_LENGTH,yi=kn.KEY_LENGTH,vi=kn.KEY_LENGTH,jn=kn.KEK_VERSIONS,Bo=process.env.DEVECO_CLI_DATA_DIR||Ae.join(Up(),ve.CONFIG_DIR_NAME,ve.APP_NAME),Vo=Ae.join(Up(),".local","share",ve.APP_NAME,"keys"),gr=Ae.join(Bo,ve.KEY_FILE_NAME);function $p(n){return Hp.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 Ec(n){return Ae.join(Vo,`${n}.bin`)}function Bp(){if(!Q.existsSync(Bo))try{Q.mkdirSync(Bo,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new Ie($p(Bo)):n}if(!Q.existsSync(Vo))try{Q.mkdirSync(Vo,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new Ie($p(Ae.dirname(Vo))):n}}function Vp(){Bp();for(let n of jn){let e=Ec(n);Q.existsSync(e)||Q.writeFileSync(e,Le.randomBytes(yi),{mode:384})}}function qp(n){if(!jn.includes(n))throw new Error(`Invalid kekId: ${n}`);Vp();let e=Ec(n),t=Q.readFileSync(e);if(t.length===yi)return t;let r=Le.randomBytes(yi);return Q.writeFileSync(e,r,{mode:384}),r}function Pc(n,e){let t=Le.randomBytes(Wp),r=qp(e),i=Le.createCipheriv(gi,r,t),o=Buffer.concat([i.update(n),i.final()]),s=i.getAuthTag();return{version:1,algorithm:gi,kekId:e,encryptedDek:o.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function Gp(n,e){return zp(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function zp(n,e,t,r){let i=Le.createDecipheriv(gi,e,Buffer.from(t,"base64"));return i.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([i.update(n),i.final()])}function Jp(n,e){return zp(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function ES(){if(Vp(),Q.existsSync(gr))return;let n=Le.randomBytes(vi),e=Pc(n,jn[0]);Q.writeFileSync(gr,JSON.stringify(e,null,2),{mode:384})}function Yp(){ES();let n=JSON.parse(Q.readFileSync(gr,"utf8")),e=Gp(n,qp(n.kekId));if(e.length===vi)return e;let t=Le.randomBytes(vi),r=Pc(t,jn[0]);return Q.writeFileSync(gr,JSON.stringify(r,null,2),{mode:384}),t}function PS(){Bp();for(let t of jn){let r=Ec(t);Q.existsSync(r)||Q.writeFileSync(r,Le.randomBytes(yi),{mode:384})}if(Q.existsSync(gr))return;let n=Le.randomBytes(vi),e=Pc(n,jn[0]);Q.writeFileSync(gr,JSON.stringify(e,null,2),{mode:384})}function CS(n){let e=Yp(),t=Le.randomBytes(Wp),r=Le.createCipheriv(gi,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o=r.getAuthTag();return{version:1,algorithm:gi,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:o.toString("base64"),timeStamp:Date.now()}}function kS(n){try{return Jp(n,Yp())}catch{throw PS(),new Error("Failed to decrypt local ciphertext")}}function IS(n,e){let t=Ae.join(e,ve.KEY_FILE_NAME),r=JSON.parse(Q.readFileSync(t,"utf8"));if(!jn.includes(r.kekId))throw new Error(`Invalid kekId: ${r.kekId}`);let i=Ae.join(e,"keys",`${r.kekId}.bin`),o=Ae.resolve(i),s=Ae.resolve(Ae.join(e,"keys"));if(!o.startsWith(s+Ae.sep)&&o!==s)throw new Error("kekId resolves outside the keys directory");let a=Q.readFileSync(o);if(a.length!==yi)throw new Error("Invalid external root key");let c=Gp(r,a);if(c.length!==vi)throw new Error("Invalid external data encryption key");return Jp(n,c)}function AS(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 Oe(){return process.env.DEVECO_CLI_AUTH_SOURCE===ve.AUTH_SOURCE_DEVECO_CODE}var qo=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR||tn.join(DS(),ve.CONFIG_DIR_NAME,ve.APP_NAME);return tn.join(e,ve.TOKEN_FILE_NAME)}ensureConfigDir(){let e=tn.dirname(this.getLocalTokenFilePath());Ne.existsSync(e)||Ne.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=Lt.encryptForLocalStorage(e);this.ensureConfigDir();let r=this.getLocalTokenFilePath();Ne.writeFileSync(r,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return Oe()?this.loadDevecoCodeToken():this.loadLocalJwtToken()}loadDevecoCodeToken(){if(!Oe())return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;let t=tn.resolve(e);try{let r=tn.join(t,ve.TOKEN_FILE_NAME);if(!Ne.existsSync(r))return null;let i=JSON.parse(Ne.readFileSync(r,"utf8"));return Lt.isEncryptedBlob(i)?Lt.decryptForLocalStorageFromDirectory(i,e):null}catch{return null}}async loadLocalJwtToken(){let e=this.getLocalTokenFilePath();try{if(!Ne.existsSync(e))return null;let t=JSON.parse(Ne.readFileSync(e,"utf8"));return Lt.isEncryptedBlob(t)?Lt.decryptForLocalStorage(t):null}catch(t){let r=t.code;return r==="EACCES"||r==="EPERM"||r==="ENOENT"||await this.clearToken(),null}}async clearToken(){if(Oe()){p("clearToken: skipped, session managed by DevEco Code");return}let e=this.getLocalTokenFilePath();try{Ne.existsSync(e)&&Ne.unlinkSync(e)}catch(t){throw new Error("Failed to clear token",{cause:t})}}},Nt=new qo;import{spawn as RS}from"child_process";function TS(n){try{let e=new URL(n);return!(!["http:","https:"].includes(e.protocol)||e.hostname===""||n.includes('"'))}catch{return!1}}function xS(n){return n.replace(/[&|<>()^%!]/g,e=>`^${e}`)}async function Kp(n){if(!TS(n))throw new Error(`Invalid URL: ${JSON.stringify(n)}`);let e,t;switch(process.platform){case"win32":e="cmd",t=["/c","start",'""',xS(n)];break;case"darwin":e="open",t=[n];break;default:e="xdg-open",t=[n];break}let r=RS(e,t,{stdio:"ignore",shell:!1,windowsHide:!0});return new Promise((i,o)=>{r.on("error",s=>{o(new Error("Failed to open browser",{cause:s}))}),r.on("close",s=>{s===0?i():o(new Error(`Browser process exited with code ${s}`))})})}import LS from"axios";var Cc=class{client;constructor(){let e={timeout:Vr.HTTP_TIMEOUT_MS,headers:{"User-Agent":Gi.USER_AGENT,"accept-language":Gi.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=LS.create(e),this.client.interceptors.response.use(t=>t,t=>{let r=`Network connection failed (${t.code}). Please check your proxy configuration or network settings`;throw new Error(`${t.message}
1274
- ${r}`)})}async get(e,t){let r=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}async post(e,t){let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,statusText:e.statusText??"",headers:e.headers}}parseJson(e){try{return JSON.parse(e.data)}catch(t){throw new Error(`Failed to parse JSON response: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}async getBinary(e,t){let 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)}async postAllowFailure(e,t){let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(r)}async deleteAllowFailure(e,t){let r=await this.client.request({method:"DELETE",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(r)}async getBinaryAllowFailure(e,t){let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0}),i=Buffer.from(r.data),o=i.toString("utf8");return{statusCode:r.status,statusText:r.statusText??"",buffer:i,body:o}}},L=new Cc;function Xp(n){let e=n.split(".");return e.length===3&&e.every(t=>t.length>0)}var Ot={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},Fn={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},Go={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},NS={[Ot.CHINA]:Fn.CHINA,[Ot.RUSSIA]:Fn.RUSSIA,[Ot.EUROPE]:Fn.EUROPE,[Ot.SINGAPORE]:Fn.CHINA},OS={[Go.CHINA]:Ot.CHINA,[Go.SINGAPORE]:Ot.SINGAPORE,[Go.EUROPE]:Ot.EUROPE,[Go.RUSSIA]:Ot.RUSSIA};function Zp(n){return NS[n]??Fn.CHINA}function Qp(n){return OS[n]??Ot.CHINA}var kc=class{async getJwtToken(e,t,r,i,o){let s=e.split("&")[0],a=Qp(t),c={tempToken:s,site:a,version:ve.API_VERSION,appid:o},l=`${r}/${i}`,d=await L.get(l,{params:c});if(d.statusCode!==200)throw new Error(`Failed to get jwtToken: status=${d.statusCode}`);let g=d.data.trim();if(!Xp(g))throw new Error("Invalid jwtToken format");return g}},ef=new kc;var Ic=class{async checkJwtToken(e,t,r=!1){let i={refresh:String(r),jwtToken:e},o=`${t}/${G.JWT_TOKEN_CHECK_PATH}`,s=await L.get(o,{headers:i});if(s.statusCode!==200)throw new Error(`Failed to check jwtToken: ${s.statusCode}`);return L.parseJson(s)}async refreshToken(e){let t=await Nt.loadJwtToken();return t?this.refreshTokenWithToken(t,e):null}async refreshTokenWithToken(e,t){try{let r={refresh:"true",jwtToken:e},i=`${t}/${G.JWT_TOKEN_CHECK_PATH}`,o=await L.get(i,{headers:r});if(o.statusCode!==200)return null;let s=L.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?(p("jwtToken invalid."),await Nt.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:Zp(i.userInfo.nationalCode),isRealName:String(i.userInfo.realName)==="true"}}async fetchUserInfo(e,t){let r=await Nt.loadJwtToken();return r?this.getUserInfoFromJwt(r,e,t):null}},yr=new Ic;import MS from"querystring";import{spawn as _S}from"child_process";function tf(n){try{let e=JSON.stringify({signInfo:[{agrType:qr.PRIVACY_ID,country:"CN",language:"zh_CN",isAgree:!0}]}),t=MS.stringify({nsp_svc:"as.user.sign",access_token:n,request:e}),r=_S("curl",["-s","-X","POST",qr.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"?p("Agreement sign reported successfully"):p(`Agreement sign failed: HTTP ${o}`)}).on("error",()=>{})}catch(e){p(`Agreement sign error: ${e.message}`)}}var zo=class{config;server=null;constructor(e){this.config={...Gr,...e}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}async login(){try{p(`Login started, isDevecoCodeAuth: ${Oe()}`);let e=this.generateClientSecret();this.server=new Wo(e,G.CN_LOGIN_URL,this.config.successRedirectUrl,this.config.failedRedirectUrl),await this.server.start(),p(`Local auth server started on port ${this.server.getPort()}`),await this.openLoginPage(this.server.getPort(),e),p("Browser opened for authentication");let t=await this.server.waitForCallback(this.config.timeout);if(p(`Callback received: siteId=${t.siteId}`),t.siteId!=="1")throw new Ie("Non-China accounts are not supported.");let r=await ef.getJwtToken(t.tempToken,t.siteId,G.CN_LOGIN_URL,this.config.tempTokenCheckUrl,this.config.appId);p("JWT token received");let i=await yr.getUserInfoFromJwt(r,G.CN_LOGIN_URL);if(!i)throw new Ie("Login failed: failed to get user info");return p(`User info received: ${i.userName}`),await Nt.saveJwtToken(r),p("JWT token saved"),tf(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 Nt.loadJwtToken();if(!e)return!1;let r=`${G.CN_LOGIN_URL}/${this.config.logoutUrl}?jwtToken=${e}`;try{await L.post(r,{timeout:5e3})}catch{p("Logout: server notification failed, local token cleared")}finally{await Nt.clearToken()}return!0}async getUserInfo(e=!0){return yr.fetchUserInfo(G.CN_LOGIN_URL,e)}generateClientSecret(){return nf.randomUUID().replace(/-/g,"")}async openLoginPage(e,t){let i=`${G.CN_LOGIN_URL}/${this.config.authUrl}?port=${e}&appid=${this.config.appId}&code=${t}`;await Kp(i)}async refreshToken(){return yr.refreshToken(G.CN_LOGIN_URL)}},De=new zo;function FS(){return Oe()?"Not logged in. Please login via DevEco Code first.":"Please run `devecocli auth login` first."}function $S(n){if(n==null||typeof n!="object")return[];let e=n;if(e.ret&&e.ret.code!==0)throw new Error(`team list request failed: code=${e.ret.code}${e.ret.msg?`, msg=${e.ret.msg}`:""}`);return Array.isArray(e.teams)?e.teams.filter(t=>typeof t=="object"&&t!==null).map(t=>({id:String(t.id??""),upSiteId:Number(t.upSiteId??0),name:String(t.name??""),countryCode:String(t.countryCode??""),siteId:Number(t.siteId??0),userType:Number(t.userType??0),lastLoginTime:String(t.lastLoginTime??""),isMirror:t.isMirror===!0})).filter(t=>t.id.length>0):[]}var Jo=class{config;constructor(e){this.config={...Gr,...e}}updateConfig(e){this.config={...this.config,...e}}async listTeams(){let e=await yr.fetchUserInfo(G.CN_LOGIN_URL,!0);if(!e)throw new Ie(FS());let t=await this.fetchTeamList(e.accessToken,e.userId),r=$S(t);return{userId:e.userId,teamList:r}}async fetchTeamList(e,t){let r=this.config.agcTeamListUrl,i;try{i=await L.get(r,{headers:{oauth2Token:e,uid:t,source:"cli",lang:Fn.CHINA},timeout:15e3})}catch(o){let s=o.message;throw s.includes("401")?new Ie("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}},rf=new Jo;async function nn(){return rf.listTeams()}async function Yo(n,e,t){let r=Date.now(),i=!0,o=null;try{await e()}catch(s){i=!1,o=B(s);let a=t?.(s);if(a)throw a}finally{let s={duration_ms:Date.now()-r,success:i,error_code:o};await I.track(n,s)}}function US(n){if(n.length===0)return bt("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(`
1275
- `)}function WS(){return new Promise(n=>{let e=of.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}var wi=new HS("auth").description("Authentication commands (login, logout, status, team)");wi.command("login").description("Log in to your Huawei Developer account").action(async()=>{if(Oe()){console.log(Ac("Login is managed by DevEco Code. Login from DevEco Code instead."));return}let n={event:b.CommandExecuted,args:["auth","login"]};await Yo(n,async()=>{let e=await De.getUserInfo();if(e){console.log(bt(`Already logged in, User Name:${e.userName}`));return}console.log(bt("Starting login process...")),console.log(bt("Press Enter to open browser for login...")),await WS();let t=await De.login();console.log(bt(`Login successful. Logged in as ${t.userName}.`))},e=>{throw e instanceof Ie||(e instanceof Error?e.message:String(e)).includes("Network connection failed")?e:new Error("Login failed",{cause:e})})});wi.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(Oe()){console.log(Ac("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}let n={event:b.CommandExecuted,args:["auth","logout"]};await Yo(n,async()=>{let e=await De.logout();console.log(e?bt("Logout successful"):bt("Already logged out."))},e=>new Error("Logout failed",{cause:e}))});wi.command("status").description("Show the currently logged-in user").action(async()=>{let n={event:b.CommandExecuted,args:["auth","status"]};await Yo(n,async()=>{let e=await De.getUserInfo();if(!e){console.log(bt("Not logged in"));return}console.log(bt(`Current user: ${e.userName}`))},()=>{console.log(bt("Not logged in"))})});var BS=wi.command("team").description("Team-related commands");BS.command("list").description("List team accounts the current user has joined").action(async()=>{let n={event:b.CommandExecuted,args:["auth","team","list"]};await Yo(n,async()=>{let e=await nn();console.log(US(e.teamList))},e=>{if(e instanceof Ie){console.log(Ac(e.message));return}throw new Error("Failed to list teams",{cause:e})})});var sf=wi;import{Command as iE}from"commander";import{green as oE,red as Ci,cyan as Df,yellow as Rf,dim as Tf}from"colorette";import sE from"p-limit";import VS from"ora";var dt=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=VS(e),this.spinner.start(),this.isRunning=!0}stop(){this.spinner&&this.isRunning&&(this.spinner.stop(),this.isRunning=!1)}succeed(e){this.spinner&&(this.spinner.succeed(e),this.isRunning=!1)}fail(e){this.spinner&&(this.spinner.fail(e),this.isRunning=!1)}};import*as cf from"fs";import*as Dc from"path";import{homedir as af}from"os";function rn(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}var lf=["DevEco"];async function Ko(){let n=await L.get(Ke.TAGS_API_URL),t=Xo(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 qS(n){let e=[],t=Ke.DEFAULT_PAGE_SIZE,r=Ke.DEFAULT_MAX_PAGES,i=1;for(;i<=r;){let o=await L.post(Ke.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:i,pageSize:t,tagIds:[n]}}),s=Xo(o,"Skills API");if(e.push(...s.data.list),s.data.list.length<t)break;i++}return e}async function Rc(n){let e=new Map,t=n.map(i=>qS(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=>!lf.includes(o.name)))}async function GS(n,e){let t=await L.post(Ke.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:Ke.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return Xo(t,"Skills API").data.list}async function Tc(n,e){let t=new Map,r=e.map(o=>GS(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=>!lf.includes(s.name)))}function df(n){rn(n);let e=[];for(let[,t]of Object.entries(ct)){let r=S.ensurePathWithinRoot(Dc.join(af(),t.path),Dc.join(af(),t.path,n));cf.existsSync(r)&&e.push(t.displayName)}return e.sort()}function Xo(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=L.parseJson(n);if(t.code!==Ke.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function uf(n){rn(n);let e=`${Ke.SKILL_API_BASE}/${n}/checksum`,t=await L.get(e);return Xo(t,"Checksum API").data}import zS from"adm-zip";import JS from"crypto";import{timingSafeEqual as YS}from"crypto";import ff from"fs";import ne from"path";import{fileURLToPath as KS}from"url";import{homedir as mf}from"os";import{red as XS}from"colorette";var Mt=ff.promises;function pf(n,e){let t=ne.resolve(e),r=ne.resolve(n),i=ne.relative(r,t);if(i.startsWith("..")||ne.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function xc(n){return ne.isAbsolute(n)?n:ne.resolve(process.cwd(),n)}function ZS(n){return JS.createHash("sha256").update(n).digest("hex")}async function QS(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=ZS(n),i=e.sha256.toLowerCase(),o=Buffer.from(r,"hex"),s=Buffer.from(i,"hex");if(o.length!==s.length||!YS(o,s))throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function hf(n){rn(n);let e=`${Ke.SKILL_API_BASE}/${n}/install?format=zip`,t=await L.getBinary(e),r=await uf(n);return await QS(t,r),t}async function eE(n,e,t){rn(t);let r=new zS(n),i=r.getEntries();try{await Mt.stat(e)}catch{await Mt.mkdir(e,{recursive:!0})}let o=ne.join(e,t);pf(e,o);for(let s of i){let a=ne.join(o,s.entryName);pf(o,a)}r.extractAllTo(o,!0)}async function Lc(n){let e=ct[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(ct).join(", ")}`);let t=ne.join(mf(),e.path.replace("/skills",""));try{return await Mt.access(t),!0}catch{return!1}}function Nc(n){let e=ct[n];return ne.join(mf(),e.path)}function tE(n){let e=ct[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(ct).join(", ")}`);return e}function Oc(n,e){let t=tE(e),r="projectPath"in t?t.projectPath:ne.join("."+e,"skills");return ne.join(n,r)}async function nE(n,e,t){rn(e);let r=ne.join(n,e);try{if(await Mt.access(r),t)await Mt.rm(r,{recursive:!0,force:!0});else return console.log(`Skill ${e} exists in ${n}.`),{skillDir:r,shouldSkip:!0}}catch{}return{skillDir:r,shouldSkip:!1}}async function Mc(n,e,t){await eE(n,e,t),console.log(`Skill ${t} installed to ${ne.join(e,t)}.`)}async function _c(n,e,t){let r=ne.join(e,t);await Mt.mkdir(r,{recursive:!0});let i=ne.join(r,ne.basename(n));await Mt.copyFile(n,i),console.log(`Skill ${t} installed to ${r}.`)}function gf(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(XS(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function vr(n,e,t,r){try{let i=await e(),{shouldSkip:o}=await nE(i,n,r);return o?{success:!0,skipped:!0}:(await t(i),{success:!0})}catch(i){return gf(n,i,"Installation failed")}}async function jc(n,e){try{rn(n);let t=await e(),r=ne.join(t,n);try{await Mt.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await Mt.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return gf(n,t,"Removal failed")}}async function yf(n,e,t,r=!1){return vr(n,()=>Nc(e),i=>Mc(t,i,n),r)}async function vf(n,e,t,r=!1){return vr(n,()=>t,i=>Mc(e,i,n),r)}async function wf(n,e,t,r,i=!1){return vr(n,()=>Oc(t,r),o=>Mc(e,o,n),i)}async function bf(n,e,t,r=!1){return vr(n,()=>Nc(t),i=>_c(e,i,n),r)}async function Sf(n,e,t,r,i=!1){return vr(n,()=>Oc(t,r),o=>_c(e,o,n),i)}async function Ef(n,e,t,r=!1){return vr(n,()=>t,i=>_c(e,i,n),r)}async function Fc(n,e){return jc(n,()=>Nc(e))}async function Pf(n,e){return jc(n,()=>e)}async function Cf(n,e,t){return jc(n,()=>Oc(e,t))}function kf(){let e=ne.dirname(KS(import.meta.url));for(;;){let t=ne.join(e,"SKILL.md");if(ff.existsSync(t))return t;let r=ne.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import If from"fs";import{cyan as rE}from"colorette";async function bi(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await Lc(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function Si(){let n=[];for(let e of Object.keys(ct))await Lc(e)&&n.push(e);return n}function Ei(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(rE("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function on(n,e,t){if(!If.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!If.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function Pi(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?xc(n):void 0,resolvedProject:e?xc(e):void 0}}async function Zo(n,e,t){let r=[],i=[],o;if(e?o=e:t&&n.agent?i=(await bi(n.agent)).map(a=>({project:t,agent:a})):t?i=(await Si()).map(a=>({project:t,agent:a})):n.agent?r=await bi(n.agent):r=await Si(),!o&&r.length===0&&i.length===0)throw new Error("No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location.");return{agents:r,projectAgents:i,customPath:o}}var xf="deveco";async function aE(n){let e=await Ko();if(n.all)return(await Rc(e)).map(r=>r.enName);{let r=(await Tc(n.skill,e)).find(i=>i.enName===n.skill);if(!r)throw new $n("errorCode",`Skill "${n.skill}" not found`);return[r.enName]}}async function cE(n,e,t,r){let i=[];if(t.customPath){let o=await vf(n,e,t.customPath,r);return i.push(o),i}for(let o of t.agents){let s=await yf(n,o,e,r);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await wf(n,e,o,s,r);i.push(a)}return i}function lE(n){if(n.all&&n.skill)throw new $n("errorCode","`--all` and `--skill` cannot be specified together.");if(!n.all&&!n.skill)throw new $n("errorCode","Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=Pi(n.path,n.project,n.agent);return t&&on(t,"Project directory",n.force),e&&on(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}function dE(n,e,t){return!!(e||t||n.path||n.project||n.agent)}function uE(){return{agents:[xf],projectAgents:[],customPath:void 0}}async function pE(n,e,t){let r=Oe()&&!dE(n,e,t)?uE():await Zo(n,e,t);return{skillNames:await aE(n),targets:r}}async function fE(n,e,t,r){let i=[],o=0,s=n.length,a=sE(5),c=n.map(l=>a(()=>mE(l)));for(let l=0;l<n.length;l++){let d=n[l],g=s>1?` (${l+1}/${s})`:"";r.start(`Installing ${d}${g}...`);let v=await c[l];if(!v.success){r.fail(),console.log(Ci(`${d}: Download failed - ${v.error}`)),i.push({success:!1});continue}o+=v.buffer.length,r.stop();let D=await cE(d,v.buffer,e,t);i.push(...D)}return{results:i,diskBytes:o}}async function mE(n){try{let e=await hf(n);return{name:n,buffer:e,success:!0}}catch(e){let t=e instanceof Error?e.message:"unknown error";return{name:n,error:t,success:!1}}}async function hE(n){let e=new dt;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=lE(n),{skillNames:i,targets:o}=await pE(n,t,r),{results:s,diskBytes:a}=await fE(i,o,n.force||!1,e);return e.stop(),Ei(s),{diskBytes:a,results:s}}catch(t){throw e.stop(),t}}function Lf(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=>gE(s.error)))];return{opTotal:e,opSuccess:t,opFailed:i,opSkipped:r,...o.length>0?{failedErrors:o}:{}}}function gE(n){let e=/^([A-Za-z_][A-Za-z0-9_-]*)/.exec(n.trim());return e?e[1].slice(0,32):"error"}var $n=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function yE(n){let e=n;return n instanceof $n?n.code:e.code??e.name??"UnknownError"}function es(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 ts(n,e,t){let r=Date.now(),i=!0,o=null,s={};try{s=await e()}catch(a){throw i=!1,o=yE(a),a}finally{let a={event:b.SkillOperation,subAction:n,args:t,...s};await I.track(a,{duration_ms:Date.now()-r,success:i,error_code:o})}}function vE(n){return ts("add",async()=>{let{diskBytes:e,results:t}=await hE(n);return{diskUsage:ce(e),...Lf(t)}},es("add",n))}function wE(n){let{resolvedPath:e,resolvedProject:t}=Pi(n.path,n.project,n.agent);return t&&on(t,"Project directory"),e&&on(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function bE(n,e){let t=new dt;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:i}=wE(e);t.stop();let o=await SE(e,n,r,i);return t.stop(),Ei(o),o}catch(r){throw t.stop(),r}}function Af(n,e=""){if(n.length===0)throw new $n("errorCode",`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function Qo(n,e){let t=[];for(let r of e){let i=r.type==="agent"?await Fc(n,r.agent):await Cf(n,r.project,r.agent);t.push(i)}return t}async function SE(n,e,t,r){if(t)return[await Pf(e,t)];if(r&&n.agent){let a=(await bi(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return Qo(e,a)}if(r){let s=await Si();Af(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return Qo(e,a)}if(n.agent){let a=(await bi(n.agent)).map(c=>({type:"agent",agent:c}));return Qo(e,a)}if(Oe())return[await Fc(e,xf)];let i=await Si();Af(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return Qo(e,o)}var ki=new iE("skills").description("Manage HarmonyOS skills");ki.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async n=>{try{await ts("list",async()=>{let e=new dt;try{e.start("Fetching skills...");let t=await Ko(),r=await Rc(t);if(r.length===0)return e.stop(),console.log(Rf("No skills available.")),{resultTotal:0};e.succeed(`Fetched ${r.length} skills`);for(let i of r)if(n.long){console.log(Df(i.enName)),console.log(Tf(i.description));let o=df(i.enName);o.length>0&&console.log(oE(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName);return{resultTotal:r.length}}finally{e.stop()}},es("list",n))}catch(e){console.error(Ci(e.message)),process.exit(1)}});ki.command("find <keyword>").description("Search skills by keyword").action(async n=>{try{await ts("find",async()=>{let e=new dt;try{e.start("Searching skills...");let t=await Ko(),r=await Tc(n,t);if(r.length===0)return console.log(Rf(`No skills found matching '${n}'.`)),e.stop(),{resultTotal:0,queryLen:n.length};e.succeed(`Found ${r.length} skills.`);for(let i of r)console.log(Df(i.enName)),console.log(Tf(i.description)),console.log();return{resultTotal:r.length,queryLen:n.length}}finally{e.stop()}},es("find"))}catch(e){console.error(Ci(e.message)),process.exit(1)}});ki.command("add").description("Install skills to AI agents").option("--all","Install all available skills").option("--agent <agents>","Target agents, comma-separated; Omit to install to all available agents").option("--skill <skill-name>","Name of the skill to install").option("-f, --force","Overwrite an existing skill installation").option("--project <path>","Project root directory for skill installation").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").action(async n=>{try{await vE(n)}catch(e){console.error(Ci(e.message)),process.exit(1)}});ki.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 ts("remove",async()=>{let e=await bE(n.skill,n);return Lf(e)},es("remove",n))}catch(e){console.error(Ci(e.message)),process.exit(1)}});var Nf=ki;import{Command as PE,InvalidArgumentError as rs}from"commander";import{cyan as ns}from"colorette";function Hn(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=nr(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 $c=[800,1500,2500];function EE(n){return new Promise(e=>setTimeout(e,n))}var wr=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=oe.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(`
1276
- `)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let i=t[0];return p(ns(`Using device serial: ${i}`)),i}if(e&&t.includes(e))return p(ns(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let i=this.findDeviceByArg(r,e);if(i)return p(ns(`Using device: ${i.name} (${i.serial})`)),i.serial;let o=this.formatConnectedDeviceList(r);throw new w(`Device '${e}' not found.
1277
- Available devices:
1278
- ${o}`,"Device not found.")}if(r.length===1){let i=r[0];return p(ns(`Using device: ${i.name} (${i.serial})`)),i.serial}throw new w("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){p(`Retrieving PID for bundle ${r}`),S.assertBundleNameStrict(r);let i=await ie(e,["-t",t,"shell","pidof",r]),o=Hn(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 p(`Found PID for ${r}: ${a}`),a}return p(`No PID found for bundle: ${r}`),null}async resizeHilogBuffer(e,t,r){if(p(`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 ie(e,["-t",t,"shell","hilog","-G",r]),o=Hn(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&&(S.assertHilogToken(e.tag,"tag"),r.push("-T",e.tag)),e.level&&(S.assertHilogLevel(e.level),r.push("-L",e.level)),e.domain&&(S.assertHilogToken(e.domain,"domain"),r.push("-D",e.domain)),t&&r.push("-P",t),e.keyword&&(S.assertHilogKeyword(e.keyword),r.push("-e",S.quotePosixShellArg(e.keyword))),r.join(" ")}async followHilog(e,t,r,i,o){let a=await du(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+$c.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||nr(a.stderr)!=="transient"||c>=s-1)return a;p(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${$c[c]}ms`),await EE($c[c])}return a}async runHilogStreamingCollect(e,t,r){return this.runHilogWithSpawnRetry(e,t,()=>{},i=>{p(`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);p(`Ready to run hilog snapshot command: ${s} ${a.join(" ")}`);let c=await this.runHilogStreamingCollect(s,a,"a hilog snapshot streaming read"),l=Hn(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=S.filterLogsByRelativeWindow(c.stdout||c.stderr,r.fromSeconds,r.toSeconds);d=S.getLastLines(d,r.tail),d.trim()&&console.log(d)}async getHilogOnce(e,t,r,i){let[o,s]=this.buildHilogCommand(e,t,r,i);p(`Ready to run hilog command: ${o} ${s.join(" ")}`);let a=await this.runHilogStreamingCollect(o,s,"a single hilog streaming read"),c=Hn(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=S.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return d=S.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);p(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${o} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(o,s,this.createFollowLineHandler(),l=>{p(`Spawn error during hilog follow: ${l.message}`)},()=>{}),c=Hn(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 w(`No running process found for bundle '${t.bundleName}'. Ensure the app is launched on the device before fetching logs.`,"No running process found for bundle.");return t.logSize&&await this.resizeHilogBuffer(r,e,t.logSize),t.isFollow?await this.runHilogFollow(r,e,t,i||""):await this.getHilogOnce(r,e,t,i||"")}async getCrashLog(e,t){p(`Fetching crash logs from device: ${e}`);let r=this.toolProvider.hdcPath,i=await this.listCrashLogs(r,e,t);if(i.length===0)return t?`No crash logs found for bundle '${t}'.`:"No crash logs found.";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 listCrashLogs(e,t,r){let i=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];p(`Running command: ${e} ${i.join(" ")}`);let o=await this.runHilogStreamingCollect(e,i,"a crash log list streaming read"),s=Hn(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 p(`Crash logs list output:
1279
- ${o.stdout}`),this.parseCrashLogFilenames(o.stdout,r)}parseCrashLogFilenames(e,t){return e.split(`
1280
- `).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return S.assertCrashFilename(r),!0}catch{return!1}}).filter(r=>t?r.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){p(`Fetching latest crash log file: ${r}`);let i=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];p(`Executing command: ${e} ${i.join(" ")}`);let o=await this.runHilogStreamingCollect(e,i,"a crash log streaming read"),s=Hn(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{cyan as Hc,red as Mf}from"colorette";import CE from"ora";function kE(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 IE(n){return{event:b.CommandExecuted,args:kE(n),logType:n.crash?"crash":"common",level:n.level??"ALL",bundleName:n.bundleName??"ALL"}}function AE(n){return n instanceof w?n.traceMessage:n instanceof Error?n.code??n.name:"UnknownError"}async function DE(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=AE(o),console.error(Mf(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(n,o).catch(()=>{})}}function RE(n){try{return S.parsePositiveInteger(n,"tail")}catch{throw new rs("`tail` must be a positive integer.")}}function Of(n,e){try{return S.parseDurationToSeconds(n,e)}catch{throw new rs(`${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 TE(n){try{return S.assertHilogLevel(n),n}catch{throw new rs("`level` must be one of: D, I, W, E, F.")}}function xE(n){try{return S.assertBundleNameStrict(n),n}catch(e){throw new rs(e.message)}}function LE(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.")}async function NE(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 OE(n,e,t,r){let i=S.filterLogsByRelativeWindow(n,t,r);return e.tail?S.getLastLines(i,e.tail):i}var ME=new PE("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(Mf(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",TE).option("--bundle-name <bundle-name>","Filter by application bundle name",xE).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",RE).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>Of(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>Of(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await DE(IE(n),()=>_E(n))});async function _E(n){let e=CE({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};e.start();try{LE(n);let r=n.from,i=n.to,o=await A.new(),s=new wr(o),a=await s.selectDevice(n.device);if(!a)throw new w("No active devices found.","No active devices found.");p(Hc(`deviceId: ${a}`)),p(Hc(`type: ${n.crash?"Crash logs":"Common logs"}`)),p(Hc("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await NE(s,a,n,r,i);t(),n.crash&&c&&(c=OE(c,n,r,i)),c&&console.log(c)}finally{t()}}var _f=ME;import Ai from"path";import _t from"fs";import Bc from"process";import qf from"os";import{Command as YE}from"commander";import{green as Uf,red as Uc,cyan as KE,yellow as Wf}from"colorette";import de from"fs-extra";import H from"path";import*as Ff from"os";import{fileURLToPath as jE}from"url";var jf={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"}},FE=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function $E(){let n=import.meta.url,e=jE(n);if(e.includes("dist")){let o=H.dirname(e),s=H.dirname(o);return H.join(s,"templates","application")}let t=H.dirname(e),r=H.dirname(t),i=H.dirname(r);return H.join(i,"templates","application")}function $f(n,e){de.mkdirSync(e,{recursive:!0});for(let t of de.readdirSync(n,{withFileTypes:!0})){let r=H.join(n,t.name),i=H.join(e,t.name);if(t.isDirectory()){$f(r,i);continue}de.existsSync(i)||(de.mkdirSync(H.dirname(i),{recursive:!0}),de.copyFileSync(r,i))}}function Ii(n,e){let t=de.readFileSync(n,"utf-8"),r=t;for(let[i,o]of e)r=r.replaceAll(i,o);r!==t&&de.writeFileSync(n,r,"utf-8")}function HE(n){if(jf[n])return jf[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function UE(n,e){if(e===22)return;let t=HE(e);t&&(Ii(H.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),Ii(H.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),Ii(H.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function WE(n){return FE.filter(t=>!de.existsSync(H.join(n,t))).length===0}function BE(){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 VE(n){return Ff.platform()==="darwin"?H.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):H.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function qE(n,e){let t=VE(e);if(!de.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=H.join(t,i),a=H.join(n,o);de.existsSync(s)&&(de.mkdirSync(H.dirname(a),{recursive:!0}),de.copyFileSync(s,a))}return!0}function GE(n){let e=BE(),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=H.join(n,r);de.mkdirSync(H.dirname(i),{recursive:!0}),de.writeFileSync(i,e)}}function zE(n,e){e&&qE(n,e)||GE(n)}function JE(n){let e=[H.join(n,"gitignore.txt"),H.join(n,"entry","gitignore.txt")];for(let t of e)if(de.existsSync(t)){let r=H.dirname(t);de.renameSync(t,H.join(r,".gitignore"))}}function Hf(n,e,t,r,i){let o=$E();if(!de.existsSync(o))throw new Error(`Template directory not found: ${o}`);de.mkdirSync(n,{recursive:!0}),$f(o,n),JE(n),zE(n,i),Ii(H.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),Ii(H.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),UE(n,r);let s=WE(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function XE(n){if(n.length<1||n.length>200)throw new ue("errorCode",`App name length must be 1-200 characters. Current: ${n.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(n))throw new ue("errorCode","Application name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function Gf(n){if(qf.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function Bf(n){if(n.length===0)throw new ue("errorCode","Project path cannot be empty.");if(n.length>120)throw new ue("errorCode",`Project path cannot exceed 120 characters (current: ${n.length}).`);let e=qf.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 ue("errorCode",`Project path can only contain ${o}.`)}let r=Gf(n);if(/[\u4e00-\u9fff]/.test(r))throw new ue("errorCode","Project path cannot contain Chinese characters.");if(r.endsWith("."))throw new ue("errorCode","Project path cannot end with a dot (.)")}function ZE(n){let e=n,t=Ai.parse(n).root;for(;e!==t;){if(_t.existsSync(e))return e;e=Ai.dirname(e)}return _t.existsSync(t)?t:null}function Vf(n){let e=ZE(n);if(!e)throw new ue("errorCode",`No existing parent directory found for '${n}'. Cannot create project directory.`);try{_t.accessSync(e,_t.constants.W_OK)}catch{throw new ue("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}let t=Ai.join(e,`.deveco_write_test_${Date.now()}`);try{_t.writeFileSync(t,"test"),_t.unlinkSync(t)}catch{throw new ue("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}}function QE(n){return`com.example.${n.toLowerCase()}`}function eP(n,e){if(e){let i=Gf(e),o=Ai.resolve(i);if(_t.existsSync(o)){if(_t.readdirSync(o).length>0)throw new ue("errorCode",`Directory '${o}' is not empty. Cannot create project here.`)}else Vf(o);return o}let t=Bc.cwd(),r=Ai.join(t,n);if(_t.existsSync(r))throw new ue("errorCode",`Directory '${r}' already exists. Cannot create project here.`);return Vf(r),r}function tP(n,e){let t=e?.getMaxApiLevel(),r=23;if(n.apiLevel){let i=Number(n.apiLevel);if(!Number.isInteger(i)||i<17)throw new ue("errorCode",`Invalid API version ${n.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(i>t)throw new ue("errorCode",`Invalid API version ${n.apiLevel}. Your SDK supports API version 17-${t}`)}else if(i>r)throw new ue("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 nP(){try{return await A.new()}catch(n){console.error(Wf(`DevEco Studio not found: ${n.message}`)),console.log(Wf("Use placeholder API level instead."));return}}var ue=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};async function Wc(n,e,t,r){let i={event:b.CommandExecuted,args:["create"],apiLevel:r?.apiLevel??null},o={duration_ms:Date.now()-n,success:e,error_code:t};await I.track(i,o).catch(()=>{})}function rP(n){console.log(`
1281
- `+Uf("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(Uf("Template integrity check passed."))}var iP=new YE("create").description("Scaffold a new HarmonyOS application project").option("--project-path <path>","Project directory path (default: ./<app-name>)").option("--app-name <name>","Application name").option("--bundle-name <bundle>","Bundle name (auto-derived as com.example.<app-name> if omitted)").option("--api-level <level>","API level (auto-detected from SDK if omitted; minimum: 17)").action(async n=>{let e=Date.now();try{n.appName||(console.error(Uc("Error: --app-name is required")),await Wc(e,!1,"errorCode",n),Bc.exit(1));let t=n.appName;XE(t);let r=n.bundleName||QE(t);S.assertBundleNameStrict(r),n.projectPath&&Bf(n.projectPath);let i=eP(t,n.projectPath);Bf(i),console.log(KE("Initializing project...")),console.log(`Project path: ${i}`),console.log(`App name: ${t}`),console.log(`Bundle name: ${r}`);let o=await nP(),s=tP(n,o);console.log(`API level: ${s}`);let a=o?.devecoStudioPath,c=Hf(i,t,r,s,a);rP(c),await Wc(e,!0,null,n)}catch(t){let r=t,o=t instanceof ue?t.code:r.code??r.name??"UnknownError";console.error(Uc(`
1282
- Failed to create project.`)),console.error(Uc(r.message)),await Wc(e,!1,o,n),Bc.exit(1)}}),zf=iP;import{Command as uP}from"commander";import{red as pP,cyan as tm}from"colorette";import oP from"fs";import is from"path";import{cyan as sP}from"colorette";import*as os from"smol-toml";var br=oP.promises;async function aP(n){try{let e=await br.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 cP(n){try{let e=await br.readFile(n,"utf8");return e.trim()===""?{}:os.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 lP(n,e){let t=is.dirname(n);await br.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await br.writeFile(n,r,"utf8")}async function dP(n,e){let t=is.dirname(n);await br.mkdir(t,{recursive:!0});let r=os.stringify(e);await br.writeFile(n,r,"utf8")}function Jf(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function Yf(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 Kf(n,e){return n.format==="codex"?cP(e):aP(e)}async function Xf(n,e,t){return n.format==="codex"?dP(e,t):lP(e,t)}async function Zf(n,e,t=!1){let r=Gt[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Gt).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 Kf(r,r.globalConfigPath);if(Jf(i,r.mcpServersKey,gt)&&!t)return console.log(`MCP server ${gt} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let o=lo(r,void 0);return Yf(i,r.mcpServersKey,gt,o,t),await Xf(r,r.globalConfigPath,i),console.log(`MCP server ${gt} 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 Vc(n,e,t=!1){let r=Gt[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Gt).join(", ")}`};let i=is.isAbsolute(r.projectConfigPath)?r.projectConfigPath:is.join(e,r.projectConfigPath);try{let o=await Kf(r,i);if(Jf(o,r.mcpServersKey,gt)&&!t)return console.log(`MCP server ${gt} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:n,installType:"project"};let s=lo(r,e);return Yf(o,r.mcpServersKey,gt,s,t),await Xf(r,i,o),console.log(`MCP server ${gt} 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 Qf(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(sP("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`);for(let i of n)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);r>0&&(process.exitCode=1)}var qc="deveco-cli";async function fP(n,e,t){if(n.customPath)return[await Ef(qc,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>Sf(qc,e,s,a,t.force)),...n.agents.map(s=>()=>bf(qc,e,s,t.force))],i=5,o=[];for(let s=0;s<r.length;s+=i){let a=r.slice(s,s+i);o.push(...await Promise.all(a.map(c=>c())))}return o}function mP(n){return[...new Set([...n.agents,...n.projectAgents.map(({agent:e})=>e)])]}async function em(n,e,t,r){await I.track(n,{duration_ms:Date.now()-e,success:t,error_code:r}).catch(()=>{})}async function hP(n,e,t,r,i){let o={event:b.SkillConfigOperation,subAction:"install",targetType:r?"path":i?"project":"global",agents:mP(n)},s=Date.now();try{let a=await fP(n,e,t),c=a.every(l=>l.success||l.skipped);return await em(o,s,c,c?null:"SKILL_INSTALL_FAILED"),a}catch(a){let c=a instanceof Error?a.code??a.name:"UnknownError";throw await em(o,s,!1,c),a}}async function gP(n,e,t){let r=[];for(let{project:i,agent:o}of n.projectAgents){let s=await Vc(o,i,t);r.push(s)}for(let i of n.agents){let o=await Vc(i,e,t);r.push(o)}return r}async function yP(n,e){let t=[];for(let r of n){if(!Gt[r])continue;let o=await Zf(r,process.cwd(),e);t.push(o)}return t}async function vP(n,e,t){if(t.agent&&t.agent.split(",").map(l=>l.trim()).includes("qoder"))throw new Error("Qoder does not support MCP configuration via DevEco CLI. Use other supported agents instead.");let r=t.force??!1,i=n.projectAgents.filter(c=>c.agent!=="qoder"),o=n.agents.filter(c=>c!=="qoder"),s={...n,projectAgents:i,agents:o},a=e?await gP(s,e,r):await yP(s.agents,r);a.length>0&&(console.log(tm("MCP Configuration:")),Qf(a))}async function wP(n,e,t){let r={event:b.Init,subAction:"install",targetType:e?"project":"global",agentName:t.agent},i=Date.now(),o=!0,s=null;try{await vP(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 I.track(r,a)}}async function bP(n){if(n.skill&&n.mcp)throw new Error("Cannot use `--skill` and `--mcp` together. Use `--skill` for skill installation only, or `--mcp` for MCP configuration only.");let{resolvedPath:e,resolvedProject:t}=Pi(n.path,n.project,n.agent);t&&on(t,"Project directory",n.force),e&&on(e,"Directory",n.force);let r=await Zo(n,e,t);if(n.mcp){await wP(r,t,n);return}let i=kf(),o=await hP(r,i,n,e,t);console.log(),o.length>0&&(console.log(tm("Skill Installation:")),Ei(o))}var SP=new uP("init").description("Install the deveco-cli skill or configure the deveco-mcp server into AI agents").option("--agent <agents>","Target agents, comma-separated; installs to all available agents if omitted").option("--project <path>","Project root directory for skill or MCP configuration").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").option("--skill","Install the deveco-cli skill only (same as default behavior; explicit for symmetry with --mcp)").option("--mcp","Configure the deveco-mcp server (syntax checking for .ets and C/C++) only; no skill installation").option("-f, --force","Overwrite existing skill/MCP configuration").action(async n=>{try{await bP(n)}catch(e){console.error(pP(e instanceof Error?e.message:String(e))),process.exit(1)}}),nm=SP;import{Command as PC}from"commander";import{McpServer as aC}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as cC}from"@modelcontextprotocol/sdk/server/stdio.js";import*as Oi from"fs";import*as pn from"path";import{z as pe}from"zod";import ss from"path";function om(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=EP(o);break;case"hover":s={hit:Sr(o)!=null};break;case"definition":case"declaration":s=rm(o,t,r,i,!0);break;case"references":s=CP(o);break;case"implementation":s=rm(o,t,r,i,!1);break;case"documentSymbol":s=kP(o);break;case"callHierarchy":s=IP(o,t,r,i);break;case"workspaceSymbol":s=AP(o,t);break;default:s={}}return s}function sm(n){let e=Array.isArray(n.files)?n.files[0]:n.file;return typeof e!="string"||!e?void 0:ss.extname(e).toLowerCase().replace(/^\./,"")||void 0}function Sr(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 EP(n){let e={total:0,error:0,warn:0,info:0},t=new Set,r=" => Diagnostic: ";for(let o of n.split(`
1283
- `)){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"&&PP(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 PP(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 CP(n){let e=Sr(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 rm(n,e,t,r,i){let o=Sr(n);if(o==null)return{found:!1};let s=Array.isArray(o)?o:[o],a=s[0]?.uri;return i?{found:!0,sameFile:DP(a,e),sourceType:cm(a,t,r)}:{implTotal:s.length,found:!0}}function kP(n){let e=Sr(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:Gc(i)}}function IP(n,e,t,r){let o=Sr(n)?.calls,s=Array.isArray(o)?o:[],a=e.direction,c=new Map;for(let l of s){if(!l||typeof l!="object")continue;let g=(a==="incoming"?l.from:l.to)?.uri,v=cm(g,t,r);c.set(v,(c.get(v)??0)+1)}return{callsTotal:s.length,calleeSrcDist:Gc(c)}}function AP(n,e){let t=Sr(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:Gc(i),deprecatedHit:o},a=e.query;return typeof a=="string"&&(s.queryLen=a.length),s}function am(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 cm(n,e,t){let r=am(n);return r?e&&im(r,e)?"user_project":t&&im(r,t)?"sdk":"system":"unknown"}function DP(n,e){let t=am(n),r=e.file;return!t||typeof r!="string"?!1:as(t)===as(r)}function as(n){try{return ss.resolve(n).replace(/\\/g,"/").toLowerCase()}catch{return n.replace(/\\/g,"/").toLowerCase()}}function im(n,e){let t=ss.relative(as(e),as(n));return t!==""&&!t.startsWith("..")&&!ss.isAbsolute(t)}function Gc(n){let e={};for(let[t,r]of n)e[String(t)]=r;return e}var cs=class{constructor(e,t,r,i){this.telemetry=e;this.getAceServerPid=t;this.getProjectPath=r;this.getSdkPath=i}telemetry;getAceServerPid;getProjectPath;getSdkPath;tools=new Map;add(e,t){return this.tools.set(e.name,{definition:e,handler:t}),this}getAll(){return Array.from(this.tools.values())}registerToServer(e){for(let{definition:t,handler:r}of this.getAll())e.registerTool(t.name,{description:t.description,inputSchema:t.inputSchema},(async i=>this.invokeTool(t.name,i,r)))}async invokeTool(e,t,r){if(h.info(`[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?om(e,r,t,this.getProjectPath?.()??"",this.getSdkPath?.()??""):{},g=l?!1:a,v=l&&r?RP(r):c,D={event:b.McpToolCall,subAction:e,mcpMemory:o,lspMemory:s,fileExt:sm(t),...d};typeof t.direction=="string"&&(D.direction=t.direction),await this.telemetry.track(D,{duration_ms:Date.now()-i,success:g,error_code:v})}async resolveLspMemory(){let e=this.getAceServerPid?.()??null;if(e===null)return"unknown";let t=await Xe(e);return t===null?"unknown":ce(Number(t)*1024)}};function RP(n){let e=n.content.map(t=>t.text).join(`
1284
- `);return/not ready|未初始化|初始中|稍后重试|please retry|retry \d+s|syncing|initializing|初始化失败|C\+\+ project initialization failed/i.test(e)?"NotReady":/No project detected|PROJECT_PATH|工程路径/i.test(e)?"NoProject":/Missing.*parameter|invalid parameters|Unknown feature|must be|不能同时|Must specify|无效/i.test(e)?"BadRequest":/Too many files|Maximum allowed/i.test(e)?"TooManyFiles":/不存在|does not exist|not exist|not found|No valid|不是 \.ets|not a supported|Unsupported/i.test(e)?"InvalidFile":"ToolError"}function zc(n,e,t,r){return new cs(n,e,t,r)}import*as qe from"fs";import*as Ee from"path";import{z as Kc}from"zod";function lm(n){return"method"in n&&!("id"in n)}import{spawn as TP}from"child_process";import{EventEmitter as xP}from"events";import*as Er from"fs";import*as dm from"path";var LP=50*1024*1024,sn=class extends xP{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;get pid(){return this.process?.pid??null}ensureDirectories(){let t=dm.join(this.config.logPath,"lspLog");return Er.existsSync(t)||Er.mkdirSync(t,{recursive:!0}),Er.existsSync(this.config.indexingDataLocation)||Er.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let r=this.ensureDirectories();u.info(`[LspClient] serverMaxSize=${t}MB`);let i=V(r),o=["--expose-gc",`--max-old-space-size=${t}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${i}`,this.config.serverPath,"--stdio",`--logger-path=${i}`,"--logger-level=TRACE"];u.info(`[LspClient] Starting process: node ${o.join(" ")}`);let s=process.execPath??"node";u.info(`[LspClient] nodePath: ${s}`),this.process=TP(s,o,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0}),this.bindProcessEvents(),await new Promise(a=>setTimeout(a,500)),u.info("[LspClient] start lsp process success")}attachProcess(t,r){if(this.process)throw new Error("[LspClient] process already attached");this.process=t,this.bindProcessEvents(r?.stderrAsError??!0),u.info("[LspClient] attached to external process")}bindProcessEvents(t=!0){this.process&&(this.process.stdout?.on("data",r=>{this.handleData(r)}),this.process.stderr?.on("data",r=>{let i=r.toString("utf8").trim();u.error(`[LspClient] stderr: ${i}`),!this.isClosing&&t&&this.emit("error",new Error(`[LspClient] stderr: ${i}`))}),this.process.on("exit",r=>{u.info(`[LSP EXIT] code=${r}`),this.isClosing||this.emit("error",new Error(`LSP process exited with code ${r}`))}))}sendRaw(t,r){if(!this.process?.stdin?.writable){u.warn("[LspClient] Cannot send message, stdin not writable");return}u.info(`[LspClient] send message: ${r}`);let i=this.buildLspMessage(t);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
1291
+ `,kE="6.1.0";function IE(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function AE(n){let e=n.trim();if(!Nm.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${Nm.join(", ")}`);return e}function Om(n,e,t,r){let o=e.trim();if(!/^-?\d+$/.test(o))throw new Error(`${n} must be an integer in [${t}, ${r}].`);let i=Number(o);if(i<t||i>r)throw new Error(`${n} must be in [${t}, ${r}].`);return i}function _m(n,e,t,r,o){let i=e.trim(),s=Number(i);if(!i||Number.isNaN(s))throw new Error(`${n} must be a number in [${t}, ${r}].`);if(o!==void 0&&!DE(i,o))throw new Error(`${n} supports at most ${o} decimal place(s).`);if(s<t||s>r)throw new Error(`${n} must be in [${t}, ${r}].`);return i}function DE(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function Gr(n,e,t,r,o){return Number(_m(n,e,t,r,o))}var RE=["Name","Status","Serial","Device Type","OS Version"];function TE(n){return{cells:[n.name,n.status,n.serial??"-",n.deviceType??"-",n.osVersion??"-"],highlight:n.status==="running"}}async function xE(n,e){let t=await Promise.all(e.map(async r=>{let o=await pn(n,r,PE);return[r,o]}));return new Map(t)}async function LE(n){let e=await _c(n),t=await xE(n,e);return{serials:e,params:t}}function NE(n,e,t,r,o){if(e)for(let i of["const.product.name","const.product.model"]){let s=e.get(i);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),o.set(s,n);let c=r.indexOf(n);c!==-1&&r.splice(c,1);return}}function ME(n,e,t){let r=new Map,o=new Map,i=[...n],s=[...t];for(let a of n){let c=e.get(a),l=c?.get("ohos.qemu.hvd.name");l&&o.set(l,a),t.length>0&&NE(a,c,s,i,r)}for(let a=0;a<s.length&&a<i.length;a++)r.set(s[a],i[a]);return{productSerialMap:r,hvdSerialMap:o}}function OE(n,e,t){let r=n.map(o=>({emu:o,serial:e.get(o.name)??t.get(o.name),effectiveRunning:o.isRunning===!0||t.has(o.name)}));return r.sort((o,i)=>o.effectiveRunning!==i.effectiveRunning?o.effectiveRunning?-1:1:o.emu.name.localeCompare(i.emu.name)),r.map(({emu:o,serial:i,effectiveRunning:s})=>({name:o.name,status:s?"running":"stopped",serial:i??null,deviceType:o.deviceType??null,osVersion:o.osVersion??null}))}async function _E(n,e,t,r){try{let[o,i]=await Promise.all([n.listEmulators(),LE(e)]);if(o.length===0){r?.stop(),console.log(t==="json"?"[]":lr(" No emulator instances found."));return}let s=o.filter(g=>g.isRunning).map(g=>g.name),{productSerialMap:a,hvdSerialMap:c}=ME(i.serials,i.params,s);r?.stop();let l=OE(o,a,c);if(t==="json"){console.log(JSON.stringify(l,null,2));return}let d=l.map(TE);console.log(Ft(RE,d))}catch(o){throw r?.stop(),new Error(`Failed to list emulators: ${o.message}`,{cause:o})}}function jm(n,e,t){let r=!1;for(let o=0;o<n.length;o++){let i=n[o];if(i.status!=="rejected")continue;r=!0;let s=i.reason;console.error(Yc(`Failed to ${t} emulator "${e[o]}": ${s.message}`)),s.stdout&&console.error(Gc(s.stdout)),s.stderr&&console.error(Gc(s.stderr))}return r}var jE=2e3,FE=6e4;async function $E(n,e){let t=Ce(e);return(await jc(n)).some(o=>Ce(o)===t)}async function Fm(n,e,t,r=FE,o=jE){let i=Date.now()+r;for(;Date.now()<i;){if(await $E(n,e)===t)return!0;await new Promise(a=>setTimeout(a,o))}return!1}function HE(n){if(!n)return null;let e=n.indexOf("-bootmode");return e>=0&&e+1<n.length&&n[e+1]==="snapshot"}async function UE(n,e,t){let r=await n.startEmulator(t);if(r.status==="already-running")return console.log(lr(`Emulator "${t}" is already running.`)),{started:!1,memoryBytes:0,hotBoot:null};console.log(An(`Starting emulator "${t}"...`));let o=r.tracker,i=0,s=HE(r.args);try{let a=await Fm(e,t,!0);console.log(a?No(`Emulator "${t}" started successfully.`):lr(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}finally{if(o)try{i=await o.stop()}catch{}}return{started:!0,memoryBytes:i,hotBoot:s}}async function BE(n,e,t){let r=await Promise.allSettled(t.map(s=>UE(n,e,s)));if(jm(r,t,"start"))throw new w("One or more emulators failed to start.");let o=r.filter(s=>s.status==="fulfilled").map(s=>s.value).filter(s=>s.started);return{emulatorMemory:o.length===0||o.some(s=>s.memoryBytes===0)?"unknown":Q(o.reduce((s,a)=>s+a.memoryBytes,0)),hotBoot:o.length===0?null:o.every(s=>s.hotBoot===!0)}}async function $m(n,e){let t=e.trim();if(!It(t))return t;let r=await de.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 WE(n,e,t){let r=await $m(e,t);if(console.log(An(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(lr(`Emulator "${r}" is already stopped.`));return}let i=await Fm(e,r,!1);console.log(i?No(`Emulator "${r}" stopped successfully.`):lr(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function VE(n,e,t){let r=await Promise.allSettled(t.map(o=>WE(n,e,o)));jm(r,t,"stop")}async function dt(){let n=await A.new();return{manager:kn.from(n),toolProvider:n}}async function Ht(n,e,t){let r={event:b.CommandExecuted,args:["emulator",t,"--target"]};await lt(r,async()=>{let o=IE(n.target),i=e(),s=Array.isArray(i)?i:[i],{manager:a,toolProvider:c}=await dt(),l=await $m(c.hdcPath,o);for(let d of s)await a.controlEmulator(l,d);console.log(No(`Emulator "${o}" operation completed.`))})}function qE(n){let e=[];if(cs(e,"longitude",n.longitude,-180,180,8),cs(e,"latitude",n.latitude,-90,90,8),cs(e,"altitude",n.altitude,-1e4,1e4,2),cs(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(lr("Warning: --longitude and --latitude should be specified together to form a valid location.")),e}function GE(n){let e=[];if(xo(e,"light",n.lightIntensity,0,1e5,!1,"--light-intensity"),xo(e,"humidity",n.humidity,0,100,!1),xo(e,"temperature",n.temperature,-273.1,100,!1),xo(e,"steps",n.steps,0,1e4,!0),xo(e,"heartrate",n.heartrate,0,255,!0),e.length===0)throw new Error("Specify at least one sensor option.");return e}function cs(n,e,t,r,o,i,s=`--${e}`){t!==void 0&&n.push({type:"gps",key:e,value:_m(s,t,r,o,i)})}function xo(n,e,t,r,o,i,s=`--${e}`){if(t===void 0)return;let a=i?Om(s,t,r,o):Gr(s,t,r,o,1);n.push({type:"sensor",key:e,value:a})}function zE(n){let e=[];if(n.status!==void 0){let o=n.status==="charging"?1:0;e.push({type:"battery-status",status:o})}if(n.level!==void 0&&e.push({type:"battery",level:Om("--level",n.level,0,100),assumedCharging:n.status==="charging"}),e.length===0)throw new Error("Specify --level or --status.");let t=e.some(o=>o.type==="battery"&&o.level===0),r=e.some(o=>o.type==="battery-status"&&o.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 pe=new Jc("emulator").description("Manage emulator instances");pe.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
1292
+ ${lr("Tip: ")}${Gc("An option value containing spaces/parentheses must be quoted. Use:")}
1293
+ ${An('devecocli emulator <subcommand> --<option> "value with spaces"')}
1294
+ ${An('devecocli emulator <subcommand> --<option>="value with spaces"')}
1295
+ `)}});pe.hook("preAction",async()=>{(await A.new()).require({studio:kE})});var JE=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Kc(n){let e=new ct("--device-type <type>","Emulator device type").choices([...JE]);return n?e.makeOptionMandatory():e}function YE(){return new ct("--device-type <type>","Emulator device type (case-insensitive)").argParser(n=>{if(!n.trim())throw new SE("--device-type must not be empty.");return n}).makeOptionMandatory()}function KE(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+/),o=n.length===1?"--screen":`--screen configuration ${e+1}`;if(r.length!==4||r.some(i=>i.length===0))throw new Error(`${o} must contain four values: width(px), height(px), DPI, and screen diagonal length(inch).`);Gr(`${o} width`,r[0],720,3500),Gr(`${o} height`,r[1],720,3500),Gr(`${o} DPI`,r[2],240,640),Gr(`${o} screen diagonal length`,r[3],3.5,9)}return n}}function XE(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 In(n,e){for(let t of e)if(t in n)return n[t]}function Lo(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function Mm(n){let e=Lo(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var ZE=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],QE="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";async function eP(n,e,t){if(!await n.hasAvailableEmulatorImage({deviceType:e,osVersion:t}))throw new Error(`Invalid --os-version value "${t}".
1296
+ Run \`devecocli emulator image list --all\` and use an exact OS Version value.`)}function Hm(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function Um(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let o=r,i=Lo(In(o,["osVersion","OsVersion","OSVersion","os_version"])),s=Lo(In(o,["deviceType","DeviceType","device_type"])),a=Mm(In(o,["downloaded","Downloaded","isDownloaded"])),c=Lo(In(o,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=Lo(In(o,["releaseType","ReleaseType","release_type"])),d=Mm(In(o,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[i,s,c,l,d,a],highlight:e&&a==="true"})}return t}function tP(n){let e=n.trim();if(!e)return!0;let t=Hm(e);return t===null?!1:t.length===0?!0:Um(t,!0).length===0}function rP(n,e){let t=n.trim();if(!t)return"";let r=Hm(t);if(!r)return n.trimEnd();let o=Um(r,e);return Ft(ZE,o)}var ls=new Jc("image").description("HarmonyOS emulator system images (download, list, remove)");ls.command("download").description("Download system image").addOption(Kc(!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:b.CommandExecuted,args:["emulator","image","download",...n.deviceType?["--device-type"]:[],...n.osVersion?["--os-version"]:[],...n.force?["--force"]:[]]};await lt(e,async()=>{let{manager:t,toolProvider:r}=await dt();await qc(r.emulatorPath,r.sdkPath);let o=n.deviceType?.trim(),i=n.osVersion?.trim();if(!o)throw new w("Error: missing required option '--device-type <type>'","Missing required device type.");if(!i)throw new w("Error: misssing required option '--os-version <version>'","Missing required OS version.");await eP(t,o,i),await t.installEmulatorImage({deviceType:o,osVersion:i,force:n.force===!0})})});ls.command("remove").description("Remove a downloaded system image").addOption(Kc(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let e={event:b.CommandExecuted,args:["emulator","image","remove","--device-type","--os-version"]};await lt(e,async()=>{let{manager:t}=await dt();await t.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})})});ls.command("list").description("List system images").addOption(Kc(!1)).option("--all","List all images (local and remote)").addOption(new ct("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:b.CommandExecuted,args:["emulator","image","list",...n.deviceType?["--device-type"]:[],...n.all?["--all"]:[],...n.format!=="table"?["--format"]:[]]};await lt(e,async()=>{let{manager:t}=await dt(),r;n.all?r=void 0:r=!0;let o=await t.listEmulatorImages({deviceType:n.deviceType,downloaded:r});if(tP(o)){console.log(lr(QE));return}if(n.format==="json"){console.log(o.trimEnd());return}let i=rP(o,n.all===!0);console.log(i)})});pe.addCommand(ls);var ds=new Jc("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");ds.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let n={event:b.CommandExecuted,args:["emulator","license","view"]};await lt(n,async()=>{let{toolProvider:e}=await dt(),t=await Rm(e.emulatorPath,e.sdkPath);process.exitCode=t})});ds.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let n={event:b.CommandExecuted,args:["emulator","license","accept"]};await lt(n,async()=>{let{toolProvider:e}=await dt(),t=await Lm(e.emulatorPath,e.sdkPath);process.exitCode=t})});ds.action(async()=>{let n={event:b.CommandExecuted,args:["emulator","license"]};await lt(n,async()=>{let{toolProvider:e}=await dt(),t=await xm(e.emulatorPath,e.sdkPath);process.exitCode=t})});pe.addCommand(ds);pe.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Ht(n,()=>({type:"shake"}),"shake"));pe.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Ht(n,()=>({type:"power"}),"power"));pe.command("rotate").description("Rotate emulator").addOption(new ct("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new zc("<direction>").choices(["left","right"])).action((n,e)=>Ht(e,()=>({type:"rotation",direction:n}),"rotate"));pe.command("volume").description("Change volume").addOption(new ct("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new zc("<direction>").choices(["up","down"])).action((n,e)=>Ht(e,()=>({type:"volume",direction:n}),"volume"));pe.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",CE).action((n,e)=>Ht(e,()=>({type:"folded-state",state:AE(n)}),"fold"));pe.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 ct("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>Ht(n,()=>zE(n),"battery"));pe.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=>Ht(n,()=>qE(n),"geolocation"));pe.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new zc("<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 Ht(e,()=>t[n],"scene")});pe.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=>Ht(n,()=>GE(n),"sensor"));pe.command("list").description("List all emulator instances").addOption(new ct("--details","Output the raw JSON of `Emulator -list -details` without transformation").conflicts("format")).addOption(new ct("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:b.CommandExecuted,args:["emulator","list",...n.details?["--details"]:[],...n.format!=="table"?["--format"]:[]]};await lt(e,async()=>{let{manager:t,toolProvider:r}=await dt();if(n.details){let i=await t.listEmulatorDetails();console.log(i.trimEnd());return}let o=n.format==="table"?EE({text:"Listing emulators\u2026",color:"cyan"}).start():void 0;await _E(t,r.hdcPath,n.format,o)})});pe.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let e={event:b.CommandExecuted,args:["emulator","start"],emulatorMemory:"unknown",hotBoot:null};await lt(e,async()=>{let{manager:t,toolProvider:r}=await dt();if(await Vc(r.emulatorPath,r.sdkPath),!n?.length)throw new w("Error: missing required argument 'names'","Missing required emulator name.");let o=await BE(t,r.hdcPath,n);e.emulatorMemory=o.emulatorMemory,e.hotBoot=o.hotBoot})});pe.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:b.CommandExecuted,args:["emulator","stop"]};await lt(e,async()=>{let{manager:t,toolProvider:r}=await dt();if(!n?.length){console.error(Yc("Error: missing required argument 'names'")),process.exitCode=1;return}await VE(t,r.hdcPath,n)})});var nP=pe.command("create <name>").description("Create a local emulator instance.").addOption(YE()).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 ct("--path, --instance-path <path>","Emulator instance path")).option("--image-root <path>","Emulator image path").option("--screen-profile <model>","Emulator screen profile").addOption(new ct("--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 ct("--hot-boot <boolean>","Enable or disable hot boot").choices(["true","false"])).option("--force","Overwrite an existing emulator instance");nP.action(async(n,e)=>{let t={event:b.CommandExecuted,args:["emulator","create",...XE(e)]};await lt(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:KE(e.screen),storage:e.storage===void 0?void 0:Gr("--storage",e.storage,2,1023),memory:e.memory===void 0?void 0:Gr("--memory",e.memory,2,32),hotBoot:e.hotBoot===void 0?void 0:e.hotBoot==="true",force:e.force===!0},{manager:o}=await dt();console.log(An(`Creating emulator "${n}"...`)),await o.createVirtualDevice(r),console.log(No(`Emulator "${n}" created successfully.`))})});pe.command("delete <name>").description("Delete a local emulator instance").addOption(new ct("--path, --instance-path <path>","Emulator instance path")).action(async(n,e)=>{let t={event:b.CommandExecuted,args:["emulator","delete",...e.instancePath!==void 0?["--instance-path"]:[]]};await lt(t,async()=>{let{manager:r}=await dt();console.log(An(`Deleting emulator "${n}"...`));let o=await r.deleteVirtualDevice(n,e.instancePath);console.log(No(`Emulator "${o}" deleted successfully.`))})});var Bm=pe;import{Command as AP}from"commander";import{red as nl,cyan as Rt}from"colorette";import*as pf from"readline";import*as df from"crypto";import*as Wm from"http";import*as Vm from"crypto";import{URL as oP}from"url";var us=class{server=null;port=0;clientSecret;callbackPath="/callback";resolveCallback=null;rejectCallback=null;timeoutId=null;baseUrl;successRedirectUrl;failedRedirectUrl;constructor(e,t,r,o){this.clientSecret=e,this.baseUrl=t,this.successRedirectUrl=r,this.failedRedirectUrl=o}async start(){return new Promise((e,t)=>{let r=Wm.createServer((o,i)=>{this.handleRequest(o,i)});r.keepAliveTimeout=1,r.on("error",o=>{t(new Error("Failed to start local auth server",{cause:o}))}),r.listen(0,"127.0.0.1",()=>{this.server=r;let o=r.address();this.port=o.port,e()})})}async waitForCallback(e=3e4){return new Promise((t,r)=>{this.resolveCallback=o=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),t(o)},this.rejectCallback=o=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),r(o)},this.timeoutId=setTimeout(()=>{this.timeoutId=null,this.rejectCallback?.(new Error("Callback timeout"))},e)})}async stop(){return this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.server?new Promise(e=>{let t=this.server;this.server=null,typeof t.closeAllConnections=="function"&&t.closeAllConnections();let 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 i=new oP(e.url??"",`http://${r}`);if(i.pathname!==this.callbackPath){t.writeHead(404),t.end("Not Found");return}try{let s=i.searchParams;e.method==="POST"?this.readBody(e,t,s):this.handleCallbackRequest(e,t,s,"")}catch(s){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(s)}}readBody(e,t,r){let o="",i=0,s=65536;e.on("data",a=>{if(i+=a.length,i>s){e.destroy(new Error("Request body too large"));return}o+=a.toString()}),e.on("end",()=>{this.handleCallbackRequest(e,t,r,o)})}handleCallbackRequest(e,t,r,o){try{let i=this.parseParams(r,o),s=i.get("code"),a=i.get("tempToken"),c=i.get("siteId"),l=i.get("quit");if(!this.validateCode(s)){t.writeHead(400),t.end("Bad Request");return}if(this.isQuitRequest(l)){this.handleQuitRequest(t);return}if(!a||!c){t.writeHead(400),t.end("Bad Request");return}let d={tempToken:a,siteId:c,quit:l??void 0};this.resolveCallback?.(d),this.sendSuccessResponse(t)}catch(i){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(i)}}parseParams(e,t){return t&&t.trim()?new URLSearchParams(t):e}validateCode(e){let t=Buffer.from(e||"","utf8"),r=Buffer.from(this.clientSecret,"utf8");return t.length===r.length&&Vm.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 He from"fs";import*as dr from"path";import{homedir as uP}from"os";var Ut={};Iy(Ut,{LocalCrypto:()=>Ut,decryptForLocalStorage:()=>cP,decryptForLocalStorageFromDirectory:()=>lP,encryptForLocalStorage:()=>aP,isEncryptedBlob:()=>dP});import*as ne from"fs";import*as Le from"path";import*as $e from"crypto";import*as Gm from"os";import{homedir as zm}from"os";var xe=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var Mo=xr.ALGORITHM,Jm=xr.IV_LENGTH,Oo=xr.KEY_LENGTH,_o=xr.KEY_LENGTH,zr=xr.KEK_VERSIONS,ps=process.env.DEVECO_CLI_DATA_DIR||Le.join(zm(),be.CONFIG_DIR_NAME,be.APP_NAME),ms=Le.join(zm(),".local","share",be.APP_NAME,"keys"),Dn=Le.join(ps,be.KEY_FILE_NAME);function qm(n){return Gm.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 Xc(n){return Le.join(ms,`${n}.bin`)}function Ym(){if(!ne.existsSync(ps))try{ne.mkdirSync(ps,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new xe(qm(ps)):n}if(!ne.existsSync(ms))try{ne.mkdirSync(ms,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new xe(qm(Le.dirname(ms))):n}}function Km(){Ym();for(let n of zr){let e=Xc(n);ne.existsSync(e)||ne.writeFileSync(e,$e.randomBytes(Oo),{mode:384})}}function Xm(n){if(!zr.includes(n))throw new Error(`Invalid kekId: ${n}`);Km();let e=Xc(n),t=ne.readFileSync(e);if(t.length===Oo)return t;let r=$e.randomBytes(Oo);return ne.writeFileSync(e,r,{mode:384}),r}function Zc(n,e){let t=$e.randomBytes(Jm),r=Xm(e),o=$e.createCipheriv(Mo,r,t),i=Buffer.concat([o.update(n),o.final()]),s=o.getAuthTag();return{version:1,algorithm:Mo,kekId:e,encryptedDek:i.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function Zm(n,e){return Qm(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function Qm(n,e,t,r){let o=$e.createDecipheriv(Mo,e,Buffer.from(t,"base64"));return o.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([o.update(n),o.final()])}function ef(n,e){return Qm(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function iP(){if(Km(),ne.existsSync(Dn))return;let n=$e.randomBytes(_o),e=Zc(n,zr[0]);ne.writeFileSync(Dn,JSON.stringify(e,null,2),{mode:384})}function tf(){iP();let n=JSON.parse(ne.readFileSync(Dn,"utf8")),e=Zm(n,Xm(n.kekId));if(e.length===_o)return e;let t=$e.randomBytes(_o),r=Zc(t,zr[0]);return ne.writeFileSync(Dn,JSON.stringify(r,null,2),{mode:384}),t}function sP(){Ym();for(let t of zr){let r=Xc(t);ne.existsSync(r)||ne.writeFileSync(r,$e.randomBytes(Oo),{mode:384})}if(ne.existsSync(Dn))return;let n=$e.randomBytes(_o),e=Zc(n,zr[0]);ne.writeFileSync(Dn,JSON.stringify(e,null,2),{mode:384})}function aP(n){let e=tf(),t=$e.randomBytes(Jm),r=$e.createCipheriv(Mo,e,t),o=Buffer.concat([r.update(n,"utf8"),r.final()]),i=r.getAuthTag();return{version:1,algorithm:Mo,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:i.toString("base64"),timeStamp:Date.now()}}function cP(n){try{return ef(n,tf())}catch{throw sP(),new Error("Failed to decrypt local ciphertext")}}function lP(n,e){let t=Le.join(e,be.KEY_FILE_NAME),r=JSON.parse(ne.readFileSync(t,"utf8"));if(!zr.includes(r.kekId))throw new Error(`Invalid kekId: ${r.kekId}`);let o=Le.join(e,"keys",`${r.kekId}.bin`),i=Le.resolve(o),s=Le.resolve(Le.join(e,"keys"));if(!i.startsWith(s+Le.sep)&&i!==s)throw new Error("kekId resolves outside the keys directory");let a=ne.readFileSync(i);if(a.length!==Oo)throw new Error("Invalid external root key");let c=Zm(r,a);if(c.length!==_o)throw new Error("Invalid external data encryption key");return ef(n,c)}function dP(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 Ue(){return process.env.DEVECO_CLI_AUTH_SOURCE===be.AUTH_SOURCE_DEVECO_CODE}var fs=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR||dr.join(uP(),be.CONFIG_DIR_NAME,be.APP_NAME);return dr.join(e,be.TOKEN_FILE_NAME)}ensureConfigDir(){let e=dr.dirname(this.getLocalTokenFilePath());He.existsSync(e)||He.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=Ut.encryptForLocalStorage(e);this.ensureConfigDir();let r=this.getLocalTokenFilePath();He.writeFileSync(r,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return Ue()?this.loadDevecoCodeToken():this.loadLocalJwtToken()}loadDevecoCodeToken(){if(!Ue())return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;let t=dr.resolve(e);try{let r=dr.join(t,be.TOKEN_FILE_NAME);if(!He.existsSync(r))return null;let o=JSON.parse(He.readFileSync(r,"utf8"));return Ut.isEncryptedBlob(o)?Ut.decryptForLocalStorageFromDirectory(o,e):null}catch{return null}}async loadLocalJwtToken(){let e=this.getLocalTokenFilePath();try{if(!He.existsSync(e))return null;let t=JSON.parse(He.readFileSync(e,"utf8"));return Ut.isEncryptedBlob(t)?Ut.decryptForLocalStorage(t):null}catch(t){let r=t.code;return r==="EACCES"||r==="EPERM"||r==="ENOENT"||await this.clearToken(),null}}async clearToken(){if(Ue()){u("clearToken: skipped, session managed by DevEco Code");return}let e=this.getLocalTokenFilePath();try{He.existsSync(e)&&He.unlinkSync(e)}catch(t){throw new Error("Failed to clear token",{cause:t})}}},Bt=new fs;import{spawn as pP}from"child_process";function mP(n){try{let e=new URL(n);return!(!["http:","https:"].includes(e.protocol)||e.hostname===""||n.includes('"'))}catch{return!1}}function fP(n){return n.replace(/[&|<>()^%!]/g,e=>`^${e}`)}async function rf(n){if(!mP(n))throw new Error(`Invalid URL: ${JSON.stringify(n)}`);let e,t;switch(process.platform){case"win32":e="cmd",t=["/c","start",'""',fP(n)];break;case"darwin":e="open",t=[n];break;default:e="xdg-open",t=[n];break}let r=pP(e,t,{stdio:"ignore",shell:!1,windowsHide:!0});return new Promise((o,i)=>{r.on("error",s=>{i(new Error("Failed to open browser",{cause:s}))}),r.on("close",s=>{s===0?o():i(new Error(`Browser process exited with code ${s}`))})})}import vP from"axios";var hP={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function gP(n){try{return new URL(n)}catch{return null}}function nf(n){var e=(typeof n=="string"?gP(n):n)||{},t=e.protocol,r=e.host,o=e.port;if(typeof r!="string"||!r||typeof t!="string"||(t=t.split(":",1)[0],r=r.replace(/:\d*$/,""),o=parseInt(o)||hP[t]||0,!yP(r,o)))return"";var i=Qc(t+"_proxy")||Qc("all_proxy");return i&&i.indexOf("://")===-1&&(i=t+"://"+i),i}function yP(n,e){var t=Qc("no_proxy").toLowerCase();return t?t==="*"?!1:t.split(/[,\s]/).every(function(r){if(!r)return!0;var o=r.match(/^(.+):(\d+)$/),i=o?o[1]:r,s=o?parseInt(o[2]):0;return s&&s!==e?!0:/^[.*]/.test(i)?(i.charAt(0)==="*"&&(i=i.slice(1)),!n.endsWith(i)):n!==i}):!0}function Qc(n){return process.env[n.toLowerCase()]||process.env[n.toUpperCase()]||""}function wP(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 el=class{client;constructor(){let e={timeout:Zn.HTTP_TIMEOUT_MS,headers:{"User-Agent":li.USER_AGENT,"accept-language":li.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=vP.create(e),this.client.interceptors.request.use(t=>{let r=nf(t.url??"");return t.proxy=r?wP(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`;throw new Error(`${t.message}
1297
+ ${r}`)})}async get(e,t){let r=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}async post(e,t){let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,statusText:e.statusText??"",headers:e.headers}}parseJson(e){try{return JSON.parse(e.data)}catch(t){throw new Error(`Failed to parse JSON response: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}async getBinary(e,t){let 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)}async postAllowFailure(e,t){let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(r)}async deleteAllowFailure(e,t){let r=await this.client.request({method:"DELETE",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(r)}async getBinaryAllowFailure(e,t){let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0}),o=Buffer.from(r.data),i=o.toString("utf8");return{statusCode:r.status,statusText:r.statusText??"",buffer:o,body:i}}},L=new el;function of(n){let e=n.split(".");return e.length===3&&e.every(t=>t.length>0)}var Wt={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},Jr={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},hs={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},bP={[Wt.CHINA]:Jr.CHINA,[Wt.RUSSIA]:Jr.RUSSIA,[Wt.EUROPE]:Jr.EUROPE,[Wt.SINGAPORE]:Jr.CHINA},SP={[hs.CHINA]:Wt.CHINA,[hs.SINGAPORE]:Wt.SINGAPORE,[hs.EUROPE]:Wt.EUROPE,[hs.RUSSIA]:Wt.RUSSIA};function sf(n){return bP[n]??Jr.CHINA}function af(n){return SP[n]??Wt.CHINA}var tl=class{async getJwtToken(e,t,r,o,i){let s=e.split("&")[0],a=af(t),c={tempToken:s,site:a,version:be.API_VERSION,appid:i},l=`${r}/${o}`,d=await L.get(l,{params:c});if(d.statusCode!==200)throw new Error(`Failed to get jwtToken: status=${d.statusCode}`);let g=d.data.trim();if(!of(g))throw new Error("Invalid jwtToken format");return g}},cf=new tl;var rl=class{async checkJwtToken(e,t,r=!1){let o={refresh:String(r),jwtToken:e},i=`${t}/${Y.JWT_TOKEN_CHECK_PATH}`,s=await L.get(i,{headers:o});if(s.statusCode!==200)throw new Error(`Failed to check jwtToken: ${s.statusCode}`);return L.parseJson(s)}async refreshToken(e){let t=await Bt.loadJwtToken();return t?this.refreshTokenWithToken(t,e):null}async refreshTokenWithToken(e,t){try{let r={refresh:"true",jwtToken:e},o=`${t}/${Y.JWT_TOKEN_CHECK_PATH}`,i=await L.get(o,{headers:r});if(i.statusCode!==200)return null;let s=L.parseJson(i);return!s.status||!s.userInfo?null:{accessToken:s.userInfo.accessToken,refreshToken:s.userInfo.refreshToken??""}}catch(r){let o=r;return console.error(`Failed to refresh token: ${o.code??""} ${o.message??""}`),null}}async getUserInfoFromJwt(e,t,r=!1){let o=await this.checkJwtToken(e,t,r);return!o.status||!o.userInfo||!o.userInfo.accessToken?(u("jwtToken invalid."),await Bt.clearToken(),null):{userId:o.userInfo.userId??"",userName:o.userInfo.name??"",accessToken:o.userInfo.accessToken,refreshToken:o.userInfo.refreshToken??"",jwtToken:e,countryCode:o.userInfo.nationalCode,language:sf(o.userInfo.nationalCode),isRealName:String(o.userInfo.realName)==="true"}}async fetchUserInfo(e,t){let r=await Bt.loadJwtToken();return r?this.getUserInfoFromJwt(r,e,t):null}},Rn=new rl;import EP from"querystring";import{spawn as PP}from"child_process";function lf(n){try{let e=JSON.stringify({signInfo:[{agrType:Qn.PRIVACY_ID,country:"CN",language:"zh_CN",isAgree:!0}]}),t=EP.stringify({nsp_svc:"as.user.sign",access_token:n,request:e}),r=PP("curl",["-s","-X","POST",Qn.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",o=>{let i=o.toString().trim();i==="200"?u("Agreement sign reported successfully"):u(`Agreement sign failed: HTTP ${i}`)}).on("error",()=>{})}catch(e){u(`Agreement sign error: ${e.message}`)}}var gs=class{config;server=null;constructor(e){this.config={...eo,...e}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}async login(){try{u(`Login started, isDevecoCodeAuth: ${Ue()}`);let e=this.generateClientSecret();this.server=new us(e,Y.CN_LOGIN_URL,this.config.successRedirectUrl,this.config.failedRedirectUrl),await this.server.start(),u(`Local auth server started on port ${this.server.getPort()}`),await this.openLoginPage(this.server.getPort(),e),u("Browser opened for authentication");let t=await this.server.waitForCallback(this.config.timeout);if(u(`Callback received: siteId=${t.siteId}`),t.siteId!=="1")throw new xe("Non-China accounts are not supported.");let r=await cf.getJwtToken(t.tempToken,t.siteId,Y.CN_LOGIN_URL,this.config.tempTokenCheckUrl,this.config.appId);u("JWT token received");let o=await Rn.getUserInfoFromJwt(r,Y.CN_LOGIN_URL);if(!o)throw new xe("Login failed: failed to get user info");return u(`User info received: ${o.userName}`),await Bt.saveJwtToken(r),u("JWT token saved"),lf(o.accessToken),o}finally{this.server&&(await this.server.stop(),this.server=null)}}async isLoggedIn(){return await this.getUserInfo(!0)!==null}async logout(){let e=await Bt.loadJwtToken();if(!e)return!1;let r=`${Y.CN_LOGIN_URL}/${this.config.logoutUrl}?jwtToken=${e}`;try{await L.post(r,{timeout:5e3})}catch{u("Logout: server notification failed, local token cleared")}finally{await Bt.clearToken()}return!0}async getUserInfo(e=!0){return Rn.fetchUserInfo(Y.CN_LOGIN_URL,e)}generateClientSecret(){return df.randomUUID().replace(/-/g,"")}async openLoginPage(e,t){let o=`${Y.CN_LOGIN_URL}/${this.config.authUrl}?port=${e}&appid=${this.config.appId}&code=${t}`;await rf(o)}async refreshToken(){return Rn.refreshToken(Y.CN_LOGIN_URL)}},Ne=new gs;function kP(){return Ue()?"Not logged in. Please login via DevEco Code first.":"Please run `devecocli auth login` first."}function IP(n){if(n==null||typeof n!="object")return[];let e=n;if(e.ret&&e.ret.code!==0)throw new Error(`team list request failed: code=${e.ret.code}${e.ret.msg?`, msg=${e.ret.msg}`:""}`);return Array.isArray(e.teams)?e.teams.filter(t=>typeof t=="object"&&t!==null).map(t=>({id:String(t.id??""),upSiteId:Number(t.upSiteId??0),name:String(t.name??""),countryCode:String(t.countryCode??""),siteId:Number(t.siteId??0),userType:Number(t.userType??0),lastLoginTime:String(t.lastLoginTime??""),isMirror:t.isMirror===!0})).filter(t=>t.id.length>0):[]}var ys=class{config;constructor(e){this.config={...eo,...e}}updateConfig(e){this.config={...this.config,...e}}async listTeams(){let e=await Rn.fetchUserInfo(Y.CN_LOGIN_URL,!0);if(!e)throw new xe(kP());let t=await this.fetchTeamList(e.accessToken,e.userId),r=IP(t);return{userId:e.userId,teamList:r}}async fetchTeamList(e,t){let r=this.config.agcTeamListUrl,o;try{o=await L.get(r,{headers:{oauth2Token:e,uid:t,source:"cli",lang:Jr.CHINA},timeout:15e3})}catch(i){let s=i.message;throw s.includes("401")?new xe("Token expired. Run `devecocli auth login` again."):new Error(`Network error while listing teams: ${s}`,{cause:i})}if(o.statusCode!==200)throw new Error(`Failed to list teams: HTTP ${o.statusCode}`);return typeof o.data=="string"?JSON.parse(o.data):o.data}},uf=new ys;async function ur(){return uf.listTeams()}async function vs(n,e,t){let r=Date.now(),o=!0,i=null;try{await e()}catch(s){o=!1,i=G(s);let a=t?.(s);if(a)throw a}finally{let s={duration_ms:Date.now()-r,success:o,error_code:i};await I.track(n,s)}}function DP(n){if(n.length===0)return Rt("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))),o=s=>s.map((a,c)=>a.padEnd(r[c])).join(" "),i=r.map(s=>"-".repeat(s)).join(" ");return[o(e),i,...t.map(o)].join(`
1298
+ `)}function RP(){return new Promise(n=>{let e=pf.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}var jo=new AP("auth").description("Authentication commands (login, logout, status, team)");jo.command("login").description("Log in to your Huawei Developer account").action(async()=>{if(Ue()){console.log(nl("Login is managed by DevEco Code. Login from DevEco Code instead."));return}let n={event:b.CommandExecuted,args:["auth","login"]};await vs(n,async()=>{let e=await Ne.getUserInfo();if(e){console.log(Rt(`Already logged in, User Name:${e.userName}`));return}console.log(Rt("Starting login process...")),console.log(Rt("Press Enter to open browser for login...")),await RP();let t=await Ne.login();console.log(Rt(`Login successful. Logged in as ${t.userName}.`))},e=>{throw e instanceof xe||(e instanceof Error?e.message:String(e)).includes("Network connection failed")?e:new Error("Login failed",{cause:e})})});jo.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(Ue()){console.log(nl("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}let n={event:b.CommandExecuted,args:["auth","logout"]};await vs(n,async()=>{let e=await Ne.logout();console.log(e?Rt("Logout successful"):Rt("Already logged out."))},e=>new Error("Logout failed",{cause:e}))});jo.command("status").description("Show the currently logged-in user").action(async()=>{let n={event:b.CommandExecuted,args:["auth","status"]};await vs(n,async()=>{let e=await Ne.getUserInfo();if(!e){console.log(Rt("Not logged in"));return}console.log(Rt(`Current user: ${e.userName}`))},()=>{console.log(Rt("Not logged in"))})});var TP=jo.command("team").description("Team-related commands");TP.command("list").description("List team accounts the current user has joined").action(async()=>{let n={event:b.CommandExecuted,args:["auth","team","list"]};await vs(n,async()=>{let e=await ur();console.log(DP(e.teamList))},e=>{if(e instanceof xe){console.log(nl(e.message));return}throw new Error("Failed to list teams",{cause:e})})});var mf=jo;import{Command as qP}from"commander";import{green as GP,red as Bo,cyan as Of,yellow as _f,dim as jf}from"colorette";import zP from"p-limit";import xP from"ora";var Ke=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=xP(e),this.spinner.start(),this.isRunning=!0}stop(){this.spinner&&this.isRunning&&(this.spinner.stop(),this.isRunning=!1)}succeed(e){this.spinner&&(this.spinner.succeed(e),this.isRunning=!1)}fail(e){this.spinner&&(this.spinner.fail(e),this.isRunning=!1)}};import*as hf from"fs";import*as ol from"path";import{homedir as ff}from"os";function pr(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}var gf=["DevEco"];async function ws(){let n=await L.get(rt.TAGS_API_URL),t=bs(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 LP(n){let e=[],t=rt.DEFAULT_PAGE_SIZE,r=rt.DEFAULT_MAX_PAGES,o=1;for(;o<=r;){let i=await L.post(rt.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:o,pageSize:t,tagIds:[n]}}),s=bs(i,"Skills API");if(e.push(...s.data.list),s.data.list.length<t)break;o++}return e}async function il(n){let e=new Map,t=n.map(o=>LP(o)),r=await Promise.all(t);for(let o of r)for(let i of o)e.has(i.id)||e.set(i.id,i);return Array.from(e.values()).filter(o=>o.tags?.every(i=>!gf.includes(i.name)))}async function NP(n,e){let t=await L.post(rt.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:rt.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return bs(t,"Skills API").data.list}async function sl(n,e){let t=new Map,r=e.map(i=>NP(n,i)),o=await Promise.all(r);for(let i of o)for(let s of i)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(i=>i.tags?.every(s=>!gf.includes(s.name)))}function yf(n){pr(n);let e=[];for(let[,t]of Object.entries(mt)){let r=S.ensurePathWithinRoot(ol.join(ff(),t.path),ol.join(ff(),t.path,n));hf.existsSync(r)&&e.push(t.displayName)}return e.sort()}function bs(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=L.parseJson(n);if(t.code!==rt.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function vf(n){pr(n);let e=`${rt.SKILL_API_BASE}/${n}/checksum`,t=await L.get(e);return bs(t,"Checksum API").data}import MP from"adm-zip";import OP from"crypto";import{timingSafeEqual as _P}from"crypto";import bf from"fs";import ae from"path";import{fileURLToPath as jP}from"url";import{homedir as Sf}from"os";import{red as FP}from"colorette";var Vt=bf.promises;function wf(n,e){let t=ae.resolve(e),r=ae.resolve(n),o=ae.relative(r,t);if(o.startsWith("..")||ae.isAbsolute(o))throw new Error(`Path traversal detected: ${e}.`)}function al(n){return ae.isAbsolute(n)?n:ae.resolve(process.cwd(),n)}function $P(n){return OP.createHash("sha256").update(n).digest("hex")}async function HP(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=$P(n),o=e.sha256.toLowerCase(),i=Buffer.from(r,"hex"),s=Buffer.from(o,"hex");if(i.length!==s.length||!_P(i,s))throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function Ef(n){pr(n);let e=`${rt.SKILL_API_BASE}/${n}/install?format=zip`,t=await L.getBinary(e),r=await vf(n);return await HP(t,r),t}async function UP(n,e,t){pr(t);let r=new MP(n),o=r.getEntries();try{await Vt.stat(e)}catch{await Vt.mkdir(e,{recursive:!0})}let i=ae.join(e,t);wf(e,i);for(let s of o){let a=ae.join(i,s.entryName);wf(i,a)}r.extractAllTo(i,!0)}async function cl(n){let e=mt[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(mt).join(", ")}`);let t=ae.join(Sf(),e.path.replace("/skills",""));try{return await Vt.access(t),!0}catch{return!1}}function ll(n){let e=mt[n];return ae.join(Sf(),e.path)}function BP(n){let e=mt[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(mt).join(", ")}`);return e}function dl(n,e){let t=BP(e),r="projectPath"in t?t.projectPath:ae.join("."+e,"skills");return ae.join(n,r)}async function WP(n,e,t){pr(e);let r=ae.join(n,e);try{if(await Vt.access(r),t)await Vt.rm(r,{recursive:!0,force:!0});else return console.log(`Skill ${e} exists in ${n}.`),{skillDir:r,shouldSkip:!0}}catch{}return{skillDir:r,shouldSkip:!1}}async function ul(n,e,t){await UP(n,e,t),console.log(`Skill ${t} installed to ${ae.join(e,t)}.`)}async function pl(n,e,t){let r=ae.join(e,t);await Vt.mkdir(r,{recursive:!0});let o=ae.join(r,ae.basename(n));await Vt.copyFile(n,o),console.log(`Skill ${t} installed to ${r}.`)}function Pf(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(FP(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function Tn(n,e,t,r){try{let o=await e(),{shouldSkip:i}=await WP(o,n,r);return i?{success:!0,skipped:!0}:(await t(o),{success:!0})}catch(o){return Pf(n,o,"Installation failed")}}async function ml(n,e){try{pr(n);let t=await e(),r=ae.join(t,n);try{await Vt.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await Vt.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return Pf(n,t,"Removal failed")}}async function Cf(n,e,t,r=!1){return Tn(n,()=>ll(e),o=>ul(t,o,n),r)}async function kf(n,e,t,r=!1){return Tn(n,()=>t,o=>ul(e,o,n),r)}async function If(n,e,t,r,o=!1){return Tn(n,()=>dl(t,r),i=>ul(e,i,n),o)}async function Af(n,e,t,r=!1){return Tn(n,()=>ll(t),o=>pl(e,o,n),r)}async function Df(n,e,t,r,o=!1){return Tn(n,()=>dl(t,r),i=>pl(e,i,n),o)}async function Rf(n,e,t,r=!1){return Tn(n,()=>t,o=>pl(e,o,n),r)}async function fl(n,e){return ml(n,()=>ll(e))}async function Tf(n,e){return ml(n,()=>e)}async function xf(n,e,t){return ml(n,()=>dl(e,t))}function Lf(){let e=ae.dirname(jP(import.meta.url));for(;;){let t=ae.join(e,"SKILL.md");if(bf.existsSync(t))return t;let r=ae.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import Nf from"fs";import{cyan as VP}from"colorette";async function Fo(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await cl(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function $o(){let n=[];for(let e of Object.keys(mt))await cl(e)&&n.push(e);return n}function Ho(n){let e=n.filter(o=>o.success&&!o.skipped).length,t=n.filter(o=>o.skipped).length,r=n.filter(o=>!o.success).length;console.log(),console.log(VP("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function mr(n,e,t){if(!Nf.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!Nf.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function Uo(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?al(n):void 0,resolvedProject:e?al(e):void 0}}async function Ss(n,e,t){let r=[],o=[],i;if(e?i=e:t&&n.agent?o=(await Fo(n.agent)).map(a=>({project:t,agent:a})):t?o=(await $o()).map(a=>({project:t,agent:a})):n.agent?r=await Fo(n.agent):r=await $o(),!i&&r.length===0&&o.length===0)throw new Error("No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location.");return{agents:r,projectAgents:o,customPath:i}}var Ff="deveco";async function JP(n){let e=await ws();if(n.all)return(await il(e)).map(r=>r.enName);{let r=(await sl(n.skill,e)).find(o=>o.enName===n.skill);if(!r)throw new Yr("errorCode",`Skill "${n.skill}" not found`);return[r.enName]}}async function YP(n,e,t,r){let o=[];if(t.customPath){let i=await kf(n,e,t.customPath,r);return o.push(i),o}for(let i of t.agents){let s=await Cf(n,i,e,r);o.push(s)}for(let{project:i,agent:s}of t.projectAgents){let a=await If(n,e,i,s,r);o.push(a)}return o}function KP(n){if(n.all&&n.skill)throw new Yr("errorCode","`--all` and `--skill` cannot be specified together.");if(!n.all&&!n.skill)throw new Yr("errorCode","Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=Uo(n.path,n.project,n.agent);return t&&mr(t,"Project directory",n.force),e&&mr(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}function XP(n,e,t){return!!(e||t||n.path||n.project||n.agent)}function ZP(){return{agents:[Ff],projectAgents:[],customPath:void 0}}async function QP(n,e,t){let r=Ue()&&!XP(n,e,t)?ZP():await Ss(n,e,t);return{skillNames:await JP(n),targets:r}}async function eC(n,e,t,r){let o=[],i=0,s=n.length,a=zP(5),c=n.map(l=>a(()=>tC(l)));for(let l=0;l<n.length;l++){let d=n[l],g=s>1?` (${l+1}/${s})`:"";r.start(`Installing ${d}${g}...`);let v=await c[l];if(!v.success){r.fail(),console.log(Bo(`${d}: Download failed - ${v.error}`)),o.push({success:!1});continue}i+=v.buffer.length,r.stop();let P=await YP(d,v.buffer,e,t);o.push(...P)}return{results:o,diskBytes:i}}async function tC(n){try{let e=await Ef(n);return{name:n,buffer:e,success:!0}}catch(e){let t=e instanceof Error?e.message:"unknown error";return{name:n,error:t,success:!1}}}async function rC(n){let e=new Ke;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=KP(n),{skillNames:o,targets:i}=await QP(n,t,r),{results:s,diskBytes:a}=await eC(o,i,n.force||!1,e);return e.stop(),Ho(s),{diskBytes:a,results:s}}catch(t){throw e.stop(),t}}function $f(n){let e=n.length,t=n.filter(s=>s.success&&!s.skipped).length,r=n.filter(s=>s.skipped).length,o=n.filter(s=>!s.success).length,i=[...new Set(n.filter(s=>!s.success&&typeof s.error=="string").map(s=>nC(s.error)))];return{opTotal:e,opSuccess:t,opFailed:o,opSkipped:r,...i.length>0?{failedErrors:i}:{}}}function nC(n){let e=/^([A-Za-z_][A-Za-z0-9_-]*)/.exec(n.trim());return e?e[1].slice(0,32):"error"}var Yr=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function oC(n){let e=n;return n instanceof Yr?n.code:e.code??e.name??"UnknownError"}function Ps(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 Cs(n,e,t){let r=Date.now(),o=!0,i=null,s={};try{s=await e()}catch(a){throw o=!1,i=oC(a),a}finally{let a={event:b.SkillOperation,subAction:n,args:t,...s};await I.track(a,{duration_ms:Date.now()-r,success:o,error_code:i})}}function iC(n){return Cs("add",async()=>{let{diskBytes:e,results:t}=await rC(n);return{diskUsage:Q(e),...n.skill?{skillName:n.skill}:{},...$f(t)}},Ps("add",n))}function sC(n){let{resolvedPath:e,resolvedProject:t}=Uo(n.path,n.project,n.agent);return t&&mr(t,"Project directory"),e&&mr(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function aC(n,e){let t=new Ke;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:o}=sC(e);t.stop();let i=await cC(e,n,r,o);return t.stop(),Ho(i),i}catch(r){throw t.stop(),r}}function Mf(n,e=""){if(n.length===0)throw new Yr("errorCode",`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function Es(n,e){let t=[];for(let r of e){let o=r.type==="agent"?await fl(n,r.agent):await xf(n,r.project,r.agent);t.push(o)}return t}async function cC(n,e,t,r){if(t)return[await Tf(e,t)];if(r&&n.agent){let a=(await Fo(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return Es(e,a)}if(r){let s=await $o();Mf(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return Es(e,a)}if(n.agent){let a=(await Fo(n.agent)).map(c=>({type:"agent",agent:c}));return Es(e,a)}if(Ue())return[await fl(e,Ff)];let o=await $o();Mf(o,"or use --path for a custom location.");let i=o.map(s=>({type:"agent",agent:s}));return Es(e,i)}var Wo=new qP("skills").description("Manage HarmonyOS skills");Wo.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async n=>{try{await Cs("list",async()=>{let e=new Ke;try{e.start("Fetching skills...");let t=await ws(),r=await il(t);if(r.length===0)return e.stop(),console.log(_f("No skills available.")),{resultTotal:0};e.succeed(`Fetched ${r.length} skills`);for(let o of r)if(n.long){console.log(Of(o.enName)),console.log(jf(o.description));let i=yf(o.enName);i.length>0&&console.log(GP(`Installed for: ${i.join(", ")}`)),console.log()}else console.log(o.enName);return{resultTotal:r.length}}finally{e.stop()}},Ps("list",n))}catch(e){console.error(Bo(e.message)),process.exit(1)}});Wo.command("find <keyword>").description("Search skills by keyword").action(async n=>{try{await Cs("find",async()=>{let e=new Ke;try{e.start("Searching skills...");let t=await ws(),r=await sl(n,t);if(r.length===0)return console.log(_f(`No skills found matching '${n}'.`)),e.stop(),{resultTotal:0,queryLen:n.length,keyword:n};e.succeed(`Found ${r.length} skills.`);for(let o of r)console.log(Of(o.enName)),console.log(jf(o.description)),console.log();return{resultTotal:r.length,queryLen:n.length,keyword:n}}finally{e.stop()}},Ps("find"))}catch(e){console.error(Bo(e.message)),process.exit(1)}});Wo.command("add").description("Install skills to AI agents").option("--all","Install all available skills").option("--agent <agents>","Target agents, comma-separated; Omit to install to all available agents").option("--skill <skill-name>","Name of the skill to install").option("-f, --force","Overwrite an existing skill installation").option("--project <path>","Project root directory for skill installation").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").action(async n=>{try{await iC(n)}catch(e){console.error(Bo(e.message)),process.exit(1)}});Wo.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 Cs("remove",async()=>{let e=await aC(n.skill,n);return{skillName:n.skill,...$f(e)}},Ps("remove",n))}catch(e){console.error(Bo(e.message)),process.exit(1)}});var Hf=Wo;import{Command as lC,InvalidArgumentError as ks}from"commander";import{cyan as hl,red as Bf}from"colorette";import dC from"ora";function uC(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 pC(n){return{event:b.CommandExecuted,args:uC(n),logType:n.crash?"crash":"common",level:n.level??"ALL",bundleName:n.bundleName??"ALL"}}function mC(n){return n instanceof w?n.traceMessage:n instanceof Error?n.code??n.name:"UnknownError"}async function fC(n,e){let t=Date.now(),r=!0,o=null;try{await e()}catch(i){r=!1,o=mC(i),console.error(Bf(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await I.track(n,i).catch(()=>{})}}function hC(n){try{return S.parsePositiveInteger(n,"tail")}catch{throw new ks("`tail` must be a positive integer.")}}function Uf(n,e){try{return S.parseDurationToSeconds(n,e)}catch{throw new ks(`${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 gC(n){try{return S.assertHilogLevel(n),n}catch{throw new ks("`level` must be one of: D, I, W, E, F.")}}function yC(n){try{return S.assertBundleNameStrict(n),n}catch(e){throw new ks(e.message)}}function vC(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.")}async function wC(n,e,t,r,o){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:o})}function bC(n,e,t,r){let o=S.filterLogsByRelativeWindow(n,t,r);return e.tail?S.getLastLines(o,e.tail):o}var SC=new lC("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(Bf(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",gC).option("--bundle-name <bundle-name>","Filter by application bundle name",yC).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",hC).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>Uf(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>Uf(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await fC(pC(n),()=>EC(n))});async function EC(n){let e=dC({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};e.start();try{vC(n);let r=n.from,o=n.to,i=await A.new(),s=new or(i),a=await s.selectDevice(n.device);if(!a)throw new w("No active devices found.","No active devices found.");u(hl(`deviceId: ${a}`)),u(hl(`type: ${n.crash?"Crash logs":"Common logs"}`)),u(hl("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await wC(s,a,n,r,o);t(),n.crash&&c&&(c=bC(c,n,r,o)),c&&console.log(c)}finally{t()}}var Wf=SC;import qo from"path";import qt from"fs";import vl from"process";import Zf from"os";import{Command as OC}from"commander";import{green as Jf,red as gl,cyan as _C,yellow as Yf}from"colorette";import me from"fs-extra";import H from"path";import*as qf from"os";import{fileURLToPath as PC}from"url";var Vf={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"}},CC=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function kC(){let n=import.meta.url,e=PC(n);if(e.includes("dist")){let i=H.dirname(e),s=H.dirname(i);return H.join(s,"templates","application")}let t=H.dirname(e),r=H.dirname(t),o=H.dirname(r);return H.join(o,"templates","application")}function Gf(n,e){me.mkdirSync(e,{recursive:!0});for(let t of me.readdirSync(n,{withFileTypes:!0})){let r=H.join(n,t.name),o=H.join(e,t.name);if(t.isDirectory()){Gf(r,o);continue}me.existsSync(o)||(me.mkdirSync(H.dirname(o),{recursive:!0}),me.copyFileSync(r,o))}}function Vo(n,e){let t=me.readFileSync(n,"utf-8"),r=t;for(let[o,i]of e)r=r.replaceAll(o,i);r!==t&&me.writeFileSync(n,r,"utf-8")}function IC(n){if(Vf[n])return Vf[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function AC(n,e){if(e===22)return;let t=IC(e);t&&(Vo(H.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),Vo(H.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),Vo(H.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function DC(n){return CC.filter(t=>!me.existsSync(H.join(n,t))).length===0}function RC(){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 TC(n){return qf.platform()==="darwin"?H.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):H.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function xC(n,e){let t=TC(e);if(!me.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[o,i]of r){let s=H.join(t,o),a=H.join(n,i);me.existsSync(s)&&(me.mkdirSync(H.dirname(a),{recursive:!0}),me.copyFileSync(s,a))}return!0}function LC(n){let e=RC(),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 o=H.join(n,r);me.mkdirSync(H.dirname(o),{recursive:!0}),me.writeFileSync(o,e)}}function NC(n,e){e&&xC(n,e)||LC(n)}function MC(n){let e=[H.join(n,"gitignore.txt"),H.join(n,"entry","gitignore.txt")];for(let t of e)if(me.existsSync(t)){let r=H.dirname(t);me.renameSync(t,H.join(r,".gitignore"))}}function zf(n,e,t,r,o){let i=kC();if(!me.existsSync(i))throw new Error(`Template directory not found: ${i}`);me.mkdirSync(n,{recursive:!0}),Gf(i,n),MC(n),NC(n,o),Vo(H.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),Vo(H.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),AC(n,r);let s=DC(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function jC(n){if(n.length<1||n.length>200)throw new fe("errorCode",`App name length must be 1-200 characters. Current: ${n.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(n))throw new fe("errorCode","Application name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function Qf(n){if(Zf.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function Kf(n){if(n.length===0)throw new fe("errorCode","Project path cannot be empty.");if(n.length>120)throw new fe("errorCode",`Project path cannot exceed 120 characters (current: ${n.length}).`);let e=Zf.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(n)){let i=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new fe("errorCode",`Project path can only contain ${i}.`)}let r=Qf(n);if(/[\u4e00-\u9fff]/.test(r))throw new fe("errorCode","Project path cannot contain Chinese characters.");if(r.endsWith("."))throw new fe("errorCode","Project path cannot end with a dot (.)")}function FC(n){let e=n,t=qo.parse(n).root;for(;e!==t;){if(qt.existsSync(e))return e;e=qo.dirname(e)}return qt.existsSync(t)?t:null}function Xf(n){let e=FC(n);if(!e)throw new fe("errorCode",`No existing parent directory found for '${n}'. Cannot create project directory.`);try{qt.accessSync(e,qt.constants.W_OK)}catch{throw new fe("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}let t=qo.join(e,`.deveco_write_test_${Date.now()}`);try{qt.writeFileSync(t,"test"),qt.unlinkSync(t)}catch{throw new fe("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}}function $C(n){return`com.example.${n.toLowerCase()}`}function HC(n,e){if(e){let o=Qf(e),i=qo.resolve(o);if(qt.existsSync(i)){if(qt.readdirSync(i).length>0)throw new fe("errorCode",`Directory '${i}' is not empty. Cannot create project here.`)}else Xf(i);return i}let t=vl.cwd(),r=qo.join(t,n);if(qt.existsSync(r))throw new fe("errorCode",`Directory '${r}' already exists. Cannot create project here.`);return Xf(r),r}function UC(n,e){let t=e?.getMaxApiLevel(),r=23;if(n.apiLevel){let o=Number(n.apiLevel);if(!Number.isInteger(o)||o<17)throw new fe("errorCode",`Invalid API version ${n.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(o>t)throw new fe("errorCode",`Invalid API version ${n.apiLevel}. Your SDK supports API version 17-${t}`)}else if(o>r)throw new fe("errorCode",`Invalid API version ${n.apiLevel}. Without DevEco Studio, supported range is API version 17-${r}`);return o}return t!==void 0?t:23}async function BC(){try{return await A.new()}catch(n){console.error(Yf(`DevEco Studio not found: ${n.message}`)),console.log(Yf("Use placeholder API level instead."));return}}var fe=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};async function yl(n,e,t,r){let o={event:b.CommandExecuted,args:["create"],apiLevel:r?.apiLevel??null},i={duration_ms:Date.now()-n,success:e,error_code:t};await I.track(o,i).catch(()=>{})}function WC(n){console.log(`
1299
+ `+Jf("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(Jf("Template integrity check passed."))}var VC=new OC("create").description("Scaffold a new HarmonyOS application project").option("--project-path <path>","Project directory path (default: ./<app-name>)").option("--app-name <name>","Application name").option("--bundle-name <bundle>","Bundle name (auto-derived as com.example.<app-name> if omitted)").option("--api-level <level>","API level (auto-detected from SDK if omitted; minimum: 17)").action(async n=>{let e=Date.now();try{n.appName||(console.error(gl("Error: --app-name is required")),await yl(e,!1,"errorCode",n),vl.exit(1));let t=n.appName;jC(t);let r=n.bundleName||$C(t);S.assertBundleNameStrict(r),n.projectPath&&Kf(n.projectPath);let o=HC(t,n.projectPath);Kf(o),console.log(_C("Initializing project...")),console.log(`Project path: ${o}`),console.log(`App name: ${t}`),console.log(`Bundle name: ${r}`);let i=await BC(),s=UC(n,i);console.log(`API level: ${s}`);let a=i?.devecoStudioPath,c=zf(o,t,r,s,a);WC(c),await yl(e,!0,null,n)}catch(t){let r=t,i=t instanceof fe?t.code:r.code??r.name??"UnknownError";console.error(gl(`
1300
+ Failed to create project.`)),console.error(gl(r.message)),await yl(e,!1,i,n),vl.exit(1)}}),eh=VC;import{Command as XC}from"commander";import{red as ZC,cyan as ch}from"colorette";import qC from"fs";import Is from"path";import{cyan as GC}from"colorette";import*as As from"smol-toml";var xn=qC.promises;async function zC(n){try{let e=await xn.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 JC(n){try{let e=await xn.readFile(n,"utf8");return e.trim()===""?{}:As.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 YC(n,e){let t=Is.dirname(n);await xn.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await xn.writeFile(n,r,"utf8")}async function KC(n,e){let t=Is.dirname(n);await xn.mkdir(t,{recursive:!0});let r=As.stringify(e);await xn.writeFile(n,r,"utf8")}function th(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function rh(n,e,t,r,o){(!n[e]||typeof n[e]!="object")&&(n[e]={});let i=n[e];return t in i&&!o?!1:(i[t]=r,!0)}async function nh(n,e){return n.format==="codex"?JC(e):zC(e)}async function oh(n,e,t){return n.format==="codex"?KC(e,t):YC(e,t)}async function ih(n,e,t=!1){let r=Qt[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Qt).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 o=await nh(r,r.globalConfigPath);if(th(o,r.mcpServersKey,kt)&&!t)return console.log(`MCP server ${kt} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let i=Ii(r,void 0);return rh(o,r.mcpServersKey,kt,i,t),await oh(r,r.globalConfigPath,o),console.log(`MCP server ${kt} configured in ${r.globalConfigPath}.`),{success:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${o.message}`}}}async function wl(n,e,t=!1){let r=Qt[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Qt).join(", ")}`};let o=Is.isAbsolute(r.projectConfigPath)?r.projectConfigPath:Is.join(e,r.projectConfigPath);try{let i=await nh(r,o);if(th(i,r.mcpServersKey,kt)&&!t)return console.log(`MCP server ${kt} already configured in ${o}.`),{success:!0,skipped:!0,configPath:o,agentName:n,installType:"project"};let s=Ii(r,e);return rh(i,r.mcpServersKey,kt,s,t),await oh(r,o,i),console.log(`MCP server ${kt} configured in ${o}.`),{success:!0,configPath:o,agentName:n,installType:"project"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${i.message}`}}}function sh(n){let e=n.filter(o=>o.success&&!o.skipped).length,t=n.filter(o=>o.skipped).length,r=n.filter(o=>!o.success).length;console.log(),console.log(GC("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`);for(let o of n)!o.success&&o.error&&console.error(` - ${o.agentName??"unknown"}: ${o.error}`);r>0&&(process.exitCode=1)}var bl="deveco-cli";async function QC(n,e,t){if(n.customPath)return[await Rf(bl,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>Df(bl,e,s,a,t.force)),...n.agents.map(s=>()=>Af(bl,e,s,t.force))],o=5,i=[];for(let s=0;s<r.length;s+=o){let a=r.slice(s,s+o);i.push(...await Promise.all(a.map(c=>c())))}return i}function ek(n){return[...new Set([...n.agents,...n.projectAgents.map(({agent:e})=>e)])]}async function ah(n,e,t,r){await I.track(n,{duration_ms:Date.now()-e,success:t,error_code:r}).catch(()=>{})}async function tk(n,e,t,r,o){let i={event:b.SkillConfigOperation,subAction:"install",targetType:r?"path":o?"project":"global",agents:ek(n)},s=Date.now();try{let a=await QC(n,e,t),c=a.every(l=>l.success||l.skipped);return await ah(i,s,c,c?null:"SKILL_INSTALL_FAILED"),a}catch(a){let c=a instanceof Error?a.code??a.name:"UnknownError";throw await ah(i,s,!1,c),a}}async function rk(n,e,t){let r=[];for(let{project:o,agent:i}of n.projectAgents){let s=await wl(i,o,t);r.push(s)}for(let o of n.agents){let i=await wl(o,e,t);r.push(i)}return r}async function nk(n,e){let t=[];for(let r of n){if(!Qt[r])continue;let i=await ih(r,process.cwd(),e);t.push(i)}return t}async function ok(n,e,t){let r=["qoder","dsh"];if(t.agent){let l=t.agent.split(",").map(d=>d.trim());for(let d of r)if(l.includes(d))throw new Error(`${d} does not support MCP configuration via DevEco CLI. Use --skill instead, or use other supported agents for MCP.`)}let o=t.force??!1,i=n.projectAgents.filter(l=>!r.includes(l.agent)),s=n.agents.filter(l=>!r.includes(l)),a={...n,projectAgents:i,agents:s},c=e?await rk(a,e,o):await nk(a.agents,o);c.length>0&&(console.log(ch("MCP Configuration:")),sh(c))}async function ik(n,e,t){let r={event:b.Init,subAction:"install",targetType:e?"project":"global",agentName:t.agent},o=Date.now(),i=!0,s=null;try{await ok(n,e,t)}catch(a){throw i=!1,s=a instanceof Error?a.code??a.name:"UnknownError",a}finally{let a={duration_ms:Date.now()-o,success:i,error_code:s};await I.track(r,a)}}async function sk(n){if(n.skill&&n.mcp)throw new Error("Cannot use `--skill` and `--mcp` together. Use `--skill` for skill installation only, or `--mcp` for MCP configuration only.");let{resolvedPath:e,resolvedProject:t}=Uo(n.path,n.project,n.agent);t&&mr(t,"Project directory",n.force),e&&mr(e,"Directory",n.force);let r=await Ss(n,e,t);if(n.mcp){await ik(r,t,n);return}let o=Lf(),i=await tk(r,o,n,e,t);console.log(),i.length>0&&(console.log(ch("Skill Installation:")),Ho(i))}var ak=new XC("init").description("Install the deveco-cli skill or configure the deveco-mcp server into AI agents").option("--agent <agents>","Target agents, comma-separated; installs to all available agents if omitted").option("--project <path>","Project root directory for skill or MCP configuration").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").option("--skill","Install the deveco-cli skill only (same as default behavior; explicit for symmetry with --mcp)").option("--mcp","Configure the deveco-mcp server (syntax checking for .ets and C/C++) only; no skill installation").option("-f, --force","Overwrite existing skill/MCP configuration").action(async n=>{try{await sk(n)}catch(e){console.error(ZC(e instanceof Error?e.message:String(e))),process.exit(1)}}),lh=ak;import{Command as uI}from"commander";import{McpServer as Yk}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Kk}from"@modelcontextprotocol/sdk/server/stdio.js";import*as Zo from"fs";import*as br from"path";import{z as he}from"zod";import Ds from"path";function ph(n,e,t,r,o){if(e.isError)return{};let i=e.content?.[0]?.text??"";if(!i)return{};let s;switch(n){case"check":s=ck(i);break;case"hover":s={hit:Ln(i)!=null};break;case"definition":case"declaration":s=dh(i,t,r,o,!0);break;case"references":s=dk(i);break;case"implementation":s=dh(i,t,r,o,!1);break;case"documentSymbol":s=uk(i);break;case"callHierarchy":s=pk(i,t,r,o);break;case"workspaceSymbol":s=mk(i,t);break;default:s={}}return s}function mh(n){let e=Array.isArray(n.files)?n.files[0]:n.file;return typeof e!="string"||!e?void 0:Ds.extname(e).toLowerCase().replace(/^\./,"")||void 0}function Ln(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 ck(n){let e={total:0,error:0,warn:0,info:0},t=new Set,r=" => Diagnostic: ";for(let i of n.split(`
1301
+ `)){let s=i.indexOf(r);if(s<0)continue;let a;try{a=JSON.parse(i.slice(s+r.length))}catch{continue}if(Array.isArray(a))for(let c of a)c&&typeof c=="object"&&lk(c,e,t)}let o={diagTotal:e.total,diagError:e.error,diagWarn:e.warn,diagInfo:e.info};return t.size>0&&(o.rules=[...t]),o}function lk(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 dk(n){let e=Ln(n),t=Array.isArray(e)?e:[],r=new Set;for(let o of t){let i=o?.uri;typeof i=="string"&&r.add(i)}return{refTotal:t.length,fileCount:r.size}}function dh(n,e,t,r,o){let i=Ln(n);if(i==null)return{found:!1};let s=Array.isArray(i)?i:[i],a=s[0]?.uri;return o?{found:!0,sameFile:fk(a,e),sourceType:hh(a,t,r)}:{implTotal:s.length,found:!0}}function uk(n){let e=Ln(n),t=Array.isArray(e)?e:[],r=0,o=new Map,i=s=>{for(let a of s){if(!a||typeof a!="object")continue;r++;let c=a.kind;typeof c=="number"&&o.set(c,(o.get(c)??0)+1);let l=a.children;Array.isArray(l)&&i(l)}};return i(t),{symbolTotal:r,kindDist:Sl(o)}}function pk(n,e,t,r){let i=Ln(n)?.calls,s=Array.isArray(i)?i:[],a=e.direction,c=new Map;for(let l of s){if(!l||typeof l!="object")continue;let g=(a==="incoming"?l.from:l.to)?.uri,v=hh(g,t,r);c.set(v,(c.get(v)??0)+1)}return{callsTotal:s.length,calleeSrcDist:Sl(c)}}function mk(n,e){let t=Ln(n),r=Array.isArray(t)?t:[],o=new Map,i=0;for(let c of r){if(!c||typeof c!="object")continue;let l=c.kind;typeof l=="number"&&o.set(l,(o.get(l)??0)+1);let d=c.tags;(Array.isArray(d)&&d.includes(1)||c.deprecated===!0)&&i++}let s={resultTotal:r.length,kindDist:Sl(o),deprecatedHit:i},a=e.query;return typeof a=="string"&&(s.queryLen=a.length),s}function fh(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 hh(n,e,t){let r=fh(n);return r?e&&uh(r,e)?"user_project":t&&uh(r,t)?"sdk":"system":"unknown"}function fk(n,e){let t=fh(n),r=e.file;return!t||typeof r!="string"?!1:Rs(t)===Rs(r)}function Rs(n){try{return Ds.resolve(n).replace(/\\/g,"/").toLowerCase()}catch{return n.replace(/\\/g,"/").toLowerCase()}}function uh(n,e){let t=Ds.relative(Rs(e),Rs(n));return t!==""&&!t.startsWith("..")&&!Ds.isAbsolute(t)}function Sl(n){let e={};for(let[t,r]of n)e[String(t)]=r;return e}var Ts=class{constructor(e,t,r,o){this.telemetry=e;this.getAceServerPid=t;this.getProjectPath=r;this.getSdkPath=o}telemetry;getAceServerPid;getProjectPath;getSdkPath;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 o=>this.invokeTool(t.name,o,r)))}async invokeTool(e,t,r){if(h.info(`[telemetry] mcp tool call: ${e}`),!this.telemetry)return r(t);let o=Q(process.memoryUsage().rss),i=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,o,i,a,c)}return l}async trackToolCall(e,t,r,o,i,s,a,c){if(!this.telemetry)return;let l=r?.isError===!0,d=r&&!l?ph(e,r,t,this.getProjectPath?.()??"",this.getSdkPath?.()??""):{},g=l?!1:a,v=l&&r?hk(r):c,P={event:b.McpToolCall,subAction:e,mcpMemory:i,lspMemory:s,fileExt:mh(t),...d};typeof t.direction=="string"&&(P.direction=t.direction),await this.telemetry.track(P,{duration_ms:Date.now()-o,success:g,error_code:v})}async resolveLspMemory(){let e=this.getAceServerPid?.()??null;if(e===null)return"unknown";let t=await je(e);return t===null?"unknown":Q(Number(t)*1024)}};function hk(n){let e=n.content.map(t=>t.text).join(`
1302
+ `);return/not ready|未初始化|初始中|稍后重试|please retry|retry \d+s|syncing|initializing|初始化失败|C\+\+ project initialization failed/i.test(e)?"NotReady":/No project detected|PROJECT_PATH|工程路径/i.test(e)?"NoProject":/Missing.*parameter|invalid parameters|Unknown feature|must be|不能同时|Must specify|无效/i.test(e)?"BadRequest":/Too many files|Maximum allowed/i.test(e)?"TooManyFiles":/不存在|does not exist|not exist|not found|No valid|不是 \.ets|not a supported|Unsupported/i.test(e)?"InvalidFile":"ToolError"}function El(n,e,t,r){return new Ts(n,e,t,r)}import*as Xe from"fs";import*as ke from"path";import{z as kl}from"zod";function gh(n){return"method"in n&&!("id"in n)}import{spawn as gk}from"child_process";import{EventEmitter as yk}from"events";import*as Nn from"fs";import*as yh from"path";var vk=50*1024*1024,fr=class extends yk{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;get pid(){return this.process?.pid??null}ensureDirectories(){let t=yh.join(this.config.logPath,"lspLog");return Nn.existsSync(t)||Nn.mkdirSync(t,{recursive:!0}),Nn.existsSync(this.config.indexingDataLocation)||Nn.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let r=this.ensureDirectories();f.info(`[LspClient] serverMaxSize=${t}MB`);let o=z(r),i=["--expose-gc",`--max-old-space-size=${t}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${o}`,this.config.serverPath,"--stdio",`--logger-path=${o}`,"--logger-level=TRACE"];f.info(`[LspClient] Starting process: node ${i.join(" ")}`);let s=process.execPath??"node";f.info(`[LspClient] nodePath: ${s}`),this.process=gk(s,i,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0}),this.bindProcessEvents(),await new Promise(a=>setTimeout(a,500)),f.info("[LspClient] start lsp process success")}attachProcess(t,r){if(this.process)throw new Error("[LspClient] process already attached");this.process=t,this.bindProcessEvents(r?.stderrAsError??!0),f.info("[LspClient] attached to external process")}bindProcessEvents(t=!0){this.process&&(this.process.stdout?.on("data",r=>{this.handleData(r)}),this.process.stderr?.on("data",r=>{let o=r.toString("utf8").trim();f.error(`[LspClient] stderr: ${o}`),!this.isClosing&&t&&this.emit("error",new Error(`[LspClient] stderr: ${o}`))}),this.process.on("exit",r=>{f.info(`[LSP EXIT] code=${r}`),this.isClosing||this.emit("error",new Error(`LSP process exited with code ${r}`))}))}sendRaw(t,r){if(!this.process?.stdin?.writable){f.warn("[LspClient] Cannot send message, stdin not writable");return}f.info(`[LspClient] send message: ${r}`);let o=this.buildLspMessage(t);this.process.stdin.write(o,"utf8")}send(t,r,o){let i={jsonrpc:"2.0",method:t,params:r};o!==void 0&&(i.id=o),this.sendRaw(JSON.stringify(i),t)}sendNotification(t,r){this.sendRaw(JSON.stringify({jsonrpc:"2.0",method:t,params:r}),t)}sendRequest(t,r,o){this.sendRaw(JSON.stringify({jsonrpc:"2.0",id:o,method:t,params:r}),t)}buildLspMessage(t){return`Content-Length: ${Buffer.from(t,"utf8").length}\r
1285
1303
  \r
1286
1304
  ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this.buffer.indexOf(`\r
1287
1305
  \r
1288
- `);if(r===-1)break;let o=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!o){u.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>LP){u.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){u.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${l.length}, restLen=${d.rest.length}`),this.emit("message",d.json),this.buffer=Buffer.concat([Buffer.from(d.rest,"utf8"),this.buffer.slice(c)]);continue}this.emit("message",l),this.buffer=this.buffer.slice(c)}}waitForExitOrTimeout(t){let 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(){this.isClosing=!0;let t=this.process;if(!t)return;if(this.process=null,t.exitCode===null&&t.signalCode===null)try{t.kill()}catch{}}};var an=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){u.info(`[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));u.info(`[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(()=>{u.info(`[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 ls=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var Pr=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 R(n){return typeof n=="object"&&n!==null}var um=20*1e3,NP=30*1e3,ds=class{client;nextRequestId=1;stopOnce=null;callbacks=new Pr;requestCallbacks=new an;diagnosticMap=new Map;initProgressReset=null;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()=>{u.info("[ClientMessageHandle] Sending shutdown request"),this.client.sendRequest(y.SHUTDOWN,null,this.nextRequestId++),u.info("[ClientMessageHandle] Sending exit notification"),this.client.sendNotification(y.EXIT,null),u.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),u.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(y.BROADCAST),this.callbacks.register(y.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(y.BROADCAST,e)}async sendInitialize(e){let t=this.nextRequestId++,r=this.requestCallbacks.registerPending(t,y.INITIALIZE,Ze);return this.client.sendRequest(y.INITIALIZE,e,t),r}sendInitializeResettable(e,t){let r=this.nextRequestId++,i=this.requestCallbacks.registerPending(r,y.INITIALIZE,0);return this.client.sendRequest(y.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(y.INITIALIZED,{})}sendDidOpen(e){let t=e.textDocument.uri;this.diagnosticMap.has(t)||(this.diagnosticMap.set(t,new ls(t)),this.registerDiagnosticTimeout(t)),this.client.sendNotification(y.DID_OPEN,e)}sendDidChange(e){let t=e.textDocument.uri,r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t)),this.client.sendNotification(y.DID_CHANGE,e)}closeFile(e){this.cleanupDiagnosticState(e.textDocument.uri),this.client.sendNotification(y.DID_CLOSE,e)}sendLspRequest(e,t,r=NP){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(y.WORKSPACE_DID_CHANGE_WATCHED_FILES,{changes:e})}sendDidChangeConfiguration(e){this.client.sendNotification(y.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);u.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):u.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)switch(this.initProgressReset?.(),t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.handleProgress(e.params);break;case y.WINDOW_SHOW_MESSAGE:u.info(`[LSP] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:u.info(`[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){R(e)&&this.broadcastToClients({jsonrpc:T,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,um,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${um}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,r){let i={uri:e,diagnostics:t,...r?{errorMessage:r}:{}};this.requestCallbacks.emit(e,y.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:T,method:y.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var us=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)){u.info(`[LegacyDiagnostic] addMessage: duplicate message=${r}`);return}this.uniqueMessages.add(r),this.messages.push(new Jc(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)}},Jc=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var OP={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"},MP={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing"},x={...OP,...MP},cn={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"},pm=new Set([1e3,2e3,3e3,3001]);function _P(n){if(!R(n))return!1;let e=n.textDocument;return R(e)&&typeof e.uri=="string"}function jP(n){return R(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function FP(n){return R(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 ps=class n{client;isInitialized=!1;stopOnce=null;callbacks=new Pr;requestCallbacks=new an;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()=>{u.info("[LegacyClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:x.EXIT,params:{}}),cn.EXIT),u.info("[LegacyClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),u.info("[LegacyClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(x.BROADCAST),this.callbacks.register(x.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(x.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(x.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(x.INDEXING_PROGRESS_UPDATE,e)}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}sendInitialize(e,t){this.client.send("initialize",e,t)}sendInitialized(e){this.client.sendRaw(JSON.stringify({jsonrpc:T,method:x.INITIALIZED,params:{editors:e}}),cn.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:T,id:0,result:{}}),cn.EMPTY)}sendAsyncRequest(e,t,r,i){if(!R(t)){u.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!_P(t)){u.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof r!="number"){u.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(r)}`);return}let o=t.textDocument.uri,s=lt(o);t.textDocument.uri=s,delete t.requestId;let a=i??e;u.info(`[LSP] sendAsyncRequest ${a}, filePath: ${o}`),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:e,params:{params:t,requestId:r}}),a)}onDidChangeWatchedFiles(e){if(u.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let r of e){if(!jP(r)){u.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:T,method:x.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),x.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!R(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){u.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;u.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:x.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),cn.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let i=lt(t);e.textDocument.uri=i,u.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new us(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,x.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:x.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),cn.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=lt(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,x.PUBLISH_DIAGNOSTICS)),u.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:x.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),cn.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=lt(e);u.info(`[LSP] didClose, uri: ${r}`);let i=this.diagnosticMap.get(r);if(!t&&(!i||i.isFromEditor)){u.info(`[LSP] closeFile skip, !diagnostic: ${!i}, isFromEditor: ${i?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:x.DID_CLOSE,params:{textDocument:{uri:r}}}),cn.DID_CLOSE)}getDiagnosticMessage(e){let t=lt(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);u.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,x.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:T,method:x.ARKTS_ERROR,params:{message:e.message}})}handleLspMessage(e){let t=e.method;t!==void 0&&(!this.isInitialized&&this.handlePreInitMessage(t,e)||this.handlePostInitMessage(t,e))}handlePreInitMessage(e,t){switch(e){case x.MODULE_INIT_FINISH:return u.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(x.MODULE_INIT_FINISH),this.callbacks.unregister(x.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case x.INDEXING_PROGRESS_UPDATE:return u.info(`[LSP] onIndexingProgressUpdate: ${FP(t.params)}`),this.callbacks.invoke(x.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case x.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case x.ON_PACKAGE_CHANGE_FINISH:u.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case x.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case x.ON_ASYNC_HOVER:this.handleAsyncResponse(t,x.HOVER);return;case x.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,x.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case x.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,x.REFERENCES);return;default:u.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){u.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;R(t)&&R(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){u.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,r={jsonrpc:T,method:x.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){u.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(r);return}if(!(t.length>0&&t[0]===!0)){u.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(r);return}u.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){u.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let r=e.params;if(!R(r)){u.warn("[LSP] aceProject/onAsyncHover message invalid");return}let i=r.requestId;if(typeof i!="number"){u.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(i,t,r)}handleForceOpenFile(e){if(!e){u.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,x.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){u.info("[LSP] publishDiagnostics uri is null");return}let r=e.version??-1;if(r===-1)return;let i=this.diagnosticMap.get(t);if(!i){u.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(pm)&&this.finalizeDiagnostic(t,x.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 Yc from"path";import*as ws from"path";var fs=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var ms=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var hs=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var gs=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var ys=class{typeSetting=new hs;parameterNames=new gs};var vs=class{constructor(e,t,r,i){this.rootUri=e;this.lspServerWorkspacePath=V(ws.dirname(t)),this.indexingDataLocation=V(i),this.loggerPath=V(ws.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new fs;gutterIconsSetting=new ms;inlayHintsSetting=new ys;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as fm from"path";var Di=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(V(fm.join(e,"src","main","resources")))}};var $P="OS",Cr=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${$P}`;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 Di(e)):this.buildProfileParam=new Di}toString(){return JSON.stringify(this)}};var kr=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as Re from"path";import*as Dr from"fs";var bs=class{modulePath;dependencies={};dynamicDependencies={}};var Un=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 Ir=class{constructor(e,t,r){this.projectPath=e;this.moduleName=t;this.modulePath=r}projectPath;moduleName;modulePath;dependencies=[];devDependencies=[];dynamicDependencies=[];finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[]};import*as jt from"path";import*as Ss from"fs";var Ar=class{name="";version="";storePath="";dependencyPath="";path=""};var _={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:Ce.OH_PACKAGE_JSON5},Ri=`${_.HVIGOR_CACHE}/${_.DEPENDENCY}`,Wn=`${_.DEPENDENCY}${_.JSON5}`,MU=Ce.SYNC_OUTPUT_PATH;var Ti=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=jt.join(this.dependencyPath,_.OH_PACKAGE_JSON5),r=Ve(t);r&&(this.dependencies=this.getDependencyList(r,_.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(r,_.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(r,_.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let r=[];if(!R(e))return r;let i=e[t];if(!R(i))return r;for(let[o,s]of Object.entries(i)){if(typeof s!="string"){u.error(`${o} package dependency value is not String ${t}`);continue}let a=new Ar;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=jt.normalize(jt.join(this.modulePath,_.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)),jt.isAbsolute(s)){r.dependencyPath=o;return}i||(o=jt.resolve(this.modulePath,s)),Ss.existsSync(o)&&Ss.statSync(o).isDirectory()&&(r.dependencyPath=o)}catch(o){u.error("parser dependency path is invalid",o)}}};import*as Bn from"fs";import*as ln from"path";import HP from"json5";var Es=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 ln.join(this.projectPath,_.OH_MODULES_PATH,_.OHPM_PATH,_.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(!Bn.existsSync(e))return u.error("lock file does not exist"),this.clearDependencies(),null;try{let t=Bn.statSync(e);if(t.size>n.MAX_LOCK_FILE_SIZE)return u.error(`lock file is too large (${t.size} bytes), read aborted`),this.clearDependencies(),null}catch(t){return u.error(`Failed to stat lock file: ${t instanceof Error?t.message:String(t)}`),this.clearDependencies(),null}try{let t=Bn.readFileSync(e,"utf8"),r=HP.parse(t);return r?n.checkObjectDepth(r,n.MAX_JSON_DEPTH)?r:(u.error("lock.json5 nesting depth exceeds limit"),this.clearDependencies(),null):(u.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return u.error(`Error parsing lock.json5: ${t instanceof Error?t.message:String(t)}`),this.clearDependencies(),null}}validateLockFile(e){if(!R(e))return u.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return u.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let r=e.packages;return r?{valid:!0,modules:t,packages:r}:(u.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,r){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,_.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,_.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,_.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!R(e))return t;let r=0;for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;let o=e[i];if(!R(o)){u.error(`${i} value is not json object`);continue}if(++r>n.MAX_KEYS_PER_OBJECT){u.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(!R(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){u.warn("lock.json5 modules object exceeds key limit, truncating");break}let s=e[o];if(R(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(!R(i))return u.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!R(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){u.warn("lock.json5 dependencies object exceeds key limit, truncating");break}let l=s[c];if(!R(l))continue;let d=typeof l.specifier=="string"?l.specifier:"",g=typeof l.version=="string"?l.version:"",v=new Ar;v.name=c,v.version=g.startsWith(n.FILE_DEPENDENCY_PREFIX)?g.substring(n.FILE_DEPENDENCY_PREFIX.length):g,this.parseDependencyPath(v,r,c,d,g);let D=`${c}@${g}`;this.storePathMap.has(D)&&(v.storePath=this.storePathMap.get(D)||""),o.push(v)}return o}parseDependencyPath(e,t,r,i,o){let s=ln.resolve(this.projectPath,ln.join(t,_.OH_MODULES_PATH,r));try{let a=o.startsWith(n.FILE_DEPENDENCY_PREFIX)?o.substring(n.FILE_DEPENDENCY_PREFIX.length):o,c=ln.isAbsolute(a)?a:ln.resolve(this.projectPath,a);Bn.existsSync(c)?(e.path=i,e.dependencyPath=this.fileNameForOhpm.test(o)?s:c):e.dependencyPath=s}catch(a){u.error("Invalid dependency path in lock.json5, msg:",a instanceof Error?a.message:String(a))}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function mm(n){return R(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var Vn=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new It(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=Re.join(t,Ri),i=Re.join(r,Wn);if(!Dr.existsSync(r)||!Dr.existsSync(i)){let c="Dependency map or JSON not found";return u.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let o=new Ir(this.projectPath,".",this.projectPath);this.parseProjectDependencies(r,o),this.parseLockJson(o);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return u.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:c}}let a=Date.now();for(let c=0;c<s.length;c++){let l=s[c];if(mm(l)){try{S.assertModuleName(l.name)}catch{u.warn(`[Parser] Skipping module with invalid name: ${l.name}`);continue}this.parseSingleModule(l,r,o,e),(c+1)%100===0&&u.info(`[Parser] getAllDependencyMap progress: ${c+1}/${s.length} (${Date.now()-a}ms)`)}}return u.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-a}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],r=this.projectPath,i=Re.join(r,Ri),o=Re.join(i,Wn);if(!Dr.existsSync(i)||!Dr.existsSync(o))return u.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 Ir(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return u.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let l of c){if(!mm(l))continue;let d=l.name;try{S.assertModuleName(d)}catch{u.warn(`[Parser] Skipping module with invalid name: ${d}`);continue}if(s&&!s.has(d))continue;let g=Re.resolve(this.projectPath,l.srcPath),v=Re.join(i,d),D=V(g),He=this.buildModuleDependencies(d,D,v,a);He.moduleName=d,t.push(He)}return t}parseSingleModule(e,t,r,i){let o=e.name,s=Re.resolve(this.projectPath,e.srcPath),a=Re.join(t,o),c=V(s),l=new Cr(c),d=this.buildModuleDependencies(o,c,a,r);this.parseModuleJson5(c,l);let g=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=o,l.moduleType=o,l.packageName=o,l.moduleDependencies=d,l.moduleJsonParam=new kr(g),i.push(l)}buildModuleDependencies(e,t,r,i){let o=new Ir(this.projectPath,e,t);Ti.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 bs;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 Un(o);for(let o of e.finalDynamicDependencies)i[o.name]=new Un(o);t.dependencies=r,t.dynamicDependencies=i}parseProjectDependencies(e,t){let r=Re.join(e,_.OH_PACKAGE_JSON5);if(!Dr.existsSync(r))return;Ti.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 Es(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=Re.join(e,"src","main","module.json5"),i=Ve(r);if(!R(i)||!R(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(R(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)R(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=Re.join(e,"src","main","resources","base","profile","main_pages.json"),r=Ve(t);return!R(r)||!Array.isArray(r.src)?[]:r.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!R(t)||!R(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=Re.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=Ve(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!R(t)||!R(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!R(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=Re.join(this.projectPath,"build-profile.json5");this.buildProfileCache=Ve(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!R(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 Ps=class{constructor(e=[]){this.valueSet=e}valueSet};var Rr=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var hm=(C=>(C[C.File=1]="File",C[C.Module=2]="Module",C[C.Namespace=3]="Namespace",C[C.Package=4]="Package",C[C.Class=5]="Class",C[C.Method=6]="Method",C[C.Property=7]="Property",C[C.Field=8]="Field",C[C.Constructor=9]="Constructor",C[C.Enum=10]="Enum",C[C.Interface=11]="Interface",C[C.Function=12]="Function",C[C.Variable=13]="Variable",C[C.Constant=14]="Constant",C[C.String=15]="String",C[C.Number=16]="Number",C[C.Boolean=17]="Boolean",C[C.Array=18]="Array",C[C.Object=19]="Object",C[C.Key=20]="Key",C[C.Null=21]="Null",C[C.EnumMember=22]="EnumMember",C[C.Struct=23]="Struct",C[C.Event=24]="Event",C[C.Operator=25]="Operator",C[C.TypeParameter=26]="TypeParameter",C))(hm||{}),gm=()=>Object.values(hm).filter(n=>typeof n=="number");var Cs=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var ks=class{applyEdit=!0;workspaceEdit=new Cs;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Ps(gm());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Rr;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Is=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var As=class{constructor(e=[]){this.valueSet=e}valueSet};var Ds=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var ym=(k=>(k[k.Text=1]="Text",k[k.Method=2]="Method",k[k.Function=3]="Function",k[k.Constructor=4]="Constructor",k[k.Field=5]="Field",k[k.Variable=6]="Variable",k[k.Class=7]="Class",k[k.Interface=8]="Interface",k[k.Module=9]="Module",k[k.Property=10]="Property",k[k.Unit=11]="Unit",k[k.Value=12]="Value",k[k.Enum=13]="Enum",k[k.Keyword=14]="Keyword",k[k.Snippet=15]="Snippet",k[k.Color=16]="Color",k[k.File=17]="File",k[k.Reference=18]="Reference",k[k.Folder=19]="Folder",k[k.EnumMember=20]="EnumMember",k[k.Constant=21]="Constant",k[k.Struct=22]="Struct",k[k.Event=23]="Event",k[k.Operator=24]="Operator",k[k.TypeParameter=25]="TypeParameter",k))(ym||{}),vm=()=>Object.values(ym).filter(n=>typeof n=="number");var Rs=class{completionItemKind=new As(vm());completionItem=new Ds;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Ts=class{synchronization=new Is;completion=new Rs;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 Rr;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var xs=class{workspace=new ks;textDocument=new Ts;notebookDocument=null;window=null;general=null;experimental=null};var Ls=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var Ns=class{constructor(e,t,r,i,o,s=!0){this.sdkPath=e;this.rootUri=r;this.nodeMaxOldSpaceSize=o;this.useStandardProtocol=s;this.serverPath=Jr(t,this.useStandardProtocol),this.logPath=Vd(),this.indexLogPath=i||this.logPath;let a={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath};this.messageHandle=this.useStandardProtocol?new ds(a):new ps(a),this.messageHandle.setBroadcastToClients(c=>this.onLspMessage(c))}sdkPath;rootUri;nodeMaxOldSpaceSize;useStandardProtocol;messageHandle;get stdHandle(){return this.messageHandle}get legacyHandle(){return this.messageHandle}get lspPid(){return this.messageHandle.lspPid}onAsyncOpenFile(e){this.legacyHandle.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.legacyHandle.closeFile(e,t)}serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}async start(e,t){let r=!1;try{u.info(`serverPath: ${this.serverPath}`),u.info(`rootUri: ${this.rootUri}`),u.info(`sdkPath: ${this.sdkPath}`),u.info(`logPath: ${this.logPath}`);let i=lt(this.rootUri),o=new vs(i,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new Vn(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),o.modules=s;let l=vo(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new Ls(i,o,new xs),this.useStandardProtocol){let d=this.messageHandle;await d.sendInitializeResettable(this.currentParams,Ze),u.info("[LSP] initialize response received"),d.broadcastToClients({jsonrpc:T,method:y.ARKTS_INDEXING_PROGRESS,params:{}}),d.sendInitialized()}else await this.startLegacy(this.currentParams,e);r=!0}catch(i){this.lastStartErrorMessage=i instanceof Error?i.message:String(i),u.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(r)}async startLegacy(e,t){let r=this.messageHandle;r.sendInitialize(e,1),r.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:T,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((i,o)=>{r.onIndexingProgressUpdate(o),r.onInitializationCompleted(i)},"LSP initialization",Ze),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){u.info(`[LSP] registerDiagnosticCallback uri='${e}', useStandardProtocol=${this.useStandardProtocol}`),this.messageHandle.registerRequestCallback(e,(t,r)=>{let i=R(r)?r:{};u.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let o={jsonrpc:T,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(y.HOVER,e)}async definition(e){return this.stdHandle.sendLspRequest(y.DEFINITION,e)}async references(e){return this.stdHandle.sendLspRequest(y.REFERENCES,e)}async completion(e){return this.stdHandle.sendLspRequest(y.COMPLETION,e)}async documentSymbol(e){return this.stdHandle.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async diagnostic(e){return this.stdHandle.sendLspRequest(y.DIAGNOSTIC,e,120*1e3)}async sendFeatureRequest(e,t){return this.stdHandle.sendLspRequest(e,t)}reloadDependenciesOnly(e){let t=e?.fullReload??!1,r=new Vn(this.rootUri,this.sdkPath),i=this.getModuleModelsByName();if(t){u.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}),u.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 u.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];u.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}),u.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}sendDidChangeConfiguration(e){this.stdHandle.sendDidChangeConfiguration(e)}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),r=new Map(this.lastDepsOnlyForDiff.map(i=>[i.moduleName??"",i]));for(let i of e){let o=i.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(o,t,r),c=i.dependencies??{},l=i.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(d,g)=>{(i.dependencies??={})[d]=this.makeDeleteEntry(d,g)}),this.markAddAndDeleteInDeps(a,l,(d,g)=>{(i.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,g)})}}getOldDepsForModule(e,t,r){let i=t.get(e),o=i?.moduleDependencies?.dependencies??{},s=i?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(o).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(o=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:o,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let i of Object.keys(t))i in e||(t[i].type="add");for(let i of Object.keys(e))i in t||r(i,e[i])}makeDeleteEntry(e,t){return new Un({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Cr(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new kr([]),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=tr(Yc.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=tr(Yc.join(t,"default/openharmony/ets/api")),o=tr(Yc.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=i,s.hosSdkPath=o}sendRequest(e){switch(e.method){case y.HOVER:this.stdHandle.sendLspRequest(y.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:T,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:T,id:e.id,error:{code:-32603,message:t.message}}));break;case y.DEFINITION:this.stdHandle.sendLspRequest(y.DEFINITION,e.params).then(t=>this.onLspMessage({jsonrpc:T,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:T,id:e.id,error:{code:-32603,message:t.message}}));break;case y.REFERENCES:this.stdHandle.sendLspRequest(y.REFERENCES,e.params).then(t=>this.onLspMessage({jsonrpc:T,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:T,id:e.id,error:{code:-32603,message:t.message}}));break;default:u.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!lm(e)){u.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case y.DID_OPEN:this.handleDidOpenNotification(e);break;case y.DID_CHANGE:this.handleDidChangeNotification(e);break;case y.DID_CLOSE:this.handleDidCloseNotification(e);break;case y.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;case y.DID_CREATE_FILES:this.handleDidCreateFiles(e);break;case y.DID_DELETE_FILES:this.handleDidDeleteFiles(e);break;default:u.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){u.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"){u.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"){u.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(y.DID_CREATE_FILES,t)}handleDidDeleteFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(y.DID_DELETE_FILES,t)}async dispose(){await this.messageHandle.stop()}};import*as Ft from"fs";import*as Me from"path";import{createHash as WP}from"crypto";import{EventEmitter as BP}from"events";var Os=class extends BP{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r}projectRoot;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),u.info(`[ConfigFileWatcher] Stopped watching: ${i}`));u.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!Ft.existsSync(t)){u.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Ft.watch(t,r=>{r==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",r=>{u.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${r.message}`)}),u.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(r){u.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=Me.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=Me.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=Me.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=Me.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){u.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,o);this.lastModules=o,this.lastModulesSnapshot=s,u.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=Ve(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 u.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=Me.join(this.projectRoot,_.OH_PACKAGE_JSON5);Ft.existsSync(r)&&t.push(r);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=Me.resolve(this.projectRoot,o.srcPath),a=Me.join(s,_.OH_PACKAGE_JSON5);Ft.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Me.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Ft.readFileSync(t,"utf-8");return WP("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=Ft.watch(t,o=>{o==="change"&&this.onFileChanged(t)});i.on("error",o=>{u.error(`[ConfigFileWatcher] Watch error for ${t}: ${o.message}`)}),this.watchers.set(t,i)}catch(r){u.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){u.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===o){u.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,o),u.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:Me.basename(t),relativePath:Me.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(),u.info("[ConfigFileWatcher] All watchers stopped")}};import*as dn from"fs";import*as ut from"path";import{createHash as VP}from"crypto";import{EventEmitter as qP}from"events";var Ms=class extends qP{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=ut.join(t,Ri)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!dn.existsSync(this.depMapDir)){u.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=dn.watch(this.depMapDir,{recursive:!0},(t,r)=>this.onDirEvent(t,r)),this.dirWatcher.on("error",t=>{u.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){u.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),u.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return V(ut.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let i=r.replace(/\\/g,"/"),o;if(i===_.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===Wn)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=ut.join(this.depMapDir,r);dn.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,u.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=ut.join(this.depMapDir,_.OH_PACKAGE_JSON5),r=ut.join(this.depMapDir,Wn),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...i.map(s=>({path:(S.assertModuleName(s.name),ut.join(this.depMapDir,s.name,_.OH_PACKAGE_JSON5)),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!dn.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),u.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=ut.join(this.depMapDir,Wn);try{let r=Ve(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 u.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){u.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(u.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${r.length}`),t.includes("root-oh-package")){u.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){u.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 V(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=(S.assertModuleName(a.name),ut.join(this.depMapDir,a.name,_.OH_PACKAGE_JSON5));this.contentHashes.delete(this.canonicalPath(l)),u.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),u.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=(S.assertModuleName(o),ut.join(this.depMapDir,o,_.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})`);u.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=dn.readFileSync(t,"utf-8");return VP("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as GP}from"child_process";var zP=["install","--all"];async function JP(n,e,t,r){return new Promise(i=>{let o=GP(n,[e,...zP],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";o.stdout?.on("data",c=>{s+=c.toString()}),o.stderr?.on("data",c=>{a+=c.toString()}),o.on("close",c=>{let l=[s,a].filter(Boolean).join(`
1289
- `);i({exitCode:c??-1,output:l})}),o.on("error",c=>{let l=[s,a].filter(Boolean).join(`
1290
- `);i({exitCode:-1,output:l+`
1291
- `+c.message})})})}function YP(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>u.info("[ohpm] %s",e))}async function wm(n,e,t,r){try{if(!t)return u.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;if(!r)return u.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:i,output:o}=await JP(t,r,n,e);return YP(o),i===0?(u.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(u.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",i),u.error("ohpm \u8F93\u51FA: %s",o),!1)}catch(i){return u.error("ohpm \u5B89\u88C5\u5F02\u5E38",i),!1}}var bm={UNINITIALIZED:-32099,UNKNOWN:-32e3},xi=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,bm.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,bm.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var Tr=class{config;lspProxy=null;configWatcher=null;depMapWatcher=null;isInitialized=!1;lastEditorOpenFiles=[];onMessage=()=>{};onConfigChanged=null;disposeOnce=null;get aceServerPid(){return this.lspProxy?.lspPid??null}constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}async start(e=[]){this.lastEditorOpenFiles=e;try{this.startConfigWatcher(),this.startLspProxy(e)}catch(t){throw u.error(`[ArktsLspManager] start() synchronous failure: ${t instanceof Error?t.message:String(t)}`),t}}sendNotification(e){if(!this.lspProxy){u.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){u.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){if(u.info("[ArktsLspManager] Received arkts/syncProject"),!e||!t)return u.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let a=s?.skipHvigorSync===!0,c=await fo(e,async()=>await wm(e,t,r??"",i??"")?a?(u.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await Yd(e,t,r??"",o??"")?(u.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(u.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(u.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return c.acquired?c.result:(u.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){u.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){u.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){u.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new Ns(this.config.sdkPath,this.config.arktsLangServerPath,this.config.workspaceRoot,this.config.indexLogPath,this.config.nodeMaxOldSpaceSize,this.config.useStandardProtocol);t.setOnMessage(r=>this.handleLspMessage(r)),t.start(e,r=>this.handleLspInitialized(r)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)u.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:T,method:y.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();u.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?xi.uninitialized(t):xi.unknown();this.onMessage({jsonrpc:T,method:y.ARKTS_INITIALIZATION_FAILED,params:r.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(u.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:T,method:y.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Os(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Ms(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){u.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:T,method:y.ARKTS_SYNC_COMPLETED,params:{success:!0,moduleSet:r}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){u.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var KP=10080*60*1e3,XP=7200*60*1e3,ZP=120*1e3,xr=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;nodeMaxOldSpaceSize;onConfigChangedCallback=null;useStandardProtocol=!0;diagnosticWaiters=new Map;documentVersion=0;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION,completion:y.COMPLETION,signatureHelp:y.SIGNATURE_HELP,documentHighlight:y.DOCUMENT_HIGHLIGHT};constructor(e,t,r,i){this.projectPath=e,this.sdkPath=t,this.arktsLangServerPath=r,this.nodeMaxOldSpaceSize=i}setOnConfigChanged(e){this.onConfigChangedCallback=e}static getToolDefinition(){return{name:"check_ets_files",description:"\u5BF9\u4F20\u5165\u7684ets\u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5(ArkTS-Check)\u5E76\u5B9E\u65F6\u8FD4\u56DE\u8BCA\u65AD\u4FE1\u606F\u3002",inputSchema:Kc.object({files:Kc.array(Kc.string()).describe('\u5F85\u68C0\u67E5\u7684 ETS \u6587\u4EF6\u8DEF\u5F84\u5217\u8868\uFF0C\u683C\u5F0F\u4E3A ["file1.ets","file2.ets",...]')})}}isInitializing(){return this.initializing}isInitialized(){return this.initialized}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=fe(e),{logPath:o,indexPath:s}=this.getLogAndIndexPath(i);setImmediate(()=>{Sa(s,KP,"[ArkTS-Check]"),Sa(o,XP,"[ArkTS-Check]")}),yo(o);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a;h.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${c??"undefined \u2192 dynamic formula applies"}`);let l=this.sdkPath;h.info(`[ArktsCheck] sdkPath=${l}, arktsLangServerPath=${t}, useStandardProtocol=${r}`),this.manager=new Tr({sdkPath:l,arktsLangServerPath:t,workspaceRoot:V(i),indexLogPath:s,nodeMaxOldSpaceSize:c,useStandardProtocol:r}),this.manager.setOnMessage(d=>this.handleLspMessage(d)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((d,g)=>{this.initResolve=d,this.initReject=g,this.armInitTimer(Ze),this.manager.start([]).catch(v=>{let D=v instanceof Error?v:new Error(String(v));this.failInit(D)})})}resolveProjectAndDeveco(){let e=Ct(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=Qi(t);return h.info(`ArktsCheck protocol: ${r?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${r})`),{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=Dn(e),i=await qe.promises.readFile(e,"utf8"),s=`deveco.apptool.${Ee.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,r,i,s):this.checkFileLegacy(t,e,r,i,s)}async checkFileStandard(e,t,r,i){h.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:i,version:++this.documentVersion}});try{h.debug(`textDocument/diagnostic uri=${t}`);let o=await e.diagnostic({textDocument:{uri:t}});return QP(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"))},ZP);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});h.debug(`textDocument/didOpen(legacy) uri=${r} content_len=${i.length}`),e.onAsyncOpenFile({textDocument:{uri:r,text:i,languageId:o,version:i.length},editorFiles:[r],isFromEditor:!1});try{return await a}finally{e.closeFileLegacy(r,!1)}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],r=[],i=this.collectValidFiles(e.files,t);return i.length===0?{content:[{type:"text",text:t.length>0?t.join(`
1292
- `):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],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:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){let s=o instanceof Error?o.message:String(o);return h.error(`handleLspFeature ${e} failed: ${s}`),{content:[{type:"text",text:`${e} failed: ${s}`}],isError:!0}}}async handleWorkspaceSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();h.info(`handleWorkspaceSymbol: query="${e}"`);try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return{content:[{type:"text",text:t==null?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(t,null,2)}`}]}}catch(t){let r=t instanceof Error?t.message:String(t);return h.error(`handleWorkspaceSymbol failed: ${r}`),{content:[{type:"text",text:`workspaceSymbol failed: ${r}`}],isError:!0}}}async handleWorkspaceSymbolRaw(e){if(!this.initialized)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return h.error(`handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};h.info(`handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return h.error(`handleDocumentSymbol failed: ${i}`),{content:[{type:"text",text:`documentSymbol failed: ${i}`}],isError:!0}}}async handleCallHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,async o=>{let s=await this.manager.sendFeatureRequest(y.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"?y.INCOMING_CALLS:y.OUTGOING_CALLS,l=[];for(let d of a){let g=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(g)?l.push(...g):g&&l.push(g)}return{items:a,calls:l}});return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return h.error(`handleCallHierarchy failed: ${i}`),{content:[{type:"text",text:`callHierarchy failed: ${i}`}],isError:!0}}}async handleCodeAction(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleCodeAction: file=${t} line=${e.line} char=${e.character}`);try{let r=await this.withOpenFile(t,async o=>{let s={line:e.line,character:e.character};return this.manager.sendFeatureRequest(y.CODE_ACTION,{textDocument:{uri:o},range:{start:s,end:s},context:{diagnostics:[]}})});return{content:[{type:"text",text:r==null?"codeAction: no result":`codeAction: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("codeAction",r)}}async handleRename(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleRename: file=${t} line=${e.line} char=${e.character} newName=${e.newName}`);try{let r=await this.withOpenFile(t,async o=>{let s={line:e.line,character:e.character};if(await this.manager.sendFeatureRequest(y.PREPARE_RENAME,{textDocument:{uri:o},position:s})==null)throw new Error("Symbol at this position cannot be renamed");return this.manager.sendFeatureRequest(y.RENAME,{textDocument:{uri:o},position:s,newName:e.newName})});return{content:[{type:"text",text:r==null?"rename: no result":`rename: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("rename",r)}}async handleTypeHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleTypeHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.fetchTypeHierarchy(t,e.line,e.character,e.direction);return{content:[{type:"text",text:`typeHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("typeHierarchy",r)}}async handleCompletionItemResolve(e){if(!this.initialized)return this.buildNotReadyResponse();h.info("handleCompletionItemResolve");try{let t=await this.manager.sendFeatureRequest(y.COMPLETION_ITEM_RESOLVE,{item:e});return{content:[{type:"text",text:t==null?"completionItemResolve: no result":`completionItemResolve: ${JSON.stringify(t,null,2)}`}]}}catch(t){return this.buildErrorResponse("completionItemResolve",t)}}async fetchTypeHierarchy(e,t,r,i){return this.withOpenFile(e,async o=>{let s=await this.manager.sendFeatureRequest(y.PREPARE_TYPE_HIERARCHY,{textDocument:{uri:o},position:{line:t,character:r}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],results:[]};let c=i==="supertypes"?y.SUPERTYPES:y.SUBTYPES,l=await this.collectHierarchyItems(c,a);return{items:a,results:l}})}async collectHierarchyItems(e,t){let r=[];for(let i of t){let o=await this.manager.sendFeatureRequest(e,{item:i});Array.isArray(o)?r.push(...o):o&&r.push(o)}return r}async handleInlayHint(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};try{let i=(await qe.promises.readFile(t,"utf8")).split(`
1293
- `).length,o=await this.withOpenFile(t,async a=>this.manager.sendFeatureRequest(y.INLAY_HINT,{textDocument:{uri:a},range:{start:{line:0,character:0},end:{line:i,character:0}}}));return{content:[{type:"text",text:o==null?"inlayHint: no result":`inlayHint: ${JSON.stringify(o,null,2)}`}]}}catch(r){return this.buildErrorResponse("inlayHint",r)}}async handleDocumentLink(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_LINK,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentLink: no result":`documentLink: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("documentLink",r)}}buildErrorResponse(e,t){let r=t instanceof Error?t.message:String(t);return h.error(`${e} failed: ${r}`),{content:[{type:"text",text:`${e} failed: ${r}`}],isError:!0}}async withOpenFile(e,t){let r=Dn(e),i=await qe.promises.readFile(e,"utf8"),s=`deveco.apptool.${Ee.extname(e).replace(/^\./,"")||"plaintext"}`;h.debug(`withOpenFile didOpen uri=${r} len=${i.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,text:i,languageId:s,version:++this.documentVersion}});try{return await t(r)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:r},isManual:!1})}}resolveSingleFile(e){let t=Ee.isAbsolute(e)?e:Ee.join(this.projectPath,e);return!qe.existsSync(t)||!qe.statSync(t).isFile()||!t.endsWith(".ets")?null:t}buildNotReadyResponse(){return{content:[{type:"text",text:this.initializing?"LSP \u6B63\u5728\u521D\u59CB\u5316\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5":this.projectPath?"LSP\u672A\u521D\u59CB\u5316":"\u6CA1\u6709\u914D\u7F6E\u5DE5\u7A0B\u8DEF\u5F84\uFF0C\u8BF7\u914D\u7F6EPROJECT_PATH\u53C2\u6570"}],isError:!0}}collectValidFiles(e,t){let r=Ee.resolve(this.projectPath),i=[];for(let o of e){let s=Ee.resolve(Ee.isAbsolute(o)?o:Ee.join(r,o));if(!qe.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!qe.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${o}`);continue}if(!s.endsWith(".ets")){t.push(`\u4E0D\u662F .ets \u6587\u4EF6: ${o}`);continue}i.push(s)}return i}async runDiagnosticsForFiles(e,t,r){for(let i of e){await ld(500);try{let o=await this.checkFile(i);r.push(eC(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(`
1306
+ `);if(r===-1)break;let i=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!i){f.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(i[1],10);if(!Number.isFinite(s)||s<0||s>vk){f.warn(`[LspClient] Invalid Content-Length: ${i[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.emit("message",d.json),this.buffer=Buffer.concat([Buffer.from(d.rest,"utf8"),this.buffer.slice(c)]);continue}this.emit("message",l),this.buffer=this.buffer.slice(c)}}waitForExitOrTimeout(t){let r=this.process;return!r||r.exitCode!==null||r.signalCode!==null?Promise.resolve():new Promise(o=>{let i=!1,s=()=>{i||(i=!0,clearTimeout(c),r.off("exit",a),o())},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 o=0,i=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(i){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(i=!1);continue}if(c==='"'){i=!0;continue}if(c==="{"||c==="["){o++;continue}if((c==="}"||c==="]")&&(o--,o===0)){let l=t.slice(r,a+1),d=t.slice(a+1);return{json:l,rest:d}}}return null}stop(){this.isClosing=!0;let t=this.process;if(!t)return;if(this.process=null,t.exitCode===null&&t.signalCode===null)try{t.kill()}catch{}}};var hr=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,r){return new Promise((o,i)=>{let s;r>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),i(new Error(`LSP request '${t}' (id=${e}) timeout after ${r}ms`))},r),this.timeouts.set(e,s)),this.pending.set(e,{resolve:o,reject:i,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.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let o=this.callbacks.get(e);if(o)try{o(t,r)}finally{this.callbacks.delete(e)}else{let i=[...this.callbacks.keys()].map(s=>String(s));f.info(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${i.join(",")}]`)}}registerTimeout(e,t,r,o){let i=this.timeouts.get(e);i&&clearTimeout(i);let s=setTimeout(()=>{f.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`);try{o()}finally{this.timeouts.delete(e)}},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 xs=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var Mn=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 o of r)try{o(...t)}catch(i){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,i)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function R(n){return typeof n=="object"&&n!==null}var vh=20*1e3,wk=30*1e3,wh=300,bk=300;function Sk(){let n=process.env.DEVECO_CLI_LSP_STANDARD_EXIT_TIMEOUT_MS;if(n===void 0||n==="")return wh;let e=parseInt(n,10);return Number.isFinite(e)?Math.max(bk,e):wh}var Ls=class{client;nextRequestId=1;stopOnce=null;callbacks=new Mn;requestCallbacks=new hr;diagnosticMap=new Map;initProgressReset=null;get lspPid(){return this.client.pid}constructor(e){this.client=new fr(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(y.SHUTDOWN,null,this.nextRequestId++),f.info("[ClientMessageHandle] Sending exit notification"),this.client.sendNotification(y.EXIT,null),f.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(Sk()),f.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(y.BROADCAST),this.callbacks.register(y.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(y.BROADCAST,e)}async sendInitialize(e){let t=this.nextRequestId++,r=this.requestCallbacks.registerPending(t,y.INITIALIZE,nt);return this.client.sendRequest(y.INITIALIZE,e,t),r}sendInitializeResettable(e,t){let r=this.nextRequestId++,o=this.requestCallbacks.registerPending(r,y.INITIALIZE,0);return this.client.sendRequest(y.INITIALIZE,e,r),new Promise((i,s)=>{let a,c=()=>{a=setTimeout(()=>{this.initProgressReset=null,s(new Error(`LSP initialization timeout after ${t}ms`))},t)},l=()=>{clearTimeout(a),c()};this.initProgressReset=l,c(),o.then(()=>{clearTimeout(a),this.initProgressReset=null,i()},d=>{clearTimeout(a),this.initProgressReset=null,s(d)})})}sendInitialized(){this.client.sendNotification(y.INITIALIZED,{})}sendDidOpen(e){let t=e.textDocument.uri;this.diagnosticMap.has(t)||(this.diagnosticMap.set(t,new xs(t)),this.registerDiagnosticTimeout(t)),this.client.sendNotification(y.DID_OPEN,e)}sendDidChange(e){let t=e.textDocument.uri,r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t)),this.client.sendNotification(y.DID_CHANGE,e)}closeFile(e){this.cleanupDiagnosticState(e.textDocument.uri),this.client.sendNotification(y.DID_CLOSE,e)}sendLspRequest(e,t,r=wk){let o=this.nextRequestId++,i=this.requestCallbacks.registerPending(o,e,r);return this.client.sendRequest(e,t,o),i}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}onDidChangeWatchedFiles(e){e.length!==0&&this.client.sendNotification(y.WORKSPACE_DID_CHANGE_WATCHED_FILES,{changes:e})}sendDidChangeConfiguration(e){this.client.sendNotification(y.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 o=r instanceof Error?r.message:String(r);f.error(`[LSP] JSON parse error: ${o}, raw: ${e}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotificationOrRequest(t):f.warn(`[LSP] Unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t===void 0)return;let r=t;if(e.error){let o=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(r,o)}else this.requestCallbacks.resolvePending(r,e.result)}handleNotificationOrRequest(e){let t=e.method;if(t)switch(this.initProgressReset?.(),t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.handleProgress(e.params);break;case y.WINDOW_SHOW_MESSAGE:f.info(`[LSP] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:f.info(`[LSP] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.broadcastToClients(e)}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=e.uri,r=this.diagnosticMap.get(t);if(!r)return;let o=e.diagnostics||[];this.normalizeDiagnostics(o),r.set(o),this.finalizeDiagnostic(t,o)}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){R(e)&&this.broadcastToClients({jsonrpc:T,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,vh,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${vh}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,r){let o={uri:e,diagnostics:t,...r?{errorMessage:r}:{}};this.requestCallbacks.emit(e,y.PUBLISH_DIAGNOSTICS,o),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 o of t)this.finalizeDiagnostic(o,[r]);return}this.broadcastToClients({jsonrpc:T,method:y.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var Ns=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 Pl(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)}},Pl=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var Ek={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"},Pk={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing"},x={...Ek,...Pk},gr={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"},bh=new Set([1e3,2e3,3e3,3001]);function Ck(n){if(!R(n))return!1;let e=n.textDocument;return R(e)&&typeof e.uri=="string"}function kk(n){return R(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function Ik(n){return R(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 Ms=class n{client;isInitialized=!1;stopOnce=null;callbacks=new Mn;requestCallbacks=new hr;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;get lspPid(){return this.client.pid}constructor(e){this.client=new fr(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:T,method:x.EXIT,params:{}}),gr.EXIT),f.info("[LegacyClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),f.info("[LegacyClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(x.BROADCAST),this.callbacks.register(x.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(x.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(x.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(x.INDEXING_PROGRESS_UPDATE,e)}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}sendInitialize(e,t){this.client.send("initialize",e,t)}sendInitialized(e){this.client.sendRaw(JSON.stringify({jsonrpc:T,method:x.INITIALIZED,params:{editors:e}}),gr.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:T,id:0,result:{}}),gr.EMPTY)}sendAsyncRequest(e,t,r,o){if(!R(t)){f.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!Ck(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 i=t.textDocument.uri,s=ft(i);t.textDocument.uri=s,delete t.requestId;let a=o??e;f.info(`[LSP] sendAsyncRequest ${a}, filePath: ${i}`),this.client.sendRaw(JSON.stringify({jsonrpc:T,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(!kk(r)){f.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:T,method:x.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),x.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!R(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:T,method:x.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),gr.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let o=ft(t);e.textDocument.uri=o,f.info(`[LSP] onAsyncOpenFile, uri: ${o}`);let i=this.diagnosticMap.get(o);i||(i=new Ns(o),this.diagnosticMap.set(o,i),this.registerDiagnosticTimeout(o,x.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(i.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:x.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),gr.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=ft(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,x.PUBLISH_DIAGNOSTICS)),f.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:x.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),gr.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=ft(e);f.info(`[LSP] didClose, uri: ${r}`);let o=this.diagnosticMap.get(r);if(!t&&(!o||o.isFromEditor)){f.info(`[LSP] closeFile skip, !diagnostic: ${!o}, isFromEditor: ${o?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:x.DID_CLOSE,params:{textDocument:{uri:r}}}),gr.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 o of t)this.finalizeDiagnostic(o,x.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:T,method:x.ARKTS_ERROR,params:{message:e.message}})}handleLspMessage(e){let t=e.method;t!==void 0&&(!this.isInitialized&&this.handlePreInitMessage(t,e)||this.handlePostInitMessage(t,e))}handlePreInitMessage(e,t){switch(e){case x.MODULE_INIT_FINISH:return f.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(x.MODULE_INIT_FINISH),this.callbacks.unregister(x.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case x.INDEXING_PROGRESS_UPDATE:return f.info(`[LSP] onIndexingProgressUpdate: ${Ik(t.params)}`),this.callbacks.invoke(x.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case x.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case x.ON_PACKAGE_CHANGE_FINISH:f.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case x.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case x.ON_ASYNC_HOVER:this.handleAsyncResponse(t,x.HOVER);return;case x.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,x.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case x.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,x.REFERENCES);return;default:f.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){f.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;R(t)&&R(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:T,method:x.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(!R(r)){f.warn("[LSP] aceProject/onAsyncHover message invalid");return}let o=r.requestId;if(typeof o!="number"){f.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(o,t,r)}handleForceOpenFile(e){if(!e){f.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,x.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){f.info("[LSP] publishDiagnostics uri is null");return}let r=e.version??-1;if(r===-1)return;let o=this.diagnosticMap.get(t);if(!o){f.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let i=e.diagnostics||[];i.length!==0?i.forEach(s=>{this.normalizeDiagnostic(s),o.addMessage(r,JSON.stringify(s))}):o.setReceivedType(r),o.hasReceivedAllTypes(bh)&&this.finalizeDiagnostic(t,x.PUBLISH_DIAGNOSTICS,o.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),i={1:"Error",2:"Warning",3:"Information",4:"Hint"}[r]||"Unknown";t.severityStr=i,t.severity=i}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),o=r?r.getMessages():[];this.finalizeDiagnostic(e,t,o,o.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,o){let i={uri:e,diagnostics:r,...o?{errorMessage:o}:{}};this.requestCallbacks.emit(e,t,i),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import Cl from"path";import*as Us from"path";var Os=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var _s=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var js=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var Fs=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var $s=class{typeSetting=new js;parameterNames=new Fs};var Hs=class{constructor(e,t,r,o){this.rootUri=e;this.lspServerWorkspacePath=z(Us.dirname(t)),this.indexingDataLocation=z(o),this.loggerPath=z(Us.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new Os;gutterIconsSetting=new _s;inlayHintsSetting=new $s;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Sh from"path";var Go=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(z(Sh.join(e,"src","main","resources")))}};var Ak="OS",On=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${Ak}`;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 Go(e)):this.buildProfileParam=new Go}toString(){return JSON.stringify(this)}};var _n=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as Me from"path";import*as $n from"fs";var Bs=class{modulePath;dependencies={};dynamicDependencies={}};var Kr=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 jn=class{constructor(e,t,r){this.projectPath=e;this.moduleName=t;this.modulePath=r}projectPath;moduleName;modulePath;dependencies=[];devDependencies=[];dynamicDependencies=[];finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[]};import*as Gt from"path";import*as Ws from"fs";var Fn=class{name="";version="";storePath="";dependencyPath="";path=""};var _={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:De.OH_PACKAGE_JSON5},zo=`${_.HVIGOR_CACHE}/${_.DEPENDENCY}`,Xr=`${_.DEPENDENCY}${_.JSON5}`,gV=De.SYNC_OUTPUT_PATH;var Jo=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 o=this.PACKAGE_JSON_PARSER_MAP.get(e);return o||(o=new n(e,t,r),this.PACKAGE_JSON_PARSER_MAP.set(e,o)),o}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=Gt.join(this.dependencyPath,_.OH_PACKAGE_JSON5),r=Je(t);r&&(this.dependencies=this.getDependencyList(r,_.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(r,_.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(r,_.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let r=[];if(!R(e))return r;let o=e[t];if(!R(o))return r;for(let[i,s]of Object.entries(o)){if(typeof s!="string"){f.error(`${i} package dependency value is not String ${t}`);continue}let a=new Fn;a.name=i;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(n.PARAMETER_PREFIX)||this.parseDependencyPath(i,c,a,!1),r.push(a)}return r}parseDependencyPath(e,t,r,o){if(!(!e||!t))try{let i=Gt.normalize(Gt.join(this.modulePath,_.OH_MODULES_PATH,e));if(!(t.startsWith(n.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){r.dependencyPath=i;return}if(r.path=t,this.fileNameForOhpm.test(t)){r.dependencyPath=i;return}let s=t;if(t.startsWith(n.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(n.FILE_DEPENDENCY_PREFIX.length)),Gt.isAbsolute(s)){r.dependencyPath=i;return}o||(i=Gt.resolve(this.modulePath,s)),Ws.existsSync(i)&&Ws.statSync(i).isDirectory()&&(r.dependencyPath=i)}catch(i){f.error("parser dependency path is invalid",i)}}};import*as Zr from"fs";import*as yr from"path";import Dk from"json5";var Vs=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 yr.join(this.projectPath,_.OH_MODULES_PATH,_.OHPM_PATH,_.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 o of e)if(!n.checkObjectDepth(o,t,r+1))return!1;return!0}for(let o in e)if(Object.prototype.hasOwnProperty.call(e,o)&&!n.checkObjectDepth(e[o],t,r+1))return!1;return!0}readLockFile(e){if(!Zr.existsSync(e))return f.error("lock file does not exist"),this.clearDependencies(),null;try{let t=Zr.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=Zr.readFileSync(e,"utf8"),r=Dk.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(!R(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,_.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,_.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,_.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!R(e))return t;let r=0;for(let o in e){if(!Object.prototype.hasOwnProperty.call(e,o))continue;let i=e[o];if(!R(i)){f.error(`${o} 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 i.storePath=="string"&&t.set(o,i.storePath)}return t}getDependencyList(e,t,r){if(!R(e))return[];let o=0;for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;if(++o>n.MAX_KEYS_PER_OBJECT){f.warn("lock.json5 modules object exceeds key limit, truncating");break}let s=e[i];if(R(s)){let a=typeof s.name=="string"?s.name:"";if(r==="."&&a===""||a===r)return this.getFinalDependencyList(e,t,i)}}return[]}getFinalDependencyList(e,t,r){let o=e[r];if(!R(o))return f.error("moduleJsonObject is null"),[];let i=[],s=o[t];if(!R(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(!R(l))continue;let d=typeof l.specifier=="string"?l.specifier:"",g=typeof l.version=="string"?l.version:"",v=new Fn;v.name=c,v.version=g.startsWith(n.FILE_DEPENDENCY_PREFIX)?g.substring(n.FILE_DEPENDENCY_PREFIX.length):g,this.parseDependencyPath(v,r,c,d,g);let P=`${c}@${g}`;this.storePathMap.has(P)&&(v.storePath=this.storePathMap.get(P)||""),i.push(v)}return i}parseDependencyPath(e,t,r,o,i){let s=yr.resolve(this.projectPath,yr.join(t,_.OH_MODULES_PATH,r));try{let a=i.startsWith(n.FILE_DEPENDENCY_PREFIX)?i.substring(n.FILE_DEPENDENCY_PREFIX.length):i,c=yr.isAbsolute(a)?a:yr.resolve(this.projectPath,a);Zr.existsSync(c)?(e.path=o,e.dependencyPath=this.fileNameForOhpm.test(i)?s:c):e.dependencyPath=s}catch(a){f.error("Invalid dependency path in lock.json5, msg:",a instanceof Error?a.message:String(a))}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function Eh(n){return R(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var Qr=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new Nt(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=Me.join(t,zo),o=Me.join(r,Xr);if(!$n.existsSync(r)||!$n.existsSync(o)){let c="Dependency map or JSON not found";return f.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let i=new jn(this.projectPath,".",this.projectPath);this.parseProjectDependencies(r,i),this.parseLockJson(i);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return f.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:c}}let a=Date.now();for(let c=0;c<s.length;c++){let l=s[c];if(Eh(l)){try{S.assertModuleName(l.name)}catch{f.warn(`[Parser] Skipping module with invalid name: ${l.name}`);continue}this.parseSingleModule(l,r,i,e),(c+1)%100===0&&f.info(`[Parser] getAllDependencyMap progress: ${c+1}/${s.length} (${Date.now()-a}ms)`)}}return f.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-a}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],r=this.projectPath,o=Me.join(r,zo),i=Me.join(o,Xr);if(!$n.existsSync(o)||!$n.existsSync(i))return f.warn("[Parser] Dependency map or JSON not found."),t;let s=e&&e.length>0?new Set(e.map(l=>l.trim()).filter(Boolean)):null,a=new jn(this.projectPath,".",this.projectPath);this.parseProjectDependencies(o,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return f.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let l of c){if(!Eh(l))continue;let d=l.name;try{S.assertModuleName(d)}catch{f.warn(`[Parser] Skipping module with invalid name: ${d}`);continue}if(s&&!s.has(d))continue;let g=Me.resolve(this.projectPath,l.srcPath),v=Me.join(o,d),P=z(g),ie=this.buildModuleDependencies(d,P,v,a);ie.moduleName=d,t.push(ie)}return t}parseSingleModule(e,t,r,o){let i=e.name,s=Me.resolve(this.projectPath,e.srcPath),a=Me.join(t,i),c=z(s),l=new On(c),d=this.buildModuleDependencies(i,c,a,r);this.parseModuleJson5(c,l);let g=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=i,l.moduleType=i,l.packageName=i,l.moduleDependencies=d,l.moduleJsonParam=new _n(g),o.push(l)}buildModuleDependencies(e,t,r,o){let i=new jn(this.projectPath,e,t);Jo.getInstance(r,t,this.projectPath).parseDependency(i),this.parseLockJson(i),i.finalDependencies.push(...o.finalDependencies),i.finalDevDependencies.push(...o.finalDevDependencies),i.finalDynamicDependencies.push(...o.finalDynamicDependencies),i.finalDependencies.push(...i.finalDevDependencies);let a=new Bs;return a.modulePath=t,this.toModuleDependencies(i,a),a}toModuleDependencies(e,t){let r={},o={};for(let i of e.finalDependencies)r[i.name]=new Kr(i);for(let i of e.finalDynamicDependencies)o[i.name]=new Kr(i);t.dependencies=r,t.dynamicDependencies=o}parseProjectDependencies(e,t){let r=Me.join(e,_.OH_PACKAGE_JSON5);if(!$n.existsSync(r))return;Jo.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 Vs(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=Me.join(e,"src","main","module.json5"),o=Je(r);if(!R(o)||!R(o.module))return;let i=o.module;t.permissions=this.parseRequestPermissions(i),t.deviceType=this.parseDeviceTypes(i)}parseRequestPermissions(e){let t=[];if(R(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)R(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=Me.join(e,"src","main","resources","base","profile","main_pages.json"),r=Je(t);return!R(r)||!Array.isArray(r.src)?[]:r.src.filter(o=>typeof o=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!R(t)||!R(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=Me.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=Je(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!R(t)||!R(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!R(r)||typeof r.compatibleSdkVersion!="string")return;let[o,i]=this.parseBySplit(r.compatibleSdkVersion);e.compatibleSdkVersion=o,e.compatibleSdkLevel=i}getBuildProfile(){if(this.buildProfileCache===void 0){let e=Me.join(this.projectPath,"build-profile.json5");this.buildProfileCache=Je(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,e];let r=e.substring(0,t),o=e.substring(t+1,e.length-1);return[r,o]}parseDeviceTypes(e){return!R(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 qs=class{constructor(e=[]){this.valueSet=e}valueSet};var Hn=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Ph=(k=>(k[k.File=1]="File",k[k.Module=2]="Module",k[k.Namespace=3]="Namespace",k[k.Package=4]="Package",k[k.Class=5]="Class",k[k.Method=6]="Method",k[k.Property=7]="Property",k[k.Field=8]="Field",k[k.Constructor=9]="Constructor",k[k.Enum=10]="Enum",k[k.Interface=11]="Interface",k[k.Function=12]="Function",k[k.Variable=13]="Variable",k[k.Constant=14]="Constant",k[k.String=15]="String",k[k.Number=16]="Number",k[k.Boolean=17]="Boolean",k[k.Array=18]="Array",k[k.Object=19]="Object",k[k.Key=20]="Key",k[k.Null=21]="Null",k[k.EnumMember=22]="EnumMember",k[k.Struct=23]="Struct",k[k.Event=24]="Event",k[k.Operator=25]="Operator",k[k.TypeParameter=26]="TypeParameter",k))(Ph||{}),Ch=()=>Object.values(Ph).filter(n=>typeof n=="number");var Gs=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var zs=class{applyEdit=!0;workspaceEdit=new Gs;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new qs(Ch());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Hn;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Js=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Ys=class{constructor(e=[]){this.valueSet=e}valueSet};var Ks=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var kh=(D=>(D[D.Text=1]="Text",D[D.Method=2]="Method",D[D.Function=3]="Function",D[D.Constructor=4]="Constructor",D[D.Field=5]="Field",D[D.Variable=6]="Variable",D[D.Class=7]="Class",D[D.Interface=8]="Interface",D[D.Module=9]="Module",D[D.Property=10]="Property",D[D.Unit=11]="Unit",D[D.Value=12]="Value",D[D.Enum=13]="Enum",D[D.Keyword=14]="Keyword",D[D.Snippet=15]="Snippet",D[D.Color=16]="Color",D[D.File=17]="File",D[D.Reference=18]="Reference",D[D.Folder=19]="Folder",D[D.EnumMember=20]="EnumMember",D[D.Constant=21]="Constant",D[D.Struct=22]="Struct",D[D.Event=23]="Event",D[D.Operator=24]="Operator",D[D.TypeParameter=25]="TypeParameter",D))(kh||{}),Ih=()=>Object.values(kh).filter(n=>typeof n=="number");var Xs=class{completionItemKind=new Ys(Ih());completionItem=new Ks;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Zs=class{synchronization=new Js;completion=new Xs;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 Hn;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var Qs=class{workspace=new zs;textDocument=new Zs;notebookDocument=null;window=null;general=null;experimental=null};var ea=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var ta=class{constructor(e,t,r,o,i,s=!0){this.sdkPath=e;this.rootUri=r;this.nodeMaxOldSpaceSize=i;this.useStandardProtocol=s;this.serverPath=ro(t,this.useStandardProtocol),this.logPath=Eu(),this.indexLogPath=o||this.logPath;let a={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath};this.messageHandle=this.useStandardProtocol?new Ls(a):new Ms(a),this.messageHandle.setBroadcastToClients(c=>this.onLspMessage(c))}sdkPath;rootUri;nodeMaxOldSpaceSize;useStandardProtocol;messageHandle;get stdHandle(){return this.messageHandle}get legacyHandle(){return this.messageHandle}get lspPid(){return this.messageHandle.lspPid}onAsyncOpenFile(e){this.legacyHandle.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.legacyHandle.closeFile(e,t)}serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}async start(e,t){let r=!1;try{f.info(`serverPath: ${this.serverPath}`),f.info(`rootUri: ${this.rootUri}`),f.info(`sdkPath: ${this.sdkPath}`),f.info(`logPath: ${this.logPath}`);let o=ft(this.rootUri),i=new Hs(o,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new Qr(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),i.modules=s;let l=Ni(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new ea(o,i,new Qs),this.useStandardProtocol){let d=this.messageHandle;await d.sendInitializeResettable(this.currentParams,nt),f.info("[LSP] initialize response received"),d.broadcastToClients({jsonrpc:T,method:y.ARKTS_INDEXING_PROGRESS,params:{}}),d.sendInitialized()}else await this.startLegacy(this.currentParams,e);r=!0}catch(o){this.lastStartErrorMessage=o instanceof Error?o.message:String(o),f.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(r)}async startLegacy(e,t){let r=this.messageHandle;r.sendInitialize(e,1),r.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:T,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((o,i)=>{r.onIndexingProgressUpdate(i),r.onInitializationCompleted(o)},"LSP initialization",nt),r.sendInitialized(t)}withResettableTimeout(e,t,r){return new Promise((o,i)=>{let s,a=()=>{s=setTimeout(()=>{i(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),o()},c)})}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){f.info(`[LSP] registerDiagnosticCallback uri='${e}', useStandardProtocol=${this.useStandardProtocol}`),this.messageHandle.registerRequestCallback(e,(t,r)=>{let o=R(r)?r:{};f.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let i={jsonrpc:T,method:t,params:{uri:typeof o.uri=="string"?o.uri:e,diagnostics:Array.isArray(o.diagnostics)?o.diagnostics:[],...typeof o.errorMessage=="string"?{errorMessage:o.errorMessage}:{}}};this.onLspMessage(i)})}async hover(e){let t=e.textDocument.uri;return this.registerDiagnosticCallback(t),this.stdHandle.sendLspRequest(y.HOVER,e)}async definition(e){return this.stdHandle.sendLspRequest(y.DEFINITION,e)}async references(e){return this.stdHandle.sendLspRequest(y.REFERENCES,e)}async completion(e){return this.stdHandle.sendLspRequest(y.COMPLETION,e)}async documentSymbol(e){return this.stdHandle.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async diagnostic(e){return this.stdHandle.sendLspRequest(y.DIAGNOSTIC,e,120*1e3)}async sendFeatureRequest(e,t){return this.stdHandle.sendLspRequest(e,t)}reloadDependenciesOnly(e){let t=e?.fullReload??!1,r=new Qr(this.rootUri,this.sdkPath),o=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,o);return this.applyModuleModelsUpdate(d),this.sendDidChangeConfiguration({moduleSet:d}),f.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${d.length}`),this.lastDepsOnlyForDiff=l,l}let i=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(i.length===0&&s.size===0)return f.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];f.info(`[LspServerProxy] Module-level deps changed, parsing: [${i.join(", ")}]`);let a=r.getDependenciesOnly(i);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),this.sendDidChangeConfiguration({moduleSet:c}),f.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}sendDidChangeConfiguration(e){this.stdHandle.sendDidChangeConfiguration(e)}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),r=new Map(this.lastDepsOnlyForDiff.map(o=>[o.moduleName??"",o]));for(let o of e){let i=o.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(i,t,r),c=o.dependencies??{},l=o.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(d,g)=>{(o.dependencies??={})[d]=this.makeDeleteEntry(d,g)}),this.markAddAndDeleteInDeps(a,l,(d,g)=>{(o.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,g)})}}getOldDepsForModule(e,t,r){let o=t.get(e),i=o?.moduleDependencies?.dependencies??{},s=o?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(i).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(i=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:i,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let o of Object.keys(t))o in e||(t[o].type="add");for(let o of Object.keys(e))o in t||r(o,e[o])}makeDeleteEntry(e,t){return new Kr({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new On(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new _n([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let o of e){let i=o.moduleName??"",s=t.get(i);s?(s.modulePath=o.modulePath,s.moduleDependencies=o):s=this.createMinimalModelFromDepsItem(o),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let o=new Map(r.map(s=>[s.moduleName??"",s])),i=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=o.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,o.delete(a)),i.push(s)}for(let[,s]of o)i.push(this.createMinimalModelFromDepsItem(s));return i}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=un(Cl.join(t,"default/openharmony/ets/build-tools/ets-loader")),o=un(Cl.join(t,"default/openharmony/ets/api")),i=un(Cl.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=o,s.hosSdkPath=i}sendRequest(e){switch(e.method){case y.HOVER:this.stdHandle.sendLspRequest(y.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:T,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:T,id:e.id,error:{code:-32603,message:t.message}}));break;case y.DEFINITION:this.stdHandle.sendLspRequest(y.DEFINITION,e.params).then(t=>this.onLspMessage({jsonrpc:T,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:T,id:e.id,error:{code:-32603,message:t.message}}));break;case y.REFERENCES:this.stdHandle.sendLspRequest(y.REFERENCES,e.params).then(t=>this.onLspMessage({jsonrpc:T,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:T,id:e.id,error:{code:-32603,message:t.message}}));break;default:f.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!gh(e)){f.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case y.DID_OPEN:this.handleDidOpenNotification(e);break;case y.DID_CHANGE:this.handleDidChangeNotification(e);break;case y.DID_CLOSE:this.handleDidCloseNotification(e);break;case y.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;case y.DID_CREATE_FILES:this.handleDidCreateFiles(e);break;case y.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(y.DID_CREATE_FILES,t)}handleDidDeleteFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(y.DID_DELETE_FILES,t)}async dispose(){await this.messageHandle.stop()}};import*as zt from"fs";import*as Be from"path";import{createHash as Tk}from"crypto";import{EventEmitter as xk}from"events";var ra=class extends xk{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r}projectRoot;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 o of t)r.has(o)||this.watchFile(o);for(let o of r)t.has(o)||(this.unwatchFile(o),f.info(`[ConfigFileWatcher] Stopped watching: ${o}`));f.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!zt.existsSync(t)){f.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=zt.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 o of t){let i=Be.resolve(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:i,relativePath:o.srcPath,timestamp:r,moduleName:o.name})}}emitModuleRemovedEvents(t,r){for(let o of t){let i=Be.resolve(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:i,relativePath:o.srcPath,timestamp:r,removedModuleName:o.name})}}emitModuleRenamedEvents(t,r){for(let o of t){let i=Be.resolve(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:i,relativePath:o.after.srcPath,timestamp:r,moduleName:o.after.name,removedModuleName:o.before.name})}}emitModuleMovedEvents(t,r){for(let o of t){let i=Be.resolve(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:i,relativePath:o.after.srcPath,timestamp:r,moduleName:o.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 o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(i);if(s===this.lastModulesSnapshot){f.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,i);this.lastModules=i,this.lastModulesSnapshot=s,f.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,o)}computeModulesSnapshot(t){return t.map(o=>`${o.name}::${o.srcPath}`).sort().join("|")}diffModules(t,r){let o=this.buildModuleMatchState(r),i={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,o),this.matchRenamedModules(t,o,i),this.matchMovedModules(t,o,i),this.collectRemovedModules(t,o,i),this.collectAddedModules(r,o,i),i}buildModuleMatchState(t){let r=new Map,o=new Map;for(let i of t)r.set(i.srcPath,i),o.set(i.name,i);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:o}}matchExactModules(t,r){for(let o of t){let i=r.newBySrc.get(o.srcPath);i&&i.name===o.name&&(r.matchedOld.add(o),r.matchedNew.add(i))}}matchRenamedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newBySrc.get(i.srcPath);s&&!r.matchedNew.has(s)&&s.name!==i.name&&(o.renamed.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}matchMovedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newByName.get(i.name);s&&!r.matchedNew.has(s)&&s.srcPath!==i.srcPath&&(o.moved.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}collectRemovedModules(t,r,o){for(let i of t)r.matchedOld.has(i)||o.removed.push(i)}collectAddedModules(t,r,o){for(let i of t)r.matchedNew.has(i)||o.added.push(i)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=Je(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=Be.join(this.projectRoot,_.OH_PACKAGE_JSON5);zt.existsSync(r)&&t.push(r);let o=this.parseModulesFromBuildProfile();for(let i of o){let s=Be.resolve(this.projectRoot,i.srcPath),a=Be.join(s,_.OH_PACKAGE_JSON5);zt.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Be.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=zt.readFileSync(t,"utf-8");return Tk("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 o=zt.watch(t,i=>{i==="change"&&this.onFileChanged(t)});o.on("error",i=>{f.error(`[ConfigFileWatcher] Watch error for ${t}: ${i.message}`)}),this.watchers.set(t,o)}catch(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 o=this.debounceTimers.get(t);o&&(clearTimeout(o),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.computeFileHash(t);if(!i){f.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===i){f.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,i),f.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:Be.basename(t),relativePath:Be.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,o)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),f.info("[ConfigFileWatcher] All watchers stopped")}};import*as vr from"fs";import*as yt from"path";import{createHash as Lk}from"crypto";import{EventEmitter as Nk}from"events";var na=class extends Nk{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=yt.join(t,zo)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!vr.existsSync(this.depMapDir)){f.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=vr.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 z(yt.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let o=r.replace(/\\/g,"/"),i;if(o===_.OH_PACKAGE_JSON5)i="root-oh-package";else if(o===Xr)i="dep-map-json";else{let a=o.match(/^([^/]+)\/oh-package\.json5$/);i=a?`module:${a[1]}`:""}if(!i)return;let s=yt.join(this.depMapDir,r);vr.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,_.OH_PACKAGE_JSON5),r=yt.join(this.depMapDir,Xr),o=this.parseModulesFromDepMap(),i=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...o.map(s=>({path:(S.assertModuleName(s.name),yt.join(this.depMapDir,s.name,_.OH_PACKAGE_JSON5)),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of i){if(!vr.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,Xr);try{let r=Je(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(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,o,i){for(let s of t)s.startsWith("module:")?(o.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(o.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(i.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,o,i,s){for(let a of t)s.push(a.info),o.add(a.info.newName),i.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let o=new Set;for(let i of t)i.startsWith("dep-added:")&&o.add(i.substring(10));for(let i of r)o.add(i.info.newName);return o}emitIncrementalReload(t,r,o,i,s){f.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...o].join(",")}], added=[${[...i].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...o],addedModuleNames:[...i],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 o=new Set,i=new Set,s=new Set,a=[];this.processTagsIntoSets(t,o,i,s),this.processRenameEntries(r,o,i,s,a);for(let l of i)s.delete(l);if(i.size===0&&s.size===0&&a.length===0){f.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(o,i,s,c,a)}normalizeSrcPath(t){return z(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(i=>[i.name,i])),o=new Map(t.map(i=>[this.normalizeSrcPath(i.srcPath),i]));return{byName:r,bySrcPath:o}}detectModuleRenames(t,r,o,i){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"}}),o.add(a.name),i.add(c.name);let l=(S.assertModuleName(a.name),yt.join(this.depMapDir,a.name,_.OH_PACKAGE_JSON5));this.contentHashes.delete(this.canonicalPath(l)),f.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,r,o,i){for(let[s,a]of t){if(o.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"}}),o.add(s),i.add(s),f.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,o){for(let[i]of t)o.has(i)||r.has(i)||(this.pendingTags.push(`dep-added:${i}`),o.add(i))}detectRemovedModules(t,r,o){for(let[i]of t)if(!o.has(i)&&!r.has(i)){this.pendingTags.push(`dep-removed:${i}`),o.add(i);let s=(S.assertModuleName(i),yt.join(this.depMapDir,i,_.OH_PACKAGE_JSON5));this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(o=>o.startsWith("dep-")),r=this.pendingRenames.map(o=>`${o.kind}(${o.info.oldName}\u2192${o.info.newName})`);f.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:o}=this.buildModuleLookupMaps(this.lastModules),{byName:i,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(o,s,a,c),this.detectModuleMoves(r,i,a,c),this.detectAddedModules(i,r,c),this.detectRemovedModules(r,i,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=vr.readFileSync(t,"utf-8");return Lk("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as Mk}from"child_process";var Ok=["install","--all"];async function _k(n,e,t,r){return new Promise(o=>{let i=Mk(n,[e,...Ok],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";i.stdout?.on("data",c=>{s+=c.toString()}),i.stderr?.on("data",c=>{a+=c.toString()}),i.on("close",c=>{let l=[s,a].filter(Boolean).join(`
1307
+ `);o({exitCode:c??-1,output:l})}),i.on("error",c=>{let l=[s,a].filter(Boolean).join(`
1308
+ `);o({exitCode:-1,output:l+`
1309
+ `+c.message})})})}function jk(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>f.info("[ohpm] %s",e))}async function Ah(n,e,t,r){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,output:i}=await _k(t,r,n,e);return jk(i),o===0?(f.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(f.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",o),f.error("ohpm \u8F93\u51FA: %s",i),!1)}catch(o){return f.error("ohpm \u5B89\u88C5\u5F02\u5E38",o),!1}}var Dh={UNINITIALIZED:-32099,UNKNOWN:-32e3},Yo=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,Dh.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,Dh.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var Un=class{config;lspProxy=null;configWatcher=null;depMapWatcher=null;isInitialized=!1;lastEditorOpenFiles=[];onMessage=()=>{};onConfigChanged=null;disposeOnce=null;get aceServerPid(){return this.lspProxy?.lspPid??null}constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}async start(e=[]){this.lastEditorOpenFiles=e;try{this.startConfigWatcher(),this.startLspProxy(e)}catch(t){throw f.error(`[ArktsLspManager] start() synchronous failure: ${t instanceof Error?t.message:String(t)}`),t}}sendNotification(e){if(!this.lspProxy){f.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){f.warn("[ArktsLspManager] sendRequest before LSP ready, dropped");return}this.lspProxy.sendRequest(e)}async diagnostic(e){if(!this.lspProxy)throw new Error("[ArktsLspManager] diagnostic before LSP ready");return this.lspProxy.diagnostic(e)}async sendFeatureRequest(e,t){if(!this.useStandardProtocol)throw new Error(`Language feature '${e}' is not supported on the installed DevEco Studio. The standard LSP protocol entry (plugins/openharmony/ace-server/out/standardIndex/index.js) was not found. Please upgrade DevEco Studio to version 26.0.0.610 or later to use this tool.`);if(!this.lspProxy)throw new Error("LSP not ready");return this.lspProxy.sendFeatureRequest(e,t)}get useStandardProtocol(){return this.config.useStandardProtocol}onAsyncOpenFile(e){this.lspProxy?.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.lspProxy?.closeFileLegacy(e,t)}registerDiagnosticCallback(e){this.lspProxy?.registerDiagnosticCallback(e)}static async handleSyncProject(e,t,r,o,i,s){if(f.info("[ArktsLspManager] Received arkts/syncProject"),!e||!t)return f.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let a=s?.skipHvigorSync===!0,c=await Di(e,async()=>await Ah(e,t,r??"",o??"")?a?(f.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await Au(e,t,r??"",i??"")?(f.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(f.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(f.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return c.acquired?c.result:(f.info("[ArktsLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){try{this.configWatcher?.stop()}catch(e){f.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){f.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){f.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new ta(this.config.sdkPath,this.config.arktsLangServerPath,this.config.workspaceRoot,this.config.indexLogPath,this.config.nodeMaxOldSpaceSize,this.config.useStandardProtocol);t.setOnMessage(r=>this.handleLspMessage(r)),t.start(e,r=>this.handleLspInitialized(r)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)f.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:T,method:y.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();f.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?Yo.uninitialized(t):Yo.unknown();this.onMessage({jsonrpc:T,method:y.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:T,method:y.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new ra(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new na(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(o=>({modulePath:o.modulePath??"",dependencies:o.dependencies??{},dynamicDependencies:o.dynamicDependencies??{}}));this.onMessage({jsonrpc:T,method:y.ARKTS_SYNC_COMPLETED,params:{success:!0,moduleSet:r}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){f.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var Fk=10080*60*1e3,$k=7200*60*1e3,Hk=120*1e3,Bn=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;nodeMaxOldSpaceSize;onConfigChangedCallback=null;useStandardProtocol=!0;diagnosticWaiters=new Map;documentVersion=0;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION,completion:y.COMPLETION,signatureHelp:y.SIGNATURE_HELP,documentHighlight:y.DOCUMENT_HIGHLIGHT};constructor(e,t,r,o){this.projectPath=e,this.sdkPath=t,this.arktsLangServerPath=r,this.nodeMaxOldSpaceSize=o}setOnConfigChanged(e){this.onConfigChangedCallback=e}static getToolDefinition(){return{name:"check_ets_files",description:"\u5BF9\u4F20\u5165\u7684ets\u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5(ArkTS-Check)\u5E76\u5B9E\u65F6\u8FD4\u56DE\u8BCA\u65AD\u4FE1\u606F\u3002",inputSchema:kl.object({files:kl.array(kl.string()).describe('\u5F85\u68C0\u67E5\u7684 ETS \u6587\u4EF6\u8DEF\u5F84\u5217\u8868\uFF0C\u683C\u5F0F\u4E3A ["file1.ets","file2.ets",...]')})}}isInitializing(){return this.initializing}isInitialized(){return this.initialized}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 o=ge(e),{logPath:i,indexPath:s}=this.getLogAndIndexPath(o);setImmediate(()=>{Ba(s,Fk,"[ArkTS-Check]"),Ba(i,$k,"[ArkTS-Check]")}),Li(i);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a;h.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${c??"undefined \u2192 dynamic formula applies"}`);let l=this.sdkPath;h.info(`[ArktsCheck] sdkPath=${l}, arktsLangServerPath=${t}, useStandardProtocol=${r}`),this.manager=new Un({sdkPath:l,arktsLangServerPath:t,workspaceRoot:z(o),indexLogPath:s,nodeMaxOldSpaceSize:c,useStandardProtocol:r}),this.manager.setOnMessage(d=>this.handleLspMessage(d)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((d,g)=>{this.initResolve=d,this.initReject=g,this.armInitTimer(nt),this.manager.start([]).catch(v=>{let P=v instanceof Error?v:new Error(String(v));this.failInit(P)})})}resolveProjectAndDeveco(){let e=Lt(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=gi(t);return h.info(`ArktsCheck protocol: ${r?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${r})`),{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=Mr(e),o=await Xe.promises.readFile(e,"utf8"),s=`deveco.apptool.${ke.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,r,o,s):this.checkFileLegacy(t,e,r,o,s)}async checkFileStandard(e,t,r,o){h.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:o,version:++this.documentVersion}});try{h.debug(`textDocument/diagnostic uri=${t}`);let i=await e.diagnostic({textDocument:{uri:t}});return Uk(i)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:t}})}}async checkFileLegacy(e,t,r,o,i){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"))},Hk);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});h.debug(`textDocument/didOpen(legacy) uri=${r} content_len=${o.length}`),e.onAsyncOpenFile({textDocument:{uri:r,text:o,languageId:i,version:o.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=[],o=this.collectValidFiles(e.files,t);return o.length===0?{content:[{type:"text",text:t.length>0?t.join(`
1310
+ `):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],isError:!0}:(await this.runDiagnosticsForFiles(o,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:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${t.file}`}],isError:!0};let o=n.FEATURE_METHOD_MAP[e];if(!o)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let i=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(o,c)});return{content:[{type:"text",text:i==null?`${e}: no result`:`${e}: ${JSON.stringify(i,null,2)}`}]}}catch(i){let s=i instanceof Error?i.message:String(i);return h.error(`handleLspFeature ${e} failed: ${s}`),{content:[{type:"text",text:`${e} failed: ${s}`}],isError:!0}}}async handleWorkspaceSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();h.info(`handleWorkspaceSymbol: query="${e}"`);try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return{content:[{type:"text",text:t==null?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(t,null,2)}`}]}}catch(t){let r=t instanceof Error?t.message:String(t);return h.error(`handleWorkspaceSymbol failed: ${r}`),{content:[{type:"text",text:`workspaceSymbol failed: ${r}`}],isError:!0}}}async handleWorkspaceSymbolRaw(e){if(!this.initialized)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return h.error(`handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};h.info(`handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async i=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:i}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){let o=r instanceof Error?r.message:String(r);return h.error(`handleDocumentSymbol failed: ${o}`),{content:[{type:"text",text:`documentSymbol failed: ${o}`}],isError:!0}}}async handleCallHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,async i=>{let s=await this.manager.sendFeatureRequest(y.PREPARE_CALL_HIERARCHY,{textDocument:{uri:i},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],calls:[]};let c=e.direction==="incoming"?y.INCOMING_CALLS:y.OUTGOING_CALLS,l=[];for(let d of a){let g=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(g)?l.push(...g):g&&l.push(g)}return{items:a,calls:l}});return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){let o=r instanceof Error?r.message:String(r);return h.error(`handleCallHierarchy failed: ${o}`),{content:[{type:"text",text:`callHierarchy failed: ${o}`}],isError:!0}}}async handleCodeAction(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleCodeAction: file=${t} line=${e.line} char=${e.character}`);try{let r=await this.withOpenFile(t,async i=>{let s={line:e.line,character:e.character};return this.manager.sendFeatureRequest(y.CODE_ACTION,{textDocument:{uri:i},range:{start:s,end:s},context:{diagnostics:[]}})});return{content:[{type:"text",text:r==null?"codeAction: no result":`codeAction: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("codeAction",r)}}async handleRename(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleRename: file=${t} line=${e.line} char=${e.character} newName=${e.newName}`);try{let r=await this.withOpenFile(t,async i=>{let s={line:e.line,character:e.character};if(await this.manager.sendFeatureRequest(y.PREPARE_RENAME,{textDocument:{uri:i},position:s})==null)throw new Error("Symbol at this position cannot be renamed");return this.manager.sendFeatureRequest(y.RENAME,{textDocument:{uri:i},position:s,newName:e.newName})});return{content:[{type:"text",text:r==null?"rename: no result":`rename: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("rename",r)}}async handleTypeHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleTypeHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.fetchTypeHierarchy(t,e.line,e.character,e.direction);return{content:[{type:"text",text:`typeHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("typeHierarchy",r)}}async handleCompletionItemResolve(e){if(!this.initialized)return this.buildNotReadyResponse();h.info("handleCompletionItemResolve");try{let t=await this.manager.sendFeatureRequest(y.COMPLETION_ITEM_RESOLVE,{item:e});return{content:[{type:"text",text:t==null?"completionItemResolve: no result":`completionItemResolve: ${JSON.stringify(t,null,2)}`}]}}catch(t){return this.buildErrorResponse("completionItemResolve",t)}}async fetchTypeHierarchy(e,t,r,o){return this.withOpenFile(e,async i=>{let s=await this.manager.sendFeatureRequest(y.PREPARE_TYPE_HIERARCHY,{textDocument:{uri:i},position:{line:t,character:r}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],results:[]};let c=o==="supertypes"?y.SUPERTYPES:y.SUBTYPES,l=await this.collectHierarchyItems(c,a);return{items:a,results:l}})}async collectHierarchyItems(e,t){let r=[];for(let o of t){let i=await this.manager.sendFeatureRequest(e,{item:o});Array.isArray(i)?r.push(...i):i&&r.push(i)}return r}async handleInlayHint(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};try{let o=(await Xe.promises.readFile(t,"utf8")).split(`
1311
+ `).length,i=await this.withOpenFile(t,async a=>this.manager.sendFeatureRequest(y.INLAY_HINT,{textDocument:{uri:a},range:{start:{line:0,character:0},end:{line:o,character:0}}}));return{content:[{type:"text",text:i==null?"inlayHint: no result":`inlayHint: ${JSON.stringify(i,null,2)}`}]}}catch(r){return this.buildErrorResponse("inlayHint",r)}}async handleDocumentLink(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};try{let r=await this.withOpenFile(t,async i=>this.manager.sendFeatureRequest(y.DOCUMENT_LINK,{textDocument:{uri:i}}));return{content:[{type:"text",text:r==null?"documentLink: no result":`documentLink: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("documentLink",r)}}buildErrorResponse(e,t){let r=t instanceof Error?t.message:String(t);return h.error(`${e} failed: ${r}`),{content:[{type:"text",text:`${e} failed: ${r}`}],isError:!0}}async withOpenFile(e,t){let r=Mr(e),o=await Xe.promises.readFile(e,"utf8"),s=`deveco.apptool.${ke.extname(e).replace(/^\./,"")||"plaintext"}`;h.debug(`withOpenFile didOpen uri=${r} len=${o.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,text:o,languageId:s,version:++this.documentVersion}});try{return await t(r)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:r},isManual:!1})}}resolveSingleFile(e){let t=ke.isAbsolute(e)?e:ke.join(this.projectPath,e);return!Xe.existsSync(t)||!Xe.statSync(t).isFile()||!t.endsWith(".ets")?null:t}buildNotReadyResponse(){return{content:[{type:"text",text:this.initializing?"LSP \u6B63\u5728\u521D\u59CB\u5316\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5":this.projectPath?"LSP\u672A\u521D\u59CB\u5316":"\u6CA1\u6709\u914D\u7F6E\u5DE5\u7A0B\u8DEF\u5F84\uFF0C\u8BF7\u914D\u7F6EPROJECT_PATH\u53C2\u6570"}],isError:!0}}collectValidFiles(e,t){let r=ke.resolve(this.projectPath),o=[];for(let i of e){let s=ke.resolve(ke.isAbsolute(i)?i:ke.join(r,i));if(!Xe.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${i}`);continue}if(!Xe.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${i}`);continue}if(!s.endsWith(".ets")){t.push(`\u4E0D\u662F .ets \u6587\u4EF6: ${i}`);continue}o.push(s)}return o}async runDiagnosticsForFiles(e,t,r){for(let o of e){await Ud(500);try{let i=await this.checkFile(o);r.push(Bk(o,i))}catch(i){t.push(`${o} => wait for diagnostics failed: ${i.message}`)}}}formatCallResult(e,t){let r=[];e.length>0&&r.push(e.join(`
1294
1312
  `)),t.length>0&&r.push(t.join(`
1295
- `));let i=r.join(`
1296
- `).trim(),o=e.length>0;return!o&&t.length===0&&(i="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:i}],isError:o}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){h.warn(`Failed to dispose ArktsLspManager: ${t}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":{this.handleDiagnosticsNotification(t.params);break}case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(Ze),h.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{h.info("Received arkts/initialized");let i=this.initResolve;this.clearInitHandlers(),i?.();break}case"arkts/initializationFailed":{let o=t.params?.message??"unknown";h.error(`LSP initialization failed: ${o}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${o}`));break}case"workspace/didChangeConfiguration":h.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let r=this.popDiagnosticWaiter(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.popDiagnosticWaiter(s)}if(!r)return;if(typeof e.errorMessage=="string"){h.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let i=e.diagnostics,o=Array.isArray(i)?i.length:0;h.debug(`diagnostics received uri=${t} count=${o}`),r.resolve(Array.isArray(i)?i:[])}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}getLogAndIndexPath(e){try{let t=Ee.join(Wt(),"ArkTSCheck"),r=Ee.join(t,"mapping-config.properties"),i=dd(e,r),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=Ee.join(t,"lsp-log",String(i),o),a=Ee.join(t,"lsp-index",String(i));return qe.mkdirSync(s,{recursive:!0}),qe.mkdirSync(a,{recursive:!0}),{logPath:fe(s),indexPath:fe(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function QP(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 eC(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 un from"fs";import*as qn from"path";import{z as Xc}from"zod";function Lr(){return{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}function _s(n,e){let t=e instanceof Error?e.message:String(e);return h.error(`[CppLsp] ${n} failed: ${t}`),{content:[{type:"text",text:`${n} failed: ${t}`}],isError:!0}}var tC=500,Nr=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:Xc.object({files:Xc.array(Xc.string()).describe('List of C/C++ file paths to check, format: ["file1.cpp","file2.hpp",...]')})}}async handleCall(e){if(!this.manager.ready)return Lr();let t=[],r=[],i=this.collectValidFiles(e.files,t);if(i.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
1297
- `):"No valid C/C++ files"}],isError:!0};for(let c of i){await rC(tC);try{let l=await this.checkFile(c);r.push(nC(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(`
1313
+ `));let o=r.join(`
1314
+ `).trim(),i=e.length>0;return!i&&t.length===0&&(o="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:o}],isError:i}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){h.warn(`Failed to dispose ArktsLspManager: ${t}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":{this.handleDiagnosticsNotification(t.params);break}case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(nt),h.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{h.info("Received arkts/initialized");let o=this.initResolve;this.clearInitHandlers(),o?.();break}case"arkts/initializationFailed":{let i=t.params?.message??"unknown";h.error(`LSP initialization failed: ${i}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${i}`));break}case"workspace/didChangeConfiguration":h.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let r=this.popDiagnosticWaiter(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.popDiagnosticWaiter(s)}if(!r)return;if(typeof e.errorMessage=="string"){h.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let o=e.diagnostics,i=Array.isArray(o)?o.length:0;h.debug(`diagnostics received uri=${t} count=${i}`),r.resolve(Array.isArray(o)?o:[])}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}getLogAndIndexPath(e){try{let t=ke.join(Kt(),"ArkTSCheck"),r=ke.join(t,"mapping-config.properties"),o=Bd(e,r),i=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=ke.join(t,"lsp-log",String(o),i),a=ke.join(t,"lsp-index",String(o));return Xe.mkdirSync(s,{recursive:!0}),Xe.mkdirSync(a,{recursive:!0}),{logPath:ge(s),indexPath:ge(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function Uk(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 Bk(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 wr from"fs";import*as en from"path";import{z as Il}from"zod";function Wn(){return{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}function oa(n,e){let t=e instanceof Error?e.message:String(e);return h.error(`[CppLsp] ${n} failed: ${t}`),{content:[{type:"text",text:`${n} failed: ${t}`}],isError:!0}}var Wk=500,Vn=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:Il.object({files:Il.array(Il.string()).describe('List of C/C++ file paths to check, format: ["file1.cpp","file2.hpp",...]')})}}async handleCall(e){if(!this.manager.ready)return Wn();let t=[],r=[],o=this.collectValidFiles(e.files,t);if(o.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
1315
+ `):"No valid C/C++ files"}],isError:!0};for(let c of o){await qk(Wk);try{let l=await this.checkFile(c);r.push(Vk(c,l))}catch(l){t.push(`${c} => wait for diagnostics failed: ${l.message}`)}}let i=t.length>0,s=[];t.length>0&&s.push(t.join(`
1298
1316
  `)),r.length>0&&s.push(r.join(`
1299
1317
  `));let a=s.join(`
1300
- `).trim();return!o&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:o}}async checkFile(e){let t=Dn(e),r=await un.promises.readFile(e,"utf8"),i=eo(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=qn.resolve(this.manager.projectRoot),i=[];for(let o of e){let s=qn.resolve(qn.isAbsolute(o)?o:qn.join(r,o));if(!un.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!un.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!An(s)){t.push(`Not a supported C/C++ file: ${o}`);continue}try{i.push(un.realpathSync(s))}catch{i.push(s)}}return i}};function nC(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 rC(n){return new Promise(e=>setTimeout(e,n))}import*as Mr from"fs";import*as js from"path";var Or=class n{manager;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION};constructor(e){this.manager=e}async handleLspFeature(e,t){if(!this.manager.ready)return Lr();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`[ClangdLspTool] handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){return _s(e,o)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return h.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return Lr();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};h.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return _s("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return Lr();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};h.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,o=>this.fetchCallHierarchyResult(o,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return _s("callHierarchy",r)}}async fetchCallHierarchyResult(e,t){let r=await this.manager.sendFeatureRequest(y.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(y.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let r=Dn(e),i=await Mr.promises.readFile(e,"utf8"),o=eo(e);h.info(`[ClangdLspTool] withOpenFile didOpen uri=${r} langId=${o} len=${i.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:r,text:i,languageId:o,version:i.length}}});try{return await t(r)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:r}}})}}resolveSingleFile(e){let t=js.isAbsolute(e)?e:js.join(this.manager.projectRoot,e);return!Mr.existsSync(t)||!Mr.statSync(t).isFile()||!An(t)?null:t}};import{spawn as iC}from"child_process";import*as $s from"fs";import*as Sm from"path";var oC=30*1e3,sC=30*1e3,Fs=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new an;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{u.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),u.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),u.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(y.INITIALIZE,i,Ze),u.info("[ClangdLspProxy] initialize response received"),this.sendNotification(y.INITIALIZED,{}),t=!0}catch(r){this.lastStartErrorMessage=r instanceof Error?r.message:String(r),u.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(y.HOVER,e)}async definition(e){return this.sendLspRequest(y.DEFINITION,e)}async declaration(e){return this.sendLspRequest(y.DECLARATION,e)}async references(e){return this.sendLspRequest(y.REFERENCES,e)}async implementation(e){return this.sendLspRequest(y.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(y.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(y.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(y.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(y.DID_OPEN,e)}sendDidChange(e){this.sendNotification(y.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(y.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){u.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){u.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}`))},sC);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(y.SHUTDOWN,null,3e3).catch(e=>{u.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(y.EXIT,null),await this.client.waitForExitOrTimeout(300)}catch(e){u.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=${V(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];u.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=iC(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=tr(this.config.workspaceRoot),t=lt(e),r=Sm.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.1"},rootPath:e,rootUri:t,workspaceFolders:[{uri:t,name:r}],capabilities:this.buildClientCapabilities(),initializationOptions:null}}buildClientCapabilities(){return{textDocument:{synchronization:{didOpen:!0,didChange:!0,didClose:!0,willSave:!1,save:!1},publishDiagnostics:{relatedInformation:!0,versionSupport:!1,tagSupport:{valueSet:[1,2]}},hover:{contentFormat:["markdown","plaintext"]},completion:{contextSupport:!1,completionItemKind:{valueSet:[]}},signatureHelp:{signatureInformation:{documentationFormat:["markdown","plaintext"]}},references:{},declaration:{linkSupport:!0},definition:{linkSupport:!0},implementation:{linkSupport:!0},documentSymbol:{hierarchicalDocumentSymbolSupport:!0,symbolKind:{valueSet:[]}},callHierarchy:{dynamicRegistration:!1}},workspace:{symbol:{symbolKind:{valueSet:[]}},configuration:!1,didChangeWatchedFiles:{dynamicRegistration:!1}}}}sendLspRequest(e,t,r=oC){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);u.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):u.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;u.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 y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.onMessage({jsonrpc:T,method:y.PROGRESS,params:e.params});break;case y.WINDOW_SHOW_MESSAGE:u.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:u.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:T,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;u.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:T,method:y.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{$s.existsSync(this.config.logPath)||$s.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)),lt(r)}}catch{}return e}};import*as Li from"path";import*as Zc from"fs";var Ni=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){u.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(u.info("[ClangdLspManager] Received cpp/syncProject"),!e||!t)return u.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};if(Yt(e).length===0)return u.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let a=o?.skipCompileNative===!0,c=await fo(e,a?async()=>(u.info("[ClangdLspManager] compileNative skipped (C++ project up-to-date)"),{status:"success"}):async()=>n.executeCompileNative(e,t,r,i));return c.acquired?c.result:(u.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 Qd(e,t,r,i),u.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(o){let s=o instanceof Error?o.message:String(o);return u.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(Ze);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=Ct(this.config.workspaceRoot);this.resolvedRoot=e?fe(e):fe(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();yo(t);let r=this.config.clangdPath;if(!r){let s="clangd not found (install DevEco Studio / CLT)";u.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let i=Li.dirname(In(this.resolvedRoot));try{Zc.mkdirSync(i,{recursive:!0})}catch(s){u.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}u.info(`[ClangdLspManager] clangdPath: ${r}`),u.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),u.info(`[ClangdLspManager] compileCommandsDir: ${i}`);let o=new Fs({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,u.info("[ClangdLspManager] clangd initialized");let r=this.initResolve;this.clearInitHandlers(),r?.()}else{let r=t??this.proxy?.consumeStartErrorMessage()??"unknown error";u.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){u.warn("[ClangdLspManager] dispatchNotification: missing method");return}let i=t.params;switch(r){case y.DID_OPEN:this.proxy.sendDidOpen(i);break;case y.DID_CHANGE:this.proxy.sendDidChange(i);break;case y.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){u.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){try{let e=Li.join(Wt(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=Li.join(e,"lsp-log",t);return Zc.mkdirSync(r,{recursive:!0}),fe(r)}catch{return"auto"}}};function Em(n){let e=ho(n);return u.info(`[SyncGuard] ${e.reason}`),e}var tl=(s=>(s[s.IDLE=0]="IDLE",s[s.DISCOVERING=1]="DISCOVERING",s[s.SYNCING=2]="SYNCING",s[s.INITIALIZING=3]="INITIALIZING",s[s.READY=4]="READY",s[s.ERROR=5]="ERROR",s))(tl||{}),Pm=(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))(Pm||{}),St=3,Qc=600*1e3,el=100,Hs=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";sdkPath="";arktsLangServerPath=null;nodePath="";ohpmJsPath="";hvigorJsPath="";clangdPath=null;initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;standardProtocolAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;cppEnabled;constructor(e={}){this.config=e,Rn(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),h.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",h.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,h.info(`Constructor: using configured path as startPath: '${t}'`));let i=Ct(t);h.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0,this.sdkPath=this.config.sdkPath??"",this.arktsLangServerPath=this.config.arktsLangServerPath??null,this.nodePath=this.config.nodePath??"",this.ohpmJsPath=this.config.ohpmJsPath??"",this.hvigorJsPath=this.config.hvigorJsPath??"",this.clangdPath=this.config.clangdPath??null,this.cppEnabled=this.config.cppEnabled??!0,h.info(`Constructor: sdkPath='${this.sdkPath}', arktsLangServerPath='${this.arktsLangServerPath??"(null)"}', cppEnabled=${this.cppEnabled}`),this.server=new aC({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=zc(e.telemetry,()=>this.arktsCheckTool?.aceServerPid??null,()=>this.config.projectPath??"",()=>this.sdkPath??""),this.standardProtocolAvailable=this.detectStandardProtocolAvailable(),this.registerTools()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools(),this.registerRestartTool()}registerRestartTool(){this.toolRouter.add({name:"restart",description:"Restart the MCP server in-place: re-sync the project and re-initialize the LSP, without dropping the client connection. Use to recover from a stuck/ERROR state after fixing the root cause, instead of exiting and reopening the agent. Use target to restart one side only (arkts/cpp) or both (all, default). Only callable when the project state is ready/idle/error; during discovery/sync/init (large-project init can take minutes) it returns an error\u2014wait for ready and retry tools instead. Caution: if initialization fails again after a restart, the cause is likely a persistent project/SDK configuration issue\u2014do not call restart repeatedly; ask the user to fix the project first.",inputSchema:pe.object({target:pe.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:pe.object({files:pe.array(pe.string()).min(1).describe("List of source file paths to check, relative to the project root (absolute paths within the project are also accepted). Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}registerLspFeatureTools(){if(!this.standardProtocolAvailable){h.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=pe.object({file:pe.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:pe.number().describe("Line number (0-based)"),character:pe.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:pe.object({query:pe.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:pe.object({file:pe.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:pe.object({file:pe.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:pe.number().describe("Line number (0-based)"),character:pe.number().describe("Character offset in the line (0-based)"),direction:pe.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.arktsLangServerPath;if(!e)return h.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=Qi(e);return h.info(`ArktsCheck protocol: ${t?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${t})`),t}catch(e){return h.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}validateContainment(e){let t=this.config.projectPath;if(t){let i=[];for(let o of e){let s=S.isPathContainedWithSymlink(o,t);s.contained||(h.warn(`Containment check failed: ${s.reason}`),i.push(s.reason))}return i.length>0?{content:[{type:"text",text:i.join(`
1301
- `)}],isError:!0}:null}let r=e.filter(i=>pn.isAbsolute(i));return r.length>0?(h.warn(`Absolute paths rejected (no project root): ${r.join(", ")}`),{content:[{type:"text",text:r.map(i=>`Absolute path is not allowed: ${i}`).join(`
1302
- `)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(d=>typeof d=="string"):[];if(t.length===0)return h.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>el)return h.warn(`check tool called with ${t.length} files (max: ${el})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${el}.`}],isError:!0};let{etsFiles:r,cppFiles:i,unsupported:o}=lC(t);o.length>0&&h.warn(`Unsupported file types in check request: ${o.join(", ")}`);let s=o.map(d=>`Unsupported file type: ${d} (only .ets and C/C++ source/header files are supported)`),a=[];r.length>0&&this.mergeCheckResult(await this.callArktsCheck(r),s,a),i.length>0&&this.mergeCheckResult(await this.callCppCheck(i),s,a);let c=s.length>0;return{content:[{type:"text",text:[a.join(`
1318
+ `).trim();return!i&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:i}}async checkFile(e){let t=Mr(e),r=await wr.promises.readFile(e,"utf8"),o=yi(e),i=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:r,languageId:o,version:r.length}}});try{return await i}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let r=en.resolve(this.manager.projectRoot),o=[];for(let i of e){let s=en.resolve(en.isAbsolute(i)?i:en.join(r,i));if(!wr.existsSync(s)){t.push(`File does not exist: ${i}`);continue}if(!wr.statSync(s).isFile()){t.push(`Not a regular file: ${i}`);continue}if(!Nr(s)){t.push(`Not a supported C/C++ file: ${i}`);continue}try{o.push(wr.realpathSync(s))}catch{o.push(s)}}return o}};function Vk(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 qk(n){return new Promise(e=>setTimeout(e,n))}import*as Gn from"fs";import*as ia from"path";var qn=class n{manager;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION};constructor(e){this.manager=e}async handleLspFeature(e,t){if(!this.manager.ready)return Wn();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 o=n.FEATURE_METHOD_MAP[e];if(!o)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`[ClangdLspTool] handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let i=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(o,c)});return{content:[{type:"text",text:i==null?`${e}: no result`:`${e}: ${JSON.stringify(i,null,2)}`}]}}catch(i){return oa(e,i)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return h.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return Wn();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};h.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async i=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:i}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return oa("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return Wn();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};h.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,i=>this.fetchCallHierarchyResult(i,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return oa("callHierarchy",r)}}async fetchCallHierarchyResult(e,t){let r=await this.manager.sendFeatureRequest(y.PREPARE_CALL_HIERARCHY,{textDocument:{uri:e},position:{line:t.line,character:t.character}}),o=this.normalizeCallHierarchyItems(r);if(o.length===0)return{items:[],calls:[]};let i=await this.collectIncomingCalls(o);return{items:o,calls:i}}normalizeCallHierarchyItems(e){return Array.isArray(e)?e:e?[e]:[]}async collectIncomingCalls(e){let t=[];for(let r of e)t.push(...await this.fetchIncomingCalls(r));return t}async fetchIncomingCalls(e){let t=await this.manager.sendFeatureRequest(y.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let r=Mr(e),o=await Gn.promises.readFile(e,"utf8"),i=yi(e);h.info(`[ClangdLspTool] withOpenFile didOpen uri=${r} langId=${i} len=${o.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:r,text:o,languageId:i,version:o.length}}});try{return await t(r)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:r}}})}}resolveSingleFile(e){let t=ia.isAbsolute(e)?e:ia.join(this.manager.projectRoot,e);return!Gn.existsSync(t)||!Gn.statSync(t).isFile()||!Nr(t)?null:t}};import{spawn as Gk}from"child_process";import*as aa from"fs";import*as Rh from"path";var zk=30*1e3,Jk=30*1e3,sa=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new hr;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 fr(r),this.client.on("message",i=>this.handleRawMessage(i)),this.client.on("error",i=>this.handleError(i)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let o=this.buildInitializeParams();await this.sendLspRequest(y.INITIALIZE,o,nt),f.info("[ClangdLspProxy] initialize response received"),this.sendNotification(y.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(y.HOVER,e)}async definition(e){return this.sendLspRequest(y.DEFINITION,e)}async declaration(e){return this.sendLspRequest(y.DECLARATION,e)}async references(e){return this.sendLspRequest(y.REFERENCES,e)}async implementation(e){return this.sendLspRequest(y.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(y.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(y.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(y.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(y.DID_OPEN,e)}sendDidChange(e){this.sendNotification(y.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(y.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,o)=>{let i=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&o(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},Jk);this.diagnosticWaiters.set(t,{resolve:r,reject:o,timer:i})})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){this.requestCallbacks.rejectAll(new Error("ClangdLspProxy disposing"));for(let[,e]of this.diagnosticWaiters)clearTimeout(e.timer),e.reject(new Error("ClangdLspProxy disposing"));if(this.diagnosticWaiters.clear(),this.client&&this.clangdProcess)try{await this.sendLspRequest(y.SHUTDOWN,null,3e3).catch(e=>{f.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(y.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=${z(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];f.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=Gk(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=un(this.config.workspaceRoot),t=ft(e),r=Rh.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.3-Test.2"},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=zk){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let o=this.nextRequestId++,i=this.requestCallbacks.registerPending(o,e,r);return this.client.sendRequest(e,t,o),i}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let o=r instanceof Error?r.message:String(r);f.error(`[ClangdLspProxy] JSON parse error: ${o}, raw: ${e.slice(0,200)}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotification(t):f.warn(`[ClangdLspProxy] unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t==null||typeof t!="string"&&typeof t!="number")return;let r=t;if(e.error!==void 0&&e.error!==null){let o=e.error;f.warn(`[ClangdLspProxy] LSP error id=${r}: code=${o.code??-1} message=${o.message??"unknown"}`),this.requestCallbacks.rejectPending(r,new Error(`LSP error ${o.code??-1}: ${o.message??"unknown"}`))}else this.requestCallbacks.resolvePending(r,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.onMessage({jsonrpc:T,method:y.PROGRESS,params:e.params});break;case y.WINDOW_SHOW_MESSAGE:f.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:f.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:T,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 o=Array.isArray(e.diagnostics)?e.diagnostics:[],i=o.length;f.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${i}`),r.resolve(o)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:T,method:y.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{aa.existsSync(this.config.logPath)||aa.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 Ko from"path";import*as Al from"fs";var Xo=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,o,i){if(f.info("[ClangdLspManager] Received cpp/syncProject"),!e||!t)return f.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};if(rr(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let a=i?.skipCompileNative===!0,c=await Di(e,a?async()=>(f.info("[ClangdLspManager] compileNative skipped (C++ project up-to-date)"),{status:"success"}):async()=>n.executeCompileNative(e,t,r,o));return c.acquired?c.result:(f.info("[ClangdLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}static async executeCompileNative(e,t,r,o){try{return await xu(e,t,r,o),f.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(i){let s=i instanceof Error?i.message:String(i);return f.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}doStart(){return new Promise((e,t)=>{this.initResolve=e,this.initReject=t,this.armInitTimer(nt);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=Lt(this.config.workspaceRoot);this.resolvedRoot=e?ge(e):ge(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();Li(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 o=Ko.dirname(Lr(this.resolvedRoot));try{Al.mkdirSync(o,{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: ${o}`);let i=new sa({clangdPath:r,workspaceRoot:this.resolvedRoot,compileCommandsDir:o,logPath:t});i.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=i,i.start(s=>this.handleProxyInitialized(s)).catch(s=>{let a=s instanceof Error?s:new Error(String(s));this.handleProxyInitialized(!1,a.message)})}handleProxyInitialized=(e,t)=>{if(this.clearInitTimer(),e){this.isInitialized=!0,f.info("[ClangdLspManager] clangd initialized");let 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 o=this.initReject;this.clearInitHandlers(),o?.(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 o=t.params;switch(r){case y.DID_OPEN:this.proxy.sendDidOpen(o);break;case y.DID_CHANGE:this.proxy.sendDidChange(o);break;case y.DID_CLOSE:this.proxy.sendDidClose(o);break;default:this.proxy.sendNotification(r,o)}}armInitTimer(e){this.clearInitTimer(),this.initDeadlineTimer=setTimeout(()=>{this.failInit(new Error("C++ LSP initialize timeout"))},e)}clearInitTimer(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null)}clearInitHandlers(){this.clearInitTimer(),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async performDispose(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("ClangdLspManager disposing")),this.proxy){try{await this.proxy.dispose()}catch(t){f.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){try{let e=Ko.join(Kt(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=Ko.join(e,"lsp-log",t);return Al.mkdirSync(r,{recursive:!0}),ge(r)}catch{return"auto"}}};function Th(n){let e=Ti(n);return f.info(`[SyncGuard] ${e.reason}`),e}var Tl=(s=>(s[s.IDLE=0]="IDLE",s[s.DISCOVERING=1]="DISCOVERING",s[s.SYNCING=2]="SYNCING",s[s.INITIALIZING=3]="INITIALIZING",s[s.READY=4]="READY",s[s.ERROR=5]="ERROR",s))(Tl||{}),xh=(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))(xh||{}),Tt=3,Dl=600*1e3,Rl=100,ca=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";sdkPath="";arktsLangServerPath=null;nodePath="";ohpmJsPath="";hvigorJsPath="";clangdPath=null;initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;standardProtocolAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;cppEnabled;constructor(e={}){this.config=e,Or(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),h.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",h.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,h.info(`Constructor: using configured path as startPath: '${t}'`));let o=Lt(t);h.info(`Constructor: findHarmonyProject('${t}') => ${o??"null"}`),this.config.projectPath=o??void 0,this.sdkPath=this.config.sdkPath??"",this.arktsLangServerPath=this.config.arktsLangServerPath??null,this.nodePath=this.config.nodePath??"",this.ohpmJsPath=this.config.ohpmJsPath??"",this.hvigorJsPath=this.config.hvigorJsPath??"",this.clangdPath=this.config.clangdPath??null,this.cppEnabled=this.config.cppEnabled??!0,h.info(`Constructor: sdkPath='${this.sdkPath}', arktsLangServerPath='${this.arktsLangServerPath??"(null)"}', cppEnabled=${this.cppEnabled}`),this.server=new Yk({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=El(e.telemetry,()=>this.arktsCheckTool?.aceServerPid??null,()=>this.config.projectPath??"",()=>this.sdkPath??""),this.standardProtocolAvailable=this.detectStandardProtocolAvailable(),this.registerTools()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools(),this.registerRestartTool()}registerRestartTool(){this.toolRouter.add({name:"restart",description:"Restart the MCP server in-place: re-sync the project and re-initialize the LSP, without dropping the client connection. Use to recover from a stuck/ERROR state after fixing the root cause, instead of exiting and reopening the agent. Use target to restart one side only (arkts/cpp) or both (all, default). Only callable when the project state is ready/idle/error; during discovery/sync/init (large-project init can take minutes) it returns an error\u2014wait for ready and retry tools instead. Caution: if initialization fails again after a restart, the cause is likely a persistent project/SDK configuration issue\u2014do not call restart repeatedly; ask the user to fix the project first.",inputSchema:he.object({target:he.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:he.object({files:he.array(he.string()).min(1).describe("List of source file paths to check, relative to the project root (absolute paths within the project are also accepted). Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}registerLspFeatureTools(){if(!this.standardProtocolAvailable){h.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=he.object({file:he.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:he.number().describe("Line number (0-based)"),character:he.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature:o}of this.getPositionFeatures())this.toolRouter.add({name:t,description:r,inputSchema:e},async i=>this.handleLspFeatureCall(o,i));this.registerSymbolTools(),this.registerCallHierarchyTool()}getPositionFeatures(){return[{name:"hover",description:"Get hover information (type info, documentation) at a specific position in an ArkTS (.ets) or C/C++ file.",feature:"hover"},{name:"definition",description:"Find where the symbol at the given position is defined. Returns file path, line, and character.",feature:"definition"},{name:"declaration",description:"Find the declaration of the symbol at the given position. In ArkTS, this may differ from definition.",feature:"declaration"},{name:"references",description:"Find all references to the symbol at the given position across the HarmonyOS project.",feature:"references"},{name:"implementation",description:"Find implementations of the symbol at the given position (e.g., interface implementations).",feature:"implementation"}]}registerSymbolTools(){this.toolRouter.add({name:"workspaceSymbol",description:"Search for symbols by name across the entire HarmonyOS project.",inputSchema:he.object({query:he.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:he.object({file:he.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:he.object({file:he.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:he.number().describe("Line number (0-based)"),character:he.number().describe("Character offset in the line (0-based)"),direction:he.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.arktsLangServerPath;if(!e)return h.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=gi(e);return h.info(`ArktsCheck protocol: ${t?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${t})`),t}catch(e){return h.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}validateContainment(e){let t=this.config.projectPath;if(t){let o=[];for(let i of e){let s=S.isPathContainedWithSymlink(i,t);s.contained||(h.warn(`Containment check failed: ${s.reason}`),o.push(s.reason))}return o.length>0?{content:[{type:"text",text:o.join(`
1319
+ `)}],isError:!0}:null}let r=e.filter(o=>br.isAbsolute(o));return r.length>0?(h.warn(`Absolute paths rejected (no project root): ${r.join(", ")}`),{content:[{type:"text",text:r.map(o=>`Absolute path is not allowed: ${o}`).join(`
1320
+ `)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(d=>typeof d=="string"):[];if(t.length===0)return h.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>Rl)return h.warn(`check tool called with ${t.length} files (max: ${Rl})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${Rl}.`}],isError:!0};let{etsFiles:r,cppFiles:o,unsupported:i}=Xk(t);i.length>0&&h.warn(`Unsupported file types in check request: ${i.join(", ")}`);let s=i.map(d=>`Unsupported file type: ${d} (only .ets and C/C++ source/header files are supported)`),a=[];r.length>0&&this.mergeCheckResult(await this.callArktsCheck(r),s,a),o.length>0&&this.mergeCheckResult(await this.callCppCheck(o),s,a);let c=s.length>0;return{content:[{type:"text",text:[a.join(`
1303
1321
  `),s.join(`
1304
1322
  `)].filter(d=>d.trim().length>0).join(`
1305
- `).trim()||"No diagnostics collected"}],isError:c}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS check rejected: project is ${tl[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e});default:return h.error(`ArkTS check: unknown project state ${this.projectState}, files: ${e.join(", ")}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],isError:!0}}}async handleLspFeatureCall(e,t){let r=t.file,i=t.line,o=t.character;return typeof r!="string"||typeof i!="number"||typeof o!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:this.routeLspRequest(r,e,async()=>{if(r.endsWith(".ets"))return this.arktsCheckTool.handleLspFeature(e,{file:r,line:i,character:o});let s=e;return this.cppLspTool.handleLspFeature(s,{file:r,line:i,character:o})})}async handleWorkspaceSymbolCall(e){let t=e.query;return typeof t!="string"||t.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameter: query (non-empty string required)."}],isError:!0}:this.routeWorkspaceSymbolRequest(t)}async routeWorkspaceSymbolRequest(e){let t=this.projectState===4&&this.arktsCheckTool!==null,r=this.cppProjectState===4&&!this.cppHasNoCppCode&&this.cppLspTool!==null;if(!t&&!r){let a=this.describeArktsState(),c=this.describeCppState();return h.info(`workspaceSymbol rejected: ArkTS ${a}; C++ ${c}`),{content:[{type:"text",text:`workspaceSymbol: ArkTS ${a}; C++ ${c}`}],isError:!0}}let i=[],o=new Set;if(t)try{this.mergeSymbolItems(await this.arktsCheckTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){h.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(r)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){h.warn(`workspaceSymbol C++ query failed: ${a.message}`)}return{content:[{type:"text",text:i.length===0?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(i,null,2)}`}]}}symbolDedupKey(e){let t=e,r=t?.location?.uri??"",i=t?.location?.range?.start?.line??0,o=t?.location?.range?.start?.character??0;return`${r}:${i}:${o}`}mergeSymbolItems(e,t,r){if(e)for(let i of e){let o=this.symbolDedupKey(i);t.has(o)||(t.add(o),r.push(i))}}describeArktsState(){switch(this.projectState){case 0:return"idle";case 1:return"discovering";case 2:return"syncing (retry 10s)";case 3:return"initializing (retry 10s)";case 5:return`error (${this.initRetryCount}/${St})`;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}/${St})`;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 handleCodeActionCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e);return t?this.routeArktsRequest("codeAction",()=>this.arktsCheckTool.handleCodeAction({file:t,line:r,character:i})):{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}}async handleRenameCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e),o=e.newName;return!t||typeof o!="string"||o.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number), newName (non-empty string)."}],isError:!0}:this.routeArktsRequest("rename",()=>this.arktsCheckTool.handleRename({file:t,line:r,character:i,newName:o}))}async handleTypeHierarchyCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e),o=e.direction;return t?o!=="supertypes"&&o!=="subtypes"?{content:[{type:"text",text:'Parameter direction must be "supertypes" or "subtypes".'}],isError:!0}:this.routeArktsRequest(`typeHierarchy(${o})`,()=>this.arktsCheckTool.handleTypeHierarchy({file:t,line:r,character:i,direction:o})):{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}}async handleCompletionItemResolveCall(e){let t=e.item;return t==null?{content:[{type:"text",text:"Missing parameter: item (completion item object required)."}],isError:!0}:this.routeArktsRequest("completionItemResolve",()=>this.arktsCheckTool.handleCompletionItemResolve(t))}extractPositionArgs(e){let t=e.file,r=e.line,i=e.character;return typeof t!="string"||typeof r!="number"||typeof i!="number"?{file:null,line:0,character:0}:{file:t,line:r,character:i}}async routeArktsRequest(e,t){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS ${e} rejected: project is ${tl[this.projectState]}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS ${e} rejected: LSP is initializing`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return t();default:return h.warn(`ArkTS ${e} rejected: unknown project state ${this.projectState}`),{content:[{type:"text",text:"Unknown project state, please retry"}],isError:!0}}}async handleIdleCheck(){if(this.ensureProjectReady(),this.config.projectPath){let e,t;return this.syncSkippedDueToLock?(e=`Another build process is running, sync deferred (waiting ${this.syncSkipStartedAt>0?Math.round((Date.now()-this.syncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,t="lock contention",this.syncSkippedDueToLock=!1):this.configChangedTriggeredResync?(e="Config file changed, resyncing project, please retry in 10 seconds",t="config changed",this.configChangedTriggeredResync=!1):(e="HarmonyOS project detected, syncing, please retry in 10 seconds",t="initial"),h.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(h.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(h.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=St?(h.error(`Init retry limit reached (${this.initRetryCount}/${St}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${St}). Ask the user to investigate and confirm \`ohpm install\` + \`hvigor\` sync succeed manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],isError:!0}):(h.info(`Error check: auto-retrying (${this.initRetryCount}/${St})`),this.ensureProjectReady(),{content:[{type:"text",text:"Project initialization failed, auto-retrying, please retry in 10 seconds"}],isError:!0})}async routeCppRequest(e,t){switch(this.cppProjectState){case 0:return this.handleCppIdleCheck();case 1:case 2:return h.warn(`C++ ${e} rejected: C++ project is ${Pm[this.cppProjectState]}`),{content:[{type:"text",text:"C++ project is syncing (compileNative), please retry in 25 seconds"}],isError:!0};case 3:return h.warn(`C++ ${e} rejected: clangd is initializing`),{content:[{type:"text",text:"C++ LSP (clangd) is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleCppErrorCheck();case 4:return this.cppEnabled?this.cppHasNoCppCode?{content:[{type:"text",text:"No C++ code in this project"}],isError:!0}:this.cppLspManager?.ready?t():{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}:{content:[{type:"text",text:"C++ LSP is disabled. Set DEVECO_CLI_CPP_ENABLED=true to enable."}],isError:!0};default:return h.warn(`C++ ${e} rejected: unknown C++ project state ${this.cppProjectState}`),{content:[{type:"text",text:"Unknown C++ project state, please retry"}],isError:!0}}}async routeLspRequest(e,t,r){return e.endsWith(".ets")?this.routeArktsRequest(t,r):An(e)?this.routeCppRequest(t,r):{content:[{type:"text",text:`Unsupported file type: ${e} (only .ets and C/C++ source/header files are supported)`}],isError:!0}}async handleCppIdleCheck(){if(this.ensureCppProjectReady(),this.config.projectPath){let e;return this.cppSyncSkippedDueToLock?(e=`Another build process is running, C++ sync deferred (waiting ${this.cppSyncSkipStartedAt>0?Math.round((Date.now()-this.cppSyncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,this.cppSyncSkippedDueToLock=!1):e="C++ project detected, syncing (compileNative), please retry in 25 seconds",h.info(`C++ idle check: project '${this.config.projectPath}', triggering C++ init`),{content:[{type:"text",text:e}],isError:!0}}return{content:[{type:"text",text:"No HarmonyOS project detected for C++ tools."}],isError:!0}}async handleCppErrorCheck(){return this.cppInitRetryCount>=St?(h.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${St}), will not auto-retry`),{content:[{type:"text",text:`C++ project initialization failed repeatedly (auto-retry exhausted: ${this.cppInitRetryCount}/${St}). Ask the user to investigate and confirm \`hvigor compileNative\` succeeds manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],isError:!0}):(h.info(`C++ error check: auto-retrying (${this.cppInitRetryCount}/${St})`),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(`
1306
- `);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 ~10 seconds.`}]})}restartProject(e){h.info(`[restart] resetting tools + state, re-init (target=${e})`),(e==="arkts"||e==="all")&&this.restartArkts(),(e==="cpp"||e==="all")&&this.cppEnabled&&this.restartCpp()}restartArkts(){this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(e=>h.warn("Failed to shutdown ArktsCheckTool during restart:",e)),this.arktsCheckTool=null),this.initRetryCount=0,this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.configChangedTriggeredResync=!1,this.initPromise?(this.needsReinit=!0,h.info("[restart] ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(e=>h.warn("Failed to re-init ArkTS project during restart:",e)))}restartCpp(){this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(e=>h.warn("Failed to dispose ClangdLspManager during restart:",e)),this.cppLspManager=null),this.cppInitRetryCount=0,this.cppHasNoCppCode=!1,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitPromise?(this.cppNeedsReinit=!0,h.info("[restart] C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>h.warn("Failed to re-init C++ project during restart:",e)))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{h.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(t=>{h.warn("Failed to dispose ClangdLspManager during setProjectPath:",t)}),this.cppLspManager=null),this.initPromise?(this.needsReinit=!0,h.info("Project path changed while ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{h.warn("Failed to re-init project after setProjectPath:",t)})),this.cppInitPromise?(this.cppNeedsReinit=!0,h.info("Project path changed while C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.cppHasNoCppCode=!1,this.cppInitRetryCount=0,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.ensureCppProjectReady().catch(t=>{h.warn("Failed to re-init C++ project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new cC;if(await this.server.connect(e),h.info("devecocli-mcp-server started"),!this.config.debug){let t=md();t&&h.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=Ct(t);r?(h.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):h.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?h.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):h.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{h.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return h.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return h.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){h.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,h.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{h.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{h.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{h.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?Ct(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=Ct(this.originalProjectPath),t&&h.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(!this.discoverProject()||!await this.ensureProjectSynced())return;this.ensureCppProjectReady().catch(t=>{h.warn("Background C++ project init failed:",t)}),this.projectState=3,this.arktsCheckTool=new xr(this.config.projectPath,this.sdkPath,this.arktsLangServerPath,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{h.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});let e=Date.now();try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,h.info("Project fully initialized, check tool is available"),await this.trackInit("init_arkts",e,!0,null,this.arktsCheckTool?.aceServerPid??null)}catch(t){h.error("LSP initialization failed:",t);let r=B(t),i=this.arktsCheckTool?.aceServerPid??null;this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5,await this.trackInit("init_arkts",e,!1,r,i)}}async ensureProjectSynced(){let e=this.config.projectPath,t=Em(e),r=Oi.existsSync(pn.join(e,"oh-package-lock.json5")),i=Oi.existsSync(pn.join(e,"oh_modules"))&&Oi.readdirSync(pn.join(e,"oh_modules")).length>0;if(r&&i)return t.required?(h.info(`Sync required: ${t.reason}`),this.runSync(e,{skipHvigorSync:!1})):(h.info(`Sync skipped: ${t.reason}`),!0);let o=!t.required;return h.info(`Sync check: skipHvigor=${o}, ohpm install forced (lock=${r}, ohModules=${i}), reason=${t.reason}`),this.runSync(e,{skipHvigorSync:o})}async runSync(e,t){this.projectState=2,h.info("Starting project sync...");let r=await Tr.handleSyncProject(e,this.sdkPath,this.nodePath,this.ohpmJsPath,this.hvigorJsPath,t);switch(r.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let i=Date.now()-this.syncSkipStartedAt,o=Math.round(i/1e3);return i>=Qc?(h.error(`Sync skipped for ${o}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(h.warn(`Sync skipped: ${r.reason}, resetting to IDLE for retry (elapsed ${o}s / ${Qc/1e3}s)`),this.projectState=0,!1)}case"failed":return h.error(`Project sync failed: ${r.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return h.error(`Project sync: unknown status ${r.status}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}async ensureCppProjectReady(){if(!this.cppEnabled){h.info("[Cpp] C++ LSP disabled by config, skipping initialization"),this.cppHasNoCppCode=!0,this.cppProjectState=4;return}if(!this.cppInitPromise){this.cppInitPromise=this.doEnsureCppProjectReady();try{await this.cppInitPromise}finally{this.cppInitPromise=null}this.cppNeedsReinit&&(this.cppNeedsReinit=!1,this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>{h.warn("Failed to re-init C++ project after cppNeedsReinit:",e)}))}}async doEnsureCppProjectReady(){let e=this.config.projectPath;if(!e){h.info("[Cpp] No project path, skipping C++ init");return}this.cppProjectState=1;let t=Yt(e);if(t.length===0){h.info('[Cpp] No C++ modules found, C++ tools will return "no C++ code"'),this.cppHasNoCppCode=!0,this.cppProjectState=4,this.cppInitRetryCount=0;return}this.cppHasNoCppCode=!1,h.info(`[Cpp] Found ${t.length} C++ module(s): ${t.map(o=>o.name).join(", ")}`);let r=ru(e),i=!r.required;h.info(`[Cpp] C++ sync check: skipCompileNative=${i}, reason=${r.reason}`),await this.runSyncCpp(e,{skipCompileNative:i})&&await this.initCppLsp(e)}async initCppLsp(e){this.cppProjectState=3,this.cppLspManager=new Ni({workspaceRoot:e,clangdPath:this.clangdPath??""});let t=Date.now();try{await this.cppLspManager.start(),this.cppCheckTool=new Nr(this.cppLspManager),this.cppLspTool=new Or(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,h.info("[Cpp] C++ project fully initialized, C++ tools are available"),await this.trackInit("init_cpp",t,!0,null,this.cppLspManager?.clangdPid??null)}catch(r){h.error("[Cpp] C++ LSP initialization failed:",r);let i=B(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 Xe(o);l!==null&&(s=ce(Number(l)*1024))}let a={event:b.McpToolCall,subAction:e,mcpMemory:ce(process.memoryUsage().rss),lspMemory:s},c={duration_ms:Date.now()-t,success:r,error_code:i};await this.config.telemetry.track(a,c).catch(()=>{})}async runSyncCpp(e,t){this.cppProjectState=2,h.info("[Cpp] Starting C++ project sync (compileNative)...");let r=await Ni.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>=Qc?(h.error(`[Cpp] C++ sync skipped for ${o}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(h.warn(`[Cpp] C++ sync skipped: ${r.reason}, resetting to IDLE_CPP for retry (elapsed ${o}s)`),this.cppProjectState=0,!1)}case"failed":return h.error(`[Cpp] C++ project sync failed: ${r.reason}`),this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitRetryCount++,this.cppProjectState=5,!1}return!1}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppLspManager&&await this.cppLspManager.dispose(),this.cppCheckTool=null,this.cppLspTool=null;try{await this.server.close()}catch(e){h.warn("Failed to close MCP server connection:",e)}h.info("devecocli-mcp-server stopped"),fd(),pd()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function lC(n){let e=[],t=[],r=[];for(let i of n)pn.extname(i).toLowerCase()===".ets"?e.push(i):An(i)?t.push(i):r.push(i);return{etsFiles:e,cppFiles:t,unsupported:r}}function nl(n={}){return new Hs(n)}import*as rl from"fs";import*as Mi from"path";import{spawn as dC}from"child_process";async function Cm(n){Rn(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:i,serverMaxSize:o}=await uC(n),s=mC(e,t,r,i,o);h.info("ace-server started, bridging stdio (initialize is left to the client)"),gC(s),await ol(s.pid,il("--arkts",n))}function il(n,e){return[n,...e.projectPath?["--project-path"]:[],...e.autoDetect?["--auto-detect"]:[]]}async function ol(n,e){let t="unknown";if(n!==null){let i=await Xe(n);i!==null&&(t=ce(Number(i)*1024))}let r={event:b.ServeLsp,args:e,lspMemory:t};await I.track(r)}async function uC(n){let e=await A.new(),t;if(n.projectPath)t=fe(Mi.resolve(n.projectPath)),h.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let c=Zi(process.cwd());t=fe(c??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=fe(process.cwd()),h.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,i=e.arktsLangServerPath;i||(h.error("ace-server not found (install DevEco Studio / CLT)."),process.exit(1));let o=Jr(i,!0),s=Mi.join(Wt(),"lsp-server",String(Date.now()));rl.mkdirSync(s,{recursive:!0});let a=pC(t,r);return h.info(`projectPath=${t}, sdkPath=${r}, arktsLangServerPath=${i}, serverPath=${o}, logPath=${s}, serverMaxSize=${a}MB`),{projectPath:t,sdkPath:r,serverPath:o,logPath:s,serverMaxSize:a}}function pC(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=fC(n,e),s=vo(o,i);return h.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${o}, override=${i??"none"})`),s}function fC(n,e){try{let t=[];return new Vn(n,e).getAllDependencyMap(t).status==="OK"?t.length:new It(n).getAllModuleInfo().length}catch{return 0}}function mC(n,e,t,r,i){let o=Mi.join(e,"lspLog");rl.mkdirSync(o,{recursive:!0});let s=hC(n,o,t,r,i),a=process.execPath??"node";return h.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),dC(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function hC(n,e,t,r,i){let o=V(e);return["--expose-gc",`--max-old-space-size=${i}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${o}`,n,"--stdio",`--logger-path=${o}`,"--logger-level=TRACE",`--projectPath=${V(t)}`,`--sdkPath=${V(r)}`]}function gC(n){n.on("error",e=>{h.error(`[ace-server] spawn error: ${e.message}`),process.exit(1)}),n.stdout?.on("error",e=>{h.error(`[ace-server] stdout error: ${e.message}`)}),n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("error",e=>{h.error(`[ace-server] stderr error: ${e.message}`)}),n.stderr?.on("data",e=>{h.error(`[ace-server] ${e.toString("utf8").trim()}`)}),n.stdin?.on("error",e=>{h.error(`[ace-server] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{h.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as km from"fs";import*as Gn from"path";import{spawn as yC}from"child_process";async function Im(n){Rn(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await vC(n),i=Gn.join(t,"compile_commands.json");km.existsSync(i)||h.warn(`compile_commands.json not found at ${i}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let o=bC(e,t,r);h.info("clangd started, bridging stdio (initialize is left to the client)"),EC(o),await ol(o.pid,il("--cpp",n))}async function vC(n){let e=await wC();e?.clangdPath||(h.error("clangd not found. Ensure DevEco Studio / CLT is installed."),process.exit(1));let t;if(n.projectPath)t=fe(Gn.resolve(n.projectPath)),h.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let a=Zi(process.cwd());t=fe(a??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${a??"null, fallback to cwd"}`)}else t=fe(Gn.resolve(process.cwd())),h.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,i=e.clangdPath,o=In(t),s=Gn.dirname(o);return h.info(`projectPath=${t}, sdkPath=${r}, clangdPath=${i}, compileCommandsDir=${s}`),{projectPath:t,clangdPath:i,compileCommandsDir:s}}async function wC(){try{return await A.new()}catch{let n=cd();if(!n)return null;try{return A.fromIDE(n)}catch{return null}}}function bC(n,e,t){let r=SC(e);return h.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),yC(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function SC(n){return[`--compile-commands-dir=${V(n)}`,"--log=info","--pch-storage=memory"]}function EC(n){n.on("error",e=>{h.error(`[clangd] spawn error: ${e.message}`),process.exit(1)}),n.stdout?.on("error",e=>{h.error(`[clangd] stdout error: ${e.message}`)}),n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("error",e=>{h.error(`[clangd] stderr error: ${e.message}`)}),n.stderr?.on("data",e=>{h.error(`[clangd] ${e.toString("utf8").trim()}`)}),n.stdin?.on("error",e=>{h.error(`[clangd] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{h.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function CC(){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=n,o=await A.new(),s=nl({projectPath:i,sdkPath:o.sdkPath,arktsLangServerPath:o.arktsLangServerPath??void 0,nodePath:o.nodePath,ohpmJsPath:o.ohpmJsPath,hvigorJsPath:o.hvigorJsPath,clangdPath:o.clangdPath??void 0,nodeMaxOldSpaceSize:e,debug:t,cppEnabled:r,telemetry:I}),a,c=new Promise(d=>{a=d}),l=async()=>{await s.shutdown(),a()};process.once("SIGINT",l),process.once("SIGTERM",l),process.platform==="win32"&&process.once("SIGBREAK",l);try{await s.start()}catch(d){console.error("Failed to start MCP server:",d instanceof Error?d.message:String(d)),process.exit(1)}await c}var sl=new PC("serve").description("Host bundled auxiliary protocol servers");sl.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await CC()});sl.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 Cm({projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await Im({projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var Am=sl;import{Command as xC,InvalidArgumentError as Lm}from"commander";import{red as LC,dim as NC}from"colorette";import{createRequire as kC}from"module";import{dirname as IC,join as _r}from"path";import{pathToFileURL as AC}from"url";import{readFile as Rm,access as al}from"fs/promises";import*as Tm from"semver";var DC=kC(import.meta.url),Dm=1;async function RC(){try{let n=DC.resolve("@yinsen/deveco-cli-docs-zh/package.json"),e=JSON.parse(await Rm(n,"utf8"));return{version:e.version,apiVersion:e.apiVersion??0,dir:IC(n)}}catch{return null}}async function TC(){let n=be(),e=_r(n,"doc-data","current.json"),t;try{t=JSON.parse(await Rm(e,"utf8"))}catch{return null}let r=_r(n,"doc-data",t.version);try{return await al(_r(r,"dist","engine","index.js")),await al(_r(r,"docs.zip")),await al(_r(r,"index.zip")),{version:t.version,apiVersion:t.apiVersion,dir:r}}catch{return null}}async function Us(){let n=[await TC(),await RC()].filter(t=>t!==null).sort((t,r)=>Tm.rcompare(t.version,r.version)),e=!1;for(let t of n){if(t.apiVersion>Dm){p(`docs: skip candidate v${t.version} (apiVersion ${t.apiVersion} > ${Dm})`),e=!0;continue}try{let r=_r(t.dir,"dist","engine","index.js");return await import(AC(r).href)}catch(r){p(`docs: candidate v${t.version} load failed: ${r instanceof Error?r.message:String(r)}`)}}throw e?new Error("\u6587\u6863\u5305\u7248\u672C\u4E0D\u517C\u5BB9\uFF0C\u8BF7\u5347\u7EA7 CLI"):new Error("\u6CA1\u6709\u53EF\u7528\u7684\u6587\u6863\u5305\uFF0C\u8BF7\u66F4\u65B0\u6587\u6863\u6216\u91CD\u65B0\u5B89\u88C5 CLI")}async function cl(n,e){let t=Date.now();try{let r=await e();return await xm(n,Date.now()-t,!0,null),r}catch(r){let i=r instanceof Error?r.code??r.name:"UnknownError";throw await xm(n,Date.now()-t,!1,i),r}}async function xm(n,e,t,r){await I.track(n,{duration_ms:e,success:t,error_code:r}).catch(()=>{})}function OC(n){return n instanceof Error&&(n.name==="CacheDirError"||n.name==="DocPathSafetyError")}function ll(n){console.error(LC(MC(n))),process.exitCode=1}function MC(n){let e=n instanceof Error?n.message:String(n);return OC(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 Nm(...n){return e=>{if(!n.includes(e))throw new Lm(`Allowed values: ${n.join(", ")}`);return e}}function _C(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new Lm("Must be a positive integer.");return e}var jC=Nm("json","default"),FC=Nm("json","default");function $C(n){let e=n.map(t=>t.trim()).filter(Boolean);if(e.length===0)throw new Error("Keywords cannot be empty.");return e}function HC(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 Ws=new xC("docs").description("Search and read HarmonyOS documentation from local docs directory");Ws.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)",jC,"default").option("--limit <n>","Max number of results",_C,10).action(async(n,e)=>{let t={event:b.DocOperation,subAction:"search",queryLen:n.join(" ").length,catalog:e.catalog??"all"};try{await cl(t,async()=>{let r=$C(n),i=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await Us(),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:be()});try{let c=await a.search({keywords:r,catalog:i,limit:e.limit});e.format==="json"?console.log(JSON.stringify(c,null,2)):HC(c)}finally{await a.close()}})}catch(r){ll(r)}});Ws.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{let e=n.trim(),t={event:b.DocOperation,subAction:"read",documentId:e};try{await cl(t,async()=>{if(!e)throw new Error("Document ID cannot be empty.");let i=await(await Us()).createDocsEngine({cacheDir:be()});try{let o=await i.read({relativePath:e});console.log(o)}finally{await i.close()}})}catch(r){ll(r)}});Ws.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",FC,"default").action(async n=>{let e={event:b.DocOperation,subAction:"catalog",fmt:n.format??"default"};try{await cl(e,async()=>{let r=await(await Us()).createDocsEngine({cacheDir:be()});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)} ${NC(o.nodeName)}`)}finally{await r.close()}})}catch(t){ll(t)}});var Om=Ws;import{Command as Jk}from"commander";import{Command as ZC,InvalidArgumentError as QC,Option as ul}from"commander";import{readFileSync as WC,unlinkSync as BC}from"fs";import{tmpdir as VC}from"os";import{join as qC}from"path";var $t=class{constructor(e,t){this.hdcPath=e;this.serial=t}hdcPath;serial;async listWindows(e){let t=await this.fetchDump(),r=UC(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"];p(`Executing: ${this.hdcPath} ${e.join(" ")}`);let t=await ie(this.hdcPath,e);if(t.exitCode!==0)throw new Error(`Failed to query windows: ${(t.stderr||t.stdout).trim()}`);return t.stdout}};function UC(n){let e=n.split(`
1307
- `),t=e.findIndex(s=>s.trimStart().startsWith("WindowName"));if(t===-1)return[];let r=[];for(let s=t+1;s<e.length;s++){let a=e[s].trim();if(!a||/^-+$/.test(a)||a.startsWith("Focus window")||a.startsWith("total window"))break;let c=a.split(/\s+/);if(c.length<5)continue;let l=c[0],d=Number(c[1]),g=Number(c[2]),v=Number(c[3]),D=Number(c[4]);Number.isFinite(v)&&Number.isFinite(d)&&Number.isFinite(g)&&r.push({id:v,name:l,pid:g,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 Mm(n){if(!(!n||n==="HitTestMode.Default"))return n.startsWith("HitTestMode.")?n.slice(12):n}function _i(n){if(!(n==null||n==="")){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1}}function _m(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 jm(n){return n.originalText||void 0}function jr(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 Fm(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 v={...i,children:[]};if(a?t.push(v):o.children.push(v),d=v,e>0&&s+1>=e)continue}if(process.env.DEVECO_CLI_DEBUG){let v=i.type?i.id?`${i.type}#${i.id}`:i.type:"#";p(`collapse ${v} depth=${s} -> ${a?"root":c?"collapsed":"emitted"}`)}let g=l?s+1:s;for(let v=i.children.length-1;v>=0;v--)r.push({current:i.children[v],parent:d,depth:g})}return t}function GC(n){let e=WC(n,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function zC(n){return n.attributes??{}}function Bs(n,e,t){let r=zC(n),i={id:r.id||void 0,type:r.type||void 0,text:jm(r),bounds:_m(r.bounds),clickable:_i(r.clickable)||void 0,longClickable:_i(r.longClickable)||void 0,scrollable:_i(r.scrollable)||void 0,checkable:_i(r.checkable)||void 0,hitTestBehavior:Mm(r.hitTestBehavior),children:[]};return e>0&&t+1>=e||n.children&&(i.children=n.children.map(o=>Bs(o,e,t+1))),i}function JC(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 w(`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 zn=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),p(`Executing: ${this.hdcPath} ${o.join(" ")}`);let s=await ie(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=qC(VC(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,r),GC(r)}finally{await this.cleanupDumpArtifacts(e,r,t)}}async recvDumpFile(e,t,r){let i=["-t",e,"file","recv",t,r];p(`Executing: ${this.hdcPath} ${i.join(" ")}`);let o=await ie(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{p(`Removing local dump file: ${t}`),BC(t)}catch(o){p(`Failed to clean local dump file ${t}: ${o.message}`)}let i=["-t",e,"shell","rm","-f",r];p(`Executing: ${this.hdcPath} ${i.join(" ")}`),await ie(this.hdcPath,i).catch(o=>{p(`Failed to clean remote dump file ${r}: ${o.message}`)})}async dumpRawNodes(e,t,r){let o=await new $t(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=JC(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=>Bs(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:Bs(s,t,0)})}return i}async dumpCollapsedTree(e,t,r,i){return(await this.dumpRawNodes(e,r,i)).flatMap(s=>Fm(Bs(s,0,0),t))}};var Vs={left:"0",right:"1",up:"2",down:"3"};function Te(n,e){let t=Number(n);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function dl(n,e){n!==void 0&&Te(n,e)}function $m(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function qs(n,e){if(n!==void 0&&n.length===0)throw new Error(`${e} must not be empty`)}function ji(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 Hm(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function Um(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 Fr(n,e,t,r,i=!0){$m(n,e),qs(t,"--id"),dl(n,"x"),dl(e,"y"),Hm(r),Um(n!==void 0,!!t,!!r,i)}async function fn(n,e){let r=await new wr(n).selectDevice(e);if(!r)throw new Error("No device selected. Use `devecocli device list` to see targets.");return r}async function Et(n){let e=await A.new(),t=await fn(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function $r(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 $t(n,e).listWindows({all:!0}),c=new zn(n);return YC(c,e,a,i,o)}async function YC(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 w(`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 XC(s,r)}return KC(n,e,t,r)}async function KC(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 jr([c],r))s.push({node:l,displayId:a});if(s.length===0)throw new w(`Node "${r}" not found.`,"Node not found.");if(s.length>1)throw new w(`Multiple nodes found with id "${r}".`,"Multiple nodes found");if(s[0].displayId!==0)throw new w(`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 Wm(s[0].node,r)}function XC(n,e){let t=jr(n,e);if(t.length===0)throw new w(`Node "${e}" not found.`,"Node not found.");if(t.length>1)throw new w(`Multiple nodes found with id "${e}".`,"Multiple nodes found");return Wm(t[0],e)}function Wm(n,e){let t=n.bounds;if(!t)throw new w(`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 it(n,e,t){let r=["-t",e,"shell",...t];p(`Executing: ${n} ${r.join(" ")}`);let i=await ie(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 ek from"ora";function tk(n){let e=parseInt(n,10);if(!Number.isInteger(e)||e<0||String(e)!==n.trim())throw new QC("depth must be a non-negative integer");return e}function nk(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 Bm(n,e=0){let t=[],r=" ".repeat(e);for(let i of n)t.push(`${r}${nk(i)}`),i.children.length>0&&t.push(...Bm(i.children,e+1).split(`
1323
+ `).trim()||"No diagnostics collected"}],isError:c}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS check rejected: project is ${Tl[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e});default:return h.error(`ArkTS check: unknown project state ${this.projectState}, files: ${e.join(", ")}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],isError:!0}}}async handleLspFeatureCall(e,t){let r=t.file,o=t.line,i=t.character;return typeof r!="string"||typeof o!="number"||typeof i!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:this.routeLspRequest(r,e,async()=>{if(r.endsWith(".ets"))return this.arktsCheckTool.handleLspFeature(e,{file:r,line:o,character:i});let s=e;return this.cppLspTool.handleLspFeature(s,{file:r,line:o,character:i})})}async handleWorkspaceSymbolCall(e){let t=e.query;return typeof t!="string"||t.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameter: query (non-empty string required)."}],isError:!0}:this.routeWorkspaceSymbolRequest(t)}async routeWorkspaceSymbolRequest(e){let t=this.projectState===4&&this.arktsCheckTool!==null,r=this.cppProjectState===4&&!this.cppHasNoCppCode&&this.cppLspTool!==null;if(!t&&!r){let a=this.describeArktsState(),c=this.describeCppState();return h.info(`workspaceSymbol rejected: ArkTS ${a}; C++ ${c}`),{content:[{type:"text",text:`workspaceSymbol: ArkTS ${a}; C++ ${c}`}],isError:!0}}let o=[],i=new Set;if(t)try{this.mergeSymbolItems(await this.arktsCheckTool.handleWorkspaceSymbolRaw(e),i,o)}catch(a){h.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(r)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),i,o)}catch(a){h.warn(`workspaceSymbol C++ query failed: ${a.message}`)}return{content:[{type:"text",text:o.length===0?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(o,null,2)}`}]}}symbolDedupKey(e){let t=e,r=t?.location?.uri??"",o=t?.location?.range?.start?.line??0,i=t?.location?.range?.start?.character??0;return`${r}:${o}:${i}`}mergeSymbolItems(e,t,r){if(e)for(let o of e){let i=this.symbolDedupKey(o);t.has(i)||(t.add(i),r.push(o))}}describeArktsState(){switch(this.projectState){case 0:return"idle";case 1:return"discovering";case 2:return"syncing (retry 10s)";case 3:return"initializing (retry 10s)";case 5:return`error (${this.initRetryCount}/${Tt})`;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}/${Tt})`;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,o=e.character,i=e.direction;return typeof t!="string"||typeof r!="number"||typeof o!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:i!=="incoming"&&i!=="outgoing"?{content:[{type:"text",text:'Parameter direction must be "incoming" or "outgoing".'}],isError:!0}:this.routeLspRequest(t,`callHierarchy(${i})`,async()=>t.endsWith(".ets")?this.arktsCheckTool.handleCallHierarchy({file:t,line:r,character:o,direction:i}):this.cppLspTool.handleCallHierarchy({file:t,line:r,character:o,direction:i}))}async handleCodeActionCall(e){let{file:t,line:r,character:o}=this.extractPositionArgs(e);return t?this.routeArktsRequest("codeAction",()=>this.arktsCheckTool.handleCodeAction({file:t,line:r,character:o})):{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}}async handleRenameCall(e){let{file:t,line:r,character:o}=this.extractPositionArgs(e),i=e.newName;return!t||typeof i!="string"||i.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number), newName (non-empty string)."}],isError:!0}:this.routeArktsRequest("rename",()=>this.arktsCheckTool.handleRename({file:t,line:r,character:o,newName:i}))}async handleTypeHierarchyCall(e){let{file:t,line:r,character:o}=this.extractPositionArgs(e),i=e.direction;return t?i!=="supertypes"&&i!=="subtypes"?{content:[{type:"text",text:'Parameter direction must be "supertypes" or "subtypes".'}],isError:!0}:this.routeArktsRequest(`typeHierarchy(${i})`,()=>this.arktsCheckTool.handleTypeHierarchy({file:t,line:r,character:o,direction:i})):{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}}async handleCompletionItemResolveCall(e){let t=e.item;return t==null?{content:[{type:"text",text:"Missing parameter: item (completion item object required)."}],isError:!0}:this.routeArktsRequest("completionItemResolve",()=>this.arktsCheckTool.handleCompletionItemResolve(t))}extractPositionArgs(e){let t=e.file,r=e.line,o=e.character;return typeof t!="string"||typeof r!="number"||typeof o!="number"?{file:null,line:0,character:0}:{file:t,line:r,character:o}}async routeArktsRequest(e,t){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS ${e} rejected: project is ${Tl[this.projectState]}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS ${e} rejected: LSP is initializing`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return t();default:return h.warn(`ArkTS ${e} rejected: unknown project state ${this.projectState}`),{content:[{type:"text",text:"Unknown project state, please retry"}],isError:!0}}}async handleIdleCheck(){if(this.ensureProjectReady(),this.config.projectPath){let e,t;return this.syncSkippedDueToLock?(e=`Another build process is running, sync deferred (waiting ${this.syncSkipStartedAt>0?Math.round((Date.now()-this.syncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,t="lock contention",this.syncSkippedDueToLock=!1):this.configChangedTriggeredResync?(e="Config file changed, resyncing project, please retry in 10 seconds",t="config changed",this.configChangedTriggeredResync=!1):(e="HarmonyOS project detected, syncing, please retry in 10 seconds",t="initial"),h.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(h.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(h.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=Tt?(h.error(`Init retry limit reached (${this.initRetryCount}/${Tt}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${Tt}). Ask the user to investigate and confirm \`ohpm install\` + \`hvigor\` sync succeed manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],isError:!0}):(h.info(`Error check: auto-retrying (${this.initRetryCount}/${Tt})`),this.ensureProjectReady(),{content:[{type:"text",text:"Project initialization failed, auto-retrying, please retry in 10 seconds"}],isError:!0})}async routeCppRequest(e,t){switch(this.cppProjectState){case 0:return this.handleCppIdleCheck();case 1:case 2:return h.warn(`C++ ${e} rejected: C++ project is ${xh[this.cppProjectState]}`),{content:[{type:"text",text:"C++ project is syncing (compileNative), please retry in 25 seconds"}],isError:!0};case 3:return h.warn(`C++ ${e} rejected: clangd is initializing`),{content:[{type:"text",text:"C++ LSP (clangd) is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleCppErrorCheck();case 4:return this.cppEnabled?this.cppHasNoCppCode?{content:[{type:"text",text:"No C++ code in this project"}],isError:!0}:this.cppLspManager?.ready?t():{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}:{content:[{type:"text",text:"C++ LSP is disabled. Set DEVECO_CLI_CPP_ENABLED=true to enable."}],isError:!0};default:return h.warn(`C++ ${e} rejected: unknown C++ project state ${this.cppProjectState}`),{content:[{type:"text",text:"Unknown C++ project state, please retry"}],isError:!0}}}async routeLspRequest(e,t,r){return e.endsWith(".ets")?this.routeArktsRequest(t,r):Nr(e)?this.routeCppRequest(t,r):{content:[{type:"text",text:`Unsupported file type: ${e} (only .ets and C/C++ source/header files are supported)`}],isError:!0}}async handleCppIdleCheck(){if(this.ensureCppProjectReady(),this.config.projectPath){let e;return this.cppSyncSkippedDueToLock?(e=`Another build process is running, C++ sync deferred (waiting ${this.cppSyncSkipStartedAt>0?Math.round((Date.now()-this.cppSyncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,this.cppSyncSkippedDueToLock=!1):e="C++ project detected, syncing (compileNative), please retry in 25 seconds",h.info(`C++ idle check: project '${this.config.projectPath}', triggering C++ init`),{content:[{type:"text",text:e}],isError:!0}}return{content:[{type:"text",text:"No HarmonyOS project detected for C++ tools."}],isError:!0}}async handleCppErrorCheck(){return this.cppInitRetryCount>=Tt?(h.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${Tt}), will not auto-retry`),{content:[{type:"text",text:`C++ project initialization failed repeatedly (auto-retry exhausted: ${this.cppInitRetryCount}/${Tt}). Ask the user to investigate and confirm \`hvigor compileNative\` succeeds manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],isError:!0}):(h.info(`C++ error check: auto-retrying (${this.cppInitRetryCount}/${Tt})`),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 o=e.content.map(i=>i.text).filter(i=>i&&i.trim().length>0).join(`
1324
+ `);o&&(e.isError?t.push(o):r.push(o))}assertRestartAllowed(e){if(e==="arkts"||e==="all"){let t=this.projectState;if(t!==4&&t!==0&&t!==5)return{content:[{type:"text",text:`ArkTS project state: ${this.describeArktsState()}, sync/init in progress, restart unavailable (would interrupt the current flow). Wait for the state to become ready and retry other tools directly\u2014no restart needed. restart is only available in ready/idle/error states.`}],isError:!0}}if(e==="cpp"||e==="all"){let t=this.cppProjectState;if(t!==4&&t!==0&&t!==5)return{content:[{type:"text",text:`C++ project state: ${this.describeCppState()}, sync/init in progress, restart unavailable (would interrupt the current flow). Wait for the state to become ready and retry other tools directly\u2014no restart needed. restart is only available in ready/idle/error states.`}],isError:!0}}return null}async handleRestartCall(e){let t=e.target,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 o=this.assertRestartAllowed(r);return o||(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 ~10 seconds.`}]})}restartProject(e){h.info(`[restart] resetting tools + state, re-init (target=${e})`),(e==="arkts"||e==="all")&&this.restartArkts(),(e==="cpp"||e==="all")&&this.cppEnabled&&this.restartCpp()}restartArkts(){this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(e=>h.warn("Failed to shutdown ArktsCheckTool during restart:",e)),this.arktsCheckTool=null),this.initRetryCount=0,this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.configChangedTriggeredResync=!1,this.initPromise?(this.needsReinit=!0,h.info("[restart] ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(e=>h.warn("Failed to re-init ArkTS project during restart:",e)))}restartCpp(){this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(e=>h.warn("Failed to dispose ClangdLspManager during restart:",e)),this.cppLspManager=null),this.cppInitRetryCount=0,this.cppHasNoCppCode=!1,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitPromise?(this.cppNeedsReinit=!0,h.info("[restart] C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>h.warn("Failed to re-init C++ project during restart:",e)))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{h.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(t=>{h.warn("Failed to dispose ClangdLspManager during setProjectPath:",t)}),this.cppLspManager=null),this.initPromise?(this.needsReinit=!0,h.info("Project path changed while ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{h.warn("Failed to re-init project after setProjectPath:",t)})),this.cppInitPromise?(this.cppNeedsReinit=!0,h.info("Project path changed while C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.cppHasNoCppCode=!1,this.cppInitRetryCount=0,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.ensureCppProjectReady().catch(t=>{h.warn("Failed to re-init C++ project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new Kk;if(await this.server.connect(e),h.info("devecocli-mcp-server started"),!this.config.debug){let t=Gd();t&&h.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=Lt(t);r?(h.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):h.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?h.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):h.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{h.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return h.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return h.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){h.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,h.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{h.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{h.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{h.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?Lt(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=Lt(this.originalProjectPath),t&&h.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(!this.discoverProject()||!await this.ensureProjectSynced())return;this.ensureCppProjectReady().catch(t=>{h.warn("Background C++ project init failed:",t)}),this.projectState=3,this.arktsCheckTool=new Bn(this.config.projectPath,this.sdkPath,this.arktsLangServerPath,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{h.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});let e=Date.now();try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,h.info("Project fully initialized, check tool is available"),await this.trackInit("init_arkts",e,!0,null,this.arktsCheckTool?.aceServerPid??null)}catch(t){h.error("LSP initialization failed:",t);let r=G(t),o=this.arktsCheckTool?.aceServerPid??null;this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5,await this.trackInit("init_arkts",e,!1,r,o)}}async ensureProjectSynced(){let e=this.config.projectPath,t=Th(e),r=Zo.existsSync(br.join(e,"oh-package-lock.json5")),o=Zo.existsSync(br.join(e,"oh_modules"))&&Zo.readdirSync(br.join(e,"oh_modules")).length>0;if(r&&o)return t.required?(h.info(`Sync required: ${t.reason}`),this.runSync(e,{skipHvigorSync:!1})):(h.info(`Sync skipped: ${t.reason}`),!0);let i=!t.required;return h.info(`Sync check: skipHvigor=${i}, ohpm install forced (lock=${r}, ohModules=${o}), reason=${t.reason}`),this.runSync(e,{skipHvigorSync:i})}async runSync(e,t){this.projectState=2,h.info("Starting project sync...");let r=await Un.handleSyncProject(e,this.sdkPath,this.nodePath,this.ohpmJsPath,this.hvigorJsPath,t);switch(r.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let o=Date.now()-this.syncSkipStartedAt,i=Math.round(o/1e3);return o>=Dl?(h.error(`Sync skipped for ${i}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(h.warn(`Sync skipped: ${r.reason}, resetting to IDLE for retry (elapsed ${i}s / ${Dl/1e3}s)`),this.projectState=0,!1)}case"failed":return h.error(`Project sync failed: ${r.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return h.error(`Project sync: unknown status ${r.status}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}async ensureCppProjectReady(){if(!this.cppEnabled){h.info("[Cpp] C++ LSP disabled by config, skipping initialization"),this.cppHasNoCppCode=!0,this.cppProjectState=4;return}if(!this.cppInitPromise){this.cppInitPromise=this.doEnsureCppProjectReady();try{await this.cppInitPromise}finally{this.cppInitPromise=null}this.cppNeedsReinit&&(this.cppNeedsReinit=!1,this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>{h.warn("Failed to re-init C++ project after cppNeedsReinit:",e)}))}}async doEnsureCppProjectReady(){let e=this.config.projectPath;if(!e){h.info("[Cpp] No project path, skipping C++ init");return}this.cppProjectState=1;let t=rr(e);if(t.length===0){h.info('[Cpp] No C++ modules found, C++ tools will return "no C++ code"'),this.cppHasNoCppCode=!0,this.cppProjectState=4,this.cppInitRetryCount=0;return}this.cppHasNoCppCode=!1,h.info(`[Cpp] Found ${t.length} C++ module(s): ${t.map(i=>i.name).join(", ")}`);let r=Ou(e),o=!r.required;h.info(`[Cpp] C++ sync check: skipCompileNative=${o}, reason=${r.reason}`),await this.runSyncCpp(e,{skipCompileNative:o})&&await this.initCppLsp(e)}async initCppLsp(e){this.cppProjectState=3,this.cppLspManager=new Xo({workspaceRoot:e,clangdPath:this.clangdPath??""});let t=Date.now();try{await this.cppLspManager.start(),this.cppCheckTool=new Vn(this.cppLspManager),this.cppLspTool=new qn(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,h.info("[Cpp] C++ project fully initialized, C++ tools are available"),await this.trackInit("init_cpp",t,!0,null,this.cppLspManager?.clangdPid??null)}catch(r){h.error("[Cpp] C++ LSP initialization failed:",r);let o=G(r),i=this.cppLspManager?.clangdPid??null;this.cppLspManager&&this.cppLspManager.dispose().catch(()=>{}),this.cppLspManager=null,this.cppCheckTool=null,this.cppLspTool=null,this.cppInitRetryCount++,this.cppProjectState=5,await this.trackInit("init_cpp",t,!1,o,i)}}async trackInit(e,t,r,o,i){if(!this.config.telemetry)return;let s="unknown";if(i!==null){let l=await je(i);l!==null&&(s=Q(Number(l)*1024))}let a={event:b.McpToolCall,subAction:e,mcpMemory:Q(process.memoryUsage().rss),lspMemory:s},c={duration_ms:Date.now()-t,success:r,error_code:o};await this.config.telemetry.track(a,c).catch(()=>{})}async runSyncCpp(e,t){this.cppProjectState=2,h.info("[Cpp] Starting C++ project sync (compileNative)...");let r=await Xo.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 o=Date.now()-this.cppSyncSkipStartedAt,i=Math.round(o/1e3);return o>=Dl?(h.error(`[Cpp] C++ sync skipped for ${i}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(h.warn(`[Cpp] C++ sync skipped: ${r.reason}, resetting to IDLE_CPP for retry (elapsed ${i}s)`),this.cppProjectState=0,!1)}case"failed":return h.error(`[Cpp] C++ project sync failed: ${r.reason}`),this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitRetryCount++,this.cppProjectState=5,!1}return!1}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppLspManager&&await this.cppLspManager.dispose(),this.cppCheckTool=null,this.cppLspTool=null;try{await this.server.close()}catch(e){h.warn("Failed to close MCP server connection:",e)}h.info("devecocli-mcp-server stopped"),qd(),Vd()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function Xk(n){let e=[],t=[],r=[];for(let o of n)br.extname(o).toLowerCase()===".ets"?e.push(o):Nr(o)?t.push(o):r.push(o);return{etsFiles:e,cppFiles:t,unsupported:r}}function xl(n={}){return new ca(n)}import*as Ll from"fs";import*as Qo from"path";import{spawn as Zk}from"child_process";async function Lh(n){Or(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:o,serverMaxSize:i}=await Qk(n),s=rI(e,t,r,o,i);h.info("ace-server started, bridging stdio (initialize is left to the client)"),oI(s),await Ml(s.pid,Nl("--arkts",n))}function Nl(n,e){return[n,...e.projectPath?["--project-path"]:[],...e.autoDetect?["--auto-detect"]:[]]}async function Ml(n,e){let t="unknown";if(n!==null){let o=await je(n);o!==null&&(t=Q(Number(o)*1024))}let r={event:b.ServeLsp,args:e,lspMemory:t};await I.track(r)}async function Qk(n){let e=await A.new(),t;if(n.projectPath)t=ge(Qo.resolve(n.projectPath)),h.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let c=hi(process.cwd());t=ge(c??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=ge(process.cwd()),h.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,o=e.arktsLangServerPath;o||(h.error("ace-server not found (install DevEco Studio / CLT)."),process.exit(1));let i=ro(o,!0),s=Qo.join(Kt(),"lsp-server",String(Date.now()));Ll.mkdirSync(s,{recursive:!0});let a=eI(t,r);return h.info(`projectPath=${t}, sdkPath=${r}, arktsLangServerPath=${o}, serverPath=${i}, logPath=${s}, serverMaxSize=${a}MB`),{projectPath:t,sdkPath:r,serverPath:i,logPath:s,serverMaxSize:a}}function eI(n,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=t?parseInt(t,10):NaN,o=Number.isFinite(r)&&r>0?r:void 0,i=tI(n,e),s=Ni(i,o);return h.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${i}, override=${o??"none"})`),s}function tI(n,e){try{let t=[];return new Qr(n,e).getAllDependencyMap(t).status==="OK"?t.length:new Nt(n).getAllModuleInfo().length}catch{return 0}}function rI(n,e,t,r,o){let i=Qo.join(e,"lspLog");Ll.mkdirSync(i,{recursive:!0});let s=nI(n,i,t,r,o),a=process.execPath??"node";return h.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),Zk(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function nI(n,e,t,r,o){let i=z(e);return["--expose-gc",`--max-old-space-size=${o}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${i}`,n,"--stdio",`--logger-path=${i}`,"--logger-level=TRACE",`--projectPath=${z(t)}`,`--sdkPath=${z(r)}`]}function oI(n){n.on("error",e=>{h.error(`[ace-server] spawn error: ${e.message}`),process.exit(1)}),n.stdout?.on("error",e=>{h.error(`[ace-server] stdout error: ${e.message}`)}),n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("error",e=>{h.error(`[ace-server] stderr error: ${e.message}`)}),n.stderr?.on("data",e=>{h.error(`[ace-server] ${e.toString("utf8").trim()}`)}),n.stdin?.on("error",e=>{h.error(`[ace-server] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{h.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as Nh from"fs";import*as tn from"path";import{spawn as iI}from"child_process";async function Mh(n){Or(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await sI(n),o=tn.join(t,"compile_commands.json");Nh.existsSync(o)||h.warn(`compile_commands.json not found at ${o}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let i=cI(e,t,r);h.info("clangd started, bridging stdio (initialize is left to the client)"),dI(i),await Ml(i.pid,Nl("--cpp",n))}async function sI(n){let e=await aI();e?.clangdPath||(h.error("clangd not found. Ensure DevEco Studio / CLT is installed."),process.exit(1));let t;if(n.projectPath)t=ge(tn.resolve(n.projectPath)),h.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let a=hi(process.cwd());t=ge(a??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${a??"null, fallback to cwd"}`)}else t=ge(tn.resolve(process.cwd())),h.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,o=e.clangdPath,i=Lr(t),s=tn.dirname(i);return h.info(`projectPath=${t}, sdkPath=${r}, clangdPath=${o}, compileCommandsDir=${s}`),{projectPath:t,clangdPath:o,compileCommandsDir:s}}async function aI(){try{return await A.new()}catch{let n=Hd();if(!n)return null;try{return A.fromIDE(n)}catch{return null}}}function cI(n,e,t){let r=lI(e);return h.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),iI(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function lI(n){return[`--compile-commands-dir=${z(n)}`,"--log=info","--pch-storage=memory"]}function dI(n){n.on("error",e=>{h.error(`[clangd] spawn error: ${e.message}`),process.exit(1)}),n.stdout?.on("error",e=>{h.error(`[clangd] stdout error: ${e.message}`)}),n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("error",e=>{h.error(`[clangd] stderr error: ${e.message}`)}),n.stderr?.on("data",e=>{h.error(`[clangd] ${e.toString("utf8").trim()}`)}),n.stdin?.on("error",e=>{h.error(`[clangd] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{h.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function pI(){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",o=n,i=await A.new(),s=xl({projectPath:o,sdkPath:i.sdkPath,arktsLangServerPath:i.arktsLangServerPath??void 0,nodePath:i.nodePath,ohpmJsPath:i.ohpmJsPath,hvigorJsPath:i.hvigorJsPath,clangdPath:i.clangdPath??void 0,nodeMaxOldSpaceSize:e,debug:t,cppEnabled:r,telemetry:I}),a,c=new Promise(d=>{a=d}),l=async()=>{await s.shutdown(),a()};process.once("SIGINT",l),process.once("SIGTERM",l),process.platform==="win32"&&process.once("SIGBREAK",l);try{await s.start()}catch(d){console.error("Failed to start MCP server:",d instanceof Error?d.message:String(d)),process.exit(1)}await c}var Ol=new uI("serve").description("Host bundled auxiliary protocol servers");Ol.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await pI()});Ol.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 Lh({projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await Mh({projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var Oh=Ol;import{Command as wI,InvalidArgumentError as Hh}from"commander";import{red as bI,dim as SI}from"colorette";import{createRequire as mI}from"module";import{dirname as fI,join as zn}from"path";import{pathToFileURL as hI}from"url";import{readFile as jh,access as _l}from"fs/promises";import*as Fh from"semver";var gI=mI(import.meta.url),_h=1;async function yI(){try{let n=gI.resolve("@yinsen/deveco-cli-docs-zh/package.json"),e=JSON.parse(await jh(n,"utf8"));return{version:e.version,apiVersion:e.apiVersion??0,dir:fI(n)}}catch{return null}}async function vI(){let n=Pe(),e=zn(n,"doc-data","current.json"),t;try{t=JSON.parse(await jh(e,"utf8"))}catch{return null}let r=zn(n,"doc-data",t.version);try{return await _l(zn(r,"dist","engine","index.js")),await _l(zn(r,"docs.zip")),await _l(zn(r,"index.zip")),{version:t.version,apiVersion:t.apiVersion,dir:r}}catch{return null}}async function la(){let n=[await vI(),await yI()].filter(t=>t!==null).sort((t,r)=>Fh.rcompare(t.version,r.version)),e=!1;for(let t of n){if(t.apiVersion>_h){u(`docs: skip candidate v${t.version} (apiVersion ${t.apiVersion} > ${_h})`),e=!0;continue}try{let r=zn(t.dir,"dist","engine","index.js");return await import(hI(r).href)}catch(r){u(`docs: candidate v${t.version} load failed: ${r instanceof Error?r.message:String(r)}`)}}throw e?new Error("\u6587\u6863\u5305\u7248\u672C\u4E0D\u517C\u5BB9\uFF0C\u8BF7\u5347\u7EA7 CLI"):new Error("\u6CA1\u6709\u53EF\u7528\u7684\u6587\u6863\u5305\uFF0C\u8BF7\u66F4\u65B0\u6587\u6863\u6216\u91CD\u65B0\u5B89\u88C5 CLI")}async function jl(n,e){let t=Date.now();try{let r=await e();return await $h(n,Date.now()-t,!0,null),r}catch(r){let o=r instanceof Error?r.code??r.name:"UnknownError";throw await $h(n,Date.now()-t,!1,o),r}}async function $h(n,e,t,r){await I.track(n,{duration_ms:e,success:t,error_code:r}).catch(()=>{})}function EI(n){return n instanceof Error&&(n.name==="CacheDirError"||n.name==="DocPathSafetyError")}function Fl(n){console.error(bI(PI(n))),process.exitCode=1}function PI(n){let e=n instanceof Error?n.message:String(n);return EI(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 Uh(...n){return e=>{if(!n.includes(e))throw new Hh(`Allowed values: ${n.join(", ")}`);return e}}function CI(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new Hh("Must be a positive integer.");return e}var kI=Uh("json","default"),II=Uh("json","default");function AI(n){let e=n.map(t=>t.trim()).filter(Boolean);if(e.length===0)throw new Error("Keywords cannot be empty.");return e}function DI(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 da=new wI("docs").description("Search and read HarmonyOS documentation from local docs directory");da.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)",kI,"default").option("--limit <n>","Max number of results",CI,10).action(async(n,e)=>{let t={event:b.DocOperation,subAction:"search",queryLen:n.join(" ").length,catalog:e.catalog??"all"};try{await jl(t,async()=>{let r=AI(n),o=e.catalog&&e.catalog!=="all"?e.catalog:void 0,i=await la(),s=i.CATALOG_NAMES;if(o&&s&&!s.includes(o))throw new Error(`Invalid catalog "${e.catalog}". Allowed: all, ${s.join(", ")}`);let a=await i.createDocsEngine({cacheDir:Pe()});try{let c=await a.search({keywords:r,catalog:o,limit:e.limit});e.format==="json"?console.log(JSON.stringify(c,null,2)):DI(c)}finally{await a.close()}})}catch(r){Fl(r)}});da.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{let e=n.trim(),t={event:b.DocOperation,subAction:"read",documentId:e};try{await jl(t,async()=>{if(!e)throw new Error("Document ID cannot be empty.");let o=await(await la()).createDocsEngine({cacheDir:Pe()});try{let i=await o.read({relativePath:e});console.log(i)}finally{await o.close()}})}catch(r){Fl(r)}});da.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",II,"default").action(async n=>{let e={event:b.DocOperation,subAction:"catalog",fmt:n.format??"default"};try{await jl(e,async()=>{let r=await(await la()).createDocsEngine({cacheDir:Pe()});try{let o=await r.catalog();if(n.format==="json")console.log(JSON.stringify(o.map(i=>({name:i.nodeId,title:i.nodeName})),null,2));else for(let i of o)console.log(` ${i.nodeId.padEnd(20)} ${SI(i.nodeName)}`)}finally{await r.close()}})}catch(t){Fl(t)}});var Bh=da;import{Command as lA}from"commander";import{Command as RI,InvalidArgumentError as TI,Option as $l}from"commander";import xI from"ora";function LI(n){let e=parseInt(n,10);if(!Number.isInteger(e)||e<0||String(e)!==n.trim())throw new TI("depth must be a non-negative integer");return e}function NI(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 Wh(n,e=0){let t=[],r=" ".repeat(e);for(let o of n)t.push(`${r}${NI(o)}`),o.children.length>0&&t.push(...Wh(o.children,e+1).split(`
1308
1325
  `));return t.join(`
1309
- `)}function rk(n){if(n.allWindows&&n.window)throw new Error("--all-windows and --window are mutually exclusive.")}function ik(n,e){let t=jr(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 ok(n,e){return e.id?ik(n,e.id):e.format==="json"?JSON.stringify(n,null,2):Bm(n)}async function sk(n){rk(n);let e=ek({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let i=await A.new(),o=await fn(i,n.device),s=new zn(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=ok(t,n);return console.log(r),Buffer.byteLength(r,"utf8")}function ak(n){return{event:b.CommandExecuted,args:["ui","layout",...n.device?["--device"]:[]],mode:n.mode,outputSize:0}}async function ck(n){let e=ak(n),t=Date.now(),r=!0,i=null;try{e.outputSize=await sk(n)}catch(o){throw r=!1,i=B(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(e,o)}}var Vm=new ZC("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 ul("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(tk).default(0)).addOption(new ul("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new ul("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async n=>{await ck(n)});import{Command as lk,Option as dk}from"commander";import{yellow as uk}from"colorette";import pk from"ora";var fk=["Id","Name","Pid","DisplayId","Focused"];function mk(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(Rt(fk,t))}async function hk(n){let e=pk({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let r=await A.new(),i=await fn(r,n.device);t=await new $t(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(uk(" No windows found."));return}mk(t,n.format)}function gk(n){let e=[];return n.device&&e.push("--device"),n.format!=="default"&&e.push("--format"),n.all&&e.push("--all"),{event:b.CommandExecuted,args:["ui","window","list",...e]}}async function yk(n){let e=gk(n),t=Date.now(),r=!0,i=null;try{await hk(n)}catch(o){throw r=!1,i=B(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(e,o)}}var pl=new lk("window").description("Manage device windows");pl.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new dk("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async n=>{await yk(n)});import{Command as vk}from"commander";import _e from"fs";import ot from"path";import{randomUUID as wk}from"crypto";import{green as bk}from"colorette";function Sk(n){return{event:b.CommandExecuted,args:["ui","screenshot",...n.device?["--device"]:[]]}}function Ek(){return String(Date.now())}function qm(n){let e;try{e=_e.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{_e.accessSync(n,_e.constants.W_OK|_e.constants.X_OK)}catch(t){throw new Error(`Screenshot directory is not writable: ${n}`,{cause:t})}}function Gm(n,e){try{throw _e.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 Pk(n){if(!n?.trim())throw new Error("--path is required.");let e=n.trim(),t=ot.resolve(e);try{if(_e.statSync(t).isDirectory()){qm(t);let i=ot.join(t,`screenshot-${Ek()}.png`);return Gm(i,t),i}}catch(i){if(i.code!=="ENOENT")throw i}if(ot.extname(t).toLowerCase()!==".png")throw new Error(`Screenshot path must be an existing directory or a PNG file: ${t}`);let r=ot.dirname(t);return qm(r),Gm(t,r),t}function zm(n){if(!_e.existsSync(n))throw new Error(`Screenshot file was not created: ${n}`);let e=_e.statSync(n);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${n}`);let t=_e.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 Ck(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 kk(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}function Ik(n,e){try{_e.copyFileSync(n,e,_e.constants.COPYFILE_EXCL)}catch(t){throw t.code==="EEXIST"?new Error(`Screenshot file already exists: ${e}`,{cause:t}):t}zm(e)}function Ak(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}async function Dk(n){let e=["-t",n.serial,"shell","ls","-l",n.remotePath];p(`Executing: ${n.hdcPath} ${e.join(" ")}`);let t=await ie(n.hdcPath,e);return t.exitCode===0?Ak(t.stdout):void 0}function Rk(n){return[n.stdout,n.stderr].filter(Boolean).join(`
1310
- `).trim()}function Tk(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 xk(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)}async function Lk(n,e){let t=Ck(n,e);p(`Executing: ${n.hdcPath} ${t.join(" ")}`);let r=await ie(n.hdcPath,t),i=await Dk(n);return{created:i!==void 0&&i>0,output:Tk(Rk(r))}}async function Nk(n){let e="";for(let t of[void 0,"png"]){let r=await Lk(n,t);if(r.created)return;if(n.display!==void 0&&xk(r.output))throw new Error(`Screenshot was not created on device: ${n.remotePath}.
1311
- snapshot_display output:
1312
- ${r.output}`);r.output&&(e=r.output)}throw new Error(e?`Screenshot was not created on device: ${n.remotePath}.
1313
- snapshot_display output:
1314
- ${e}`:`Screenshot was not created on device: ${n.remotePath}.`)}function Jm(n){try{return zm(n),!0}catch{return!1}}function Ym(n){let e=[];for(let t of _e.readdirSync(n,{withFileTypes:!0})){let r=ot.join(n,t.name);if(t.isDirectory()){e.push(...Ym(r));continue}t.isFile()&&Jm(r)&&e.push(r)}return e}function Ok(n,e){let t=ot.join(n,ot.basename(e));if(Jm(t))return t;let r=Ym(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}async function fl(n,e,t){let r=["-t",n.serial,"file","recv",n.remotePath,t];p(`Executing: ${n.hdcPath} ${r.join(" ")}`);let i=await ie(n.hdcPath,r);return i.exitCode!==0&&p(`hdc file recv failed: ${i.stderr||i.stdout||`exit code ${i.exitCode}`}`),Ok(e,n.remotePath)}async function Mk(n){let e=_e.mkdtempSync(ot.join(ot.dirname(n.localPath),".devecocli-screenshot-"));try{let t=await fl(n,e,ot.join(e,ot.basename(n.remotePath)))??await fl(n,e,e)??await fl(n,e,ot.join(e,"screenshot.png"));if(!t)throw new Error(`Screenshot file was not created in ${e}.`);Ik(t,n.localPath)}finally{_e.rmSync(e,{recursive:!0,force:!0})}}async function _k(n){let e=["-t",n.serial,"shell","rm","-f",n.remotePath];p(`Executing: ${n.hdcPath} ${e.join(" ")}`),await ie(n.hdcPath,e)}async function jk(n){try{await Nk(n),await Mk(n)}finally{await _k(n)}}async function Fk(n){let e=Sk(n),t=Date.now(),r=!0,i=null;try{let o=Pk(n.path),s=n.display!==void 0?kk(n.display):void 0;if(n.device!==void 0&&!n.device.trim())throw new Error("--device must not be empty.");let a=await A.new(),c=await fn(a,n.device),l=`/data/local/tmp/devecocli-${wk()}.png`;await jk({hdcPath:a.hdcPath,serial:c,localPath:o,remotePath:l,display:s}),console.log(bk(`Screenshot saved to ${o}`))}catch(o){throw r=!1,i=B(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(e,o)}}var Km=new vk("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(Fk);import{Command as mn}from"commander";function hn(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:b.CommandExecuted,args:["ui",n,...t]}}function $k(n){let t=`"$(printf '%s' '${Buffer.from(n,"utf8").toString("base64")}' | base64 -d)"`;return p(`escapeShellText: ${n} -> ${t}`),t}async function gn(n,e,t,r){let i=new dt;i.start(n);let o=Date.now(),s=!0,a=null;try{await r(i)}catch(c){throw i.stop(),s=!1,a=B(c),new Error(`${e}: ${c.message}`,{cause:c})}finally{let c={duration_ms:Date.now()-o,success:s,error_code:a};await I.track(t,c)}}async function Hk(n,e,t){let r=hn("click",t);await gn("Executing click...","click failed",r,async i=>{Fr(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await Et(t.device),{x:a,y:c}=await $r(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await it(o,s,["uitest","uiInput","click",String(a),String(c)]),i.succeed(`click at (${a}, ${c})`)})}async function Uk(n,e,t){let r=hn("doubleclick",t);await gn("Executing doubleclick...","doubleclick failed",r,async i=>{Fr(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await Et(t.device),{x:a,y:c}=await $r(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await it(o,s,["uitest","uiInput","doubleClick",String(a),String(c)]),i.succeed(`doubleclick at (${a}, ${c})`)})}async function Wk(n,e,t){let r=hn("longclick",t);await gn("Executing longclick...","longclick failed",r,async i=>{Fr(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await Et(t.device),{x:a,y:c}=await $r(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await it(o,s,["uitest","uiInput","longClick",String(a),String(c)]),i.succeed(`longclick at (${a}, ${c})`)})}async function Bk(n,e,t,r,i){let o=hn("swipe",i);await gn("Executing swipe...","swipe failed",o,async s=>{Te(n,"x1"),Te(e,"y1"),Te(t,"x2"),Te(r,"y2");let a=ji(i.speed),{hdcPath:c,deviceId:l}=await Et(i.device),d=["uitest","uiInput","swipe",n,e,t,r];a&&d.push(a),await it(c,l,d),s.succeed(`swipe from (${n}, ${e}) to (${t}, ${r})`)})}async function Vk(n,e,t,r,i){let o=hn("fling",i);await gn("Executing fling...","fling failed",o,async s=>{Te(n,"x1"),Te(e,"y1"),Te(t,"x2"),Te(r,"y2");let a=ji(i.speed),{hdcPath:c,deviceId:l}=await Et(i.device),d=["uitest","uiInput","fling",n,e,t,r];a&&d.push(a),await it(c,l,d),s.succeed(`fling from (${n}, ${e}) to (${t}, ${r})`)})}async function qk(n,e,t,r,i){let o=hn("drag",i);await gn("Executing drag...","drag failed",o,async s=>{Te(n,"x1"),Te(e,"y1"),Te(t,"x2"),Te(r,"y2");let a=ji(i.speed),{hdcPath:c,deviceId:l}=await Et(i.device),d=["uitest","uiInput","drag",n,e,t,r];a&&d.push(a),await it(c,l,d),s.succeed(`drag from (${n}, ${e}) to (${t}, ${r})`)})}async function Gk(n,e){let t=hn("dircfling",e);await gn("Executing dircfling...","dircfling failed",t,async r=>{let i=Vs[n];if(i===void 0)throw new Error(`Invalid direction "${n}". Valid values: ${Object.keys(Vs).join(", ")}`);let{hdcPath:o,deviceId:s}=await Et(e.device);await it(o,s,["uitest","uiInput","dircFling",i]),r.succeed(`dircfling ${n}`)})}async function zk(n,e,t,r){let i=hn("text",r);await gn("Executing text input...","input failed",i,async o=>{Fr(e,t,r.id,r.window,!1),qs(n,"text");let{hdcPath:s,deviceId:a}=await Et(r.device),c=$k(n);if(e!==void 0)await it(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 $r(s,a,void 0,void 0,r.id,r.window);await it(s,a,["uitest","uiInput","inputText",`${l}`,`${d}`,c]),o.succeed(`input ${n} at (${l}, ${d})`)}else await it(s,a,["uitest","uiInput","text",c]),o.succeed(`input ${n}`)})}var Xm=new mn("click").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Tap at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(Hk),Zm=new mn("doubleclick").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Double-tap at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(Uk),Qm=new mn("longclick").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Long-press at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(Wk),eh=new mn("swipe").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Swipe from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(Bk),th=new mn("fling").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Fling from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(Vk),nh=new mn("drag").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Drag from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(qk),rh=new mn("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action(Gk),ih=new mn("text").argument("<text>","Text to input").argument("[x]","Optional X coordinate").argument("[y]","Optional Y coordinate").description("Input text at a target location or the currently focused field").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id to target before input (auto-resolves to center)").option("--window <windowId>","Target window id (used with --id)").action(zk);var st=new Jk("ui").description("Inspect and interact with UI on a connected device");st.addCommand(Vm);st.addCommand(pl);st.addCommand(Km);st.addCommand(Xm);st.addCommand(Zm);st.addCommand(Qm);st.addCommand(eh);st.addCommand(th);st.addCommand(nh);st.addCommand(rh);st.addCommand(ih);var oh=st;import{Command as jh,InvalidArgumentError as MA}from"commander";import{execa as vI}from"execa";import Pt from"fs";import*as vl from"os";import*as O from"path";var Yk=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),Kk=/\r/g,Xk=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,Zk=/^<+\s*/,Qk=/\s*>+$/,eI=[/^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\.$/],tI=new Set([1]);function hl(n){if(!n)return"";let e=n.replace(Yk,"").replace(Kk,`
1326
+ `)}function MI(n){if(n.allWindows&&n.window)throw new Error("--all-windows and --window are mutually exclusive.")}function OI(n,e){let t=gn(n,e);if(t.length===0)throw new Error(`Node '${e}' not found.`);let r=t.map(o=>({...o,children:[]}));return JSON.stringify(r,null,2)}function _I(n,e){return e.id?OI(n,e.id):e.format==="json"?JSON.stringify(n,null,2):Wh(n)}async function jI(n){MI(n);let e=xI({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let o=await A.new(),i=await ht(o,n.device),s=new Wr(o.hdcPath);t=n.mode==="full"?await s.dumpFullTree(i,n.depth,n.window,n.allWindows):await s.dumpCollapsedTree(i,n.depth,n.window,n.allWindows)}catch(o){throw e.stop(),new Error(`Failed to dump layout: ${o.message}`,{cause:o})}e.stop();let r=_I(t,n);return console.log(r),Buffer.byteLength(r,"utf8")}function FI(n){return{event:b.CommandExecuted,args:["ui","layout",...n.device?["--device"]:[]],mode:n.mode,outputSize:0}}async function $I(n){let e=FI(n),t=Date.now(),r=!0,o=null;try{e.outputSize=await jI(n)}catch(i){throw r=!1,o=G(i),i}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await I.track(e,i)}}var Vh=new RI("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 $l("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(LI).default(0)).addOption(new $l("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new $l("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async n=>{await $I(n)});import{Command as HI,Option as UI}from"commander";import{yellow as BI}from"colorette";import WI from"ora";var VI=["Id","Name","Pid","DisplayId","Focused"];function qI(n,e){if(e==="json"){let r=n.map(o=>({id:o.id,name:o.name,pid:o.pid,displayId:o.displayId,focused:o.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(Ft(VI,t))}async function GI(n){let e=WI({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let r=await A.new(),o=await ht(r,n.device);t=await new Ot(r.hdcPath,o).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(BI(" No windows found."));return}qI(t,n.format)}function zI(n){let e=[];return n.device&&e.push("--device"),n.format!=="default"&&e.push("--format"),n.all&&e.push("--all"),{event:b.CommandExecuted,args:["ui","window","list",...e]}}async function JI(n){let e=zI(n),t=Date.now(),r=!0,o=null;try{await GI(n)}catch(i){throw r=!1,o=G(i),i}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await I.track(e,i)}}var Hl=new HI("window").description("Manage device windows");Hl.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new UI("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async n=>{await JI(n)});import{Command as YI}from"commander";import{green as KI}from"colorette";function XI(n){return{event:b.CommandExecuted,args:["ui","screenshot",...n.device?["--device"]:[]]}}function ZI(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}async function QI(n){let e=XI(n),t=Date.now(),r=!0,o=null;try{if(n.device!==void 0&&!n.device.trim())throw new Error("--device must not be empty.");let i=n.display!==void 0?ZI(n.display):void 0,s=await A.new(),a=new Vr(s),c=a.resolveDestinationPath(n.path),l=await ht(s,n.device);await a.captureToPath(l,c,i),console.log(KI(`Screenshot saved to ${c}`))}catch(i){throw r=!1,o=G(i),i}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await I.track(e,i)}}var qh=new YI("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(QI);import{Command as Sr}from"commander";function Er(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:b.CommandExecuted,args:["ui",n,...t]}}function eA(n){let t=`"$(printf '%s' '${Buffer.from(n,"utf8").toString("base64")}' | base64 -d)"`;return u(`escapeShellText: ${n} -> ${t}`),t}async function Pr(n,e,t,r){let o=new Ke;o.start(n);let i=Date.now(),s=!0,a=null;try{await r(o)}catch(c){throw o.stop(),s=!1,a=G(c),new Error(`${e}: ${c.message}`,{cause:c})}finally{let c={duration_ms:Date.now()-i,success:s,error_code:a};await I.track(t,c)}}async function tA(n,e,t){let r=Er("click",t);await Pr("Executing click...","click failed",r,async o=>{yn(n,e,t.id,t.window);let{hdcPath:i,deviceId:s}=await Dt(t.device),{x:a,y:c}=await vn(i,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await st(i,s,["uitest","uiInput","click",String(a),String(c)]),o.succeed(`click at (${a}, ${c})`)})}async function rA(n,e,t){let r=Er("doubleclick",t);await Pr("Executing doubleclick...","doubleclick failed",r,async o=>{yn(n,e,t.id,t.window);let{hdcPath:i,deviceId:s}=await Dt(t.device),{x:a,y:c}=await vn(i,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await st(i,s,["uitest","uiInput","doubleClick",String(a),String(c)]),o.succeed(`doubleclick at (${a}, ${c})`)})}async function nA(n,e,t){let r=Er("longclick",t);await Pr("Executing longclick...","longclick failed",r,async o=>{yn(n,e,t.id,t.window);let{hdcPath:i,deviceId:s}=await Dt(t.device),{x:a,y:c}=await vn(i,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await st(i,s,["uitest","uiInput","longClick",String(a),String(c)]),o.succeed(`longclick at (${a}, ${c})`)})}async function oA(n,e,t,r,o){let i=Er("swipe",o);await Pr("Executing swipe...","swipe failed",i,async s=>{Te(n,"x1"),Te(e,"y1"),Te(t,"x2"),Te(r,"y2");let a=ho(o.speed),{hdcPath:c,deviceId:l}=await Dt(o.device),d=["uitest","uiInput","swipe",n,e,t,r];a&&d.push(a),await st(c,l,d),s.succeed(`swipe from (${n}, ${e}) to (${t}, ${r})`)})}async function iA(n,e,t,r,o){let i=Er("fling",o);await Pr("Executing fling...","fling failed",i,async s=>{Te(n,"x1"),Te(e,"y1"),Te(t,"x2"),Te(r,"y2");let a=ho(o.speed),{hdcPath:c,deviceId:l}=await Dt(o.device),d=["uitest","uiInput","fling",n,e,t,r];a&&d.push(a),await st(c,l,d),s.succeed(`fling from (${n}, ${e}) to (${t}, ${r})`)})}async function sA(n,e,t,r,o){let i=Er("drag",o);await Pr("Executing drag...","drag failed",i,async s=>{Te(n,"x1"),Te(e,"y1"),Te(t,"x2"),Te(r,"y2");let a=ho(o.speed),{hdcPath:c,deviceId:l}=await Dt(o.device),d=["uitest","uiInput","drag",n,e,t,r];a&&d.push(a),await st(c,l,d),s.succeed(`drag from (${n}, ${e}) to (${t}, ${r})`)})}async function aA(n,e){let t=Er("dircfling",e);await Pr("Executing dircfling...","dircfling failed",t,async r=>{let o=zi[n];if(o===void 0)throw new Error(`Invalid direction "${n}". Valid values: ${Object.keys(zi).join(", ")}`);let{hdcPath:i,deviceId:s}=await Dt(e.device);await st(i,s,["uitest","uiInput","dircFling",o]),r.succeed(`dircfling ${n}`)})}async function cA(n,e,t,r){let o=Er("text",r);await Pr("Executing text input...","input failed",o,async i=>{yn(e,t,r.id,r.window,!1),Ji(n,"text");let{hdcPath:s,deviceId:a}=await Dt(r.device),c=eA(n);if(e!==void 0)await st(s,a,[`uitest uiInput inputText ${e} ${t} ${c}`]),i.succeed(`input ${n} at (${e}, ${t})`);else if(r.id){let{x:l,y:d}=await vn(s,a,void 0,void 0,r.id,r.window);await st(s,a,[`uitest uiInput inputText ${l} ${d} ${c}`]),i.succeed(`input ${n} at (${l}, ${d})`)}else await st(s,a,[`uitest uiInput text ${c}`]),i.succeed(`input ${n}`)})}var Gh=new Sr("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(tA),zh=new Sr("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(rA),Jh=new Sr("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(nA),Yh=new Sr("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(oA),Kh=new Sr("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(iA),Xh=new Sr("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(sA),Zh=new Sr("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action(aA),Qh=new Sr("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(cA);var ut=new lA("ui").description("Inspect and interact with UI on a connected device");ut.addCommand(Vh);ut.addCommand(Hl);ut.addCommand(qh);ut.addCommand(Gh);ut.addCommand(zh);ut.addCommand(Jh);ut.addCommand(Yh);ut.addCommand(Kh);ut.addCommand(Xh);ut.addCommand(Zh);ut.addCommand(Qh);var eg=ut;import{Command as Og,InvalidArgumentError as iR}from"commander";import{execa as NA}from"execa";import xt from"fs";import*as ql from"os";import*as M from"path";var dA=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),uA=/\r/g,pA=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,mA=/^<+\s*/,fA=/\s*>+$/,hA=[/^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\.$/],gA=new Set([1]);function Bl(n){if(!n)return"";let e=n.replace(dA,"").replace(uA,`
1315
1327
  `).split(`
1316
- `).map(nI).map(t=>t.trimEnd()).filter(t=>iI(t));return e.length>0?`${e.join(`
1328
+ `).map(yA).map(t=>t.trimEnd()).filter(t=>wA(t));return e.length>0?`${e.join(`
1317
1329
  `)}
1318
- `:""}function nI(n){let e=n.trim();if(!e.startsWith("{"))return n;try{let t=JSON.parse(e);return typeof t.content!="string"||typeof t.messageType!="number"?n:tI.has(t.messageType)?"":t.content}catch{return n}}var sh=50*1024*1024;function dh(n){let e=hl(n).trim();if(!e)return{jsonText:void 0,diagnostics:""};if(e.length>sh)return{jsonText:void 0,diagnostics:`${e.slice(0,1024)}
1319
- [output truncated: exceeded ${sh} bytes]
1320
- `};if(ml(e))return{jsonText:e,diagnostics:""};let t=e.split(`
1321
- `);if(t.length>1&&t.every(ml))return{jsonText:JSON.stringify(t.map(o=>JSON.parse(o))),diagnostics:""};let r=oI(e);if(!r)return{jsonText:void 0,diagnostics:`${e}
1322
- `};let i=[e.slice(0,r.start).trim(),e.slice(r.end).trim()].filter(Boolean).join(`
1323
- `);return{jsonText:e.slice(r.start,r.end),diagnostics:i?`${i}
1324
- `:""}}function rI(n){return Xk.test(n.trim())}function iI(n){let e=n.trim();return!!e&&!rI(e)&&!eI.some(t=>t.test(e))}function ml(n){try{return JSON.parse(n),!0}catch{return!1}}function oI(n){for(let e=0;e<n.length;e++){let t=n[e];if(t!=="["&&t!=="{")continue;let i=sI(n,e,t,t==="["?"]":"}");if(i!==-1&&ml(n.slice(e,i+1)))return{start:e,end:i+1}}}function sI(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 ah=["Error","Warning","Suggestion","Info","Off","Unknown"];function uh(n){let e=gl(n);return{issues:dI(e),summary:aI(n,e)}}function aI(n,e){let t=pI(e);return{filesChecked:fI(n).size,issues:e.length,errors:t.get("Error")??0,warnings:t.get("Warning")??0,suggestions:t.get("Suggestion")??0}}function gl(n,e=""){if(Array.isArray(n))return n.flatMap(o=>gl(o,e));if(!ph(n))return[];let t=Fi(n,["filePath","file","path"])??e,r=cI(n,t);if(r.length>0)return r;let i=lI(n,t);return i?[i]:[]}function cI(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=>gl(s,e));if(o.length>0)return o}}return[]}function lI(n,e){let t=Fi(n,["message","description","desc","detail"])??"",r=yI(Fi(n,["rule","ruleId","ruleName"])),i=hI(n,["severity","level"]),o=Fi(n,["filePath","file","path"])??e;if(!(!t&&!r&&i==="Unknown"))return{file:o,line:lh(n,["line","reportLine"]),column:lh(n,["column","reportColumn"]),severity:i,rule:r,message:t}}function dI(n){return[...n].sort((e,t)=>{let r=ch(e.severity)-ch(t.severity);return r===0?uI(e,t):r})}function uI(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 pI(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 fI(n){let e=new Set;return yl(e,n,""),e}function yl(n,e,t){if(Array.isArray(e)){for(let i of e)yl(n,i,t);return}if(!ph(e))return;let r=Fi(e,["filePath","file","path"])??t;r&&n.add(r),mI(n,e,r)}function mI(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)yl(n,s,t)}}function hI(n,e){for(let t of e){let r=n[t];if(typeof r=="string"||typeof r=="number")return gI(r)}return"Unknown"}function gI(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 yI(n){let e=n?.normalize("NFKC").trim();if(e)return e.replace(Zk,"").replace(Qk,"").toLowerCase()}function ch(n){let e=ah.indexOf(n);return e===-1?ah.length:e}function Fi(n,e){for(let t of e){let r=n[t];if(typeof r=="string")return r}}function lh(n,e){for(let t of e){let r=n[t];if(typeof r=="number")return r}}function ph(n){return typeof n=="object"&&n!==null}var yn=class extends Error{code;constructor(e,t,r){super(t,r),this.name="ValidationError",this.code=e}},fh="deveco-codelinter-",mh=[".ets",".ts",".js"],$i=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 Y.discover(e).rootDir}catch{return e}}async check(e){let t=Pt.mkdtempSync(O.join(vl.tmpdir(),fh)),r=O.join(t,"report.json");try{let i=n.resolveProjectRoot(this.cwd),o=this.resolveLintTarget(e.lintPath,i),s=this.resolveConfigPath(e.configPath,o),a=this.buildNativeArgs(e,o.path,s,r,t,o.projectRoot??i),c=await this.run(a),l=dh(c.stdout),d=l.diagnostics+hl(c.stderr);try{let g=this.readJsonReport(r,l.jsonText);return{exitCode:c.exitCode,diagnostics:d,report:uh(g)}}catch(g){return{exitCode:c.exitCode,diagnostics:d,reportError:g}}}finally{this.removeTempDir(t)}}resolveLintTarget(e,t){let r=e?O.resolve(this.cwd,e):t,i=this.resolveRealPath(r,"Lint path"),o=Pt.statSync(i);if(!o.isFile()&&!o.isDirectory())throw new yn("errorCode",`Lint path must be a file or directory: ${r}`);if(o.isFile()){let a=O.extname(i).toLowerCase();if(!mh.some(l=>l===a))throw new Error(`Unsupported lint file extension "${a||"<none>"}": ${i}. Supported extensions: ${mh.join(", ")}.`)}let s=this.discoverProjectRoot(i,o.isDirectory());if(e!==void 0&&s===void 0)throw new yn("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?O.resolve(this.cwd,e):O.join(t.projectRoot??this.cwd,"code-linter.json5"),i=this.resolveRealPath(r,"`--config-path`");if(!Pt.statSync(i).isFile())throw new yn("errorCode",`--config-path must point to a file: ${r}`);if(t.projectRoot){let o=this.discoverProjectRoot(i,!1);if(o===void 0||O.relative(t.projectRoot,o)!=="")throw new yn("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:O.dirname(e);try{return Pt.realpathSync(Y.discover(r).rootDir)}catch{return}}resolveRealPath(e,t){try{return Pt.realpathSync(e)}catch(r){throw new yn("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=O.join(i,"check-paths.json");Pt.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",O.join(i,"codelinter.log"),"--workdir",O.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(),p(`Executing: ${this.resolution.command} ${t.join(" ")}`),p(`[CodelinterAdapter] Working directory: ${r}`);let i=await vI(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??[])Pt.mkdirSync(e,{recursive:!0})}readJsonReport(e,t){let i=(Pt.existsSync(e)?Pt.readFileSync(e,"utf-8").trim():void 0)||t?.trim();if(!i)throw new yn("errorCode","Native JSON report was not generated.");return JSON.parse(i)}removeTempDir(e){let t=O.resolve(e),r=O.resolve(vl.tmpdir());!(t.startsWith(`${r}${O.sep}`)||t===r)||!O.basename(t).startsWith(fh)||Pt.rmSync(t,{recursive:!0,force:!0})}static isModernStudioEntry(e){let t=["plugins","codelinter","run","index.js"],r=O.normalize(e).split(O.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(O.delimiter),DEVECO_SDK_HOME:o},isLegacyStudioArgs:c};return t==="command-line-tools"&&(l.workingDirectory=r,l.runtimeDirectories=[n.getResultDirectory(i)]),p(`[CodelinterAdapter] Selected ${a} entry: ${i}`),l}static getPathEntries(e,t){let r=[O.dirname(e.nodePath)];return t==="ide"&&e.javaPath&&r.unshift(O.dirname(e.javaPath)),r}static getResultDirectory(e){return O.resolve(e,"..","linter","result")}static getSource(e){return e.sourceType==="studio"?"ide":"command-line-tools"}};import{red as zs,yellow as Eh}from"colorette";import{Argument as RI,Command as TI,InvalidArgumentError as wn}from"commander";import Ui from"fs";import*as je from"path";import*as Hi from"path";var hh="n/a",gh=/\\/g,wI=/\|/g,bI=/\r?\n/g;function yh(n,e){if(n.issues.length===0)return`No defects found.
1325
- ${wl(n.summary)}
1326
- `;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[EI(t),wl(n.summary)];return e!==void 0&&t.length<n.issues.length&&r.push(SI(n.issues.length,t.length)),`${r.join(`
1330
+ `:""}function yA(n){let e=n.trim();if(!e.startsWith("{"))return n;try{let t=JSON.parse(e);return typeof t.content!="string"||typeof t.messageType!="number"?n:gA.has(t.messageType)?"":t.content}catch{return n}}var tg=50*1024*1024;function ig(n){let e=Bl(n).trim();if(!e)return{jsonText:void 0,diagnostics:""};if(e.length>tg)return{jsonText:void 0,diagnostics:`${e.slice(0,1024)}
1331
+ [output truncated: exceeded ${tg} bytes]
1332
+ `};if(Ul(e))return{jsonText:e,diagnostics:""};let t=e.split(`
1333
+ `);if(t.length>1&&t.every(Ul))return{jsonText:JSON.stringify(t.map(i=>JSON.parse(i))),diagnostics:""};let r=bA(e);if(!r)return{jsonText:void 0,diagnostics:`${e}
1334
+ `};let o=[e.slice(0,r.start).trim(),e.slice(r.end).trim()].filter(Boolean).join(`
1335
+ `);return{jsonText:e.slice(r.start,r.end),diagnostics:o?`${o}
1336
+ `:""}}function vA(n){return pA.test(n.trim())}function wA(n){let e=n.trim();return!!e&&!vA(e)&&!hA.some(t=>t.test(e))}function Ul(n){try{return JSON.parse(n),!0}catch{return!1}}function bA(n){for(let e=0;e<n.length;e++){let t=n[e];if(t!=="["&&t!=="{")continue;let o=SA(n,e,t,t==="["?"]":"}");if(o!==-1&&Ul(n.slice(e,o+1)))return{start:e,end:o+1}}}function SA(n,e,t,r){let o=0,i=!1,s=!1;for(let a=e;a<n.length;a++){let c=n[a];if(s){s=!1;continue}if(c==="\\"&&i){s=!0;continue}if(c==='"'){i=!i;continue}if(!i){if(c===t)o++;else if(c===r&&(o--,o===0))return a}}return-1}var rg=["Error","Warning","Suggestion","Info","Off","Unknown"];function sg(n){let e=Wl(n);return{issues:kA(e),summary:EA(n,e)}}function EA(n,e){let t=AA(e);return{filesChecked:DA(n).size,issues:e.length,errors:t.get("Error")??0,warnings:t.get("Warning")??0,suggestions:t.get("Suggestion")??0}}function Wl(n,e=""){if(Array.isArray(n))return n.flatMap(i=>Wl(i,e));if(!ag(n))return[];let t=ei(n,["filePath","file","path"])??e,r=PA(n,t);if(r.length>0)return r;let o=CA(n,t);return o?[o]:[]}function PA(n,e){let t=["messages","defects","issues","results","files"];for(let r of t){let o=n[r];if(Array.isArray(o)){let i=o.flatMap(s=>Wl(s,e));if(i.length>0)return i}}return[]}function CA(n,e){let t=ei(n,["message","description","desc","detail"])??"",r=LA(ei(n,["rule","ruleId","ruleName"])),o=TA(n,["severity","level"]),i=ei(n,["filePath","file","path"])??e;if(!(!t&&!r&&o==="Unknown"))return{file:i,line:og(n,["line","reportLine"]),column:og(n,["column","reportColumn"]),severity:o,rule:r,message:t}}function kA(n){return[...n].sort((e,t)=>{let r=ng(e.severity)-ng(t.severity);return r===0?IA(e,t):r})}function IA(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 AA(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 DA(n){let e=new Set;return Vl(e,n,""),e}function Vl(n,e,t){if(Array.isArray(e)){for(let o of e)Vl(n,o,t);return}if(!ag(e))return;let r=ei(e,["filePath","file","path"])??t;r&&n.add(r),RA(n,e,r)}function RA(n,e,t){let r=["messages","defects","issues","results","files"];for(let o of r){let i=e[o];if(Array.isArray(i))for(let s of i)Vl(n,s,t)}}function TA(n,e){for(let t of e){let r=n[t];if(typeof r=="string"||typeof r=="number")return xA(r)}return"Unknown"}function xA(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 LA(n){let e=n?.normalize("NFKC").trim();if(e)return e.replace(mA,"").replace(fA,"").toLowerCase()}function ng(n){let e=rg.indexOf(n);return e===-1?rg.length:e}function ei(n,e){for(let t of e){let r=n[t];if(typeof r=="string")return r}}function og(n,e){for(let t of e){let r=n[t];if(typeof r=="number")return r}}function ag(n){return typeof n=="object"&&n!==null}var Cr=class extends Error{code;constructor(e,t,r){super(t,r),this.name="ValidationError",this.code=e}},cg="deveco-codelinter-",lg=[".ets",".ts",".js"],ti=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 W.discover(e).rootDir}catch{return e}}async check(e){let t=xt.mkdtempSync(M.join(ql.tmpdir(),cg)),r=M.join(t,"report.json");try{let o=n.resolveProjectRoot(this.cwd),i=this.resolveLintTarget(e.lintPath,o),s=this.resolveConfigPath(e.configPath,i),a=this.buildNativeArgs(e,i.path,s,r,t,i.projectRoot??o),c=await this.run(a),l=ig(c.stdout),d=l.diagnostics+Bl(c.stderr);try{let g=this.readJsonReport(r,l.jsonText);return{exitCode:c.exitCode,diagnostics:d,report:sg(g)}}catch(g){return{exitCode:c.exitCode,diagnostics:d,reportError:g}}}finally{this.removeTempDir(t)}}resolveLintTarget(e,t){let r=e?M.resolve(this.cwd,e):t,o=this.resolveRealPath(r,"Lint path"),i=xt.statSync(o);if(!i.isFile()&&!i.isDirectory())throw new Cr("errorCode",`Lint path must be a file or directory: ${r}`);if(i.isFile()){let a=M.extname(o).toLowerCase();if(!lg.some(l=>l===a))throw new Error(`Unsupported lint file extension "${a||"<none>"}": ${o}. Supported extensions: ${lg.join(", ")}.`)}let s=this.discoverProjectRoot(o,i.isDirectory());if(e!==void 0&&s===void 0)throw new Cr("errorCode",`Lint path is not in a valid project directory (project-level build-profile.json5 not found or invalid): ${o}`);return{path:o,projectRoot:s}}resolveConfigPath(e,t){let r=e?M.resolve(this.cwd,e):M.join(t.projectRoot??this.cwd,"code-linter.json5"),o=this.resolveRealPath(r,"`--config-path`");if(!xt.statSync(o).isFile())throw new Cr("errorCode",`--config-path must point to a file: ${r}`);if(t.projectRoot){let i=this.discoverProjectRoot(o,!1);if(i===void 0||M.relative(t.projectRoot,i)!=="")throw new Cr("errorCode",`\`--config-path\` must belong to the same project as the lint path. Lint project: ${t.projectRoot}; Config project: ${i??"not found"}.`)}return o}discoverProjectRoot(e,t){let r=t?e:M.dirname(e);try{return xt.realpathSync(W.discover(r).rootDir)}catch{return}}resolveRealPath(e,t){try{return xt.realpathSync(e)}catch(r){throw new Cr("errorCode",`${t} does not exist or cannot be resolved: ${e}`,{cause:r})}}buildNativeArgs(e,t,r,o,i,s){if(this.resolution.isLegacyStudioArgs)return this.buildLegacyNativeArgs(e,t,r,i,s);let a=["--config",r];return e.fix&&a.push("--fix"),e.incremental&&a.push("--incremental"),a.push("--product",e.product,"--format","json","--output",o,t),a}buildLegacyNativeArgs(e,t,r,o,i){let s=String(this.toolProvider.getMaxApiLevel()),a=this.toolProvider.getSdkPlatformVersion(),c=M.join(o,"check-paths.json");xt.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",i,"--logPath",M.join(o,"codelinter.log"),"--workdir",M.dirname(this.toolProvider.codelinterPath),"--inIde","true"];return e.fix&&l.push("--fix","true"),e.incremental&&l.push("--incremental","true"),l}async run(e){let t=this.resolution.isLegacyStudioArgs?[this.resolution.argsPrefix[0],...e]:[...this.resolution.argsPrefix,...e],r=this.resolution.workingDirectory??this.cwd;this.prepareRuntimeDirectories(),u(`Executing: ${this.resolution.command} ${t.join(" ")}`),u(`[CodelinterAdapter] Working directory: ${r}`);let o=await NA(this.resolution.command,t,{cwd:r,env:this.resolution.env,stdout:"pipe",stderr:"pipe",reject:!1});return{exitCode:o.exitCode??1,stdout:o.stdout,stderr:o.stderr}}prepareRuntimeDirectories(){for(let e of this.resolution.runtimeDirectories??[])xt.mkdirSync(e,{recursive:!0})}readJsonReport(e,t){let o=(xt.existsSync(e)?xt.readFileSync(e,"utf-8").trim():void 0)||t?.trim();if(!o)throw new Cr("errorCode","Native JSON report was not generated.");return JSON.parse(o)}removeTempDir(e){let t=M.resolve(e),r=M.resolve(ql.tmpdir());!(t.startsWith(`${r}${M.sep}`)||t===r)||!M.basename(t).startsWith(cg)||xt.rmSync(t,{recursive:!0,force:!0})}static isModernStudioEntry(e){let t=["plugins","codelinter","run","index.js"],r=M.normalize(e).split(M.sep).slice(-t.length);return t.every((o,i)=>r[i]?.toLowerCase()===o)}static resolveWithToolProvider(e){let t=n.getSource(e),r=e.toolchainRoot,o=e.codelinterPath,i=e.sdkPath,s=n.getPathEntries(e,t),a=t==="ide"?"DevEco Studio":"DevEco Command Line Tools",c=t==="ide"&&!n.isModernStudioEntry(o),l={command:e.nodePath,argsPrefix:[o,i],env:{...process.env,PATH:[...s,process.env.PATH||""].join(M.delimiter),DEVECO_SDK_HOME:i},isLegacyStudioArgs:c};return t==="command-line-tools"&&(l.workingDirectory=r,l.runtimeDirectories=[n.getResultDirectory(o)]),u(`[CodelinterAdapter] Selected ${a} entry: ${o}`),l}static getPathEntries(e,t){let r=[M.dirname(e.nodePath)];return t==="ide"&&e.javaPath&&r.unshift(M.dirname(e.javaPath)),r}static getResultDirectory(e){return M.resolve(e,"..","linter","result")}static getSource(e){return e.sourceType==="studio"?"ide":"command-line-tools"}};import{red as pa,yellow as yg}from"colorette";import{Argument as VA,Command as qA,InvalidArgumentError as Ir}from"commander";import ni from"fs";import*as We from"path";import*as ri from"path";var dg="n/a",ug=/\\/g,MA=/\|/g,OA=/\r?\n/g;function pg(n,e){if(n.issues.length===0)return`No defects found.
1337
+ ${Gl(n.summary)}
1338
+ `;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[jA(t),Gl(n.summary)];return e!==void 0&&t.length<n.issues.length&&r.push(_A(n.issues.length,t.length)),`${r.join(`
1327
1339
  `)}
1328
- `}function vh(n,e){return[wl(n.summary),`Full report: ${bl(e)}`,""].join(`
1329
- `)}function wh(n){let e=["# CodeLinter report",""];return n.issues.length===0?e.push("No defects found.",""):e.push(...PI(n.issues),""),e.push("## Summary","",...kI(n.summary),""),e.join(`
1330
- `)}function bh(n){return`${JSON.stringify(n,null,2)}
1331
- `}function wl(n){return`Summary: Issues: ${at(n.issues)} | Errors: ${at(n.errors)} | Warnings: ${at(n.warnings)} | Suggestions: ${at(n.suggestions)} | Files checked: ${at(n.filesChecked)}`}function SI(n,e){return`Showing ${at(e)} of ${at(n)} issues. Use --output-path <path> to write all results.`}function EI(n){let e=["No","File","Line","Column","Severity","Rule","Message"],t=n.map((r,i)=>({cells:AI(r,i+1)}));return["CodeLinter report","",Rt(e,t)].join(`
1332
- `)}function PI(n){let e=["| No | File | Line | Column | Severity | Rule | Message |","| ---: | --- | ---: | ---: | --- | --- | --- |"];for(let[t,r]of n.entries())e.push(CI(r,t+1));return e}function CI(n,e){return`| ${[String(e),bl(vn(n.file)),Gs(n.line),Gs(n.column),vn(n.severity),vn(n.rule),vn(n.message)].map(II).join(" | ")} |`}function kI(n){return[`- Issues: ${at(n.issues)}`,`- Errors: ${at(n.errors)}`,`- Warnings: ${at(n.warnings)}`,`- Suggestions: ${at(n.suggestions)}`,`- Files checked: ${at(n.filesChecked)}`]}function II(n){return n.replace(gh,"\\\\").replace(wI,"\\|").replace(bI,"<br>")}function AI(n,e){return[String(e),bl(vn(DI(n.file))),Gs(n.line),Gs(n.column),vn(n.severity),vn(n.rule),vn(n.message)]}function DI(n){if(!Hi.isAbsolute(n))return n;let e=Hi.relative(process.cwd(),n);return!e||e.startsWith("..")||Hi.isAbsolute(e)?n:e}function bl(n){return n.replace(gh,"/")}function vn(n){let e=n?.trim();return e||hh}function Gs(n){return n===void 0?hh:String(n)}function at(n){return n.toLocaleString("en-US")}var Sl=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function xI(n){let e=n;return n instanceof Sl?n.code:e.code??e.name??"UnknownError"}async function Sh(n,e,t,r){let i=await Xe(process.pid),o=i!==null?ce(Number(i)*1024):"unknown",s={event:b.CheckCommand,args:r,mcpMemory:o,lspMemory:"unknown"},a={duration_ms:Date.now()-n,success:e,error_code:t};await I.track(s,a).catch(()=>{})}var LI=/^-?\d+$/;function El(){return new TI("lint").description("Run DevEco Code Linter checks for TS/ArkTS code").helpOption("-h, --help","display help for command").addArgument(new RI("[path]","File or directory to lint").argParser(jI)).option("--fix","Auto-fix fixable code issues").option("--incremental","Only check uncommitted files").option("--config-path <path>","Path to lint configuration file",OI).option("--product <product>","Product name defined in build-profile.json5",MI,"default").option("--format <format>","Report format (choices: default, json)",NI,"default").option("--output-path <path>","Complete report file or directory",_I).option("--limit <number>","Maximum terminal issues to display when --output-path is omitted",FI).action($I)}function NI(n){if(n==="default"||n==="json")return n;throw new wn("Invalid --format. Expected one of: default, json.")}function OI(n){Pl(n,"--config-path");let e=je.extname(n).toLowerCase();if(e!==".json"&&e!==".json5")throw new wn("`--config-path` must point to a .json or .json5 file.");return n}function MI(n){return Ph(n,"product"),n}function _I(n){return Pl(n,"--output-path"),n}function jI(n){return Pl(n,"path"),n}function FI(n){if(Ph(n,"limit"),!LI.test(n))throw new wn("`--limit` must be a positive integer.");let e=Number.parseInt(n,10);if(e<=0||!Number.isSafeInteger(e))throw new wn("`--limit` must be an integer greater than 0.");return e}function Ph(n,e){if(n.trim().length===0||Ih(n))throw new wn(`Invalid --${e} value.`)}function Pl(n,e){let t=`\`${e}\``;if(n.length===0||Ih(n))throw new wn(`${t} must be a non-empty path without control characters.`)}async function $I(n,e,t){let r=Date.now(),i=["check","lint"];try{let o=process.cwd(),s=await A.new(),a=new $i(s,o),c=WI(s,a,t,e),l=GI(c.outputPath,c.format,o);e.fix&&console.warn(Eh("Running codelinter with --fix. Ensure your project source is trusted."));let d=await HI(a,n,e);XI(d.diagnostics),process.exitCode=VI(d,l,c.format,e.limit,o),await Sh(r,!0,null,i)}catch(o){let s=xI(o);throw await Sh(r,!1,s,i),o}}async function HI(n,e,t){return BI(n,{lintPath:e,configPath:t.configPath,product:t.product,fix:t.fix,incremental:t.incremental})}function UI(n){return[["format","--format"],["outputPath","--output-path"]].filter(([e])=>n.getOptionValueSource(e)==="cli").map(([,e])=>e)}function WI(n,e,t,r){let i=UI(t);if(i.length===0||e.supportsReportOptions)return r;let o=Vt(n.toolchainRoot),s=i.length===1?"option":"options";return console.warn(Eh(`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 BI(n,e){let t=new dt;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 VI(n,e,t,r,i){if(!n.report)return console.error(zs("Failed to generate Code Linter report.")),console.error(zs(n.reportError?.message??"Native JSON report was not generated.")),n.exitCode===0?1:n.exitCode;try{if(e){qI(e,t,n.report);let o=kh(e,i);process.stdout.write(vh(n.report,o))}else process.stdout.write(yh(n.report,r));return n.exitCode}catch(o){return console.error(zs("Failed to generate Code Linter report.")),console.error(zs(o.message)),n.exitCode===0?1:n.exitCode}}function qI(n,e,t){Ui.mkdirSync(je.dirname(n),{recursive:!0});let r=e==="json"?bh(t):wh(t);try{Ui.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 GI(n,e,t){if(!n)return;let r=YI(n,t),i=JI(n,r),o=i?je.join(r,KI(e)):r;if(i||zI(n,e),Ui.existsSync(o))throw new wn(`Output file already exists: ${kh(o,t)}`);return o}function zI(n,e){let t=Ch(e);if(je.extname(n).toLowerCase()!==t)throw new wn(`--output-path must use the ${t} extension for --format ${e}.`)}function JI(n,e){return Ui.existsSync(e)?Ui.statSync(e).isDirectory():n.endsWith("/")||n.endsWith("\\")||je.extname(n)===""}function YI(n,e){return je.resolve(e,n)}function KI(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}${Ch(n)}`}function Ch(n){return n==="json"?".json":".md"}function kh(n,e){let t=je.relative(e,n);return t&&!t.startsWith("..")&&!je.isAbsolute(t)?t:n}function XI(n){n&&process.stderr.write(n)}function Ih(n){for(let e of n){let t=e.charCodeAt(0);if(t<=31||t===127)return!0}return!1}import{InvalidArgumentError as ZI}from"commander";import*as q from"path";import*as Cl from"os";import{readdirSync as QI,existsSync as Js,readFileSync as eA,unlinkSync as tA,copyFileSync as Th,writeFileSync as xh}from"fs";import{execa as nA}from"execa";import{cyan as he,yellow as Lh}from"colorette";import rA from"ora";var ee=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function kl(n){let e=n;return n instanceof ee?n.code:e.code??e.name??"UnknownError"}async function Hr(n,e,t,r){let i=await Xe(process.pid),o=i!==null?ce(Number(i)*1024):"unknown",s={event:b.CheckCommand,args:r,mcpMemory:o,lspMemory:"unknown"},a={duration_ms:Date.now()-n,success:e,error_code:t};await I.track(s,a).catch(()=>{})}var iA=["default","csv","json"],Ah=["default","json"];function oA(n){return[...n].sort((e,t)=>{let r=Dh(e),i=Dh(t);return r.apiVersion-i.apiVersion||r.suffix.localeCompare(i.suffix)})}function Dh(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 Nh(n){let t=QI(n,{withFileTypes:!0}).filter(r=>r.isFile()&&r.name.toLowerCase().endsWith(".json")).map(r=>r.name.slice(0,-5));return oA(t)}async function Oh(n){if(n=n===void 0?"default":n,!Ah.includes(n))throw new Error(`--format must be ${Ah.join(" or ")}. got "${n}"`);let e=Date.now(),t=["check","compat","versions"];try{let r=await A.new(),{apiChangeDir:i}=r.getApiscanPaths();p(he(`[compat:versions] apiChangeDir: "${i}"`));let o=Nh(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 Hr(e,!0,null,t);return}console.log(o.join(`
1333
- `))}await Hr(e,!0,null,t)}catch(r){let i=kl(r);throw await Hr(e,!1,i,t),r}}var Rh=new Set([".ets",".c",".cpp"]);function sA(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 ee("errorCode",`Module ${r.map(s=>`"${s}"`).join(", ")} ${o} not defined in build-profile.json5. Available modules: ${i}.`)}function aA(n){for(let e of n){let t=q.resolve(e);if(!Js(t))throw new ee("errorCode",`File "${e}" does not exist.`);let r=q.extname(t).toLowerCase();if(!Rh.has(r)){let i=Array.from(Rh).join(", ");throw new ee("errorCode",`Unsupported file extension "${r}" for "${e}". Supported: ${i}.`)}}}function cA(n){let e=[],t=[];for(let r of n)q.extname(r).toLowerCase()===".ets"?e.push(r):t.push(r);return{arkTs:e,cpp:t}}function lA(n){let e=[],t=[],r="",i=!1,o=0;for(;o<n.length;){let s=n[o];i?{field:r,inQuotes:i,i:o}=dA(n,o,s,r,i):s==='"'?(i=!0,o+=1):s===","?(t.push(r),r="",o+=1):s===`
1334
- `?(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 dA(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 uA(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 pA(n){let e=eA(n,"utf8"),t=e.startsWith("\uFEFF")?e.slice(1):e,r=lA(t);if(r.length<2)return[];let[i,...o]=r;return uA(i,o)}function fA(n,e){let t=n.match(/CSV saved to:\s*([^\r\n]+\.csv)/);if(!t)return null;let r=t[1].trim();if(q.isAbsolute(r))return r;let i=q.join(e,r);return S.ensurePathWithinRoot(e,i)}function mA(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(he("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 hA(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(he(`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(Lh(` ... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function gA(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(Lh(`... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function yA(n,e){let t=[];for(let r of e){let i=n.profile.modules.find(o=>o.name===r);if(!i)throw new ee("errorCode",`Module "${r}" not found in build-profile.json5.`);t.push(q.resolve(n.rootDir,i.srcPath))}return t}function vA(n,e,t,r){if(!r.sourceVersion||!r.targetVersion)throw new ee("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}=cA(e),a=d=>q.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=yA(t,r.modules);i.push("--modulePaths",o.join(","))}else i.push("--projectPath",t.rootDir);return i.push("--outputPath",Cl.tmpdir()),i}async function wA(n,e){let t=q.dirname(e[0]);try{let i=(await nA(n.nodePath,e,{cwd:t,stdin:"ignore",stdout:"pipe",stderr:"inherit"})).stdout;return process.env.DEVECO_CLI_DEBUG&&(console.log(he("[compat:check] === scan stdout ===")),process.stdout.write(i),i.endsWith(`
1340
+ `}function mg(n,e){return[Gl(n.summary),`Full report: ${zl(e)}`,""].join(`
1341
+ `)}function fg(n){let e=["# CodeLinter report",""];return n.issues.length===0?e.push("No defects found.",""):e.push(...FA(n.issues),""),e.push("## Summary","",...HA(n.summary),""),e.join(`
1342
+ `)}function hg(n){return`${JSON.stringify(n,null,2)}
1343
+ `}function Gl(n){return`Summary: Issues: ${pt(n.issues)} | Errors: ${pt(n.errors)} | Warnings: ${pt(n.warnings)} | Suggestions: ${pt(n.suggestions)} | Files checked: ${pt(n.filesChecked)}`}function _A(n,e){return`Showing ${pt(e)} of ${pt(n)} issues. Use --output-path <path> to write all results.`}function jA(n){let e=["No","File","Line","Column","Severity","Rule","Message"],t=n.map((r,o)=>({cells:BA(r,o+1)}));return["CodeLinter report","",Ft(e,t)].join(`
1344
+ `)}function FA(n){let e=["| No | File | Line | Column | Severity | Rule | Message |","| ---: | --- | ---: | ---: | --- | --- | --- |"];for(let[t,r]of n.entries())e.push($A(r,t+1));return e}function $A(n,e){return`| ${[String(e),zl(kr(n.file)),ua(n.line),ua(n.column),kr(n.severity),kr(n.rule),kr(n.message)].map(UA).join(" | ")} |`}function HA(n){return[`- Issues: ${pt(n.issues)}`,`- Errors: ${pt(n.errors)}`,`- Warnings: ${pt(n.warnings)}`,`- Suggestions: ${pt(n.suggestions)}`,`- Files checked: ${pt(n.filesChecked)}`]}function UA(n){return n.replace(ug,"\\\\").replace(MA,"\\|").replace(OA,"<br>")}function BA(n,e){return[String(e),zl(kr(WA(n.file))),ua(n.line),ua(n.column),kr(n.severity),kr(n.rule),kr(n.message)]}function WA(n){if(!ri.isAbsolute(n))return n;let e=ri.relative(process.cwd(),n);return!e||e.startsWith("..")||ri.isAbsolute(e)?n:e}function zl(n){return n.replace(ug,"/")}function kr(n){let e=n?.trim();return e||dg}function ua(n){return n===void 0?dg:String(n)}function pt(n){return n.toLocaleString("en-US")}var Jl=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function GA(n){let e=n;return n instanceof Jl?n.code:e.code??e.name??"UnknownError"}async function gg(n,e,t,r){let o=await je(process.pid),i=o!==null?Q(Number(o)*1024):"unknown",s={event:b.CheckCommand,args:r,mcpMemory:i,lspMemory:"unknown"},a={duration_ms:Date.now()-n,success:e,error_code:t};await I.track(s,a).catch(()=>{})}var zA=/^-?\d+$/;function Yl(){return new qA("lint").description("Run DevEco Code Linter checks for TS/ArkTS code").helpOption("-h, --help","display help for command").addArgument(new VA("[path]","File or directory to lint").argParser(ZA)).option("--fix","Auto-fix fixable code issues").option("--incremental","Only check uncommitted files").option("--config-path <path>","Path to lint configuration file",YA).option("--product <product>","Product name defined in build-profile.json5",KA,"default").option("--format <format>","Report format (choices: default, json)",JA,"default").option("--output-path <path>","Complete report file or directory",XA).option("--limit <number>","Maximum terminal issues to display when --output-path is omitted",QA).action(eD)}function JA(n){if(n==="default"||n==="json")return n;throw new Ir("Invalid --format. Expected one of: default, json.")}function YA(n){Kl(n,"--config-path");let e=We.extname(n).toLowerCase();if(e!==".json"&&e!==".json5")throw new Ir("`--config-path` must point to a .json or .json5 file.");return n}function KA(n){return vg(n,"product"),n}function XA(n){return Kl(n,"--output-path"),n}function ZA(n){return Kl(n,"path"),n}function QA(n){if(vg(n,"limit"),!zA.test(n))throw new Ir("`--limit` must be a positive integer.");let e=Number.parseInt(n,10);if(e<=0||!Number.isSafeInteger(e))throw new Ir("`--limit` must be an integer greater than 0.");return e}function vg(n,e){if(n.trim().length===0||Sg(n))throw new Ir(`Invalid --${e} value.`)}function Kl(n,e){let t=`\`${e}\``;if(n.length===0||Sg(n))throw new Ir(`${t} must be a non-empty path without control characters.`)}async function eD(n,e,t){let r=Date.now(),o=["check","lint"];try{let i=process.cwd(),s=await A.new(),a=new ti(s,i),c=nD(s,a,t,e),l=aD(c.outputPath,c.format,i);e.fix&&console.warn(yg("Running codelinter with --fix. Ensure your project source is trusted."));let d=await tD(a,n,e);pD(d.diagnostics),process.exitCode=iD(d,l,c.format,e.limit,i),await gg(r,!0,null,o)}catch(i){let s=GA(i);throw await gg(r,!1,s,o),i}}async function tD(n,e,t){return oD(n,{lintPath:e,configPath:t.configPath,product:t.product,fix:t.fix,incremental:t.incremental})}function rD(n){return[["format","--format"],["outputPath","--output-path"]].filter(([e])=>n.getOptionValueSource(e)==="cli").map(([,e])=>e)}function nD(n,e,t,r){let o=rD(t);if(o.length===0||e.supportsReportOptions)return r;let i=Xt(n.toolchainRoot),s=o.length===1?"option":"options";return console.warn(yg(`Warning: The detected DevEco Studio version is: ${i??"unknown"}. The bundled legacy Code Linter does not support ${s}: ${o.join(", ")}. Action: ignore the unsupported ${s} and continue the lint check with default terminal output.`)),{format:o.includes("--format")?"default":r.format,outputPath:o.includes("--output-path")?void 0:r.outputPath}}async function oD(n,e){let t=new Ke;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 iD(n,e,t,r,o){if(!n.report)return console.error(pa("Failed to generate Code Linter report.")),console.error(pa(n.reportError?.message??"Native JSON report was not generated.")),n.exitCode===0?1:n.exitCode;try{if(e){sD(e,t,n.report);let i=bg(e,o);process.stdout.write(mg(n.report,i))}else process.stdout.write(pg(n.report,r));return n.exitCode}catch(i){return console.error(pa("Failed to generate Code Linter report.")),console.error(pa(i.message)),n.exitCode===0?1:n.exitCode}}function sD(n,e,t){ni.mkdirSync(We.dirname(n),{recursive:!0});let r=e==="json"?hg(t):fg(t);try{ni.writeFileSync(n,r,{encoding:"utf-8",flag:"wx"})}catch(o){throw o.code==="EEXIST"?new Error(`Output file already exists: ${n}`,{cause:o}):o}}function aD(n,e,t){if(!n)return;let r=dD(n,t),o=lD(n,r),i=o?We.join(r,uD(e)):r;if(o||cD(n,e),ni.existsSync(i))throw new Ir(`Output file already exists: ${bg(i,t)}`);return i}function cD(n,e){let t=wg(e);if(We.extname(n).toLowerCase()!==t)throw new Ir(`--output-path must use the ${t} extension for --format ${e}.`)}function lD(n,e){return ni.existsSync(e)?ni.statSync(e).isDirectory():n.endsWith("/")||n.endsWith("\\")||We.extname(n)===""}function dD(n,e){return We.resolve(e,n)}function uD(n){let e=new Date,t=[e.getFullYear(),e.getMonth()+1,e.getDate()].map((i,s)=>String(i).padStart(s===0?4:2,"0")).join(""),r=[e.getHours(),e.getMinutes(),e.getSeconds()].map(i=>String(i).padStart(2,"0")).join(""),o=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${r}-${o}${wg(n)}`}function wg(n){return n==="json"?".json":".md"}function bg(n,e){let t=We.relative(e,n);return t&&!t.startsWith("..")&&!We.isAbsolute(t)?t:n}function pD(n){n&&process.stderr.write(n)}function Sg(n){for(let e of n){let t=e.charCodeAt(0);if(t<=31||t===127)return!0}return!1}import{execa as mD}from"execa";import Jt from"fs";import fD from"os";import*as q from"path";import{fileURLToPath as hD}from"url";var Eg=q.join("resources","arkts-check.cjs"),oi=class{toolProvider;cwd;constructor(e,t){this.toolProvider=e,this.cwd=t}async check(e){let t=this.resolveProjectRoot(e.projectRoot,e.files),r=this.resolveFiles(t,e.files),o=this.resolveScriptPath(),i=this.buildArgs(o,t,r,e.fix),s=this.buildEnv();u(`Executing: ${this.toolProvider.nodePath} ${i.join(" ")}`);let a=await mD(this.toolProvider.nodePath,i,{cwd:t,env:s,stdout:"pipe",stderr:"pipe",reject:!1});return this.parseResult(a.stdout,a.stderr,a.exitCode??1)}resolveProjectRoot(e,t){if(e){let o=q.resolve(this.cwd,e);if(!Jt.existsSync(o))throw new Error(`Project path not found: ${o}`);if(Jt.statSync(o).isFile()){let s=this.discoverRootFrom(q.dirname(o));if(s)return s;throw new Error(`--project path is a file, not a project root: ${o}
1345
+ Could not find a project-level build-profile.json5 above it. Pass the project root directory instead.`)}if(this.discoverRootFrom(o)!==o)throw new Error(`Not a valid Harmony project root: ${o}
1346
+ (project-level build-profile.json5 not found).`);return o}if(t&&t.length>0)for(let o of t){let i=q.isAbsolute(o)?o:q.resolve(this.cwd,o),s=this.discoverRootFrom(q.dirname(i));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 W.discover(e).rootDir}catch{return}}resolveFiles(e,t){if(t.length===0)return[];let r=t.map(a=>{if(q.isAbsolute(a))return a;let c=q.resolve(this.cwd,a);return Jt.existsSync(c)?c:q.resolve(e,a)}),o=r.filter(a=>!Jt.existsSync(a));if(o.length>0)throw new Error(`File(s) not found:
1347
+ `+o.map(a=>` ${a}`).join(`
1348
+ `));let i=r.filter(a=>{let c=q.relative(e,a);return c.startsWith("..")||q.isAbsolute(c)});if(i.length>0)throw new Error(`File(s) outside the project root ${e}:
1349
+ `+i.map(a=>` ${a}`).join(`
1350
+ `));let s=r.filter(a=>Jt.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):
1351
+ `+r.map(a=>` ${a}`).join(`
1352
+ `));return s}buildArgs(e,t,r,o){let i=[e,"--project",t];return i.push(o?"--fix":"--no-fix"),r.length>0&&i.push("--files",...r),i}buildEnv(){return{...process.env,DEVECO_HOME:this.resolveDevecoHome()}}resolveDevecoHome(){let e=this.toolProvider.toolchainRoot;if(fD.platform()==="darwin"&&!Jt.existsSync(q.join(e,"sdk"))){let t=q.join(e,"Contents");if(Jt.existsSync(q.join(t,"sdk")))return t}return e}parseResult(e,t,r){let o=e.trim();if(!o){let i=t.trim();throw new Error(`arkts-check exited with code ${r} but produced no output`+(i?`: ${i}`:""))}try{let i=JSON.parse(o);return{success:i.success??!1,error:i.error,errors:i.errors??[],fixed:i.fixed??[],alsoModified:i.alsoModified??[],summary:{errorCount:i.summary?.errorCount??0,warnCount:i.summary?.warnCount??0,fixedCount:i.summary?.fixedCount??0,checkerDiagCount:i.summary?.checkerDiagCount,fileCount:i.summary?.fileCount??0}}}catch(i){throw new Error(`Failed to parse arkts-check output: ${o.slice(0,500)}`,{cause:i})}}resolveScriptPath(){let e=hD(import.meta.url),t=q.dirname(e);if(e.includes("dist")){let s=q.dirname(t),a=q.join(s,"src",Eg);if(Jt.existsSync(a))return a}let r=q.dirname(t),o=q.dirname(r),i=q.join(o,"src",Eg);if(Jt.existsSync(i))return i;throw new Error("arkts-check.cjs not found in deveco-cli package resources. Reinstall deveco-cli.")}};import{red as Zl,yellow as Ql,green as Pg}from"colorette";import{Command as gD}from"commander";function yD(n){let e=n;return e.code??e.name??"UnknownError"}async function Xl(n,e,t,r){let o=await je(process.pid),i=o!==null?Q(Number(o)*1024):"unknown",s={event:b.CheckCommand,args:r,mcpMemory:i,lspMemory:"unknown"},a={duration_ms:Date.now()-n,success:e,error_code:t};await I.track(s,a).catch(()=>{})}function ed(){return new gD("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 vD(n,e)})}async function vD(n,e){let t=Date.now(),r=["check","arkts"];try{let o=await A.new(),i=new oi(o,process.cwd()),s=new Ke;process.stderr.isTTY&&s.start("Checking ArkTS...");let a;try{a=await i.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(Zl(a.error)),process.exitCode=1,await Xl(t,!1,"CheckFailed",r);return}s.stop(),wD(a),await Xl(t,!0,null,r)}catch(o){throw await Xl(t,!1,yD(o),r),o}}function wD(n){let{errorCount:e,warnCount:t,fixedCount:r,fileCount:o}=n.summary;if(bD(n.fixed,r,n.alsoModified),e===0){console.log(Pg(`No errors found in ${o} file(s).`)),Cg(n.errors);return}SD(n.errors,e,t),process.exitCode=1}function bD(n,e,t){if(n.length!==0){console.log(Pg(`\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(Ql(`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 SD(n,e,t){let r=n.filter(o=>o.severity==="error");console.error(Zl(`ArkTS check found ${e} error(s):`));for(let o of r){let i=o.rule?` (${o.rule})`:"";console.error(Zl(`${o.file}:${o.line}:${o.column} - ${o.severity}: ${o.message}${i}`))}Cg(n,t)}function Cg(n,e){let t=n.filter(o=>o.severity!=="error");if(t.length===0)return;let r=e??t.length;console.warn(Ql(`
1353
+ Warnings (${r}):`));for(let o of t){let i=o.rule?` (${o.rule})`:"";console.warn(Ql(`${o.file}:${o.line}:${o.column} - ${o.severity}: ${o.message}${i}`))}}import{InvalidArgumentError as ED}from"commander";import*as J from"path";import*as td from"os";import{readdirSync as PD,existsSync as ma,readFileSync as CD,unlinkSync as kD,copyFileSync as Dg,writeFileSync as Rg}from"fs";import{execa as ID}from"execa";import{cyan as ve,yellow as Tg}from"colorette";import AD from"ora";var oe=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function rd(n){let e=n;return n instanceof oe?n.code:e.code??e.name??"UnknownError"}async function Jn(n,e,t,r){let o=await je(process.pid),i=o!==null?Q(Number(o)*1024):"unknown",s={event:b.CheckCommand,args:r,mcpMemory:i,lspMemory:"unknown"},a={duration_ms:Date.now()-n,success:e,error_code:t};await I.track(s,a).catch(()=>{})}var DD=["default","csv","json"],kg=["default","json"];function RD(n){return[...n].sort((e,t)=>{let r=Ig(e),o=Ig(t);return r.apiVersion-o.apiVersion||r.suffix.localeCompare(o.suffix)})}function Ig(n){let e=n.match(/\((\d+)\)/),t=e?Number(e[1]):0,r=n.lastIndexOf("_"),o=r>=0?n.slice(r+1):n;return{apiVersion:t,suffix:o}}function xg(n){let t=PD(n,{withFileTypes:!0}).filter(r=>r.isFile()&&r.name.toLowerCase().endsWith(".json")).map(r=>r.name.slice(0,-5));return RD(t)}async function Lg(n){if(n=n===void 0?"default":n,!kg.includes(n))throw new Error(`--format must be ${kg.join(" or ")}. got "${n}"`);let e=Date.now(),t=["check","compat","versions"];try{let r=await A.new(),{apiChangeDir:o}=r.getApiscanPaths();u(ve(`[compat:versions] apiChangeDir: "${o}"`));let i=xg(o);if(n==="json")console.log(JSON.stringify({versions:i,count:i.length},null,2));else{if(i.length===0){console.log("No SDK versions available."),await Jn(e,!0,null,t);return}console.log(i.join(`
1354
+ `))}await Jn(e,!0,null,t)}catch(r){let o=rd(r);throw await Jn(e,!1,o,t),r}}var Ag=new Set([".ets",".c",".cpp"]);function TD(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 o=n.profile.modules.map(s=>s.name).join(", "),i=r.length>1?"are":"is";throw new oe("errorCode",`Module ${r.map(s=>`"${s}"`).join(", ")} ${i} not defined in build-profile.json5. Available modules: ${o}.`)}function xD(n){for(let e of n){let t=J.resolve(e);if(!ma(t))throw new oe("errorCode",`File "${e}" does not exist.`);let r=J.extname(t).toLowerCase();if(!Ag.has(r)){let o=Array.from(Ag).join(", ");throw new oe("errorCode",`Unsupported file extension "${r}" for "${e}". Supported: ${o}.`)}}}function LD(n){let e=[],t=[];for(let r of n)J.extname(r).toLowerCase()===".ets"?e.push(r):t.push(r);return{arkTs:e,cpp:t}}function ND(n){let e=[],t=[],r="",o=!1,i=0;for(;i<n.length;){let s=n[i];o?{field:r,inQuotes:o,i}=MD(n,i,s,r,o):s==='"'?(o=!0,i+=1):s===","?(t.push(r),r="",i+=1):s===`
1355
+ `?(t.push(r),e.push(t),t=[],r="",i+=1):(s==="\r"||(r+=s),i+=1)}return(r.length>0||t.length>0)&&(t.push(r),e.push(t)),e}function MD(n,e,t,r,o){return t!=='"'?{field:r+t,inQuotes:o,i:e+1}:n[e+1]==='"'?{field:r+'"',inQuotes:o,i:e+2}:{field:r,inQuotes:!1,i:e+1}}function OD(n,e){return e.map(t=>{let r=o=>{let i=n.indexOf(o);return i>=0&&i<t.length?t[i]:""};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 _D(n){let e=CD(n,"utf8"),t=e.startsWith("\uFEFF")?e.slice(1):e,r=ND(t);if(r.length<2)return[];let[o,...i]=r;return OD(o,i)}function jD(n,e){let t=n.match(/CSV saved to:\s*([^\r\n]+\.csv)/);if(!t)return null;let r=t[1].trim();if(J.isAbsolute(r))return r;let o=J.join(e,r);return S.ensurePathWithinRoot(e,o)}function FD(n,e){let t=new Map;for(let i of n){let s=i.changeType||"(unknown)";t.set(s,(t.get(s)??0)+1)}let r=Array.from(t.entries()).sort((i,s)=>s[1]-i[1]||i[0].localeCompare(s[0])),o=Math.max(5,...r.map(([i])=>i.length));console.log(ve("API change scan summary:")),console.log(` ${"Total".padEnd(o)} ${n.length}`);for(let[i,s]of r)console.log(` ${i.padEnd(o)} ${s}`);e&&console.log(` ${"Report".padEnd(o)} ${e}`)}function $D(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(ve(`Details (showing ${t.length}${r>0?` of ${n.length}`:""}):`));let o=[["Title","title"],["Language","language"],["ChangeId","changeId"],["Changed in","changedInSdk"],["Affected Versions","affectedVersions"],["Code Location","codeLocation"]],i=Math.max(...o.map(([a])=>a.length)),s=a=>a||"<unknown>";for(let a of t){console.log(` [${s(a.changeType)}] ${s(a.apiDefinition)}`);for(let[c,l]of o)console.log(` ${c.padEnd(i)} ${s(a[l])}`)}r>0&&console.log(Tg(` ... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function HD(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(Tg(`... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function UD(n,e){let t=[];for(let r of e){let o=n.profile.modules.find(i=>i.name===r);if(!o)throw new oe("errorCode",`Module "${r}" not found in build-profile.json5.`);t.push(J.resolve(n.rootDir,o.srcPath))}return t}function BD(n,e,t,r){if(!r.sourceVersion||!r.targetVersion)throw new oe("errorCode","source-version and target-version are required.");let o=[n,"--startVersion",r.sourceVersion,"--endVersion",r.targetVersion];if(e.length>0){let{arkTs:i,cpp:s}=LD(e),a=d=>J.resolve(process.cwd(),d),c=i.map(a),l=s.map(a);c.length>0&&o.push("--arkTsFiles",c.join(",")),l.length>0&&o.push("--cppFiles",l.join(","))}else if(r.modules&&r.modules.length>0){let i=UD(t,r.modules);o.push("--modulePaths",i.join(","))}else o.push("--projectPath",t.rootDir);return o.push("--outputPath",td.tmpdir()),o}async function WD(n,e){let t=J.dirname(e[0]);try{let o=(await ID(n.nodePath,e,{cwd:t,stdin:"ignore",stdout:"pipe",stderr:"inherit"})).stdout;return process.env.DEVECO_CLI_DEBUG&&(console.log(ve("[compat:check] === scan stdout ===")),process.stdout.write(o),o.endsWith(`
1335
1356
  `)||process.stdout.write(`
1336
- `),console.log(he("[compat:check] === end stdout ==="))),i}catch(r){let i=r;process.env.DEVECO_CLI_DEBUG&&i.stdout&&(console.log(he("[compat:check] === scan stdout (on error) ===")),process.stdout.write(i.stdout),i.stdout.endsWith(`
1357
+ `),console.log(ve("[compat:check] === end stdout ==="))),o}catch(r){let o=r;process.env.DEVECO_CLI_DEBUG&&o.stdout&&(console.log(ve("[compat:check] === scan stdout (on error) ===")),process.stdout.write(o.stdout),o.stdout.endsWith(`
1337
1358
  `)||process.stdout.write(`
1338
- `),console.log(he("[compat:check] === end stdout ===")));let o=new ee("errorCode",`Compatibility scan failed: ${i.message}`+(i.stderr?`
1339
- ${i.stderr}`:""));throw i.stdout&&(o.stdout=i.stdout),o}}function bA(n,e){if(!iA.includes(e.format))throw new ZI(`--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 ee("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 ee("errorCode","--source-version is required.");if(!e.targetVersion)throw new ee("errorCode","--target-version is required.");if(!e.outputPath&&e.format==="csv")throw new ee("errorCode","--format csv requires --output-path. For console output, use --format json or --format default (or omit the flag).")}function SA(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 ee("errorCode",`${t.join(" and ")} ${r} not in the available SDK version list.
1340
- 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 ee("errorCode",`--target-version "${n.targetVersion}" must be later than --source-version "${n.sourceVersion}". Run \`devecocli compat versions\` to see the available order.`)}}function EA(n,e,t,r,i){i==="none"&&(t==="json"?gA(n,r):hA(n,r)),mA(n,e)}function PA(n,e){let t=q.dirname(n),r=q.basename(n),i=e.slice(1).map(o=>o.startsWith("--")?o:`"${o}"`).join(" ");p(he(`[compat:check] command: cd "${t}" && node "${r}" ${i}`))}function CA(n){try{tA(n),p(he(`[compat:check] cleaned up tmp report: "${n}"`))}catch(e){p(he(`[compat:check] failed to clean up tmp report: ${e.message}`))}}var kA=[".csv",".json"];function IA(n){return kA.includes(n.toLowerCase())}function AA(n,e){if(!n)return{kind:"none"};let t=q.extname(n).toLowerCase();if(!IA(t))return{kind:"dir",dirPath:q.resolve(n)};if(t===".csv"&&!(e==="default"||e==="csv")||t===".json"&&e!=="json")throw new ee("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:q.resolve(n),ext:t}}function DA(n){if(n.kind==="file"){if(Js(n.filePath))throw new ee("errorCode",`Target file "${n.filePath}" already exists. Remove it first, or choose a different --output-path.`);let e=q.dirname(n.filePath);if(!Js(e))throw new ee("errorCode",`Target directory "${e}" does not exist. Create it first, or choose a different --output-path.`)}else if(n.kind==="dir"&&!Js(n.dirPath))throw new ee("errorCode",`Target directory "${n.dirPath}" does not exist. Create it first, or choose a different --output-path.`)}function Mh(n){return JSON.stringify({records:n,count:n.length},null,2)+`
1341
- `}function RA(n,e,t,r){r===".csv"?Th(n,t):xh(t,Mh(e),"utf8"),p(he(`[compat:check] saved report: "${t}"`))}function TA(n,e,t,r){if(r==="json"){let o=q.basename(n,".csv"),s=q.join(t,`${o}.json`);return xh(s,Mh(e),"utf8"),p(he(`[compat:check] saved report: "${s}"`)),s}let i=q.join(t,q.basename(n));return Th(n,i),p(he(`[compat:check] saved report: "${i}"`)),i}async function xA(n,e){let t=new Be(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 ee("errorCode",`hvigorw compileNative failed (module=${r??"<project>"}): `+i.message,{cause:i})}}async function LA(n,e){bA(n,e);let t=Y.discover(process.cwd());e.modules&&e.modules.length>0&&sA(t,e.modules),n.length>0&&aA(n);let r=await A.new(),{apiChangeDir:i,scriptPath:o}=r.getApiscanPaths();p(he(`[compat:check] script: "${o}"`));let s=Nh(i);SA(e,s),e.outputPath&&p(he(`[compat:check] outputPath: "${e.outputPath}"`));let a=AA(e.outputPath,e.format);return p(he(`[compat:check] outputTarget: ${a.kind}`)),DA(a),{project:t,scriptPath:o,target:a,toolProvider:r}}function NA(n,e,t,r){if(t.kind==="file")return RA(n,e,t.filePath,t.ext),t.filePath;if(t.kind==="dir")return TA(n,e,t.dirPath,r);if(t.kind==="none")return null;throw new ee("errorCode",`Unexpected output target kind: ${t.kind}`)}async function OA(n,e,t,r,i){let o=rA({text:"Running compatibility check...",color:"cyan"}).start();try{await xA(n.toolProvider,t);let s=vA(n.scriptPath,e,n.project,t);PA(n.scriptPath,s);let a=await wA(n.toolProvider,s),c=fA(a,Cl.tmpdir());if(!c)throw new ee("errorCode","Scanner output format unexpected: missing report path.");p(he(`[compat:check] tmp csv: "${c}"`));let l=pA(c),d=NA(c,l,n.target,t.format);CA(c),o.stop(),EA(l,d,t.format,t.limit,n.target.kind),await Hr(r,!0,null,i)}catch(s){o.fail("Compatibility check failed");let a=kl(s);throw await Hr(r,!1,a,i),s}}async function _h(n,e){let t=Date.now(),r=["check","compat"];try{let i=await LA(n,e);await OA(i,n,e,t,r)}catch(i){let o=kl(i);throw await Hr(t,!1,o,r),i}}function _A(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new MA(`--limit must be a positive integer (got "${n}")`);return e}var Il=new jh("compat").description("Compatibility checking utilities.");Il.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)",_A,100).action(async(n,e)=>{await _h(n,e)});Il.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 Oh(t)});var jA=new jh("check").description("Run DevEco project checks").addCommand(Il).addCommand(El()),Fh=jA;import{Command as kR}from"commander";import{green as Yl,red as IR}from"colorette";import Kl from"fs";import Eg from"path";import Pg from"json5";import{readFileSync as pD}from"fs";import{join as FA}from"path";var re={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"},Fe={CERT_NAME_PREFIX:"auto_debug_",CERT_TYPE_DEBUG:"1",TEAM_ID_INVALID_CHARS:/[\\/.:]/g,CERT_PATTERN:/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/,TARGET_FRIENDLY_NAME:"debugKey",CERTIFICATE_PATTERN_GLOBAL:/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g,BUNDLE_NAME_REGEX:/^[a-zA-Z][a-zA-Z0-9._-]*$/,CERT_BEGIN_HEADER:"-----BEGIN CERTIFICATE-----",CERT_SAVE_DIR:FA(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},ge={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"},pt={FORBIDDEN:403,UNAUTHORIZED:401},E={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."},se={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 Ys(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function Al(n){let e=n.replace(Fe.TEAM_ID_INVALID_CHARS,"");return`${Fe.CERT_NAME_PREFIX}${e}.cer`}function Ur(n,e,t){if(n===pt.FORBIDDEN)return e===ge.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN);if(n===pt.UNAUTHORIZED)return new Error(E.ERR_UNAUTHORIZED);if(t.includes(ge.USER_NOT_HARMONY_CODE))return new Error(E.ERR_USER_NOT_HARMONY);if(t.includes(ge.CERT_LIMIT_CODE))return new Error(E.ERR_CERT_LIMIT_REACHED);let r=$A(t);return new Error(r??E.ERR_DOWNLOAD_CER)}function $A(n){let e=$h(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?$h(t):t;if(r&&typeof r=="object"){let i=r.msg;if(typeof i=="string"&&i.trim()!=="")return i}return null}function $h(n){try{return JSON.parse(n)}catch{return null}}function Dl(n){return JSON.parse(n)}async function Hh(n){let e=`${re.BASE_URL}${re.CERT_LIST_PATH}`,t=await L.postAllowFailure(e,{headers:Ys(n)});if(t.statusCode!==200)throw Ur(t.statusCode,t.statusText,t.data);return Dl(t.data)?.certList??[]}async function Ks(n,e){return(await Hh(n)).find(r=>r.certName===e)??null}async function Rl(n,e){let t=`${re.BASE_URL}${re.CERT_DELETE_PATH}`,r=await L.deleteAllowFailure(t,{headers:Ys(n),params:{certIds:[e]}});if(r.statusCode!==200)throw Ur(r.statusCode,r.statusText,r.data);return Dl(r.data)?.ret?.code===0}async function Tl(n,e,t){let r=`${re.BASE_URL}${re.CERT_ADD_PATH}`,i={csr:e,certName:t,certType:Fe.CERT_TYPE_DEBUG},o=await L.postAllowFailure(r,{headers:Ys(n),params:i});if(o.statusCode!==200)throw Ur(o.statusCode,o.statusText,o.data);if(!o.data.includes(ge.SUCCESS_MARKER))throw Ur(void 0,o.statusText,o.data)}async function xl(n,e){let t=`${re.BASE_URL}${re.CERT_DOWNLOAD_URL_PATH}`,r=await L.postAllowFailure(t,{headers:Ys(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw Ur(r.statusCode,r.statusText,r.data);return Dl(r.data)?.urlsInfo?.[0]??null}import{mkdirSync as HA,writeFileSync as UA,existsSync as WA}from"fs";import{dirname as BA}from"path";import{createHash as VA}from"crypto";function qA(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 Wi(n,e,t){qA(n);let{statusCode:r,statusText:i,buffer:o}=await L.getBinaryAllowFailure(n,{timeout:Fe.DOWNLOAD_CONNECT_TIMEOUT_MS});if(r!==200)throw r===pt.FORBIDDEN&&i===ge.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_DOWNLOAD_CER);if(t){let a=VA("sha256").update(o).digest("hex");if(a!==t.toLowerCase())throw new Error(`SHA-256 mismatch for ${e}: expected ${t.toLowerCase()}, got ${a}`)}let s=BA(e);WA(s)||HA(s,{recursive:!0}),UA(e,o)}import lD from"fs/promises";import{readFileSync as dD}from"fs";import Xs from"path";import Bh from"crypto";import GA from"os";import Bi from"fs/promises";var Vh={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},Uh=["ECC","RSA"],Wh=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],zA={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},JA=8,Ll=64,YA=/[\\/:*?"<>|=-]/g,ft={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function KA(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>Ll)throw new Error(`The length of keyAlias cannot exceed ${Ll}`);if(!Uh.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${Uh.join(" / ")}`);let e=zA[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function XA(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(!Wh.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${Wh.join(" / ")}`)}function ZA(n){return Bh.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function QA(n){let e=n?.trim()??"";return e&&e.replace(YA,"_").replace(/\.+/g,"_").slice(0,Ll)||ft.productName}async function qh(){let n=await A.new(),e=n.javaPath;if(!e)throw new Error("Java runtime not found. DevEco Studio JBR is required to run hap-sign-tool.jar.");let t=n.sdkPath;u.info(`\u8BFB\u53D6SDK\u6839\u76EE\u5F55\uFF1A${t}`);let r=Xs.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");try{await Bi.access(r)}catch(i){throw new Error(`Sign tool jar not found: ${r}`,{cause:i})}return{javaPath:e,jarPath:r}}async function eD(n){let{javaPath:e,jarPath:t}=await qh(),r=["-jar",t,Vh.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 u.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),[e,...r]}async function tD(n){let{javaPath:e,jarPath:t}=await qh(),r=["-jar",t,Vh.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 u.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),[e,...r]}async function nD(n){u.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),KA(n);let e=await eD(n),t=await ni(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 u.info("\u751F\u6210P12\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}async function rD(n){u.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),XA(n);let e=await tD(n),t=await ni(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 u.info("\u751F\u6210CSR\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}function iD(n=JA){return Bh.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function oD(){let n=GA.homedir();try{await Bi.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=Xs.join(n,".ohos","config");try{await Bi.mkdir(e,{recursive:!0,mode:448})}catch(t){throw new Error(`Failed to create directory ${e}`,{cause:t})}return u.info(`\u7B7E\u540D\u914D\u7F6E\u76EE\u5F55\u5C31\u7EEA\uFF1A${e}`),e}async function Pe(n,e,t){let r=QA(n),i=Xs.basename(e),o=ZA(e),s=`${r}_${i}_${o}=.${t}`,a=await oD();return Xs.join(a,s)}function sD(n){let e;try{e=Y.discover(n).rootDir}catch(t){throw new Error(`Current directory ${n} is not a valid project root`,{cause:t})}return e}async function aD(n){try{await Bi.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function cD(n){try{await Bi.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function Nl(n,e,t){let r=process.cwd(),i=sD(r);await aD(i),u.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${i}`);let o=iD(),s=await Pe(n??"",i,"p12"),a=await Pe(n??"",i,"csr");return console.log("Start generating p12"),await nD({keyAlias:e?.keyAlias??ft.keyAlias,keyPwd:o,keyAlg:e?.keyAlg??ft.keyAlg,keySize:e?.keySize??ft.keySize,keystoreFile:s,keystorePwd:o}),await cD(s),console.log("Start generating csr"),await rD({subject:t?.subject??ft.csrSubject,outFile:a,keyAlias:t?.keyAlias??ft.keyAlias,keyPwd:o,signAlg:t?.signAlg??ft.signAlg,keystoreFile:s,keystorePwd:o}),{p12FilePath:s,csrFilePath:a,keyPwd:o,keyAlias:e?.keyAlias??ft.keyAlias}}var uD=["p12","cer","csr","p7b"];async function Ol(n,e){for(let t of uD){let r=await Pe(n,e,t);await lD.rm(r,{force:!0})}}function Ml(n){let e;try{e=dD(n,"utf-8")}catch{throw new Error(E.ERR_CERT_INVALIDATE)}if(!Fe.CERT_PATTERN.test(e))throw new Error(E.ERR_CERT_INVALIDATE)}async function Gh(n,e){return{certPath:await Pe(n,e,"cer"),csrPath:await Pe(n,e,"csr"),p12Path:await Pe(n,e,"p12"),profilePath:await Pe(n,e,"p7b")}}async function _l(n,e){let t=e??"",r=Y.discover(process.cwd()).rootDir;await Ol(t,r);let i=Al(n.teamId),o=await Ks(n,i);if(o&&!await Rl(n,o.id))throw new Error(E.ERR_DOWNLOAD_CER);let s=await Nl(e),a;try{a=pD(s.csrFilePath,"utf-8")}catch{throw new Error(E.ERR_READ_CSR)}console.log("Start generating certificate"),await Tl(n,a,i);let c=await Ks(n,i);if(!c)throw new Error(E.ERR_DOWNLOAD_CER);let l=await xl(n,c.certObjectId);if(!l)throw new Error(E.ERR_DOWNLOAD_CER);let d=await Pe(t,r,"cer");await Wi(l.newUrl,d,l.sha256),Ml(d);let g=await Pe(t,r,"p7b");return{p12FilePath:s.p12FilePath,csrFilePath:s.csrFilePath,cerFilePath:d,profileFilePath:g,certId:c.id,keyAlias:s.keyAlias,keyPwd:s.keyPwd,storePassword:s.keyPwd}}import aa from"crypto";import Pn from"fs";import*as ag from"path";import OD from"json5";import{execa as ig}from"execa";import og from"node-forge";import{createCipheriv as fD,createDecipheriv as mD,pbkdf2Sync as hD,randomBytes as Hl}from"crypto";import{promises as Yn}from"fs";import{dirname as gD,join as mt}from"path";var Zs=3,Vi=16,yD=1e4,zh="material",vD=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Xh="aes-128-gcm",Jn=12,Qs=16,bn=4;function jl(n){return new Uint8Array(Hl(n))}function wD(n){return Hl(n).toString("hex")}function bD(...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 Jh(n,e,t=yD,r=Vi){let i=[...n,vD],o=bD(...i),s=Buffer.from(o).toString("utf8"),a=Buffer.from(s,"utf8"),c=hD(a,e,t,r,"sha256");return new Uint8Array(c)}function Yh(n,e){let t=Hl(Jn),r=fD(Xh,n,t),i=Buffer.concat([r.update(e),r.final()]),o=r.getAuthTag(),s=Buffer.concat([i,o]),a=s.length,c=Buffer.alloc(bn+Jn+s.length);return c.writeUInt32BE(a,0),t.copy(c,bn),s.copy(c,bn+Jn),c}function Kh(n,e){if(e.length<bn+Jn+Qs)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(bn,bn+Jn),i=e.subarray(bn+Jn,bn+Jn+t);if(i.length<Qs)throw new Error("Ciphertext too short for auth tag");let o=i.subarray(0,i.length-Qs),s=i.subarray(i.length-Qs),a=mD(Xh,n,r);return a.setAuthTag(s),Buffer.concat([a.update(o),a.final()])}async function SD(n){try{await Yn.rm(n,{recursive:!0,force:!0})}catch{}}async function Fl(n){let e=await Yn.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 Yn.readFile(mt(n,t[0]))}async function $l(n,e){let t=wD(Vi),r=mt(n,t);return await Yn.writeFile(r,e,{mode:384}),t}var Sn=class{static keyChain=Promise.resolve();static async generateMaterial(e){let t=mt(e,zh);await SD(t);let r=mt(t,"ac"),i=mt(t,"ce");await Yn.mkdir(r,{recursive:!0,mode:448}),await Yn.mkdir(i,{recursive:!0,mode:448});for(let d=0;d<Zs;d++)await Yn.mkdir(mt(t,"fd",String(d)),{recursive:!0,mode:448});let o=jl(Vi),s=[];for(let d=0;d<Zs;d++)s.push(jl(Vi));let a=jl(Vi),c=Jh(s,o),l=Yh(c,a);await $l(r,o),await $l(i,l);for(let d=0;d<Zs;d++){let g=mt(t,"fd",String(d));await $l(g,s[d])}return a}static async readMaterial(e){let t=mt(e,zh),r=mt(t,"ac"),i=new Uint8Array(await Fl(r)),o=[];for(let d=0;d<Zs;d++){let g=mt(t,"fd",String(d)),v=await Fl(g);o.push(new Uint8Array(v))}let s=mt(t,"ce"),a=await Fl(s),c=Jh(o,i),l=Kh(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=gD(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 Yh(r,i).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),i=Buffer.from(e,"hex");return Kh(r,i).toString("utf8")}};import ng from"fs";import oa from"path";import AD from"json5";import*as ea from"fs";import*as Zh from"path";function ta(n){let e=Zh.resolve(n);if(!ea.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=ea.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 Br from"fs";import*as $e from"path";import{debuglog as Wr}from"util";var Qh={"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 ED(n){return Object.prototype.hasOwnProperty.call(Qh,n)}function na(n){if(ED(n))return Qh[n]}var eg={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as PD}from"url";var ia=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 ra(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function tg(n){return n==null||n.length===0}function CD(n){return!tg(n)}function Ul(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function kD(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 ID(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 En=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=$e.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=$e.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=$e.join(t.sdkPath,"default","sdk-pkg.json"),a=ta(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=$e.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(Br.existsSync(e))return Br.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=PD(e);if(t.includes("dist")){let s=$e.dirname(t),a=$e.dirname(s);return $e.join(a,"src","resources")}let r=$e.dirname(t),i=$e.dirname(r),o=$e.dirname(i);return $e.join(o,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{Wr("read builtin acl permission failed.");return}if(r!==void 0)try{let i=JSON.parse(r),s=(Array.isArray(i)?i:ra(i)?Object.values(i):[]).filter(ra).map(a=>new ia(a));s.forEach(a=>{let c=a.permissionInsteadName;CD(c)&&(a.permissionInsteadName=na(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(i){Wr(`failed to parse aclPermissionsInfo.json: ${i}`)}}static initAclPermissionFromSDK(e,t,r){let i=this.parsePermissionDefinitionFile(e);i&&i.forEach(o=>{if(!ra(o))return;let s=o,a=Ul(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(tg(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||Ul(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||Ul(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:kD(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let i=new ia;i.permissionName=t;let o=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;i.permissionDisplayName=o;let s=ID(r,this.ACL_SINCE_KEY);i.minSupportApiLevel=String(s),this.handleInsteadName(i,o),e.add(i)}static parsePermissionDefinitionFile(e){let t=$e.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!Br.existsSync(t))return;let r;try{r=Br.readFileSync(t,"utf-8")}catch(s){Wr(`failed to load permissionDefinitions.json: ${s}`);return}let i;try{let s=JSON.parse(r);if(!ra(s)){Wr("json object is null");return}i=s}catch(s){Wr(`failed to parse permissionDefinitions.json: ${s}`);return}let o=i[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(o)){Wr("definePermissions is not an array");return}return o}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=na(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=na(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function sa(n,e){let t=new Set,r=new Set;En.handleSpecificAclPermissions(),En.initAclPermission(n,e);for(let i of n.profile.modules){let o=rg(i,n,e,r,oa.join("src","main"));for(let a of o)t.add(a);let s=rg(i,n,e,r,oa.join("src","ohosTest"));for(let a of s)t.add(a)}return DD(r),t}function DD(n){if(n.size>0)throw new Error(eg.DUPLICATE_PERMISSION)}function rg(n,e,t,r,i){let o=TD(e.rootDir,n,i);if(o==null)return new Set;let s=[];for(let v of o){if(typeof v!="object"||v===null)continue;let D=RD(v,"name");D&&s.push(D)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=oa.join(t.sdkPath,"default","sdk-pkg.json"),l=ta(c),d=En.getAclPermissionInfos(e),g=new Set(Array.from(d).filter(v=>{let D=Number(v.minSupportApiLevel);return Number.isFinite(D)&&D<=l}).map(v=>v.permissionName));for(let v of Array.from(a))g.has(v)||a.delete(v);return a}function RD(n,e){let t=n[e];return typeof t=="string"?t:""}function TD(n,e,t){let r=oa.join(n,e.srcPath,t,"module.json5"),i=xD(r);if(i==null)return null;let o=LD(i,"module");return o==null?null:ND(o,"requestPermissions")}function xD(n){try{if(!ng.existsSync(n))return null;let e=ng.readFileSync(n,"utf-8");return AD.parse(e)}catch{return null}}function LD(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 ND(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var Bl=class{verifyStorePassword(e,t){try{let r=Pn.readFileSync(e),i=og.asn1.fromDer(r.toString("binary"));return og.pkcs12.pkcs12FromAsn1(i,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=Pn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(i=>this.formatFp(new aa.X509Certificate(i).fingerprint256));try{return[this.formatFp(new aa.X509Certificate(Pn.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let i=Pn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let o of i)try{let s=new aa.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 MD(n){let e=Pn.readFileSync(n,"utf-8"),t=_D(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let i=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:Wl(i["bundle-name"]),expiryDate:jD(r?.validity?.["not-after"]),cerFingerprintInProfile:FD(Wl(i["development-certificate"])),deviceUdidsInProfile:$D(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:HD(r?.acls?.["allowed-acls"]),teamIdInProfile:Wl(i["developer-id"])}}function _D(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 jD(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function FD(n){if(!n)return null;try{let t=new aa.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function $D(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 HD(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 Wl(n){return typeof n=="string"?n:null}var qi=class n{static async shouldRegenerate(e,t){let r=await n.#e(e,t);return n.#t(r)??n.#n(r)??n.#r(r)??n.#i(r)??n.#o(r)??n.#s(r)??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=Y.discover(process.cwd()),a=s.rootDir,[c,l]=await Promise.all([UD(o,a),BD(t.hdcPath)]),d=null;if(sg(c).allExist)try{d=MD(c.profileFile)}catch{}return{force:r,teamId:i,productName:o,projectPath:a,materialPaths:c,bundleName:s.getBundleName(o),deviceUdids:l,storePassword:await WD(a,o,c.storeFile),localAclPermissions:[...sa(s,t)].sort(),hapSignTool:new Bl,profileInfo:d}}static#t(e){return e.force?(p("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:Ge({force:!0})}):null}static#n(e){let t=sg(e.materialPaths);return t.allExist?null:(p(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:Ge({allFilesExist:!1,missingFiles:t.missing})})}static#r(e){return(e.profileInfo?.rawContent??"").trim().length>0?null:(p("[reGenerateSign] profile content is empty"),{shouldRegenerate:!0,reason:"Profile file content is empty",checkDetails:Ge({allFilesExist:!0,profileContentNotEmpty:!1})})}static#i(e){let t=e.profileInfo?.expiryDate;return!t||t>=new Date?null:(p(`[reGenerateSign] profile expired at ${t.toISOString()}`),{shouldRegenerate:!0,reason:`Profile expired at ${t.toISOString()}`,checkDetails:Ge({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#o(e){let t=e.profileInfo?.bundleNameInProfile;return t&&t===e.bundleName?null:(p(`[reGenerateSign] bundleName mismatch \u2014 current=${e.bundleName}, profile=${t}`),{shouldRegenerate:!0,reason:`bundleName mismatch: current=${e.bundleName}, in profile=${t}`,checkDetails:Ge({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!1})})}static#s(e){let t=e.profileInfo?.teamIdInProfile;return t&&t===e.teamId?null:(p(`[reGenerateSign] teamId mismatch \u2014 current=${e.teamId}, profile=${t}`),{shouldRegenerate:!0,reason:`teamId mismatch: current=${e.teamId}, in profile=${t}`,checkDetails:Ge({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=qD(e.profileInfo?.deviceUdidsInProfile??[],e.deviceUdids);return t.allPresent?null:(p(`[reGenerateSign] missing device UDIDs: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Device UDID(s) not in profile: ${t.missing.join(", ")}`,checkDetails:Ge({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return GD(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(p("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:Ge({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:(p("[reGenerateSign] certificate mismatch"),{shouldRegenerate:!0,reason:"Certificate mismatch between profile and local .cer file",checkDetails:Ge({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:(p(`[reGenerateSign] local certificate expired at ${r.toISOString()}`),{shouldRegenerate:!0,reason:`Local certificate expired at ${r.toISOString()}`,checkDetails:Ge({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:(p("[reGenerateSign] keystore password verification failed"),{shouldRegenerate:!0,reason:"Keystore password verification failed (storeFile may be corrupted or password changed)",checkDetails:Ge({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})}):(p("[reGenerateSign] no stored keystore password"),{shouldRegenerate:!0,reason:"No stored keystore password available for verification",checkDetails:Ge({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})})}static#p(){return p("[reGenerateSign] all checks passed \u2014 skip regeneration"),{shouldRegenerate:!1,reason:"",checkDetails:Ge({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function UD(n,e){let[t,r,i,o]=await Promise.all([Pe(n,e,"p12"),Pe(n,e,"csr"),Pe(n,e,"cer"),Pe(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:i,profileFile:o}}async function WD(n,e,t){let r=ag.join(n,"build-profile.json5");if(!Pn.existsSync(r))return;let i;try{i=OD.parse(Pn.readFileSync(r,"utf-8"))}catch{return}let a=(i?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await Sn.decryptPassword(a,t)}catch{return}}async function BD(n){p(`Executing: ${n} list targets`);let{stdout:e}=await ig(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
1342
- `)){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{p(`Executing: ${n} -t ${i} shell bm get -u`);let{stdout:o}=await ig(n,["-t",i,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),s=VD(o);s&&r.push(s)}catch{p(`[reGenerateSign] Failed to get UDID for ${i}, skipping`)}return r}function VD(n){let e=n.trim();if(!e)return null;let t=e.split(`
1343
- `);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 sg(n){let e=[n.storeFile,n.csrFile,n.cerFile,n.profileFile],t=[];for(let r of e)Pn.existsSync(r)||t.push(r);return{allExist:t.length===0,missing:t}}function qD(n,e){let t=[];for(let r of e)n.includes(r)||t.push(r);return{allPresent:t.length===0,missing:t}}function GD(n,e){let t=[...n].sort(),r=[...e].sort();return t.length!==r.length?!1:t.every((i,o)=>i===r[o])}function Ge(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 Vl}from"util";import{execa as ql}from"execa";async function lg(n,e){let t=await ca(n);if(!t)throw new Error(E.DEVICE_LIST_EMPTY);let r=await YD(e);if(t.length===0)for(let s of r)await zD(n,s.udid,s.deviceName);else for(let s of r)await JD(n,t,s.udid,s.deviceName);let o=(await ca(n)).map(s=>s.id);if(o.length===0)throw new Error(E.DEVICE_LIST_EMPTY);return o}async function zD(n,e,t){await pg(n,e,dg(t))}async function JD(n,e,t,r){for(let i=0;i<e.length;i++){if(t===e[i].udid)return;if(i===e.length-1){await pg(n,t,dg(r));return}}}function dg(n){switch(n){case"liteWearable":return"1";case"wearable":return"2";case"tv":return"3";default:return"4"}}async function cg(n,e=1,t=100){let r=`${re.BASE_URL}${re.DEVICE_LIST_PATH}?encodeFlag=0&start=${e}&pageSize=${t}`,i=fg(n),o=await L.get(r,{headers:i});if(!o)throw Vl("query devices failed: response is null"),new Error(E.ERROR_WHILE_ADD_DEVICE);if(o.statusCode!==200)throw ug(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.list)throw Vl("query devices failed: response list is null"),new Error(s.ret?.msg||E.ERROR_WHILE_ADD_DEVICE);return{deviceList:s.list,total:s.totalCount||0}}function ug(n,e,t){return n===pt.FORBIDDEN?e===ge.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN):n===pt.UNAUTHORIZED?new Error(E.ERR_UNAUTHORIZED):t.includes(ge.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(E.DEVICE_LIMIT_REACHED):new Error(E.ERROR_WHILE_ADD_DEVICE)}async function ca(n){let t=await cg(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 cg(n,s,100);if(!a||!a.deviceList||a.deviceList.length===0)break;r.push(...a.deviceList)}return r}async function pg(n,e,t){let r=`${re.BASE_URL}${re.DEVICE_ADD_PATH}`,i=fg(n),s={deviceName:`auto_sign_device_No.${Math.floor(Math.random()*3e3)}${Date.now()}`,udid:e,deviceType:t},a=await L.postAllowFailure(r,{headers:i,params:s});if(!a)throw Vl("add device failed: response is null"),new Error(E.ERROR_WHILE_ADD_DEVICE);if(a.statusCode!==200)throw ug(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(ge.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(E.DEVICE_LIMIT_REACHED):c.includes(ge.DEVICE_NAME_REPEAT_CODE)?new Error(E.DEVICE_NAME_REPEAT):new Error(E.ERROR_WHILE_ADD_DEVICE)}function fg(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}async function YD(n){let{stdout:e}=await ql(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
1344
- `)){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 KD(i,n),s=await XD(i,n);o.length>0&&r.push({id:"",udid:o,deviceName:s})}catch{p(`Failed to get device info for ${i}, skipping`)}return r}async function KD(n,e){let{stdout:t}=await ql(e,["-t",n,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),r=t.trim();if(!r)return"";let i=r.split(`
1345
- `);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 XD(n,e){let{stdout:t}=await ql(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return ZD(t)}function ZD(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 Kn from"fs";import{createHash as QD}from"crypto";import{debuglog as Ht}from"util";import{Buffer as hg}from"buffer";import{createPublicKey as eR,X509Certificate as Gl}from"crypto";import{readFileSync as tR}from"fs";import Xn from"node-forge";async function gg(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;if(s==null||s.length===0)throw new Error(E.DEVICE_LIST_EMPTY);let d=`${re.BASE_URL}${re.PROVISION_ADD_TEST_PATH}`,g=nR(t,r),v=await iR(n,d,a||[],r,s,g,o||[]);if(!v||!v.profileInfo||!v.profileInfo.provisionFileUrl)throw Ht("add provision failed, the provision file url is null"),new Error(E.ADD_PROFILE_FAIL);let D=v.profileInfo,ye=(await cR(n,D.provisionFileUrl)).urlList,ze=v.profileInfo.id;if(ye&&ye.length>0){let Cn=await Gh(t,i),Ut=Cn.profilePath;if(!await lR(ye,Ut))throw await mg(n,ze),new Error(E.ERROR_WHILE_DOWNLOAD_PROFILE);if(await mg(n,ze),Kn.existsSync(Cn.certPath)&&Kn.existsSync(Ut)&&Kn.existsSync(Cn.p12Path)){let Ig=Kn.readFileSync(Cn.certPath,"utf8"),Ag=Kn.readFileSync(Ut,"utf8");return dR(Ag,Ig,Cn.p12Path,c,l)||aR(Ut),Ut}}throw new Error(E.ADD_PROFILE_FAIL)}function nR(n,e){let t=n?`${n}_`:"";return`${rR(`${t}${e}_${e}`)}`}function rR(n){return QD("sha256").update(n).digest("hex").substring(0,16)}async function iR(n,e,t,r,i,o,s){oR(r);let a=Jl(n),c={certList:t,packageName:r,deviceList:i,provisionName:o};s.length&&(c.aclPermissionList=s);let l=await L.postAllowFailure(e,{headers:a,params:c});if(!l)throw Ht("add provision failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw zl(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw Ht(`add provision fail: ${l.data}`),sR(l.data,o),new Error(d.ret?.msg||E.ADD_PROFILE_FAIL);let g=d.provisionFileUrl;return{profileInfo:{id:d.id,name:o,provisionFileUrl:g}}}function zl(n,e,t){return n===pt.FORBIDDEN?e===ge.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN):n===pt.UNAUTHORIZED?new Error(E.ERR_UNAUTHORIZED):t.includes(ge.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(E.TEST_PROVISION_EXCEEDS_LIMIT):new Error(E.ADD_PROFILE_FAIL)}function oR(n){if(!n||n.trim().length===0)throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!Fe.BUNDLE_NAME_REGEX.test(n))throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function sR(n,e){if(n.includes(ge.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(E.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(ge.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(E.PROFILE_NAME_REPEAT)}async function mg(n,e){if(!e||e.trim().length===0)return;let t=`${re.BASE_URL}${re.PROVISION_DELETE_PATH}?id=${e}`,r=await L.deleteAllowFailure(t,{headers:Jl(n)});if(r.statusCode!==200)throw zl(r.statusCode,r.statusText,r.data);let i=JSON.parse(r.data);(!i||!i.ret||i.ret.code!==0)&&Ht(`delete provision failed: ${r.data}`)}function aR(...n){for(let e of n)try{Kn.existsSync(e)&&Kn.unlinkSync(e)}catch(t){Ht(`delete local sign file error: ${t.message}`)}}async function cR(n,e){let t=`${re.BASE_URL}${re.CERT_DOWNLOAD_URL_PATH}`,r=Jl(n),i={sourceUrls:e},o=await L.postAllowFailure(t,{headers:r,params:i});if(!o)throw Ht("get download list failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(o.statusCode!==200)throw zl(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw Ht("download: The application does not exist"),new Error(s.ret?.msg||E.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function lR(n,e){if(!n||n.length===0)return!1;let t=n[0];return await Wi(t.newUrl,e,t.sha256),!0}function dR(n,e,t,r,i){return uR(n,e),r=r||Fe.TARGET_FRIENDLY_NAME,i=i||"",pR(e,t,r,i),!0}function uR(n,e){if(e.lastIndexOf(Fe.CERT_BEGIN_HEADER)<0)throw new Error(E.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(Fe.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function pR(n,e,t,r){let i=n.matchAll(Fe.CERTIFICATE_PATTERN_GLOBAL),o=[],s=new Date;for(let c of i)try{let l=c[0],d=fR(l),g=new Date(d.validFrom),v=new Date(d.validTo);if(s<g||s>v){let D=`Certificate is not valid, Valid from ${g} to ${v}`;throw console.warn(`checkCertificateInValidityPeriod: ${D}`),new Error(E.CERTIFICATE_HAS_EXPIRED)}o.push(d)}catch(l){throw console.warn(`checkCertificateInValidityPeriod\uFF1A ${l.message}`),new Error(E.CERTIFICATE_HAS_EXPIRED,{cause:l})}if(!o||o.length===0)throw new Error(E.CERTIFICATE_HAS_EXPIRED);if(!hR(e,t,r,o))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function fR(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new Gl(t);let r=hg.from(t,"base64");return new Gl(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function mR(n){if(n.cert){let e=Xn.pki.publicKeyToPem(n.cert.publicKey);return eR(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=Xn.asn1.toDer(n.asn1).getBytes(),t=hg.from(e,"binary");return new Gl(t).publicKey.export({type:"spki",format:"der"})}catch(e){return Ht(`Failed to parse cert from asn1: ${e}`),null}return null}function hR(n,e,t,r){try{let i=tR(n),o=Xn.asn1.fromDer(Xn.util.createBuffer(i)),c=Xn.pkcs12.pkcs12FromAsn1(o,t).getBags({bagType:Xn.pki.oids.certBag})[Xn.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let g=mR(l);if(!g)continue;if(r.some(D=>{let He=D.publicKey.export({type:"spki",format:"der"});return g.equals(He)}))return!0}return!1}catch(i){let o=i instanceof Error?i.message:String(i);return Ht(`Failed to process P12 file: ${n}, error: ${o}`),!1}}function Jl(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var vg="https://developer.huawei.com",gR={"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"},yR="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function vR(n){let e=gR[n];return e?`${vg}${e}`:void 0}function wR(){return`${vg}${yR}`}var bR={"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 yg(n,e){return(bR[n]??n).replace(/\{(\d+)\}/g,(r,i)=>String(e[Number(i)]??""))}function SR(n){return Array.from(n).join(", ")}function wg(n,e){if(n.size===0)return;let t=En.getAclPermissionInfos(e),r=new Set;for(let g of t)n.has(g.permissionName)&&r.add(g);for(let g of r){let v=vR(g.permissionName);v!=null&&(g.permissionHelpUrlKey=v)}let i=new Set;for(let g of r)i.add(g.permissionDisplayName);let o=new Set;for(let g of r)if(g.permissionHelpUrlKey!=null){let v=g.permissionInsteadName??g.permissionDisplayName;o.add(`${v} (${g.permissionHelpUrlKey})`)}let s=wR(),a=yg("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=o.size>0?Array.from(o).join(", ")+".":"",d=yg("acl.permissions.warn",[SR(i),l,c]);console.log(d)}var la=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=Y.discover(process.cwd()),{passed:!0,message:""}}catch(t){return p(`[EnvCheck] Project.discover() failed: ${t.message}`),e(se.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(r){return p(`[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 p(`[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:se.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import ER from"fs";import bg from"path";var da=class{constructor(e){this.toolProvider=e}toolProvider;checkJava(e){try{return this.toolProvider.assertJava(),{passed:!0,message:""}}catch(t){return p(`[EnvCheck] Java check failed: ${t.message}`),e(`${t.message}`)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=bg.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");if(!ER.existsSync(r)){let i=bg.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 ua=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await De.getUserInfo()}catch(e){return p(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await De.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(se.LOGIN_REQUIRED)}catch(t){return p(`[EnvCheck] Login check failed: ${t.message}`),e(se.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(se.TEAM_INFO_FAILED);try{if((await nn()).teamList.length>0)return{passed:!0,message:""}}catch(r){return p(`[EnvCheck] Team API error: ${r.message}`),e(se.TEAM_INFO_FAILED)}return p("[EnvCheck] No teams found for current user"),e(se.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(se.REALNAME_REQUIRED):t.isRealName!==!0?(p("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(se.REALNAME_REQUIRED)):{passed:!0,message:""}:e(se.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let i=await nn();if(r=e??(i.teamList.length>0?i.teamList[0].id:t.userId)??"",!i.teamList.some(s=>s.id===r)){let s=`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`;return p(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(i){return p(`[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(se.REGION_CHINA_ONLY):{passed:!0,message:""}:(p("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(se.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function PR(n){try{let{teamList:e}=await nn();if(e.length>0)return e[0].id}catch(e){p(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function CR(n){let e=await De.getUserInfo(),t=await De.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await PR(e.userId);if(!r)throw new Error("No team found");let i={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await ca(i)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var pa=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t){try{let r=await CR(t);if(r.length>0)return p(`[EnvCheck] Scenario 4 Device check: ${r.length} device(s) found in AGC cloud, skipping local device check`),{passed:!0,message:""};p("[EnvCheck] Scenario 4 Device check: no cloud devices found, falling back to local hdc");let o=await oe.from(this.toolProvider).listDevices();return o.length===0?(p("[EnvCheck] Scenario 4 Device check: no local devices found"),e(se.DEVICE_MISSING)):o.some(a=>yt(a.serial))?{passed:!0,message:""}:(p("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(se.DEVICE_MISSING))}catch(r){return p(`[EnvCheck] Scenario 4 Device check failed: ${r.message}`),e(se.DEVICE_DETECT_FAILED)}}};var fa=class{projectChecker=new la;toolchainChecker=null;authChecker=new ua;deviceChecker=null;constructor(){}async preflight(e){let t=r=>this.blockingFail(r);return!(!await this.runAuthChain(e,t)||!await this.initToolchain()||!await this.runDeviceCheck(e,t)||!await this.runProjectChecks(e,t)||!await this.runAuxChecks(e))}async runAuthChain(e,t){let 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 A.new();return this.toolchainChecker=new da(e),this.deviceChecker=new pa(e),!0}catch(e){throw p(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(se.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 p(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};var Sg=5*1024*1024;function AR(n){try{let e=Kl.statSync(n);if(e.size>Sg)throw new Error(`Profile file too large: ${e.size} bytes (max ${Sg} bytes): ${n}`);let t=Kl.readFileSync(n,"utf-8");return Pg.parse(t)}catch(e){if(e.code==="ENOENT")return{app:{signingConfigs:[],products:[]}};throw new Error(`Failed to read profile: ${n}`,{cause:e})}}function DR(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function RR(n){if(n.keyPwd===n.storePassword){let r=await Sn.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await Sn.encryptedPassword(n.keyPwd,n.p12FilePath),t=await Sn.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function TR(n,e,t){let r=Eg.join(n,"build-profile.json5"),i=AR(r);DR(i);let o=t??"default",{keyPassword:s,storePassword:a}=await RR(e),c={name:o,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:ft.signAlg,storeFile:e.p12FilePath,storePassword:a}},l=i.app?.signingConfigs?.findIndex(g=>g.name===o);l!==void 0&&l>=0?i.app.signingConfigs[l]=c:i.app.signingConfigs.push(c);let d=i.app?.products?.findIndex(g=>g.name===o);d!==void 0&&d>=0?i.app.products[d].signingConfig=o:i.app.products.push({name:o,signingConfig:o}),Kl.writeFileSync(r,Pg.stringify(i,null,2),"utf-8")}async function xR(n){let e=await De.getUserInfo(),t=await De.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??""}}async function LR(n){let e=n.product||"default";await new fa().preflight({productName:e,teamId:n.teamId}),console.log("Executing signature generate command");let r=await xR(n),i=await A.new(),{shouldRegenerate:o}=await qi.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product},i);if(!o){console.log(Yl("Signature generation completed successfully."));return}await NR(n,r,i),console.log(Yl("Signature generation completed successfully."))}async function NR(n,e,t){let r=await _l(e,n.product),i=OR(n,e,r,t);i.allDeviceIds=await lg(e,t.hdcPath),await gg(e,i);let o=Y.discover(process.cwd()).rootDir;await TR(o,r,n.product??"default"),console.log(Yl(`Signing config written to ${Eg.join(o,"build-profile.json5")}`))}function OR(n,e,t,r){let i=process.cwd(),o=Y.discover(i),s=sa(o,r);return wg(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}}var Cg=new kR("signature").description("Generate application signature.");Cg.command("generate").description("Automatically generate signing materials and write them to the project configuration.").option("--force","Force overwrite existing local signing materials.").option("--team-id <team-id>","Specify the team ID to use.").option("--product <product>","Specify the product. The default value is default.").action(async n=>{let e={event:b.CommandExecuted,args:["signature","generate",...n.force?["--force"]:[],...n.teamId?["--team-id"]:[],...n.product?["--product"]:[]]},t=Date.now(),r=!0,i=null;try{await LR(n)}catch(o){r=!1,i=B(o),console.error(IR(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(e,o)}});var kg=Cg;if(!Bt())try{I.init(ma.join(be(),"TraceLogData")),I.startScheduler()}catch(n){h.error(`[telemetry] init failed: ${n instanceof Error?n.message:String(n)}`)}(async()=>{if(!Bt())try{let n=await A.new();I.setSourceType(n.sourceType);let e=await A.getCltVersion();e&&I.setCltVersion(e);let t=await A.getStudioVersion();t&&I.setStudioVersion(t)}catch(n){h.error(`[telemetry] toolchain info failed: ${n instanceof Error?n.message:String(n)}`)}})();ae.name("devecocli").description(`HarmonyOS application development command line tool
1359
+ `),console.log(ve("[compat:check] === end stdout ===")));let i=new oe("errorCode",`Compatibility scan failed: ${o.message}`+(o.stderr?`
1360
+ ${o.stderr}`:""));throw o.stdout&&(i.stdout=o.stdout),i}}function VD(n,e){if(!DD.includes(e.format))throw new ED(`--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 oe("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 oe("errorCode","--source-version is required.");if(!e.targetVersion)throw new oe("errorCode","--target-version is required.");if(!e.outputPath&&e.format==="csv")throw new oe("errorCode","--format csv requires --output-path. For console output, use --format json or --format default (or omit the flag).")}function qD(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 oe("errorCode",`${t.join(" and ")} ${r} not in the available SDK version list.
1361
+ Run \`devecocli compat versions\` to see all available versions.`)}if(n.sourceVersion&&n.targetVersion){let r=e.indexOf(n.sourceVersion),o=e.indexOf(n.targetVersion);if(r>=o)throw new oe("errorCode",`--target-version "${n.targetVersion}" must be later than --source-version "${n.sourceVersion}". Run \`devecocli compat versions\` to see the available order.`)}}function GD(n,e,t,r,o){o==="none"&&(t==="json"?HD(n,r):$D(n,r)),FD(n,e)}function zD(n,e){let t=J.dirname(n),r=J.basename(n),o=e.slice(1).map(i=>i.startsWith("--")?i:`"${i}"`).join(" ");u(ve(`[compat:check] command: cd "${t}" && node "${r}" ${o}`))}function JD(n){try{kD(n),u(ve(`[compat:check] cleaned up tmp report: "${n}"`))}catch(e){u(ve(`[compat:check] failed to clean up tmp report: ${e.message}`))}}var YD=[".csv",".json"];function KD(n){return YD.includes(n.toLowerCase())}function XD(n,e){if(!n)return{kind:"none"};let t=J.extname(n).toLowerCase();if(!KD(t))return{kind:"dir",dirPath:J.resolve(n)};if(t===".csv"&&!(e==="default"||e==="csv")||t===".json"&&e!=="json")throw new oe("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:J.resolve(n),ext:t}}function ZD(n){if(n.kind==="file"){if(ma(n.filePath))throw new oe("errorCode",`Target file "${n.filePath}" already exists. Remove it first, or choose a different --output-path.`);let e=J.dirname(n.filePath);if(!ma(e))throw new oe("errorCode",`Target directory "${e}" does not exist. Create it first, or choose a different --output-path.`)}else if(n.kind==="dir"&&!ma(n.dirPath))throw new oe("errorCode",`Target directory "${n.dirPath}" does not exist. Create it first, or choose a different --output-path.`)}function Ng(n){return JSON.stringify({records:n,count:n.length},null,2)+`
1362
+ `}function QD(n,e,t,r){r===".csv"?Dg(n,t):Rg(t,Ng(e),"utf8"),u(ve(`[compat:check] saved report: "${t}"`))}function eR(n,e,t,r){if(r==="json"){let i=J.basename(n,".csv"),s=J.join(t,`${i}.json`);return Rg(s,Ng(e),"utf8"),u(ve(`[compat:check] saved report: "${s}"`)),s}let o=J.join(t,J.basename(n));return Dg(n,o),u(ve(`[compat:check] saved report: "${o}"`)),o}async function tR(n,e){let t=new ze(n,process.cwd(),!0),r=e.modules&&e.modules.length>0?e.modules[0]:void 0;try{await t.compileNative("default",r)}catch(o){throw new oe("errorCode",`hvigorw compileNative failed (module=${r??"<project>"}): `+o.message,{cause:o})}}async function rR(n,e){VD(n,e);let t=W.discover(process.cwd());e.modules&&e.modules.length>0&&TD(t,e.modules),n.length>0&&xD(n);let r=await A.new(),{apiChangeDir:o,scriptPath:i}=r.getApiscanPaths();u(ve(`[compat:check] script: "${i}"`));let s=xg(o);qD(e,s),e.outputPath&&u(ve(`[compat:check] outputPath: "${e.outputPath}"`));let a=XD(e.outputPath,e.format);return u(ve(`[compat:check] outputTarget: ${a.kind}`)),ZD(a),{project:t,scriptPath:i,target:a,toolProvider:r}}function nR(n,e,t,r){if(t.kind==="file")return QD(n,e,t.filePath,t.ext),t.filePath;if(t.kind==="dir")return eR(n,e,t.dirPath,r);if(t.kind==="none")return null;throw new oe("errorCode",`Unexpected output target kind: ${t.kind}`)}async function oR(n,e,t,r,o){let i=AD({text:"Running compatibility check...",color:"cyan"}).start();try{await tR(n.toolProvider,t);let s=BD(n.scriptPath,e,n.project,t);zD(n.scriptPath,s);let a=await WD(n.toolProvider,s),c=jD(a,td.tmpdir());if(!c)throw new oe("errorCode","Scanner output format unexpected: missing report path.");u(ve(`[compat:check] tmp csv: "${c}"`));let l=_D(c),d=nR(c,l,n.target,t.format);JD(c),i.stop(),GD(l,d,t.format,t.limit,n.target.kind),await Jn(r,!0,null,o)}catch(s){i.fail("Compatibility check failed");let a=rd(s);throw await Jn(r,!1,a,o),s}}async function Mg(n,e){let t=Date.now(),r=["check","compat"];try{let o=await rR(n,e);await oR(o,n,e,t,r)}catch(o){let i=rd(o);throw await Jn(t,!1,i,r),o}}function sR(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new iR(`--limit must be a positive integer (got "${n}")`);return e}var nd=new Og("compat").description("Compatibility checking utilities.");nd.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)",sR,100).action(async(n,e)=>{await Mg(n,e)});nd.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 Lg(t)});var aR=new Og("check").description("Run DevEco project checks").addCommand(nd).addCommand(Yl()).addCommand(ed()),_g=aR;import{Command as YT}from"commander";import{green as Id,red as KT}from"colorette";import Ad from"fs";import by from"path";import Sy from"json5";import{readFileSync as _R}from"fs";import{join as cR}from"path";var ce={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"},Ve={CERT_NAME_PREFIX:"auto_debug_",CERT_TYPE_DEBUG:"1",TEAM_ID_INVALID_CHARS:/[\\/.:]/g,CERT_PATTERN:/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/,TARGET_FRIENDLY_NAME:"debugKey",CERTIFICATE_PATTERN_GLOBAL:/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g,BUNDLE_NAME_REGEX:/^[a-zA-Z][a-zA-Z0-9._-]*$/,CERT_BEGIN_HEADER:"-----BEGIN CERTIFICATE-----",CERT_SAVE_DIR:cR(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},we={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"},vt={FORBIDDEN:403,UNAUTHORIZED:401},E={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."},ue={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 fa(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function od(n){let e=n.replace(Ve.TEAM_ID_INVALID_CHARS,"");return`${Ve.CERT_NAME_PREFIX}${e}.cer`}function Yn(n,e,t){if(n===vt.FORBIDDEN)return e===we.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN);if(n===vt.UNAUTHORIZED)return new Error(E.ERR_UNAUTHORIZED);if(t.includes(we.USER_NOT_HARMONY_CODE))return new Error(E.ERR_USER_NOT_HARMONY);if(t.includes(we.CERT_LIMIT_CODE))return new Error(E.ERR_CERT_LIMIT_REACHED);let r=lR(t);return new Error(r??E.ERR_DOWNLOAD_CER)}function lR(n){let e=jg(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?jg(t):t;if(r&&typeof r=="object"){let o=r.msg;if(typeof o=="string"&&o.trim()!=="")return o}return null}function jg(n){try{return JSON.parse(n)}catch{return null}}function id(n){return JSON.parse(n)}async function Fg(n){let e=`${ce.BASE_URL}${ce.CERT_LIST_PATH}`,t=await L.postAllowFailure(e,{headers:fa(n)});if(t.statusCode!==200)throw Yn(t.statusCode,t.statusText,t.data);return id(t.data)?.certList??[]}async function ha(n,e){return(await Fg(n)).find(r=>r.certName===e)??null}async function sd(n,e){let t=`${ce.BASE_URL}${ce.CERT_DELETE_PATH}`,r=await L.deleteAllowFailure(t,{headers:fa(n),params:{certIds:[e]}});if(r.statusCode!==200)throw Yn(r.statusCode,r.statusText,r.data);return id(r.data)?.ret?.code===0}async function ad(n,e,t){let r=`${ce.BASE_URL}${ce.CERT_ADD_PATH}`,o={csr:e,certName:t,certType:Ve.CERT_TYPE_DEBUG},i=await L.postAllowFailure(r,{headers:fa(n),params:o});if(i.statusCode!==200)throw Yn(i.statusCode,i.statusText,i.data);if(!i.data.includes(we.SUCCESS_MARKER))throw Yn(void 0,i.statusText,i.data)}async function cd(n,e){let t=`${ce.BASE_URL}${ce.CERT_DOWNLOAD_URL_PATH}`,r=await L.postAllowFailure(t,{headers:fa(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw Yn(r.statusCode,r.statusText,r.data);return id(r.data)?.urlsInfo?.[0]??null}import{mkdirSync as dR,writeFileSync as uR,existsSync as pR}from"fs";import{dirname as mR}from"path";import{createHash as fR}from"crypto";function hR(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 ii(n,e,t){hR(n);let{statusCode:r,statusText:o,buffer:i}=await L.getBinaryAllowFailure(n,{timeout:Ve.DOWNLOAD_CONNECT_TIMEOUT_MS});if(r!==200)throw r===vt.FORBIDDEN&&o===we.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_DOWNLOAD_CER);if(t){let a=fR("sha256").update(i).digest("hex");if(a!==t.toLowerCase())throw new Error(`SHA-256 mismatch for ${e}: expected ${t.toLowerCase()}, got ${a}`)}let s=mR(e);pR(s)||dR(s,{recursive:!0}),uR(e,i)}import NR from"fs/promises";import{readFileSync as MR}from"fs";import ga from"path";import Ug from"crypto";import gR from"os";import si from"fs/promises";var Bg={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},$g=["ECC","RSA"],Hg=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],yR={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},vR=8,ld=64,wR=/[\\/:*?"<>|=-]/g,wt={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function bR(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>ld)throw new Error(`The length of keyAlias cannot exceed ${ld}`);if(!$g.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${$g.join(" / ")}`);let e=yR[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function SR(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(!Hg.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${Hg.join(" / ")}`)}function ER(n){return Ug.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function PR(n){let e=n?.trim()??"";return e&&e.replace(wR,"_").replace(/\.+/g,"_").slice(0,ld)||wt.productName}async function Wg(){let n=await A.new(),e=n.javaPath;if(!e)throw new Error("Java runtime not found. DevEco Studio JBR is required to run hap-sign-tool.jar.");let t=n.sdkPath;f.info(`\u8BFB\u53D6SDK\u6839\u76EE\u5F55\uFF1A${t}`);let r=ga.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");try{await si.access(r)}catch(o){throw new Error(`Sign tool jar not found: ${r}`,{cause:o})}return{javaPath:e,jarPath:r}}async function CR(n){let{javaPath:e,jarPath:t}=await Wg(),r=["-jar",t,Bg.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 o=r.map((i,s)=>s>0&&["-keyPwd","-keystorePwd"].includes(r[s-1])?"******":i);return f.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),[e,...r]}async function kR(n){let{javaPath:e,jarPath:t}=await Wg(),r=["-jar",t,Bg.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 o=r.map((i,s)=>s>0&&["-keyPwd","-keystorePwd"].includes(r[s-1])?"******":i);return f.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),[e,...r]}async function IR(n){f.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),bR(n);let e=await CR(n),t=await uo(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 AR(n){f.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),SR(n);let e=await kR(n),t=await uo(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 DR(n=vR){return Ug.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function RR(){let n=gR.homedir();try{await si.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=ga.join(n,".ohos","config");try{await si.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 Ie(n,e,t){let r=PR(n),o=ga.basename(e),i=ER(e),s=`${r}_${o}_${i}=.${t}`,a=await RR();return ga.join(a,s)}function TR(n){let e;try{e=W.discover(n).rootDir}catch(t){throw new Error(`Current directory ${n} is not a valid project root`,{cause:t})}return e}async function xR(n){try{await si.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function LR(n){try{await si.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function dd(n,e,t){let r=process.cwd(),o=TR(r);await xR(o),f.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${o}`);let i=DR(),s=await Ie(n??"",o,"p12"),a=await Ie(n??"",o,"csr");return console.log("Start generating p12"),await IR({keyAlias:e?.keyAlias??wt.keyAlias,keyPwd:i,keyAlg:e?.keyAlg??wt.keyAlg,keySize:e?.keySize??wt.keySize,keystoreFile:s,keystorePwd:i}),await LR(s),console.log("Start generating csr"),await AR({subject:t?.subject??wt.csrSubject,outFile:a,keyAlias:t?.keyAlias??wt.keyAlias,keyPwd:i,signAlg:t?.signAlg??wt.signAlg,keystoreFile:s,keystorePwd:i}),{p12FilePath:s,csrFilePath:a,keyPwd:i,keyAlias:e?.keyAlias??wt.keyAlias}}var OR=["p12","cer","csr","p7b"];async function ud(n,e){for(let t of OR){let r=await Ie(n,e,t);await NR.rm(r,{force:!0})}}function pd(n){let e;try{e=MR(n,"utf-8")}catch{throw new Error(E.ERR_CERT_INVALIDATE)}if(!Ve.CERT_PATTERN.test(e))throw new Error(E.ERR_CERT_INVALIDATE)}async function Vg(n,e){return{certPath:await Ie(n,e,"cer"),csrPath:await Ie(n,e,"csr"),p12Path:await Ie(n,e,"p12"),profilePath:await Ie(n,e,"p7b")}}async function md(n,e){let t=e??"",r=W.discover(process.cwd()).rootDir;await ud(t,r);let o=od(n.teamId),i=await ha(n,o);if(i&&!await sd(n,i.id))throw new Error(E.ERR_DOWNLOAD_CER);let s=await dd(e),a;try{a=_R(s.csrFilePath,"utf-8")}catch{throw new Error(E.ERR_READ_CSR)}console.log("Start generating certificate"),await ad(n,a,o);let c=await ha(n,o);if(!c)throw new Error(E.ERR_DOWNLOAD_CER);let l=await cd(n,c.certObjectId);if(!l)throw new Error(E.ERR_DOWNLOAD_CER);let d=await Ie(t,r,"cer");await ii(l.newUrl,d,l.sha256),pd(d);let g=await Ie(t,r,"p7b");return{p12FilePath:s.p12FilePath,csrFilePath:s.csrFilePath,cerFilePath:d,profileFilePath:g,certId:c.id,keyAlias:s.keyAlias,keyPwd:s.keyPwd,storePassword:s.keyPwd}}import Ia from"crypto";import Tr from"fs";import*as iy from"path";import oT from"json5";import{execa as ry}from"execa";import ny from"node-forge";import{createCipheriv as jR,createDecipheriv as FR,pbkdf2Sync as $R,randomBytes as yd}from"crypto";import{promises as nn}from"fs";import{dirname as HR,join as bt}from"path";var ya=3,ai=16,UR=1e4,qg="material",BR=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Yg="aes-128-gcm",rn=12,va=16,Ar=4;function fd(n){return new Uint8Array(yd(n))}function WR(n){return yd(n).toString("hex")}function VR(...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 o=0;for(let i of n)o^=i[r];t[r]=o}return t}function Gg(n,e,t=UR,r=ai){let o=[...n,BR],i=VR(...o),s=Buffer.from(i).toString("utf8"),a=Buffer.from(s,"utf8"),c=$R(a,e,t,r,"sha256");return new Uint8Array(c)}function zg(n,e){let t=yd(rn),r=jR(Yg,n,t),o=Buffer.concat([r.update(e),r.final()]),i=r.getAuthTag(),s=Buffer.concat([o,i]),a=s.length,c=Buffer.alloc(Ar+rn+s.length);return c.writeUInt32BE(a,0),t.copy(c,Ar),s.copy(c,Ar+rn),c}function Jg(n,e){if(e.length<Ar+rn+va)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(Ar,Ar+rn),o=e.subarray(Ar+rn,Ar+rn+t);if(o.length<va)throw new Error("Ciphertext too short for auth tag");let i=o.subarray(0,o.length-va),s=o.subarray(o.length-va),a=FR(Yg,n,r);return a.setAuthTag(s),Buffer.concat([a.update(i),a.final()])}async function qR(n){try{await nn.rm(n,{recursive:!0,force:!0})}catch{}}async function hd(n){let e=await nn.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 nn.readFile(bt(n,t[0]))}async function gd(n,e){let t=WR(ai),r=bt(n,t);return await nn.writeFile(r,e,{mode:384}),t}var Dr=class{static keyChain=Promise.resolve();static async generateMaterial(e){let t=bt(e,qg);await qR(t);let r=bt(t,"ac"),o=bt(t,"ce");await nn.mkdir(r,{recursive:!0,mode:448}),await nn.mkdir(o,{recursive:!0,mode:448});for(let d=0;d<ya;d++)await nn.mkdir(bt(t,"fd",String(d)),{recursive:!0,mode:448});let i=fd(ai),s=[];for(let d=0;d<ya;d++)s.push(fd(ai));let a=fd(ai),c=Gg(s,i),l=zg(c,a);await gd(r,i),await gd(o,l);for(let d=0;d<ya;d++){let g=bt(t,"fd",String(d));await gd(g,s[d])}return a}static async readMaterial(e){let t=bt(e,qg),r=bt(t,"ac"),o=new Uint8Array(await hd(r)),i=[];for(let d=0;d<ya;d++){let g=bt(t,"fd",String(d)),v=await hd(g);i.push(new Uint8Array(v))}let s=bt(t,"ce"),a=await hd(s),c=Gg(i,o),l=Jg(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t,r=this.keyChain;this.keyChain=new Promise(o=>{t=o}),await r;try{let o=HR(e);try{return await this.readMaterial(o)}catch{return await this.generateMaterial(o)}}finally{t()}}static async encryptedPassword(e,t){let r=await this.getStoreKey(t),o=Buffer.from(e,"utf8");return zg(r,o).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),o=Buffer.from(e,"hex");return Jg(r,o).toString("utf8")}};import ey from"fs";import Ca from"path";import XR from"json5";import*as wa from"fs";import*as Kg from"path";function ba(n){let e=Kg.resolve(n);if(!wa.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=wa.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 o=r?.data?.apiVersion;if(o==null||o==="")throw new Error(`Missing data.apiVersion in SDK info file: ${e}`);let i=Number(o);if(!Number.isFinite(i))throw new Error(`Invalid data.apiVersion in SDK info file: ${String(o)}`);return i}import*as Xn from"fs";import*as qe from"path";import{debuglog as Kn}from"util";var Xg={"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 GR(n){return Object.prototype.hasOwnProperty.call(Xg,n)}function Sa(n){if(GR(n))return Xg[n]}var Zg={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as zR}from"url";var Pa=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 Ea(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Qg(n){return n==null||n.length===0}function JR(n){return!Qg(n)}function vd(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function YR(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 KR(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 Rr=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=qe.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=qe.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,o=this.getOrCreateSet(this.aclPermissionNamesMap,r),i=this.getOrCreateSet(this.aclPermissionInfoMap,r);o.clear(),i.clear();let s=qe.join(t.sdkPath,"default","sdk-pkg.json"),a=ba(s);this.MIN_API_TO_FIND_ACL_IN_SDK-a>0?this.initAclPermissionFromBuiltInConfig(o,i):this.initAclPermissionFromSDK(t,o,i)}static getAclPermissionInfos(e){return this.aclPermissionInfoMap.get(e.rootDir)??new Set}static getAclPermissionNames(e){return this.aclPermissionNamesMap.get(e.rootDir)??new Set}static addAclWhiteList(e){for(let t of e)this.aclWhiteList.add(t)}static addAclBlackList(e){for(let t of e)this.aclBlackList.add(t)}static getOrCreateSet(e,t){let r=e.get(t);return r||(r=new Set,e.set(t,r)),r}static readBuiltInConfigText(){if(this.builtInConfigTextLoader)return this.builtInConfigTextLoader();let e=qe.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(Xn.existsSync(e))return Xn.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=zR(e);if(t.includes("dist")){let s=qe.dirname(t),a=qe.dirname(s);return qe.join(a,"src","resources")}let r=qe.dirname(t),o=qe.dirname(r),i=qe.dirname(o);return qe.join(i,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{Kn("read builtin acl permission failed.");return}if(r!==void 0)try{let o=JSON.parse(r),s=(Array.isArray(o)?o:Ea(o)?Object.values(o):[]).filter(Ea).map(a=>new Pa(a));s.forEach(a=>{let c=a.permissionInsteadName;JR(c)&&(a.permissionInsteadName=Sa(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(o){Kn(`failed to parse aclPermissionsInfo.json: ${o}`)}}static initAclPermissionFromSDK(e,t,r){let o=this.parsePermissionDefinitionFile(e);o&&o.forEach(i=>{if(!Ea(i))return;let s=i,a=vd(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(Qg(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||vd(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||vd(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:YR(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let o=new Pa;o.permissionName=t;let i=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;o.permissionDisplayName=i;let s=KR(r,this.ACL_SINCE_KEY);o.minSupportApiLevel=String(s),this.handleInsteadName(o,i),e.add(o)}static parsePermissionDefinitionFile(e){let t=qe.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!Xn.existsSync(t))return;let r;try{r=Xn.readFileSync(t,"utf-8")}catch(s){Kn(`failed to load permissionDefinitions.json: ${s}`);return}let o;try{let s=JSON.parse(r);if(!Ea(s)){Kn("json object is null");return}o=s}catch(s){Kn(`failed to parse permissionDefinitions.json: ${s}`);return}let i=o[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(i)){Kn("definePermissions is not an array");return}return i}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=Sa(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=Sa(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function ka(n,e){let t=new Set,r=new Set;Rr.handleSpecificAclPermissions(),Rr.initAclPermission(n,e);for(let o of n.profile.modules){let i=ty(o,n,e,r,Ca.join("src","main"));for(let a of i)t.add(a);let s=ty(o,n,e,r,Ca.join("src","ohosTest"));for(let a of s)t.add(a)}return ZR(r),t}function ZR(n){if(n.size>0)throw new Error(Zg.DUPLICATE_PERMISSION)}function ty(n,e,t,r,o){let i=eT(e.rootDir,n,o);if(i==null)return new Set;let s=[];for(let v of i){if(typeof v!="object"||v===null)continue;let P=QR(v,"name");P&&s.push(P)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=Ca.join(t.sdkPath,"default","sdk-pkg.json"),l=ba(c),d=Rr.getAclPermissionInfos(e),g=new Set(Array.from(d).filter(v=>{let P=Number(v.minSupportApiLevel);return Number.isFinite(P)&&P<=l}).map(v=>v.permissionName));for(let v of Array.from(a))g.has(v)||a.delete(v);return a}function QR(n,e){let t=n[e];return typeof t=="string"?t:""}function eT(n,e,t){let r=Ca.join(n,e.srcPath,t,"module.json5"),o=tT(r);if(o==null)return null;let i=rT(o,"module");return i==null?null:nT(i,"requestPermissions")}function tT(n){try{if(!ey.existsSync(n))return null;let e=ey.readFileSync(n,"utf-8");return XR.parse(e)}catch{return null}}function rT(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 nT(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var bd=class{verifyStorePassword(e,t){try{let r=Tr.readFileSync(e),o=ny.asn1.fromDer(r.toString("binary"));return ny.pkcs12.pkcs12FromAsn1(o,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=Tr.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(o=>this.formatFp(new Ia.X509Certificate(o).fingerprint256));try{return[this.formatFp(new Ia.X509Certificate(Tr.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let o=Tr.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let i of o)try{let s=new Ia.X509Certificate(i);if(this.formatFp(s.fingerprint256)===t){let a=new Date(s.validTo);return isNaN(a.getTime())?null:a}}catch{}return null}formatFp(e){let t=e.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}};function iT(n){let e=Tr.readFileSync(n,"utf-8"),t=sT(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let o=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:wd(o["bundle-name"]),expiryDate:aT(r?.validity?.["not-after"]),cerFingerprintInProfile:cT(wd(o["development-certificate"])),deviceUdidsInProfile:lT(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:dT(r?.acls?.["allowed-acls"]),teamIdInProfile:wd(o["developer-id"])}}function sT(n){let e=n.indexOf("{");if(e<0)return null;let t=0,r=-1,o=!1,i=!1;for(let s=e;s<n.length;s++){let a=n[s];if(o){i?i=!1:a==="\\"?i=!0:a==='"'&&(o=!1);continue}if(a==='"')o=!0;else if(a==="{")t++;else if(a==="}"&&(t--,t===0)){r=s;break}}return r<0?null:n.slice(e,r+1)}function aT(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function cT(n){if(!n)return null;try{let t=new Ia.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function lT(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 dT(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 wd(n){return typeof n=="string"?n:null}var ci=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.#o(r)??n.#i(r)??n.#s(r)??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,o=e.teamId,i=e.productName??"default",s=W.discover(process.cwd()),a=s.rootDir,[c,l]=await Promise.all([uT(i,a),mT(t.hdcPath)]),d=null;if(oy(c).allExist)try{d=iT(c.profileFile)}catch{}return{force:r,teamId:o,productName:i,projectPath:a,materialPaths:c,bundleName:s.getBundleName(i),deviceUdids:l,storePassword:await pT(a,i,c.storeFile),localAclPermissions:[...ka(s,t)].sort(),hapSignTool:new bd,profileInfo:d}}static#t(e){return e.force?(u("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:Ze({force:!0})}):null}static#r(e){let t=oy(e.materialPaths);return t.allExist?null:(u(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:Ze({allFilesExist:!1,missingFiles:t.missing})})}static#n(e){return(e.profileInfo?.rawContent??"").trim().length>0?null:(u("[reGenerateSign] profile content is empty"),{shouldRegenerate:!0,reason:"Profile file content is empty",checkDetails:Ze({allFilesExist:!0,profileContentNotEmpty:!1})})}static#o(e){let t=e.profileInfo?.expiryDate;return!t||t>=new Date?null:(u(`[reGenerateSign] profile expired at ${t.toISOString()}`),{shouldRegenerate:!0,reason:`Profile expired at ${t.toISOString()}`,checkDetails:Ze({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#i(e){let t=e.profileInfo?.bundleNameInProfile;return t&&t===e.bundleName?null:(u(`[reGenerateSign] bundleName mismatch \u2014 current=${e.bundleName}, profile=${t}`),{shouldRegenerate:!0,reason:`bundleName mismatch: current=${e.bundleName}, in profile=${t}`,checkDetails:Ze({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!1})})}static#s(e){let t=e.profileInfo?.teamIdInProfile;return t&&t===e.teamId?null:(u(`[reGenerateSign] teamId mismatch \u2014 current=${e.teamId}, profile=${t}`),{shouldRegenerate:!0,reason:`teamId mismatch: current=${e.teamId}, in profile=${t}`,checkDetails:Ze({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=hT(e.profileInfo?.deviceUdidsInProfile??[],e.deviceUdids);return t.allPresent?null:(u(`[reGenerateSign] missing device UDIDs: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Device UDID(s) not in profile: ${t.missing.join(", ")}`,checkDetails:Ze({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return gT(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(u("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:Ze({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:(u("[reGenerateSign] certificate mismatch"),{shouldRegenerate:!0,reason:"Certificate mismatch between profile and local .cer file",checkDetails:Ze({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:(u(`[reGenerateSign] local certificate expired at ${r.toISOString()}`),{shouldRegenerate:!0,reason:`Local certificate expired at ${r.toISOString()}`,checkDetails:Ze({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:(u("[reGenerateSign] keystore password verification failed"),{shouldRegenerate:!0,reason:"Keystore password verification failed (storeFile may be corrupted or password changed)",checkDetails:Ze({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})}):(u("[reGenerateSign] no stored keystore password"),{shouldRegenerate:!0,reason:"No stored keystore password available for verification",checkDetails:Ze({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})})}static#p(){return u("[reGenerateSign] all checks passed \u2014 skip regeneration"),{shouldRegenerate:!1,reason:"",checkDetails:Ze({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function uT(n,e){let[t,r,o,i]=await Promise.all([Ie(n,e,"p12"),Ie(n,e,"csr"),Ie(n,e,"cer"),Ie(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:o,profileFile:i}}async function pT(n,e,t){let r=iy.join(n,"build-profile.json5");if(!Tr.existsSync(r))return;let o;try{o=oT.parse(Tr.readFileSync(r,"utf-8"))}catch{return}let a=(o?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await Dr.decryptPassword(a,t)}catch{return}}async function mT(n){u(`Executing: ${n} list targets`);let{stdout:e}=await ry(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let o of e.split(`
1363
+ `)){let i=o.trim();if(!i||i.startsWith("[Empty]"))continue;let s=i.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let r=[];for(let o of t)try{u(`Executing: ${n} -t ${o} shell bm get -u`);let{stdout:i}=await ry(n,["-t",o,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),s=fT(i);s&&r.push(s)}catch{u(`[reGenerateSign] Failed to get UDID for ${o}, skipping`)}return r}function fT(n){let e=n.trim();if(!e)return null;let t=e.split(`
1364
+ `);for(let o=0;o<t.length-1;o++)if(t[o].includes("udid of current device is")){let s=t[o+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(s)return s[0].toUpperCase()}let r=e.match(/[A-Fa-f0-9]{64}/);return r?r[0].toUpperCase():null}function oy(n){let e=[n.storeFile,n.csrFile,n.cerFile,n.profileFile],t=[];for(let r of e)Tr.existsSync(r)||t.push(r);return{allExist:t.length===0,missing:t}}function hT(n,e){let t=[];for(let r of e)n.includes(r)||t.push(r);return{allPresent:t.length===0,missing:t}}function gT(n,e){let t=[...n].sort(),r=[...e].sort();return t.length!==r.length?!1:t.every((o,i)=>o===r[i])}function Ze(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 Sd}from"util";import{execa as Ed}from"execa";async function ay(n,e){let t=await Aa(n);if(!t)throw new Error(E.DEVICE_LIST_EMPTY);let r=await wT(e);if(t.length===0)for(let s of r)await yT(n,s.udid,s.deviceName);else for(let s of r)await vT(n,t,s.udid,s.deviceName);let i=(await Aa(n)).map(s=>s.id);if(i.length===0)throw new Error(E.DEVICE_LIST_EMPTY);return i}async function yT(n,e,t){await dy(n,e,cy(t))}async function vT(n,e,t,r){for(let o=0;o<e.length;o++){if(t===e[o].udid)return;if(o===e.length-1){await dy(n,t,cy(r));return}}}function cy(n){switch(n){case"liteWearable":return"1";case"wearable":return"2";case"tv":return"3";default:return"4"}}async function sy(n,e=1,t=100){let r=`${ce.BASE_URL}${ce.DEVICE_LIST_PATH}?encodeFlag=0&start=${e}&pageSize=${t}`,o=uy(n),i=await L.get(r,{headers:o});if(!i)throw Sd("query devices failed: response is null"),new Error(E.ERROR_WHILE_ADD_DEVICE);if(i.statusCode!==200)throw ly(i.statusCode,i.statusText,i.data);let s=JSON.parse(i.data);if(!s||!s.list)throw Sd("query devices failed: response list is null"),new Error(s.ret?.msg||E.ERROR_WHILE_ADD_DEVICE);return{deviceList:s.list,total:s.totalCount||0}}function ly(n,e,t){return n===vt.FORBIDDEN?e===we.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN):n===vt.UNAUTHORIZED?new Error(E.ERR_UNAUTHORIZED):t.includes(we.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(E.DEVICE_LIMIT_REACHED):new Error(E.ERROR_WHILE_ADD_DEVICE)}async function Aa(n){let t=await sy(n,1,100);if(!t||!t.deviceList||t.deviceList.length===0)return[];let r=[...t.deviceList],o=t.total,i=Math.floor(o/100)+(o%100===0?0:1);for(let s=2;s<=i;s++){let a=await sy(n,s,100);if(!a||!a.deviceList||a.deviceList.length===0)break;r.push(...a.deviceList)}return r}async function dy(n,e,t){let r=`${ce.BASE_URL}${ce.DEVICE_ADD_PATH}`,o=uy(n),s={deviceName:`auto_sign_device_No.${Math.floor(Math.random()*3e3)}${Date.now()}`,udid:e,deviceType:t},a=await L.postAllowFailure(r,{headers:o,params:s});if(!a)throw Sd("add device failed: response is null"),new Error(E.ERROR_WHILE_ADD_DEVICE);if(a.statusCode!==200)throw ly(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(we.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(E.DEVICE_LIMIT_REACHED):c.includes(we.DEVICE_NAME_REPEAT_CODE)?new Error(E.DEVICE_NAME_REPEAT):new Error(E.ERROR_WHILE_ADD_DEVICE)}function uy(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}async function wT(n){let{stdout:e}=await Ed(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let o of e.split(`
1365
+ `)){let i=o.trim();if(!i||i.startsWith("[Empty]"))continue;let s=i.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let r=[];for(let o of t)try{let i=await bT(o,n),s=await ST(o,n);i.length>0&&r.push({id:"",udid:i,deviceName:s})}catch{u(`Failed to get device info for ${o}, skipping`)}return r}async function bT(n,e){let{stdout:t}=await Ed(e,["-t",n,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),r=t.trim();if(!r)return"";let o=r.split(`
1366
+ `);for(let s=0;s<o.length-1;s++)if(o[s].includes("udid of current device is")){let c=o[s+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(c)return c[0].toUpperCase()}let i=r.match(/[A-Fa-f0-9]{64}/);return i?i[0].toUpperCase():""}async function ST(n,e){let{stdout:t}=await Ed(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return ET(t)}function ET(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 on from"fs";import{createHash as PT}from"crypto";import{debuglog as Yt}from"util";import{Buffer as my}from"buffer";import{createPublicKey as CT,X509Certificate as Pd}from"crypto";import{readFileSync as kT}from"fs";import sn from"node-forge";async function fy(n,e){console.log("Start generating profile");let{productName:t,bundleName:r,projectPath:o,aclPermissionList:i,allDeviceIds:s,certIds:a,keyAlias:c,keyPwd:l}=e;if(s==null||s.length===0)throw new Error(E.DEVICE_LIST_EMPTY);let d=`${ce.BASE_URL}${ce.PROVISION_ADD_TEST_PATH}`,g=IT(t,r),v=await DT(n,d,a||[],r,s,g,i||[]);if(!v||!v.profileInfo||!v.profileInfo.provisionFileUrl)throw Yt("add provision failed, the provision file url is null"),new Error(E.ADD_PROFILE_FAIL);let P=v.profileInfo,B=(await LT(n,P.provisionFileUrl)).urlList,Ae=v.profileInfo.id;if(B&&B.length>0){let Qe=await Vg(t,o),St=Qe.profilePath;if(!await NT(B,St))throw await py(n,Ae),new Error(E.ERROR_WHILE_DOWNLOAD_PROFILE);if(await py(n,Ae),on.existsSync(Qe.certPath)&&on.existsSync(St)&&on.existsSync(Qe.p12Path)){let Ma=on.readFileSync(Qe.certPath,"utf8"),Oa=on.readFileSync(St,"utf8");return MT(Oa,Ma,Qe.p12Path,c,l)||xT(St),St}}throw new Error(E.ADD_PROFILE_FAIL)}function IT(n,e){let t=n?`${n}_`:"";return`${AT(`${t}${e}_${e}`)}`}function AT(n){return PT("sha256").update(n).digest("hex").substring(0,16)}async function DT(n,e,t,r,o,i,s){RT(r);let a=kd(n),c={certList:t,packageName:r,deviceList:o,provisionName:i};s.length&&(c.aclPermissionList=s);let l=await L.postAllowFailure(e,{headers:a,params:c});if(!l)throw Yt("add provision failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw Cd(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw Yt(`add provision fail: ${l.data}`),TT(l.data,i),new Error(d.ret?.msg||E.ADD_PROFILE_FAIL);let g=d.provisionFileUrl;return{profileInfo:{id:d.id,name:i,provisionFileUrl:g}}}function Cd(n,e,t){return n===vt.FORBIDDEN?e===we.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN):n===vt.UNAUTHORIZED?new Error(E.ERR_UNAUTHORIZED):t.includes(we.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(E.TEST_PROVISION_EXCEEDS_LIMIT):new Error(E.ADD_PROFILE_FAIL)}function RT(n){if(!n||n.trim().length===0)throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!Ve.BUNDLE_NAME_REGEX.test(n))throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function TT(n,e){if(n.includes(we.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(E.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(we.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(E.PROFILE_NAME_REPEAT)}async function py(n,e){if(!e||e.trim().length===0)return;let t=`${ce.BASE_URL}${ce.PROVISION_DELETE_PATH}?id=${e}`,r=await L.deleteAllowFailure(t,{headers:kd(n)});if(r.statusCode!==200)throw Cd(r.statusCode,r.statusText,r.data);let o=JSON.parse(r.data);(!o||!o.ret||o.ret.code!==0)&&Yt(`delete provision failed: ${r.data}`)}function xT(...n){for(let e of n)try{on.existsSync(e)&&on.unlinkSync(e)}catch(t){Yt(`delete local sign file error: ${t.message}`)}}async function LT(n,e){let t=`${ce.BASE_URL}${ce.CERT_DOWNLOAD_URL_PATH}`,r=kd(n),o={sourceUrls:e},i=await L.postAllowFailure(t,{headers:r,params:o});if(!i)throw Yt("get download list failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(i.statusCode!==200)throw Cd(i.statusCode,i.statusText,i.data);let s=JSON.parse(i.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw Yt("download: The application does not exist"),new Error(s.ret?.msg||E.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function NT(n,e){if(!n||n.length===0)return!1;let t=n[0];return await ii(t.newUrl,e,t.sha256),!0}function MT(n,e,t,r,o){return OT(n,e),r=r||Ve.TARGET_FRIENDLY_NAME,o=o||"",_T(e,t,r,o),!0}function OT(n,e){if(e.lastIndexOf(Ve.CERT_BEGIN_HEADER)<0)throw new Error(E.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(Ve.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function _T(n,e,t,r){let o=n.matchAll(Ve.CERTIFICATE_PATTERN_GLOBAL),i=[],s=new Date;for(let c of o)try{let l=c[0],d=jT(l),g=new Date(d.validFrom),v=new Date(d.validTo);if(s<g||s>v){let P=`Certificate is not valid, Valid from ${g} to ${v}`;throw console.warn(`checkCertificateInValidityPeriod: ${P}`),new Error(E.CERTIFICATE_HAS_EXPIRED)}i.push(d)}catch(l){throw console.warn(`checkCertificateInValidityPeriod\uFF1A ${l.message}`),new Error(E.CERTIFICATE_HAS_EXPIRED,{cause:l})}if(!i||i.length===0)throw new Error(E.CERTIFICATE_HAS_EXPIRED);if(!$T(e,t,r,i))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function jT(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new Pd(t);let r=my.from(t,"base64");return new Pd(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function FT(n){if(n.cert){let e=sn.pki.publicKeyToPem(n.cert.publicKey);return CT(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=sn.asn1.toDer(n.asn1).getBytes(),t=my.from(e,"binary");return new Pd(t).publicKey.export({type:"spki",format:"der"})}catch(e){return Yt(`Failed to parse cert from asn1: ${e}`),null}return null}function $T(n,e,t,r){try{let o=kT(n),i=sn.asn1.fromDer(sn.util.createBuffer(o)),c=sn.pkcs12.pkcs12FromAsn1(i,t).getBags({bagType:sn.pki.oids.certBag})[sn.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let g=FT(l);if(!g)continue;if(r.some(P=>{let ie=P.publicKey.export({type:"spki",format:"der"});return g.equals(ie)}))return!0}return!1}catch(o){let i=o instanceof Error?o.message:String(o);return Yt(`Failed to process P12 file: ${n}, error: ${i}`),!1}}function kd(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var gy="https://developer.huawei.com",HT={"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"},UT="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function BT(n){let e=HT[n];return e?`${gy}${e}`:void 0}function WT(){return`${gy}${UT}`}var VT={"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 hy(n,e){return(VT[n]??n).replace(/\{(\d+)\}/g,(r,o)=>String(e[Number(o)]??""))}function qT(n){return Array.from(n).join(", ")}function yy(n,e){if(n.size===0)return;let t=Rr.getAclPermissionInfos(e),r=new Set;for(let g of t)n.has(g.permissionName)&&r.add(g);for(let g of r){let v=BT(g.permissionName);v!=null&&(g.permissionHelpUrlKey=v)}let o=new Set;for(let g of r)o.add(g.permissionDisplayName);let i=new Set;for(let g of r)if(g.permissionHelpUrlKey!=null){let v=g.permissionInsteadName??g.permissionDisplayName;i.add(`${v} (${g.permissionHelpUrlKey})`)}let s=WT(),a=hy("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=i.size>0?Array.from(i).join(", ")+".":"",d=hy("acl.permissions.warn",[qT(o),l,c]);console.log(d)}var Da=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=W.discover(process.cwd()),{passed:!0,message:""}}catch(t){return u(`[EnvCheck] Project.discover() failed: ${t.message}`),e(ue.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(r){return u(`[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 u(`[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:ue.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import GT from"fs";import vy from"path";var Ra=class{constructor(e){this.toolProvider=e}toolProvider;checkJava(e){try{return this.toolProvider.assertJava(),{passed:!0,message:""}}catch(t){return u(`[EnvCheck] Java check failed: ${t.message}`),e(`${t.message}`)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=vy.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");if(!GT.existsSync(r)){let o=vy.join("sdk","default","openharmony","toolchains","lib","hap_sign_tools.jar");return e(`hap_sign_tools.jar not found.Check whether ${o} exists.`)}return{passed:!0,message:""}}};var Ta=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await Ne.getUserInfo()}catch(e){return u(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await Ne.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(ue.LOGIN_REQUIRED)}catch(t){return u(`[EnvCheck] Login check failed: ${t.message}`),e(ue.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(ue.TEAM_INFO_FAILED);try{if((await ur()).teamList.length>0)return{passed:!0,message:""}}catch(r){return u(`[EnvCheck] Team API error: ${r.message}`),e(ue.TEAM_INFO_FAILED)}return u("[EnvCheck] No teams found for current user"),e(ue.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(ue.REALNAME_REQUIRED):t.isRealName!==!0?(u("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(ue.REALNAME_REQUIRED)):{passed:!0,message:""}:e(ue.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let o=await ur();if(r=e??(o.teamList.length>0?o.teamList[0].id:t.userId)??"",!o.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 u(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(o){return u(`[EnvCheck] Team ID check failed: ${o.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(ue.REGION_CHINA_ONLY):{passed:!0,message:""}:(u("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(ue.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function zT(n){try{let{teamList:e}=await ur();if(e.length>0)return e[0].id}catch(e){u(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function JT(n){let e=await Ne.getUserInfo(),t=await Ne.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await zT(e.userId);if(!r)throw new Error("No team found");let o={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await Aa(o)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var xa=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t){try{let r=await JT(t);if(r.length>0)return u(`[EnvCheck] Scenario 4 Device check: ${r.length} device(s) found in AGC cloud, skipping local device check`),{passed:!0,message:""};u("[EnvCheck] Scenario 4 Device check: no cloud devices found, falling back to local hdc");let i=await de.from(this.toolProvider).listDevices();return i.length===0?(u("[EnvCheck] Scenario 4 Device check: no local devices found"),e(ue.DEVICE_MISSING)):i.some(a=>It(a.serial))?{passed:!0,message:""}:(u("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(ue.DEVICE_MISSING))}catch(r){return u(`[EnvCheck] Scenario 4 Device check failed: ${r.message}`),e(ue.DEVICE_DETECT_FAILED)}}};var La=class{projectChecker=new Da;toolchainChecker=null;authChecker=new Ta;deviceChecker=null;constructor(){}async preflight(e){let t=r=>this.blockingFail(r);return!(!await this.runAuthChain(e,t)||!await this.initToolchain()||!await this.runDeviceCheck(e,t)||!await this.runProjectChecks(e,t)||!await this.runAuxChecks(e))}async runAuthChain(e,t){let r=i=>(i.passed||this.fail(i),!0),o=[()=>this.authChecker.checkLogin(t),()=>this.authChecker.checkRealname(t),()=>this.authChecker.checkTeamInfo(t)];for(let i of o)if(!r(await i()))return!1;return!(e.teamId&&!r(await this.authChecker.checkTeamId(e.teamId)))}async initToolchain(){try{let e=await A.new();return this.toolchainChecker=new Ra(e),this.deviceChecker=new xa(e),!0}catch(e){throw u(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(ue.TOOLCHAIN_INIT_FAILED,{cause:e})}}async runDeviceCheck(e,t){return(o=>o.passed?!0:(this.fail(o),!1))(await this.deviceChecker.checkDevice(t,e.teamId))}async runProjectChecks(e,t){let r=i=>i.passed?!0:(this.fail(i),!1);if(!r(this.projectChecker.checkProjectDir(t))||!r(this.projectChecker.checkAtomicService()))return!1;let o=[()=>this.projectChecker.checkProduct(e.productName,t),()=>this.projectChecker.checkBundleName(e.productName,t),()=>this.toolchainChecker.checkJava(t),()=>this.toolchainChecker.checkHapSignTools(t)];for(let i of o)if(!r(i()))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 u(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};var wy=5*1024*1024;function XT(n){try{let e=Ad.statSync(n);if(e.size>wy)throw new Error(`Profile file too large: ${e.size} bytes (max ${wy} bytes): ${n}`);let t=Ad.readFileSync(n,"utf-8");return Sy.parse(t)}catch(e){if(e.code==="ENOENT")return{app:{signingConfigs:[],products:[]}};throw new Error(`Failed to read profile: ${n}`,{cause:e})}}function ZT(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function QT(n){if(n.keyPwd===n.storePassword){let r=await Dr.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await Dr.encryptedPassword(n.keyPwd,n.p12FilePath),t=await Dr.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function ex(n,e,t){let r=by.join(n,"build-profile.json5"),o=XT(r);ZT(o);let i=t??"default",{keyPassword:s,storePassword:a}=await QT(e),c={name:i,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:wt.signAlg,storeFile:e.p12FilePath,storePassword:a}},l=o.app?.signingConfigs?.findIndex(g=>g.name===i);l!==void 0&&l>=0?o.app.signingConfigs[l]=c:o.app.signingConfigs.push(c);let d=o.app?.products?.findIndex(g=>g.name===i);d!==void 0&&d>=0?o.app.products[d].signingConfig=i:o.app.products.push({name:i,signingConfig:i}),Ad.writeFileSync(r,Sy.stringify(o,null,2),"utf-8")}async function tx(n){let e=await Ne.getUserInfo(),t=await Ne.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??""}}async function rx(n){let e=n.product||"default";await new La().preflight({productName:e,teamId:n.teamId}),console.log("Executing signature generate command");let r=await tx(n),o=await A.new(),{shouldRegenerate:i}=await ci.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product},o);if(!i){console.log(Id("Signature generation completed successfully."));return}await nx(n,r,o),console.log(Id("Signature generation completed successfully."))}async function nx(n,e,t){let r=await md(e,n.product),o=ox(n,e,r,t);o.allDeviceIds=await ay(e,t.hdcPath),await fy(e,o);let i=W.discover(process.cwd()).rootDir;await ex(i,r,n.product??"default"),console.log(Id(`Signing config written to ${by.join(i,"build-profile.json5")}`))}function ox(n,e,t,r){let o=process.cwd(),i=W.discover(o),s=ka(i,r);return yy(s,i),{productName:n.product||"default",bundleName:i.getBundleName(n.product||"default"),projectPath:i.rootDir,teamId:e.teamId,force:n.force||!1,aclPermissionList:[...s],certIds:[t.certId],keyAlias:t.keyAlias,keyPwd:t.keyPwd}}var Ey=new YT("signature").description("Generate application signature.");Ey.command("generate").description("Automatically generate signing materials and write them to the project configuration.").option("--force","Force overwrite existing local signing materials.").option("--team-id <team-id>","Specify the team ID to use.").option("--product <product>","Specify the product. The default value is default.").action(async n=>{let e={event:b.CommandExecuted,args:["signature","generate",...n.force?["--force"]:[],...n.teamId?["--team-id"]:[],...n.product?["--product"]:[]]},t=Date.now(),r=!0,o=null;try{await rx(n)}catch(i){r=!1,o=G(i),console.error(KT(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await I.track(e,i)}});var Py=Ey;if(!Et())try{I.init(Na.join(Pe(),"TraceLogData")),I.startScheduler()}catch(n){h.error(`[telemetry] init failed: ${n instanceof Error?n.message:String(n)}`)}(async()=>{if(!Et())try{let n=await A.new();I.setSourceType(n.sourceType);let e=await A.getCltVersion();e&&I.setCltVersion(e);let t=await A.getStudioVersion();t&&I.setStudioVersion(t)}catch(n){h.error(`[telemetry] toolchain info failed: ${n instanceof Error?n.message:String(n)}`)}})();le.name("devecocli").description(`HarmonyOS application development command line tool
1346
1367
 
1347
- Privacy: ${qr.PRIVACY_URL}`).version("1.3.1");ae.addCommand(au);ae.addCommand(Lu);ae.addCommand(Vu);ae.addCommand(lp);ae.addCommand(_p);ae.addCommand(sf);ae.addCommand(Nf);ae.addCommand(_f);ae.addCommand(zf);ae.addCommand(nm);ae.addCommand(Am);ae.addCommand(Om);ae.addCommand(oh);ae.addCommand(Fh);ae.addCommand(kg);var Xl=process.argv.slice(2);Xl.length>=2&&Xl[Xl.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);function _R(n){let e=n;for(;e.parent&&e.parent!==ae;)e=e.parent;return e}var jR=new Set(["update","auth","serve"]);ae.hook("preAction",async(n,e)=>{let t=_R(e),r=cr();if(t.name()==="update")return;let i=new Zt(ma.join(be(),"update")),o=Xt();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||jR.has(t.name())||await A.checkVersion()});ae.hook("postAction",async(n,e)=>{if(process.exitCode||cr()!=="off")return;await new di(e).checkAndNotify()});ae.parseAsync(process.argv).finally(()=>{I.stopScheduler();try{Da(ma.join(be(),"TraceLogData"))}catch(n){h.error(`[telemetry] background upload spawn check failed: ${n instanceof Error?n.message:String(n)}`)}}).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(MR(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
1368
+ Privacy: ${Qn.PRIVACY_URL}`).version("1.3.3-Test.2");var Cy=le.options.find(n=>n.long==="--version");Cy&&(Cy.flags="-V, -v, --version");le.addCommand($u);le.addCommand(Fp);le.addCommand(Kp);le.addCommand(gm);le.addCommand(Bm);le.addCommand(mf);le.addCommand(Hf);le.addCommand(Wf);le.addCommand(eh);le.addCommand(lh);le.addCommand(Oh);le.addCommand(Bh);le.addCommand(eg);le.addCommand(_g);le.addCommand(Py);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 Dd=process.argv.slice(2);Dd.length>=2&&Dd[Dd.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);function sx(n){let e=n;for(;e.parent&&e.parent!==le;)e=e.parent;return e}var ax=new Set(["update","auth","serve"]);le.hook("preAction",async(n,e)=>{let t=sx(e),r=bn();if(t.name()==="update")return;let o=new sr(Na.join(Pe(),"update")),i=ir();if(r==="off"&&o.getBlockedVersions().includes(i))throw new Error(`devecocli ${i} has been disabled, run \`devecocli update\` to upgrade`);process.env.DEVECO_CLI_SKIP_VERSION_CHECK||ax.has(t.name())||await A.checkVersion()});le.hook("postAction",async(n,e)=>{if(process.exitCode||bn()!=="off")return;await new ko(e).checkAndNotify()});le.parseAsync(process.argv).finally(()=>{I.stopScheduler();try{Ya(Na.join(Pe(),"TraceLogData"))}catch(n){h.error(`[telemetry] background upload spawn check failed: ${n instanceof Error?n.message:String(n)}`)}}).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(ix(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});