@deveco-test/deveco-cli-openharmony-arm64 1.3.10-Test.1 → 1.3.11-Test.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -1
- package/SKILL.md +6 -3
- package/THIRD-PARTY-LICENSES +5675 -5567
- package/dist/cli.js +126 -129
- package/dist/internal/telemetry-upload-background.js +1 -1
- package/index.zip +0 -0
- package/package.json +10 -9
package/dist/cli.js
CHANGED
|
@@ -1,89 +1,89 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`)}var
|
|
2
|
+
var OS=Object.defineProperty;var LS=(n,e)=>{for(var t in e)OS(n,t,{get:e[t],enumerable:!0})};import*as hp from"path";import{program as le}from"commander";import{red as k_}from"colorette";var So={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},zi={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 Pe={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"},q={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"},Hn={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},bo={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:q.LOGIN_URL,authUrl:q.AUTH_APPLY_PATH,tempTokenCheckUrl:q.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:q.JWT_TOKEN_CHECK_PATH,successRedirectUrl:q.LOGIN_SUCCESS_PATH,failedRedirectUrl:q.LOGIN_FAILED_PATH,logoutUrl:q.LOGOUT_PATH,agcTeamListUrl:q.AGC_TEAM_LIST_URL,appId:Pe.APP_ID,timeout:So.LOGIN_TIMEOUT_MS,countryCode:"CN"};import{Command as uE}from"commander";import{green as Sl,red as bm,yellow as bl}from"colorette";import re from"fs";import*as B from"path";import Nt from"json5";import*as Vc from"fs";import*as Ce from"path";function m(n){process.env.DEVECO_CLI_DEBUG&&process.stderr.write(`[DEBUG] ${n}
|
|
3
|
+
`)}var x=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(`
|
|
4
4
|
`)}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 assertRelativeTimeRange(e,t){if(e!==void 0&&t!==void 0&&e<t)throw new Error("--from must be greater than or equal to --to when both are provided (e.g. --from 30s --to 10s)")}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 h=n.extractTimestampFromLogLine(d,o);h&&(l=n.isWithinBounds(h,i,s)),l&&c.push(d)}return c.join(`
|
|
5
|
-
`)}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",h=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),w=new Date(o,i,s,a,c,l,h);return w.getTime()>t.getTime()+1440*60*1e3&&w.setFullYear(o-1),w}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertBundleNameStrict(e){if(e.length<7||e.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${e.length}`);if(e.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let t=e.split(".");if(t.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let r=/^[a-zA-Z0-9_]+$/;for(let 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 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 m(`quotePosixShellArg: ${e} -> ${r}`),r}static assertCrashFilename(e){if(!/^\w+-[\w.]+-\d+-\d+$/.test(e))throw new Error(`Invalid crash log filename: ${JSON.stringify(e)}`)}static assertHilogLevel(e){if(!/^[DIWEF]$/.test(e))throw new Error(`Invalid log level: ${e}`)}static resolvePathWithinRoot(e,t){if(
|
|
5
|
+
`)}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",h=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),w=new Date(o,i,s,a,c,l,h);return w.getTime()>t.getTime()+1440*60*1e3&&w.setFullYear(o-1),w}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertBundleNameStrict(e){if(e.length<7||e.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${e.length}`);if(e.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let t=e.split(".");if(t.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let r=/^[a-zA-Z0-9_]+$/;for(let 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 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 m(`quotePosixShellArg: ${e} -> ${r}`),r}static assertCrashFilename(e){if(!/^\w+-[\w.]+-\d+-\d+$/.test(e))throw new Error(`Invalid crash log filename: ${JSON.stringify(e)}`)}static assertHilogLevel(e){if(!/^[DIWEF]$/.test(e))throw new Error(`Invalid log level: ${e}`)}static resolvePathWithinRoot(e,t){if(Ce.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=Ce.resolve(Ce.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=Ce.normalize(e),o=Ce.relative(r,t);if(o.split(Ce.sep)[0]===".."||Ce.isAbsolute(o))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||Ce.isAbsolute(e)}static isPathContained(e,t){let r=Ce.resolve(t,e),o=Ce.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=Vc.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let i=Ce.resolve(o,e),s;try{s=Vc.realpathSync(i)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${i}`}}return n.isPathContained(s,o)}};import Wp from"crypto";import X from"fs";import os from"os";import Ge from"path";import _S from"https";var yp={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var qi=class n{static ENDPOINT=yp.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=_S.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",h=>d.push(h)),l.on("end",()=>{s({code:l.statusCode??0,body:Buffer.concat(d).toString("utf8")})})});c.on("timeout",()=>{c.destroy(new Error("request timeout"))}),c.on("error",a),c.write(r),c.end()})}};var wp={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()},Gc=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??wp.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}},vp=new Gc({namingStrategy:wp.snakeCase,fieldNames:{}});import Po from"crypto";import Yi from"fs";import FS from"path";var Ji="aes-256-gcm",jS=12,$S="deveco-cli-trace-file",HS="trace-file-secret",bp=32;function Sp(n){try{let e=Yi.readFileSync(n,"utf8").trim();return e&&Buffer.from(e,"base64").length===bp?e:null}catch{return null}}function Ep(n){let e=FS.join(n,HS),t=Sp(e);if(t)return zc(t);let r=Po.randomBytes(bp).toString("base64");try{Yi.mkdirSync(n,{recursive:!0});try{Yi.writeFileSync(e,r,{flag:"wx"})}catch{let o=Sp(e);if(o)return zc(o);Yi.writeFileSync(e,r)}}catch{}return zc(r)}function zc(n){return Po.createHash("sha256").update($S).update(n).digest()}function Pp(n,e){let t=Po.randomBytes(jS),r=Po.createCipheriv(Ji,e,t),o=Buffer.concat([r.update(n,"utf8"),r.final()]),i={version:1,algorithm:Ji,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:r.getAuthTag().toString("base64")};return JSON.stringify(i)}function Cp(n,e){let t;try{t=JSON.parse(n)}catch{return null}if(!US(t))return n;try{let r=Po.createDecipheriv(Ji,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 US(n){if(!n||typeof n!="object")return!1;let e=n;return e.version===1&&e.algorithm===Ji&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as j from"fs";import*as ts from"path";import se from"fs";import*as Ki from"os";import*as K from"path";import BS from"json5";import*as Ip from"os";function b(){return qc().toLowerCase().includes("openharmony")}function qc(){return Ip.platform()}var Ap=3;function Xi(n){if(!se.existsSync(n)||!se.statSync(n).isDirectory())return!1;let e=se.existsSync(K.join(n,"build-profile.json5")),t=se.existsSync(K.join(n,"hvigorfile.js"))||se.existsSync(K.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=se.readFileSync(K.join(n,"build-profile.json5"),"utf-8");return BS.parse(r).app!==void 0}catch{return!1}}function Yc(n,e,t){if(e>=t)return null;let r=WS(n),o=VS(r);if(o)return o;for(let i of r){let s=Yc(i,e+1,t);if(s)return s}return null}function WS(n){try{let e=se.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(K.join(n,r.name));return t}catch{return[]}}function VS(n){for(let e of n)if(Xi(e))return e;return null}function xt(n){if(!n||n.trim()==="")return null;let e=K.resolve(n),t;try{t=se.realpathSync(e)}catch{t=e}if(!se.existsSync(t))return null;if(Xi(t))return t;let r=t;for(let o=1;o<=3;o++){let i=K.dirname(r);if(i===r)break;if(Xi(i))return i;r=i}if(se.statSync(t).isDirectory()){let o=Yc(t,0,Ap);if(o)return o}return null}function Zi(n){if(!n||n.trim()==="")return null;let e=K.resolve(n),t;try{t=se.realpathSync(e)}catch{t=e}return!se.existsSync(t)||!se.statSync(t).isDirectory()?null:Xi(t)?t:Yc(t,0,Ap)}var Jc=[b()?".bitfun":".idea",".deveco",b()?".cxx":"cxx","compile_commands.json"];function gr(n){return K.join(n,...Jc)}function Dp(n){return new Promise(e=>setTimeout(e,n))}var GS=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function Un(n){let e=K.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&GS.has(e)}function Qi(n){return K.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function he(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function zS(n){return he(n)}function Bn(n){let e=zS(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function rn(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??K.join(Ki.homedir(),"AppData","Local");return K.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?K.join(Ki.homedir(),"Library","Logs","devecocli-mcp-server"):K.join(Ki.homedir(),".local","share","devecocli-mcp-server","logs")}function Tp(n,e){let t=qS(e),r=YS(t,n);if(r!==null)return r;let o=Date.now(),s=`${n.replace(/:/g,"\\:")}=${o}`,a=JS(t,n,s);return KS(e,a),o}function qS(n){let e;try{e=se.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function YS(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 JS(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 KS(n,e){try{se.mkdirSync(K.dirname(n),{recursive:!0})}catch{}try{se.writeFileSync(n,e.join(`
|
|
6
6
|
`)+`
|
|
7
|
-
`,"utf8")}catch{}}function
|
|
8
|
-
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);j.writeSync(this.fd,c),this.checkRotation(c.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{j.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},
|
|
9
|
-
`,"utf8"),
|
|
10
|
-
`).map(s=>s.trim()).filter(Boolean);if(i.length===0){try{await
|
|
7
|
+
`,"utf8")}catch{}}function Kc(n,e,t="[Cleanup]"){try{let r=K.dirname(n);if(!se.existsSync(r))return;let o=Date.now();for(let i of se.readdirSync(r,{withFileTypes:!0}))i.isDirectory()&&XS(K.join(r,i.name),o,e,t)}catch{}}function XS(n,e,t,r){try{let{mtimeMs:o}=se.statSync(n);if(e-o<=t)return;se.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 Rp="mcp-server.log",ZS="mcp-server",QS={maxSize:10*1024*1024,maxFiles:4},Xc=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={...QS,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=rn(),this.currentLogFile=ts.join(this.logDir,Rp),j.existsSync(this.logDir)||j.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${o}`}getRotatedFileName(e,t){return ts.join(this.logDir,`${ZS}-${e}.log.${t}`)}fileExists(e){try{return j.accessSync(e,j.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=j.readdirSync(this.logDir),t=[];for(let o of e)if(o===Rp||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(o)){let i=ts.join(this.logDir,o),s=j.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{j.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)&&j.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)&&j.renameSync(i,s)}let r=this.getRotatedFileName(e,1);j.renameSync(this.currentLogFile,r),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let e=j.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=j.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{j.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...r){if(this.mode==="silent"||n.LEVEL_ORDER[e]<n.LEVEL_ORDER[this.minLevel])return;let 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}
|
|
8
|
+
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);j.writeSync(this.fd,c),this.checkRotation(c.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{j.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},Xe=null;function Wn(n=!1){Xe&&Xe.dispose(),Xe=new Xc(n)}function kp(){Xe&&(Xe.dispose(),Xe=null)}function xp(){Xe&&Xe.flush()}function Np(){return Xe?.getLogFilePath()??null}function Op(){return Xe?.getLogDirectory()??null}function es(){return Xe||Wn(!1),Xe}var g={debug:(n,...e)=>es().debug(n,...e),info:(n,...e)=>es().info(n,...e),warn:(n,...e)=>es().warn(n,...e),error:(n,...e)=>es().error(n,...e)};import Co from"fs";import Zc from"path";var Io=300*1e3,Ao=3600*1e3,Qc=10080*60*1e3,yr=8*1024*1024,el=3600*1e3,Lp=".pending",eb=/\.reclaim-\d+-\d+$/;function Ze(){let n=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return n==="1"||n==="true"}var tb="upload-state.json";function _p(n){return Zc.join(n,tb)}function nb(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function ns(n){try{let e=Co.readFileSync(_p(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 nb()}}function tl(n,e){try{Co.writeFileSync(_p(n),JSON.stringify(e),"utf8")}catch{}}function Fp(n){let e=ns(n);e.firstEventAt===null&&(e.firstEventAt=Date.now(),tl(n,e))}function jp(n){let e=ns(n);e.lastUploadAt=Date.now(),e.firstEventAt=null,tl(n,e)}function $p(n){let e=ns(n);e.lastRetryAt=Date.now(),tl(n,e)}function nl(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 rl(n){if(!n.startsWith("telemetry-"))return null;let e=eb.exec(n),t=e?n.slice(0,e.index):n;if(!t.endsWith(Lp))return null;let r=t.slice(0,-Lp.length);return r.endsWith(".txt")?r:null}function ol(n){return rl(n)!==null}function rb(n,e=Date.now()){try{return e-Co.statSync(n).mtimeMs>=el}catch{return!1}}function Mp(n,e=Date.now()){let t;try{t=Co.readdirSync(n)}catch{return!1}return t.some(r=>ol(r)&&rb(Zc.join(n,r),e))}function ob(n,e=Date.now()){if(Mp(n,e))return!0;let t=Zc.join(n,"failed");if(Mp(t,e))return!0;let r;try{r=Co.readdirSync(t)}catch{return!1}for(let o of r){if(!o.startsWith("telemetry-")||!o.endsWith(".txt"))continue;let i=nl(o);if(i!==null&&e-i<=Qc)return!0}return!1}function Hp(n,e=Date.now()){let t=ns(n);return!!(t.firstEventAt!==null&&e-t.firstEventAt>=Io||ob(n,e)&&(t.lastRetryAt===null||e-t.lastRetryAt>=Ao))}import ib from"crypto";import rs from"fs";import sb from"path";var ab="install-id";function cb(n){return sb.join(n,ab)}function Up(n){try{let e=rs.readFileSync(n,"utf8").trim();return lb(e)?e:null}catch{return null}}function lb(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 Bp(n){let e=cb(n),t=Up(e);if(t)return t;let r=ib.randomUUID();try{rs.mkdirSync(n,{recursive:!0});try{rs.writeFileSync(e,r,{flag:"wx"})}catch{let o=Up(e);if(o)return o;rs.writeFileSync(e,r)}}catch{}return r}var Do=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 qi;storageDir="";failedDir="";installId="";disabled=Ze();traceFileKey=Buffer.alloc(0);sessionId=Wp.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){g.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=Ge.join(e,"failed"),this.cliVersion="1.3.11-Test.1",this.nodeVersion=process.version,this.installId=Bp(e).replace(/-/g,""),this.traceFileKey=Ep(e),X.mkdirSync(e,{recursive:!0}),X.mkdirSync(this.failedDir,{recursive:!0}),g.debug(`[telemetry] init: dir=${e}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(e){this.devecoStudioVersion=e,g.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,g.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,g.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");if(!t){await this.record(e,0,!0,null);return}if(typeof t!="function"){let 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=Pp(JSON.stringify(i),this.traceFileKey);await X.promises.appendFile(this.currentFile(),s+`
|
|
9
|
+
`,"utf8"),Fp(this.storageDir)}catch{}}buildTraceEvent(e,t,r,o){let i=`${n.EVENT_PREFIX}${e.event}`,s=vp.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:Wp.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,ram:this.resolveTotalRam(),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=os.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=os.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 os.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(os.totalmem()/1024)}KB`}formatVersion(e){return e?`${e}_${this.resolveOsSuffix()}`:""}dateString(){let e=new Date,t=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return`${e.getFullYear()}-${t}-${r}`}currentFile(){return Ge.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){g.debug("[telemetry] scheduler not started (telemetry disabled)");return}g.debug(`[telemetry] scheduler started (flush every ${Io/1e3}s, retry failed every ${Ao/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},Io)},Io),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},Ao)},Ao)}stopScheduler(){this.initialTimer&&(clearTimeout(this.initialTimer),this.initialTimer=null),this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null),this.retryInitialTimer&&(clearTimeout(this.retryInitialTimer),this.retryInitialTimer=null),this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),g.debug("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");let e=await this.listPendingFiles(),t=!0;for(let r of e)await this.flushFile(r)||(t=!1);return jp(this.storageDir),t}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");await this.reclaimStalePending();let e=Date.now(),t;try{t=await X.promises.readdir(this.failedDir)}catch{return!0}let r=t.filter(i=>i.startsWith("telemetry-")&&i.endsWith(".txt")).map(i=>Ge.join(this.failedDir,i)),o=!0;for(let i of r){let s=Ge.basename(i),a=nl(s);if(a!==null){if(e-a>Qc){try{await X.promises.unlink(i)}catch{}continue}await this.flushFile(i)||(o=!1)}}return o||g.warn("[telemetry] retry failed"),$p(this.storageDir),o}async reclaimStalePending(){let e=Date.now();for(let t of[this.storageDir,this.failedDir]){let r;try{r=await X.promises.readdir(t)}catch{continue}for(let o of r)ol(o)&&await this.reclaimOrphan(Ge.join(t,o),e)}}async reclaimOrphan(e,t){let r;try{let l=await X.promises.stat(e);if(t-l.mtimeMs<el)return;r=l.size}catch{return}let o=Ge.dirname(e),i=rl(Ge.basename(e));if(i===null)return;let s=await this.claimOrphan(e,o,i);if(s===null)return;let a=Ge.join(o,i),c=yr-await this.fileSize(a);if(r>c){try{await X.promises.unlink(s)}catch{}g.warn(`[telemetry] dropped stale orphan pending: ${s} (${r} bytes > budget ${c})`);return}if(await this.mergeOrphanInto(s,a)){g.warn(`[telemetry] reclaimed orphan pending: ${s} (${r} bytes)`);return}g.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${r} bytes)`)}async claimOrphan(e,t,r){let o=Ge.join(t,`${r}.pending.reclaim-${process.pid}-${Date.now()}`);try{await X.promises.rename(e,o)}catch{return null}return await this.touch(o),o}async mergeOrphanInto(e,t){try{await X.promises.appendFile(t,await X.promises.readFile(e))}catch(r){return g.warn(`[telemetry] merge orphan pending failed: ${e} -> ${t}: ${r instanceof Error?r.message:String(r)}`),!1}try{await X.promises.unlink(e)}catch(r){g.warn(`[telemetry] merged but failed to remove orphan pending: ${e}: ${r instanceof Error?r.message:String(r)}`)}return!0}async fileSize(e){try{return(await X.promises.stat(e)).size}catch{return 0}}async touch(e){let t=new Date;try{await X.promises.utimes(e,t,t)}catch{}}runExclusive(e){let t=()=>e(),r=this.flushChain.then(t,t);return this.flushChain=r.then(()=>{},()=>{}),r}async listPendingFiles(){let e;try{e=await X.promises.readdir(this.storageDir)}catch{return[]}return e.filter(t=>t.startsWith("telemetry-")&&t.endsWith(".txt")).map(t=>Ge.join(this.storageDir,t)).sort()}async flushFile(e){let t=await this.fileSize(e);if(t>yr){g.warn(`[telemetry] ${Ge.basename(e)} is ${t} bytes (> ${yr}), dropped without uploading`);try{await X.promises.unlink(e)}catch{}return!0}let r=e+".pending";try{await X.promises.rename(e,r)}catch{return!1}await this.touch(r);let o;try{o=await X.promises.readFile(r,"utf8")}catch{return!1}let i=o.split(`
|
|
10
|
+
`).map(s=>s.trim()).filter(Boolean);if(i.length===0){try{await X.promises.unlink(r)}catch{}return!0}return this.uploadInBatches(r,i)}collectDecryptBatch(e,t){let r=[],o=16,i=t;for(;i<e.length&&r.length<n.MAX_BATCH;){let s=Cp(e[i],this.traceFileKey);if(s===null){i++;continue}let a=Buffer.byteLength(s,"utf8")+1;if(r.length>0&&o+a>n.MAX_PAYLOAD_BYTES)break;r.push(s),o+=a,i++}return{batch:r,next:i}}async uploadInBatches(e,t){let r=0;for(;r<t.length;){let o=r,{batch:i,next:s}=this.collectDecryptBatch(t,r);r=s;let a=this.buildPayloadItems(i);if(a.length===0)continue;let c=JSON.stringify(a),l=!1;try{l=await this.uploader.upload(c,this.installId)}catch{}if(!l){g.warn("[telemetry] upload failed");let d=t.slice(o).join(`
|
|
11
11
|
`)+`
|
|
12
|
-
`;return await this.moveToFailed(e,d),!1}}try{await
|
|
13
|
-
`).filter(Boolean),s=
|
|
12
|
+
`;return await this.moveToFailed(e,d),!1}}try{await X.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=Ge.basename(e,".pending"),o=Ge.join(this.failedDir,r),i=t.split(`
|
|
13
|
+
`).filter(Boolean),s=yr-await this.fileSize(o),a=this.takeNewestWithinBudget(i,s);a.length<i.length&&g.warn(`[telemetry] failed file capped at ${yr} bytes, dropped ${i.length-a.length} older events`);try{a.length>0&&await X.promises.appendFile(o,a.join(`
|
|
14
14
|
`)+`
|
|
15
|
-
`,"utf8")}catch{return}try{await Z.promises.unlink(e)}catch{}}takeNewestWithinBudget(e,t){if(t<=0)return[];let r=[],o=0;for(let i=e.length-1;i>=0;i--){let s=Buffer.byteLength(e[i],"utf8")+1;if(o+s>t)break;o+=s,r.push(e[i])}return r.reverse(),r}};var D=new Ao;import{spawn as cb}from"child_process";import{existsSync as lb}from"fs";import{dirname as db,join as ub}from"path";import{fileURLToPath as pb}from"url";function mb(){let n=db(pb(import.meta.url)),e=ub(n,"internal","telemetry-upload-background.js");return lb(e)?e:null}function rl(n){if(Qe()||!Op(n))return;let e=mb();if(!e){g.warn("[telemetry] background upload script not found, skipping spawn");return}try{cb(process.execPath,[e],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1",DEVECO_CLI_TELEMETRY_UPLOAD:"1"}}).unref()}catch(t){g.warn("[telemetry] failed to spawn background upload:",t)}}var x=class extends Error{traceMessage;constructor(e,t,r){super(e,r),this.name="TraceError",this.traceMessage=t??e}};function ce(n){if(n instanceof x)return n.traceMessage;if(n instanceof Error){let e=n.code;return typeof e=="string"&&e!==""?e:n.name}return"UnknownError"}var T={CommandExecuted:"Command_executed",McpToolCall:"serve_mcp",SkillOperation:"skills",Init:"mcp_config_operation",SkillConfigOperation:"skill_config_operation",DocOperation:"docs",ServeLsp:"serve_lsp",CheckCommand:"check"};var K=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=W.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=W.join(e,"build-profile.json5");if(!re.existsSync(t))return null;try{let r=re.readFileSync(t,"utf-8"),o=Lt.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 x(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=R.resolvePathWithinRoot(this.rootDir,t.srcPath),o=W.join(r,"src","main","module.json5");if(!re.existsSync(o))return"entry";try{let i=re.readFileSync(o,"utf-8");return Lt.parse(i)?.module?.type||"entry"}catch(i){return console.warn(`Warning: Failed to parse ${o}:`,i),"entry"}}findOwningModule(e){let t=W.normalize(e);for(let r of this.profile.modules){let o=W.normalize(W.join(this.rootDir,r.srcPath)),i=o+W.sep;if(t.startsWith(i)||t===o)return r.name}return null}getModuleProfile(e){let t=this.profile.modules.find(a=>a.name===e);if(!t)throw new x(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=R.resolvePathWithinRoot(this.rootDir,t.srcPath),o=W.join(r,"build-profile.json5");if(!re.existsSync(o))throw new x(`Build profile for module '${e}' not found at ${o}.`,"Build profile for module not found at ${profilePath}.");let i=re.readFileSync(o,"utf-8");return Lt.parse(i)}getBundleName(){let e=W.join(this.rootDir,"AppScope","app.json5");if(re.existsSync(e))try{let t=re.readFileSync(e,"utf-8"),r=Lt.parse(t);if(r?.app?.bundleName)return r.app.bundleName}catch(t){console.warn(`Warning: Failed to parse ${e}:`,t)}throw new Error("Could not find bundleName in AppScope/app.json5.")}isAtomicService(){let e=W.join(this.rootDir,"AppScope","app.json5");if(!re.existsSync(e))return!1;try{let t=re.readFileSync(e,"utf-8");return Lt.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=R.resolvePathWithinRoot(this.rootDir,r.srcPath),i=W.join(o,"src","main","module.json5");if(!re.existsSync(i))return"EntryAbility";try{let s=re.readFileSync(i,"utf-8"),c=Lt.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 x(`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 x(`Product '${e}' not found in project configuration. Available products: ${r}`,"Productnot found in project configuration.")}}getModuleDependencies(e){let t=this.profile.modules.find(s=>s.name===e);if(!t)return[];let r=R.resolvePathWithinRoot(this.rootDir,t.srcPath),o=W.join(r,"oh-package.json5");if(!re.existsSync(o))return[];let i=[];try{let s=re.readFileSync(o,"utf-8"),c=Lt.parse(s)?.dependencies||{};for(let l of Object.values(c)){if(typeof l!="string")continue;let d=l;if(!(d.startsWith("file:")||d.startsWith(".")||d.startsWith("..")))continue;d.startsWith("file:")&&(d=d.substring(5));let w=W.join(t.srcPath,d),v=R.resolvePathWithinRoot(this.rootDir,w),I=this.profile.modules.find(H=>W.resolve(this.rootDir,H.srcPath)===v);I&&i.push(I.name)}}catch{}return i}getModuleName(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)return e;let r=R.resolvePathWithinRoot(this.rootDir,t.srcPath),o=W.join(r,"src","main","module.json5");if(!re.existsSync(o))return e;try{let i=re.readFileSync(o,"utf-8");return Lt.parse(i)?.module?.name||e}catch(i){return console.warn(`Warning: Failed to parse ${o}:`,i),e}}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 x(`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(!re.existsSync(a))throw new x(`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 v=this.getSignedHapName(c,i.srcPath,o,t);v&&(d=v)}let h=s?"-signed.hsp":"-signed.hap";if(!r&&!d.endsWith(h))throw new x(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`,"Target device is a real device, but the artifact is not signed.");let w=this.buildOutputPath(i.srcPath,o,["outputs",t,d]);if(!re.existsSync(w))throw new x(`Generated package file not found in ${w}.`,"Generated package file not found.");return w}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=W.isAbsolute(c)?c:this.buildOutputPath(o.srcPath,r,["outputs",t,c]);if(!re.existsSync(l))throw new x(`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 re.existsSync(s)?i:null}buildOutputPath(e,t,r){let o=R.resolvePathWithinRoot(this.rootDir,e),i=W.resolve(o,"build",t,...r);return R.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=re.readFileSync(e,"utf-8"),o=Lt.parse(r),i,s=!1,a=Array.isArray(o)?o:[o];for(let l of a)i||(i=l[t]),s||(s=l.isSigned===!0);if(!i)throw new x(`Could not find ${t} in output_metadata.json at ${e}`,"Could not find metadataKey in output_metadata.json at metadataPath.");this.validatePackageName(i);let c=this.collectRemoteHsps(a);return{packageName:i,isSigned:s,dependRemoteHsps:c}}validatePackageName(e){let t=W.basename(e);if(t!==e)throw new x(`Invalid traversal name: '${e}'. It must contain path characters.`,"Invalid traversal name.");if(!t.endsWith(".hap")&&!t.endsWith(".hsp"))throw new x(`Invalid package name '${t}'.It must be a .hap or .hsp file.`,"Invalid package name.")}};import we from"fs";import*as Ye from"os";import*as S from"path";import Up from"fs";import*as is from"os";import*as os from"path";import gb from"regedit";import{execFileSync as fb}from"child_process";import jp from"fs";import*as $p from"os";import*as ol from"path";function rs(n,e){let t=ol.join(n,"Contents","Info.plist");if(!jp.existsSync(t)){m(`[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=fb(r,o,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(i&&!i.includes("Does Not Exist"))return i}catch{}}function hb(n){let e=rs(n,"CFBundleShortVersionString");if(!e)return rs(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[rs(n,"CFBundleVersion"),rs(n,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let o of r){let i=o?.split(".").at(-1)?.replace(new RegExp(`^${t}`),"");if(i&&/^\d+$/.test(i))return`${e}.${i}`}return e}function yr(n){if($p.platform()==="darwin")return hb(n);let e=ol.join(n,"product-info.json");try{let t=JSON.parse(jp.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}function Do(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 yb(n){return n.filter(e=>{try{return Up.statSync(e).isDirectory()}catch{return!1}})}function wb(){let n=[];for(let e of[os.join(is.homedir(),"Applications"),"/Applications"])try{n.push(...Up.readdirSync(e).filter(t=>t.endsWith(".app")&&t.toLowerCase().includes("deveco")).map(t=>os.join(e,t)))}catch{}return n}function Hp(n){return new Promise((e,t)=>gb.list(n,(r,o)=>r?t(r):e(o)))}async function Bp(n,e,t){let o=((await Hp([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(o.length===0)return[];let i=await Hp(o);return o.flatMap(s=>{let a=i[s]?.values?.[t]?.value;return a?[a]:[]})}async function vb(){let n=[os.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 Bp(e,t=>t.normalize("NFKC").trim().toLowerCase().startsWith("deveco studio"),"InstallLocation"))}catch{}for(let e of["HKLM\\SOFTWARE\\Huawei\\DevEco Studio","HKLM\\SOFTWARE\\WOW6432Node\\Huawei\\DevEco Studio"])try{n.push(...await Bp(e,()=>!0,""))}catch{}return n}async function Wp(){let n=is.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"?wb():await vb(),t=yb(e).flatMap(r=>{let o=yr(r);return o?(m(`[ToolProvider] ${r} => version ${o}`),[{root:r,version:o}]):(m(`[ToolProvider] Skipping ${r}: could not read version`),[])});if(!t.length)throw new Error("DevEco Studio installation not found in default locations.");return t.reduce((r,o)=>Do(o.version,r.version)>0?o:r)}import*as Vp from"fs";import*as Oe from"path";function il(n,e){let t=Oe.relative(e,n);return t===""||!Oe.isAbsolute(t)&&!t.startsWith(`..${Oe.sep}`)&&t!==".."}function Ct(n){let e=Oe.resolve(n),t=[],r=e;for(;;)try{let o=Vp.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 ss(n,e){let t=Ct(e),r=Ct(n);return il(r,t)?r:null}function as(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function cs(n){let e=as(n);if(!e)throw new Error("Path must not be empty.");return Ct(e)}import{homedir as sn}from"os";import Ot from"path";import{xdgConfig as Sb}from"xdg-basedir";var ye={"trae-cn":Ot.join(sn(),".trae-cn"),opencode:Ot.join(Sb,"opencode"),cursor:Ot.join(sn(),".cursor"),codebuddy:Ot.join(sn(),".codebuddy"),qoder:Ot.join(sn(),".qoder"),"claude-code":Ot.join(sn(),".claude"),codex:Ot.join(sn(),".codex"),bitfun:Ot.join(sn(),".bitfun"),opendesk:Ot.join(sn(),".opendesk")};import an from"path";var sl="https://matrix.openharmony.cn",ut={TAGS_API_URL:`${sl}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${sl}/api/registry/skill/skills`,SKILL_API_BASE:`${sl}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},Gp={"trae-cn":{path:an.join(ye["trae-cn"],"skills"),displayName:"trae-cn"},opencode:{path:an.join(ye.opencode,"skills"),displayName:"opencode"},cursor:{path:an.join(ye.cursor,"skills"),displayName:"cursor"},codebuddy:{path:an.join(ye.codebuddy,"skills"),displayName:"codebuddy"},qoder:{path:an.join(ye.qoder,"skills"),displayName:"qoder"},"claude-code":{path:an.join(ye["claude-code"],"skills"),projectPath:".claude/skills",displayName:"claude-code"},codex:{path:an.join(ye.codex,"skills"),displayName:"codex"}},qp={opencode:{path:an.join(ye.opencode,"skills"),displayName:"opencode"}};function Mt(){return b()?qp:Gp}import{homedir as To}from"os";import ze from"path";var It="deveco-mcp";var cn={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:ze.join(ye.opencode,"opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:ze.join(process.platform==="win32"?ze.join(process.env.APPDATA??ze.join(To(),"AppData","Roaming"),"Trae CN","User"):ze.join(To(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:ze.join(ye.cursor,"mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:ze.join(ye.codebuddy,"mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:ze.join(process.platform==="win32"?ze.join(process.env.APPDATA??ze.join(To(),"AppData","Roaming"),"Qoder","SharedClientCache"):ze.join(To(),"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:ze.join(To(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:ze.join(ye.codex,"config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function Yp(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function zp(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Jp(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function ls(n,e){return n.format==="opencode"?Yp(e):n.format==="claude-code"||n.format==="codex"?zp(e):Jp(e)}var pt={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var al="https://developer.huawei.com/consumer/cn/download/";var bb=/^#\s*Version:\s*(\S+)/,Eb="26.0.0.810",Pb=["sdk","default","openharmony","native","llvm","bin","clangd"];function Cb(n){try{let e=JSON.parse(we.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch{return}}function Ib(n){let e=S.join(n,"default","openharmony");return[S.join(n,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>S.join(e,t,"oh-uni-package.json"))]}var A=class n{constructor(e,t,r,o,i,s,a,c,l,d,h="",w=""){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;this._clangdPath=h;this._lspServerPath=w}_sourceType;_toolchainRoot;_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;_clangdPath;_lspServerPath;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 javaPath(){return this._javaPath??""}get sdkPath(){return this._sdkPath}get hdcPath(){return this._hdcPath}get emulatorPath(){return this._emulatorPath}get emulatorLauncherPath(){return this.emulatorPath}get clangdPath(){return this._clangdPath&&we.existsSync(this._clangdPath)?this._clangdPath:""}get lspServerPath(){return this._lspServerPath&&we.existsSync(this._lspServerPath)?this._lspServerPath:""}assertJava(){if(!b()&&(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 Do(e,t)}static async checkVersion(){if(b())return;let e=await n.resolveInstallSource();(e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)).assertVersion()}static async new(){if(b())return n.fromOpenHarmony();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,n.resolveClangdPath(e),n.resolveLspServerPath(e))}static OPENHARMONY_STUDIO_ROOT="/data/service/hnp/hmos-clt.org/hmos-clt_1.0.0";static fromOpenHarmony(){let e=process.env.COMMAND_LINE_TOOL_PATH?.trim();if(!e&&!n.isDirectory(n.OPENHARMONY_STUDIO_ROOT))throw new Error("No toolchain found. Set COMMAND_LINE_TOOL_PATH.");return e?(m(`[ToolProvider] Using COMMAND_LINE_TOOL_PATH \u2192 ${e}`),n.buildOpenHarmonyProvider("clt",e)):(m("[ToolProvider] COMMAND_LINE_TOOL_PATH not set, using fallback DevEco Studio toolchain"),n.buildOpenHarmonyProvider("studio",n.OPENHARMONY_STUDIO_ROOT))}static buildOpenHarmonyToolPaths(e){let t=S.join(e,"sdk");return{nodePath:S.join(e,"node","bin","node"),ohpmJsPath:S.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:S.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:t,hdcPath:S.join(t,"default","openharmony","toolchains","hdc"),emulatorPath:"",clangdPath:S.join(e,"clangd","clangd"),lspServerPath:S.join(e,"ace-server","out","index.js")}}static buildOpenHarmonyProvider(e,t){let r=e==="clt"?"COMMAND_LINE_TOOL_PATH is invalid":"DevEco Studio toolchain is invalid";if(!n.isDirectory(t))throw new Error(`${r}: ${t} is not a valid directory.`);let o=n.buildOpenHarmonyToolPaths(t),i=Object.entries({node:o.nodePath,ohpm:o.ohpmJsPath,hvigor:o.hvigorJsPath,hdc:o.hdcPath}).filter(([,s])=>!s||!we.existsSync(s)).map(([s])=>s);if(i.length>0)throw new Error(`${r}: ${t} \u2014 missing required: ${i.join(", ")}.`);return n.assertBuiltPathsInsideRoot(t,o,!1),new n(e,t,e==="studio"?t:void 0,o.nodePath,o.ohpmJsPath,o.hvigorJsPath,"",o.sdkPath,o.hdcPath,o.emulatorPath,o.clangdPath,o.lspServerPath)}static devecoContentRootForClangd(e){return Ye.platform()==="darwin"&&e.endsWith(".app")?S.join(e,"Contents"):e}static clangdCandidatesFromDevecoHome(e){let t=new Set,r=[e,n.devecoContentRootForClangd(e)];for(let o of r){let i=S.join(o,...Pb);t.add(Ye.platform()==="win32"?i+".exe":i)}return[...t]}static resolveClangdPath(e){let t=n.clangdCandidatesFromDevecoHome(e);for(let r of t)if(we.existsSync(r))return r;return""}static resolveLspServerPath(e){let t=Ye.platform(),r;if(t==="win32")r=S.join(e,"plugins","openharmony");else if(t==="darwin")r=S.join(e,"Contents","plugins","openharmony");else return"";let o=S.join(r,"ace-server","out","index.js");return we.existsSync(o)?o:""}assertVersion(){if(this._sourceType==="clt"){this.assertCltVersion();return}this.assertIdeVersion()}readVersion(){return this._sourceType==="clt"?n.readCltVersion(this._toolchainRoot):yr(this._toolchainRoot)}assertCltVersion(e="26.0.0"){if(this._sourceType!=="clt")throw new Error("This operation requires Command Line Tools.");n.assertMinimumVersion(n.readCltVersion(this._toolchainRoot),"Command Line Tools","version.txt",e,this._toolchainRoot)}assertIdeVersion(e="6.1.0"){b()||(this.assertStudio(),n.assertMinimumVersion(yr(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 Error(`Failed to determine ${t} version from ${r} at ${i}`);if(!/^\d+(?:\.\d+){1,3}$/.test(e))throw new Error(`Invalid ${t} version "${e}" from ${r} at ${i}`);if(Do(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:
|
|
16
|
-
${
|
|
15
|
+
`,"utf8")}catch{return}try{await X.promises.unlink(e)}catch{}}takeNewestWithinBudget(e,t){if(t<=0)return[];let r=[],o=0;for(let i=e.length-1;i>=0;i--){let s=Buffer.byteLength(e[i],"utf8")+1;if(o+s>t)break;o+=s,r.push(e[i])}return r.reverse(),r}};var I=new Do;import{spawn as db}from"child_process";import{existsSync as ub}from"fs";import{dirname as pb,join as mb}from"path";import{fileURLToPath as fb}from"url";function hb(){let n=pb(fb(import.meta.url)),e=mb(n,"internal","telemetry-upload-background.js");return ub(e)?e:null}function il(n){if(Ze()||!Hp(n))return;let e=hb();if(!e){g.warn("[telemetry] background upload script not found, skipping spawn");return}try{db(process.execPath,[e],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1",DEVECO_CLI_TELEMETRY_UPLOAD:"1"}}).unref()}catch(t){g.warn("[telemetry] failed to spawn background upload:",t)}}var R=class extends Error{traceMessage;constructor(e,t,r){super(e,r),this.name="TraceError",this.traceMessage=t??e}};function Y(n){if(n instanceof R)return n.traceMessage;if(n instanceof Error){let e=n.code;return typeof e=="string"&&e!==""?e:n.name}return"UnknownError"}var A={CommandExecuted:"Command_executed",McpToolCall:"serve_mcp",SkillOperation:"skills",Init:"mcp_config_operation",SkillConfigOperation:"skill_config_operation",DocOperation:"docs",ServeLsp:"serve_lsp",CheckCommand:"check"};var J=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=B.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=B.join(e,"build-profile.json5");if(!re.existsSync(t))return null;try{let r=re.readFileSync(t,"utf-8"),o=Nt.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 R(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=x.resolvePathWithinRoot(this.rootDir,t.srcPath),o=B.join(r,"src","main","module.json5");if(!re.existsSync(o))return"entry";try{let i=re.readFileSync(o,"utf-8");return Nt.parse(i)?.module?.type||"entry"}catch(i){return console.warn(`Warning: Failed to parse ${o}:`,i),"entry"}}findOwningModule(e){let t=B.normalize(e);for(let r of this.profile.modules){let o=B.normalize(B.join(this.rootDir,r.srcPath)),i=o+B.sep;if(t.startsWith(i)||t===o)return r.name}return null}getModuleProfile(e){let t=this.profile.modules.find(a=>a.name===e);if(!t)throw new R(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=x.resolvePathWithinRoot(this.rootDir,t.srcPath),o=B.join(r,"build-profile.json5");if(!re.existsSync(o))throw new R(`Build profile for module '${e}' not found at ${o}.`,"Build profile for module not found at ${profilePath}.");let i=re.readFileSync(o,"utf-8");return Nt.parse(i)}getBundleName(){let e=B.join(this.rootDir,"AppScope","app.json5");if(re.existsSync(e))try{let t=re.readFileSync(e,"utf-8"),r=Nt.parse(t);if(r?.app?.bundleName)return r.app.bundleName}catch(t){console.warn(`Warning: Failed to parse ${e}:`,t)}throw new Error("Could not find bundleName in AppScope/app.json5.")}isAtomicService(){let e=B.join(this.rootDir,"AppScope","app.json5");if(!re.existsSync(e))return!1;try{let t=re.readFileSync(e,"utf-8");return Nt.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=x.resolvePathWithinRoot(this.rootDir,r.srcPath),i=B.join(o,"src","main","module.json5");if(!re.existsSync(i))return"EntryAbility";try{let s=re.readFileSync(i,"utf-8"),c=Nt.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 R(`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 R(`Product '${e}' not found in project configuration. Available products: ${r}`,"Productnot found in project configuration.")}}getModuleDependencies(e){let t=this.profile.modules.find(s=>s.name===e);if(!t)return[];let r=x.resolvePathWithinRoot(this.rootDir,t.srcPath),o=B.join(r,"oh-package.json5");if(!re.existsSync(o))return[];let i=[];try{let s=re.readFileSync(o,"utf-8"),c=Nt.parse(s)?.dependencies||{};for(let l of Object.values(c)){if(typeof l!="string")continue;let d=l;if(!(d.startsWith("file:")||d.startsWith(".")||d.startsWith("..")))continue;d.startsWith("file:")&&(d=d.substring(5));let w=B.join(t.srcPath,d),v=x.resolvePathWithinRoot(this.rootDir,w),T=this.profile.modules.find(ne=>B.resolve(this.rootDir,ne.srcPath)===v);T&&i.push(T.name)}}catch{}return i}getModuleName(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)return e;let r=x.resolvePathWithinRoot(this.rootDir,t.srcPath),o=B.join(r,"src","main","module.json5");if(!re.existsSync(o))return e;try{let i=re.readFileSync(o,"utf-8");return Nt.parse(i)?.module?.name||e}catch(i){return console.warn(`Warning: Failed to parse ${o}:`,i),e}}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 R(`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(!re.existsSync(a))throw new R(`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 v=this.getSignedHapName(c,i.srcPath,o,t);v&&(d=v)}let h=s?"-signed.hsp":"-signed.hap";if(!r&&!d.endsWith(h))throw new R(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`,"Target device is a real device, but the artifact is not signed.");let w=this.buildOutputPath(i.srcPath,o,["outputs",t,d]);if(!re.existsSync(w))throw new R(`Generated package file not found in ${w}.`,"Generated package file not found.");return w}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=B.isAbsolute(c)?c:this.buildOutputPath(o.srcPath,r,["outputs",t,c]);if(!re.existsSync(l))throw new R(`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 re.existsSync(s)?i:null}buildOutputPath(e,t,r){let o=x.resolvePathWithinRoot(this.rootDir,e),i=B.resolve(o,"build",t,...r);return x.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=re.readFileSync(e,"utf-8"),o=Nt.parse(r),i,s=!1,a=Array.isArray(o)?o:[o];for(let l of a)i||(i=l[t]),s||(s=l.isSigned===!0);if(!i)throw new R(`Could not find ${t} in output_metadata.json at ${e}`,"Could not find metadataKey in output_metadata.json at metadataPath.");this.validatePackageName(i);let c=this.collectRemoteHsps(a);return{packageName:i,isSigned:s,dependRemoteHsps:c}}validatePackageName(e){let t=B.basename(e);if(t!==e)throw new R(`Invalid traversal name: '${e}'. It must contain path characters.`,"Invalid traversal name.");if(!t.endsWith(".hap")&&!t.endsWith(".hsp"))throw new R(`Invalid package name '${t}'.It must be a .hap or .hsp file.`,"Invalid package name.")}};import ye from"fs";import*as qe from"os";import*as S from"path";import Yp from"fs";import*as as from"os";import*as ss from"path";import wb from"regedit";import{execFileSync as gb}from"child_process";import Vp from"fs";import*as Gp from"os";import*as sl from"path";function is(n,e){let t=sl.join(n,"Contents","Info.plist");if(!Vp.existsSync(t)){m(`[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=gb(r,o,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(i&&!i.includes("Does Not Exist"))return i}catch{}}function yb(n){let e=is(n,"CFBundleShortVersionString");if(!e)return is(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[is(n,"CFBundleVersion"),is(n,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let o of r){let i=o?.split(".").at(-1)?.replace(new RegExp(`^${t}`),"");if(i&&/^\d+$/.test(i))return`${e}.${i}`}return e}function wr(n){if(Gp.platform()==="darwin")return yb(n);let e=sl.join(n,"product-info.json");try{let t=JSON.parse(Vp.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}function To(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 vb(n){return n.filter(e=>{try{return Yp.statSync(e).isDirectory()}catch{return!1}})}function Sb(){let n=[];for(let e of[ss.join(as.homedir(),"Applications"),"/Applications"])try{n.push(...Yp.readdirSync(e).filter(t=>t.endsWith(".app")&&t.toLowerCase().includes("deveco")).map(t=>ss.join(e,t)))}catch{}return n}function zp(n){return new Promise((e,t)=>wb.list(n,(r,o)=>r?t(r):e(o)))}async function qp(n,e,t){let o=((await zp([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(o.length===0)return[];let i=await zp(o);return o.flatMap(s=>{let a=i[s]?.values?.[t]?.value;return a?[a]:[]})}async function bb(){let n=[ss.join("C:","Program Files","Huawei","DevEco Studio")];for(let e of["HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall","HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"])try{n.push(...await qp(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 qp(e,()=>!0,""))}catch{}return n}async function Jp(){let n=as.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"?Sb():await bb(),t=vb(e).flatMap(r=>{let o=wr(r);return o?(m(`[ToolProvider] ${r} => version ${o}`),[{root:r,version:o}]):(m(`[ToolProvider] Skipping ${r}: could not read version`),[])});if(!t.length)throw new Error("DevEco Studio installation not found in default locations.");return t.reduce((r,o)=>To(o.version,r.version)>0?o:r)}import*as Kp from"fs";import*as Ne from"path";function al(n,e){let t=Ne.relative(e,n);return t===""||!Ne.isAbsolute(t)&&!t.startsWith(`..${Ne.sep}`)&&t!==".."}function Pt(n){let e=Ne.resolve(n),t=[],r=e;for(;;)try{let o=Kp.realpathSync(r);return t.length===0?o:Ne.join(o,...t.reverse())}catch(o){if(o.code!=="ENOENT")throw o;let i=Ne.dirname(r);if(i===r)return e;t.push(Ne.basename(r)),r=i}}function cs(n,e){let t=Pt(e),r=Pt(n);return al(r,t)?r:null}function ls(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function ds(n){let e=ls(n);if(!e)throw new Error("Path must not be empty.");return Pt(e)}import{homedir as on}from"os";import Ot from"path";import{xdgConfig as Eb}from"xdg-basedir";var ge={"trae-cn":Ot.join(on(),".trae-cn"),opencode:Ot.join(Eb,"opencode"),cursor:Ot.join(on(),".cursor"),codebuddy:Ot.join(on(),".codebuddy"),qoder:Ot.join(on(),".qoder"),"claude-code":Ot.join(on(),".claude"),codex:Ot.join(on(),".codex"),bitfun:Ot.join(on(),".bitfun"),opendesk:Ot.join(on(),".opendesk")};import sn from"path";var cl="https://matrix.openharmony.cn",dt={TAGS_API_URL:`${cl}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${cl}/api/registry/skill/skills`,SKILL_API_BASE:`${cl}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},Xp={"trae-cn":{path:sn.join(ge["trae-cn"],"skills"),displayName:"trae-cn"},opencode:{path:sn.join(ge.opencode,"skills"),displayName:"opencode"},cursor:{path:sn.join(ge.cursor,"skills"),displayName:"cursor"},codebuddy:{path:sn.join(ge.codebuddy,"skills"),displayName:"codebuddy"},qoder:{path:sn.join(ge.qoder,"skills"),displayName:"qoder"},"claude-code":{path:sn.join(ge["claude-code"],"skills"),projectPath:".claude/skills",displayName:"claude-code"},codex:{path:sn.join(ge.codex,"skills"),displayName:"codex"}},Zp={opencode:{path:sn.join(ge.opencode,"skills"),displayName:"opencode"}};function Lt(){return b()?Zp:Xp}import{homedir as Ro}from"os";import ze from"path";var Ct="deveco-mcp";var an={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:ze.join(ge.opencode,"opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:ze.join(process.platform==="win32"?ze.join(process.env.APPDATA??ze.join(Ro(),"AppData","Roaming"),"Trae CN","User"):ze.join(Ro(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:ze.join(ge.cursor,"mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:ze.join(ge.codebuddy,"mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:ze.join(process.platform==="win32"?ze.join(process.env.APPDATA??ze.join(Ro(),"AppData","Roaming"),"Qoder","SharedClientCache"):ze.join(Ro(),"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:ze.join(Ro(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:ze.join(ge.codex,"config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function em(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function Qp(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function tm(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function us(n,e){return n.format==="opencode"?em(e):n.format==="claude-code"||n.format==="codex"?Qp(e):tm(e)}var ut={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var ll="https://developer.huawei.com/consumer/cn/download/";var Pb=/^#\s*Version:\s*(\S+)/,Cb="26.0.0.810",Ib=["sdk","default","openharmony","native","llvm","bin","clangd"];function Ab(n){try{let e=JSON.parse(ye.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch{return}}function Db(n){let e=S.join(n,"default","openharmony");return[S.join(n,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>S.join(e,t,"oh-uni-package.json"))]}var D=class n{constructor(e,t,r,o,i,s,a,c,l,d,h="",w=""){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;this._clangdPath=h;this._lspServerPath=w}_sourceType;_toolchainRoot;_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;_clangdPath;_lspServerPath;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 javaPath(){return this._javaPath??""}get sdkPath(){return this._sdkPath}get hdcPath(){return this._hdcPath}get emulatorPath(){return this._emulatorPath}get emulatorLauncherPath(){return this.emulatorPath}get clangdPath(){return this._clangdPath&&ye.existsSync(this._clangdPath)?this._clangdPath:""}get lspServerPath(){return this._lspServerPath&&ye.existsSync(this._lspServerPath)?this._lspServerPath:""}assertJava(){if(!b()&&(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 To(e,t)}static async checkVersion(){if(b())return;let e=await n.resolveInstallSource();(e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)).assertVersion()}static async new(){if(b())return n.fromOpenHarmony();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,n.resolveClangdPath(e),n.resolveLspServerPath(e))}static OPENHARMONY_STUDIO_ROOT="/data/service/hnp/hmos-clt.org/hmos-clt_1.0.0";static fromOpenHarmony(){let e=process.env.COMMAND_LINE_TOOL_PATH?.trim();if(!e&&!n.isDirectory(n.OPENHARMONY_STUDIO_ROOT))throw new Error("No toolchain found. Set COMMAND_LINE_TOOL_PATH.");return e?(m(`[ToolProvider] Using COMMAND_LINE_TOOL_PATH \u2192 ${e}`),n.buildOpenHarmonyProvider("clt",e)):(m("[ToolProvider] COMMAND_LINE_TOOL_PATH not set, using fallback DevEco Studio toolchain"),n.buildOpenHarmonyProvider("studio",n.OPENHARMONY_STUDIO_ROOT))}static buildOpenHarmonyToolPaths(e){let t=S.join(e,"sdk");return{nodePath:S.join(e,"node","bin","node"),ohpmJsPath:S.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:S.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:t,hdcPath:S.join(t,"default","openharmony","toolchains","hdc"),emulatorPath:"",clangdPath:S.join(e,"clangd","clangd"),lspServerPath:S.join(e,"ace-server","out","index.js")}}static buildOpenHarmonyProvider(e,t){let r=e==="clt"?"COMMAND_LINE_TOOL_PATH is invalid":"DevEco Studio toolchain is invalid";if(!n.isDirectory(t))throw new Error(`${r}: ${t} is not a valid directory.`);let o=n.buildOpenHarmonyToolPaths(t),i=Object.entries({node:o.nodePath,ohpm:o.ohpmJsPath,hvigor:o.hvigorJsPath,hdc:o.hdcPath}).filter(([,s])=>!s||!ye.existsSync(s)).map(([s])=>s);if(i.length>0)throw new Error(`${r}: ${t} \u2014 missing required: ${i.join(", ")}.`);return n.assertBuiltPathsInsideRoot(t,o,!1),new n(e,t,e==="studio"?t:void 0,o.nodePath,o.ohpmJsPath,o.hvigorJsPath,"",o.sdkPath,o.hdcPath,o.emulatorPath,o.clangdPath,o.lspServerPath)}static devecoContentRootForClangd(e){return qe.platform()==="darwin"&&e.endsWith(".app")?S.join(e,"Contents"):e}static clangdCandidatesFromDevecoHome(e){let t=new Set,r=[e,n.devecoContentRootForClangd(e)];for(let o of r){let i=S.join(o,...Ib);t.add(qe.platform()==="win32"?i+".exe":i)}return[...t]}static resolveClangdPath(e){let t=n.clangdCandidatesFromDevecoHome(e);for(let r of t)if(ye.existsSync(r))return r;return""}static resolveLspServerPath(e){let t=qe.platform(),r;if(t==="win32")r=S.join(e,"plugins","openharmony");else if(t==="darwin")r=S.join(e,"Contents","plugins","openharmony");else return"";let o=S.join(r,"ace-server","out","index.js");return ye.existsSync(o)?o:""}assertVersion(){if(this._sourceType==="clt"){this.assertCltVersion();return}this.assertIdeVersion()}readVersion(){return this._sourceType==="clt"?n.readCltVersion(this._toolchainRoot):wr(this._toolchainRoot)}assertCltVersion(e="26.0.0"){if(this._sourceType!=="clt")throw new Error("This operation requires Command Line Tools.");n.assertMinimumVersion(n.readCltVersion(this._toolchainRoot),"Command Line Tools","version.txt",e,this._toolchainRoot)}assertIdeVersion(e="6.1.0"){b()||(this.assertStudio(),n.assertMinimumVersion(wr(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 Error(`Failed to determine ${t} version from ${r} at ${i}`);if(!/^\d+(?:\.\d+){1,3}$/.test(e))throw new Error(`Invalid ${t} version "${e}" from ${r} at ${i}`);if(To(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:
|
|
16
|
+
${ll}`)}static resolveCodelinterPath(e,t){let r=n.getCodelinterCandidates(e,t),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 Error(`${a}
|
|
17
17
|
Searched paths:
|
|
18
18
|
${r.join(`
|
|
19
|
-
`)}`)}let i=
|
|
20
|
-
`)){let r=t.trim().split(/\s+/);if(r.length<3)continue;let o=Number(r[0]),i=Number(r[1]),s=Number(r[2]);isNaN(o)||isNaN(i)||isNaN(s)||e.push({pid:o,ppid:i,rssBytes:s*1024})}return e}function
|
|
21
|
-
`)){let r=t.trim();if(!r)continue;let o=r.split(",");if(o.length<3)continue;let i=Number(o[0]),s=Number(o[1]),a=Number(o[2]);isNaN(i)||isNaN(s)||isNaN(a)||e.push({pid:i,ppid:s,rssBytes:a})}return e}function tm(n,e){let t=new Map,r=new Map;for(let a of n){t.set(a.pid,a.rssBytes);let c=r.get(a.ppid);c?c.push(a.pid):r.set(a.ppid,[a.pid])}let o=0,i=new Set,s=[e];for(;s.length>0;){let a=s.shift();if(i.has(a))continue;i.add(a),o+=t.get(a)??0;let c=r.get(a);c&&s.push(...c)}return o}async function Nb(n){let e=await kb();return tm(e,n)}function Lb(n){if(process.platform==="darwin"){let e=(n/1e3).toFixed(1),t=`while true; do ps -ax -o pid=,ppid=,rss=; echo '${ll}'; sleep ${e}; done`;return m(`Executing: sh -c ${t}`),Kp("sh",["-c",t],{stdio:["ignore","pipe","ignore"],windowsHide:!0})}if(process.platform==="win32"&&Zp()){let e=`while ($true) { Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId),$($_.ParentProcessId),$($_.WorkingSetSize)" }; Write-Output '${ll}'; Start-Sleep -Milliseconds ${n} }`;return m(`Executing: ${us} -NoProfile -Command ${e}`),Kp(us,["-NoProfile","-Command",e],{stdio:["ignore","pipe","ignore"],windowsHide:!0})}return null}function At(n){return`${(n/1024/1024).toFixed(2)}MB`}async function Xp(n,e){if(!n)return process.memoryUsage().rss;if(e)return Nb(n);let t=await ko(n);return t?Number(t)*1024:0}function ps(n,e=500,t=!1){let r=0,o=!1,i=a=>{if(o||!n)return;let c=t?tm(a,n):a.find(l=>l.pid===n)?.rssBytes??0;c>r&&(r=c)};if(!n)return Mb(e);if(process.platform==="linux")return _b(e,i,()=>r);let s=Lb(e);return s?(Ob(s,i),{stop:async()=>{o=!0;try{s.kill()}catch{}let a=await Xp(n,t);return Math.max(r,a)}}):{stop:async()=>{o=!0;let a=await Xp(n,t);return Math.max(r,a)}}}function Ob(n,e){let t=process.platform==="darwin"?Qp:em,r="";n.stdout?.on("data",o=>{r+=o.toString();let i=r.split(ll);r=i.pop()??"";for(let s of i)e(t(s))}),n.on("error",()=>{})}function Mb(n){let e=process.memoryUsage().rss,t=setInterval(()=>{let r=process.memoryUsage().rss;r>e&&(e=r)},n);return{stop:async()=>(clearInterval(t),Math.max(e,process.memoryUsage().rss))}}function _b(n,e,t){e(ds());let r=setInterval(()=>e(ds()),n);return{stop:async()=>(clearInterval(r),e(ds()),t())}}function Fb(n){let e=n.trim().match(/^(\d+)$/);return e?e[1]:null}function jb(n){let e=n.match(/"([^"]+?)\s*K"/i);return e&&e[1].replace(/\D/g,"")||null}var Me=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let o={...process.env,DEVECO_SDK_HOME:e.sdkPath};if(e.javaPath){let i=_t.dirname(e.javaPath);o.PATH=`${i}${_t.delimiter}${process.env.PATH||""}`,e.sourceType==="clt"&&(o.JAVA_HOME=_t.dirname(i))}b()&&(o.HVIGOR_USER_HOME=_t.join(ul.homedir(),".hvigor")),this.env=o}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 b()?"":this.runHvigor(["--stop-daemon"])}async ensureDaemonRunning(){if(this.findProjectDaemon()){m("[HvigorAdapter] Daemon already running.");return}m("[HvigorAdapter] No daemon running, starting via --sync --daemon (no hap build)."),await this.runHvigor(["--sync","--daemon"])}isDaemonRunning(e){return this.findProjectDaemon(e)!==null}findProjectDaemon(e){let t=this.getDaemonRegistryPath();if(!ms.existsSync(t))return null;try{let r=ms.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||_t.join(ul.homedir(),".hvigor");return _t.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){b()&&(e=e.includes("--no-daemon")?e:["--no-daemon",...e]);let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];m(`Executing: ${t} ${r.join(" ")}`);let o=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit",i=$b(t,r,{cwd:this.projectRoot,env:this.env,stdout:o,stderr:o}),s=Qe()?void 0:ps(i.pid,500,!0),a="";try{await i}finally{if(s){let c=await s.stop();c>0&&(a=At(c),m(`Hvigor peak memory: ${a}`))}}return a}};import{execa as Hb}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=["--no-deprecation",this.toolProvider.ohpmJsPath,"install","--all"];m(`Executing: ${e} ${t.join(" ")}`);let r=Hb(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"}),o=Qe()?void 0:ps(r.pid,500,!1);try{await r}finally{if(o){let i=await o.stop();i>0&&(this.peakMemoryMb=At(i))}}}};import{mkdir as Bb}from"fs/promises";import{dirname as Ub,resolve as Wb}from"path";import{execa as Vb}from"execa";import{lock as pl,check as U0}from"proper-lockfile";function ml(n){return Wb(n,".hvigor",".build-lock")}function Gb(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function nm(n){let e=Ub(ml(n));if(await Bb(e,{recursive:!0}),process.platform==="win32")try{await Vb("attrib",["+h",e])}catch{}}async function qb(n,e){let t=new AbortController,r=Gb(e);await nm(n);let o={lockfilePath:ml(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await pl(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 pl(n,{...o,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Ft(n,e,t){let{release:r,signal:o}=await qb(n,t);try{return await e(o)}finally{await r()}}async function fs(n,e){let t=new AbortController;await nm(n);let r={lockfilePath:ml(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},o;try{o=await pl(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 dn from"fs";import*as Gn from"path";import zb from"json5";var Yb=1e3;function gs(n){m(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=Gn.join(n,pt.SYNC_OUTPUT_PATH);if(!dn.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return m(`[ProjectCheck] ${l.reason}`),l}let t=dn.statSync(e).mtimeMs;m(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Jb(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return m(`[ProjectCheck] ${l.reason}`),l}let o=Gn.join(n,pt.OH_PACKAGE_JSON5),i=hs(o,t,"root");if(i.required)return m(`[ProjectCheck] Root check: ${i.reason}`),i;let s=Gn.join(n,pt.BUILD_PROFILE_JSON5),a=hs(s,t,"build-profile");if(a.required)return m(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let d=Gn.join(n,l.srcPath,pt.OH_PACKAGE_JSON5),h=hs(d,t,l.name);if(h.required)return m(`[ProjectCheck] Module '${l.name}' check: ${h.reason}`),h;let w=Gn.join(n,l.srcPath,pt.BUILD_PROFILE_JSON5),v=hs(w,t,l.name);if(v.required)return m(`[ProjectCheck] Module '${l.name}' build-profile check: ${v.reason}`),v}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return m(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function hs(n,e,t){if(!dn.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=dn.statSync(n).mtimeMs;return r-e>Yb?{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 Jb(n){let e=Gn.join(n,pt.BUILD_PROFILE_JSON5);try{let t=dn.readFileSync(e,"utf-8");if(!t.trim())return null;let r=zb.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 Ke from"fs";import*as ft from"path";import*as rm from"util";var fl="";function ws(n){if(!n||n==="auto"||n==="stdout"||n==="none"){fl="";return}fl=n}function om(){return fl||(Dp()??"")}function ys(n,...e){if(e.length===0)return n;try{return rm.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var f={info(n,...e){g.info(`[lsp] ${ys(n,...e)}`)},warn(n,...e){g.warn(`[lsp] ${ys(n,...e)}`)},error(n,...e){g.error(`[lsp] ${ys(n,...e)}`)},debug(n,...e){g.debug(`[lsp] ${ys(n,...e)}`)}};import*as Ro from"fs";import*as xo from"os";import*as wr from"path";import Kb 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"},N="2.0";var im=8192,hl=100,sm=.03,am=.7,et=900*1e3,vs="/data/app/sdk.org/sdk_1.0.0";function Je(n){if(!Ro.existsSync(n))return null;try{let e=Ro.readFileSync(n,"utf-8");return e.trim()?Kb.parse(e):null}catch{return null}}function Ss(n,e){let t=Math.floor(xo.totalmem()/1048576),r=Math.floor(t*am),o,i;e!==void 0&&Number.isFinite(e)&&e>0?(o=e,i=`override(${e})`):(o=im,n>hl&&(o+=(n-hl)*sm*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 mt(n){if(n.startsWith("file:"))return n;try{let e=wr.resolve(n),t=new URL(`file://${e}`).toString();if(xo.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 vr(n){return n&&n.replace(/\\/g,"/")}function G(n){let e=wr.normalize(n).replace(/\\/g,"/");if(xo.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function cm(n){return wr.join(n,"build-profile.json5")}var jt=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=cm(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*as lm from"os";import*as dm from"path";import{spawn as Xb}from"child_process";var Zb=600*1e3;function Qb(n){let e=[],t=[];return n.stdout?.on("data",r=>{e.push(r.toString())}),n.stderr?.on("data",r=>{t.push(r.toString())}),{stdout:e,stderr:t}}function bs(n){return n.join("")}function eE(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
19
|
+
`)}`)}let i=Pt(e),s=Pt(o);return n.assertInsideRoot(s,i,"codelinter"),s}static getCodelinterCandidates(e,t){if(t==="studio"){if(b())return[S.join(e,"codelinter","index.js")];let r=qe.platform()==="darwin"?["Contents"]:[];return[S.join(e,...r,"plugins","codelinter","run","index.js"),S.join(e,...r,"plugins","codelinter","index.js"),S.join(e,...r,"tools","codelinter","bin","codelinter.js"),S.join(e,...r,"tools","codelinter","codelinter.js")]}return[S.join(e,"codelinter","index.js"),S.join(e,"codelinter","run","index.js"),S.join(e,"tool","codelinter","bin","codelinter.js"),S.join(e,"tool","codelinter","codelinter.js")]}static isValidRoot(e,t){if(!n.isDirectory(e))return!1;if(t==="clt")return ye.existsSync(S.join(e,"version.txt"));let r=qe.platform()==="darwin"?S.join(e,"Contents"):e,o=qe.platform()==="darwin"?S.join(r,"Info.plist"):S.join(r,"product-info.json");if(!ye.existsSync(o))return!1;let i=n.buildToolPaths(e,"studio");return[i.nodePath,i.ohpmJsPath,i.hvigorJsPath].every(ye.existsSync)}static buildToolPaths(e,t){return t==="clt"?n.buildCltToolPaths(e):n.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=S.join(e,"sdk"),r=qe.platform()==="win32",o=r?".exe":"";return{nodePath:r?S.join(e,"tool","node","node.exe"):S.join(e,"tool","node","bin","node"),ohpmJsPath:S.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:S.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:t,hdcPath:S.join(t,"default","openharmony","toolchains",`hdc${o}`),emulatorPath:S.join(e,"emulator",r?"Emulator.exe":"Emulator")}}static buildStudioToolPaths(e){let t=qe.platform()==="darwin",r=qe.platform()==="win32",o=t?S.join(e,"Contents"):e,i=S.join(o,"tools"),s=S.join(o,"sdk"),a=r?".exe":"";return{nodePath:r?S.join(i,"node","node.exe"):S.join(i,"node","bin","node"),ohpmJsPath:S.join(i,"ohpm","bin","pm-cli.js"),hvigorJsPath:S.join(i,"hvigor","bin","hvigorw.js"),javaPath:r?S.join(e,"jbr","bin","java.exe"):t?S.join(o,"jbr","Contents","Home","bin","java"):S.join(o,"jbr","bin","java"),sdkPath:s,hdcPath:S.join(s,"default","openharmony","toolchains",`hdc${a}`),emulatorPath:S.join(i,"emulator",r?"Emulator.exe":"Emulator")}}static isFile(e){try{return ye.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return ye.existsSync(e)&&ye.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 m(`[ToolProvider] Using ${r} \u2192 ${a}`),{sourceType:i,toolchainRoot:a}}}let t=await Jp();return m(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,r){let o;try{o=ds(e)}catch(i){throw new Error(`Invalid ${r}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return t==="studio"&&qe.platform()==="darwin"&&(o=n.normalizeMacStudioRoot(o)),n.isValidRoot(o,t)?o:n.throwInvalidSource(o,t,r,e)}static assertBuiltPathsInsideRoot(e,t,r){let o=Pt(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)a&&n.assertInsideRoot(a,o,s)}static assertInsideRoot(e,t,r){if(cs(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=`${S.sep}Contents`,r=S.normalize(e);return r.endsWith(t)?r.slice(0,-t.length):r}static readCltVersion(e){try{return ye.readFileSync(S.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(Pb)?.[1]?.trim()).find(Boolean)}catch{return}}static resolveCltJava(e){let t=process.env.JAVA_HOME?.trim(),r=t&&(n.javaIn(S.join(t,"bin"))??n.javaIn(t)),o=(process.env.Path??process.env.PATH??"").split(S.delimiter).map(s=>n.javaIn(s.trim())).find(Boolean),i=r??o;if(i)return ye.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(qe.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(r=>S.join(e,r)).find(ye.existsSync)}getMaxApiLevel(){for(let e of Db(this.sdkPath)){let t=Ab(e);if(t!==void 0)return t}return 23}detectApiLevel(){return this.getMaxApiLevel()}_apiscanPaths;getApiscanPaths(){if(this._apiscanPaths)return this._apiscanPaths;let e=qe.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=S.join(this._devecoStudioPath,t,"plugins","harmony","arkanalyzer-apiscan"),o=S.join(r,"resources","apiChange"),i=S.join(r,"api-change-scan.js");if(!ye.existsSync(o)||!ye.existsSync(i)){let s=wr(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${Cb}. Upgrade before using 'check compat' at ${ll}`)}return this._apiscanPaths={apiChangeDir:o,scriptPath:i},this._apiscanPaths}};import{execa as Ub}from"execa";import*as Mt from"path";import*as hs from"fs";import*as ml from"os";import{execFile as pl,spawn as nm}from"child_process";import{existsSync as Tb,readdirSync as Rb,readFileSync as kb}from"fs";var ms="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",dl,ul="---MEMORY-SAMPLE-DELIMITER---";function om(){return dl===void 0&&(dl=Tb(ms)),dl}function ko(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)];m(`Executing: ${r} ${o.join(" ")}`),pl(r,o,{timeout:5e3,windowsHide:!0},(i,s)=>{if(i){e(null);return}e(t?Hb(s):$b(s))})})}async function xb(){return process.platform==="linux"?ps():process.platform==="darwin"?Nb():process.platform==="win32"?Ob():[]}function ps(){let n=[],e;try{e=Rb("/proc")}catch{return n}for(let t of e){if(!/^\d+$/.test(t))continue;let r=Number(t);try{let o=kb(`/proc/${r}/status`,"utf8"),i=o.match(/VmRSS:\s+(\d+)\s+kB/),s=o.match(/^PPid:\s+(\d+)/m);if(!i||!s)continue;n.push({pid:r,ppid:Number(s[1]),rssBytes:Number(i[1])*1024})}catch{}}return n}function Nb(){return new Promise(n=>{pl("ps",["-ax","-o","pid=,ppid=,rss="],{timeout:5e3,windowsHide:!0},(e,t)=>{if(e){n([]);return}n(im(t))})})}function im(n){let e=[];for(let t of n.trim().split(`
|
|
20
|
+
`)){let r=t.trim().split(/\s+/);if(r.length<3)continue;let o=Number(r[0]),i=Number(r[1]),s=Number(r[2]);isNaN(o)||isNaN(i)||isNaN(s)||e.push({pid:o,ppid:i,rssBytes:s*1024})}return e}function Ob(){return new Promise(n=>{if(!om()){n([]);return}pl(ms,["-NoProfile","-Command",'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId),$($_.ParentProcessId),$($_.WorkingSetSize)" }'],{timeout:5e3,windowsHide:!0},(t,r)=>{if(t){n([]);return}n(sm(r))})})}function sm(n){let e=[];for(let t of n.trim().split(`
|
|
21
|
+
`)){let r=t.trim();if(!r)continue;let o=r.split(",");if(o.length<3)continue;let i=Number(o[0]),s=Number(o[1]),a=Number(o[2]);isNaN(i)||isNaN(s)||isNaN(a)||e.push({pid:i,ppid:s,rssBytes:a})}return e}function am(n,e){let t=new Map,r=new Map;for(let a of n){t.set(a.pid,a.rssBytes);let c=r.get(a.ppid);c?c.push(a.pid):r.set(a.ppid,[a.pid])}let o=0,i=new Set,s=[e];for(;s.length>0;){let a=s.shift();if(i.has(a))continue;i.add(a),o+=t.get(a)??0;let c=r.get(a);c&&s.push(...c)}return o}async function Lb(n){let e=await xb();return am(e,n)}function Mb(n){if(process.platform==="darwin"){let e=(n/1e3).toFixed(1),t=`while true; do ps -ax -o pid=,ppid=,rss=; echo '${ul}'; sleep ${e}; done`;return m(`Executing: sh -c ${t}`),nm("sh",["-c",t],{stdio:["ignore","pipe","ignore"],windowsHide:!0})}if(process.platform==="win32"&&om()){let e=`while ($true) { Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId),$($_.ParentProcessId),$($_.WorkingSetSize)" }; Write-Output '${ul}'; Start-Sleep -Milliseconds ${n} }`;return m(`Executing: ${ms} -NoProfile -Command ${e}`),nm(ms,["-NoProfile","-Command",e],{stdio:["ignore","pipe","ignore"],windowsHide:!0})}return null}function It(n){return`${(n/1024/1024).toFixed(2)}MB`}async function rm(n,e){if(!n)return process.memoryUsage().rss;if(e)return Lb(n);let t=await ko(n);return t?Number(t)*1024:0}function fs(n,e=500,t=!1){let r=0,o=!1,i=a=>{if(o||!n)return;let c=t?am(a,n):a.find(l=>l.pid===n)?.rssBytes??0;c>r&&(r=c)};if(!n)return Fb(e);if(process.platform==="linux")return jb(e,i,()=>r);let s=Mb(e);return s?(_b(s,i),{stop:async()=>{o=!0;try{s.kill()}catch{}let a=await rm(n,t);return Math.max(r,a)}}):{stop:async()=>{o=!0;let a=await rm(n,t);return Math.max(r,a)}}}function _b(n,e){let t=process.platform==="darwin"?im:sm,r="";n.stdout?.on("data",o=>{r+=o.toString();let i=r.split(ul);r=i.pop()??"";for(let s of i)e(t(s))}),n.on("error",()=>{})}function Fb(n){let e=process.memoryUsage().rss,t=setInterval(()=>{let r=process.memoryUsage().rss;r>e&&(e=r)},n);return{stop:async()=>(clearInterval(t),Math.max(e,process.memoryUsage().rss))}}function jb(n,e,t){e(ps());let r=setInterval(()=>e(ps()),n);return{stop:async()=>(clearInterval(r),e(ps()),t())}}function $b(n){let e=n.trim().match(/^(\d+)$/);return e?e[1]:null}function Hb(n){let e=n.match(/"([^"]+?)\s*K"/i);return e&&e[1].replace(/\D/g,"")||null}var Oe=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let o={...process.env,DEVECO_SDK_HOME:e.sdkPath};if(e.javaPath){let i=Mt.dirname(e.javaPath);o.PATH=`${i}${Mt.delimiter}${process.env.PATH||""}`,e.sourceType==="clt"&&(o.JAVA_HOME=Mt.dirname(i))}b()&&(o.HVIGOR_USER_HOME=Mt.join(ml.homedir(),".hvigor")),this.env=o}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 b()?"":this.runHvigor(["--stop-daemon"])}async ensureDaemonRunning(){if(this.findProjectDaemon()){m("[HvigorAdapter] Daemon already running.");return}m("[HvigorAdapter] No daemon running, starting via --sync --daemon (no hap build)."),await this.runHvigor(["--sync","--daemon"])}isDaemonRunning(e){return this.findProjectDaemon(e)!==null}findProjectDaemon(e){let t=this.getDaemonRegistryPath();if(!hs.existsSync(t))return null;try{let r=hs.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||Mt.join(ml.homedir(),".hvigor");return Mt.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){b()&&(e=e.includes("--no-daemon")?e:["--no-daemon",...e]);let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];m(`Executing: ${t} ${r.join(" ")}`);let o=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit",i=Ub(t,r,{cwd:this.projectRoot,env:this.env,stdout:o,stderr:o}),s=Ze()?void 0:fs(i.pid,500,!0),a="";try{await i}finally{if(s){let c=await s.stop();c>0&&(a=It(c),m(`Hvigor peak memory: ${a}`))}}return a}};import{execa as Bb}from"execa";var cn=class{toolProvider;projectRoot;peakMemoryMb="";constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=["--no-deprecation",this.toolProvider.ohpmJsPath,"install","--all"];m(`Executing: ${e} ${t.join(" ")}`);let r=Bb(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"}),o=Ze()?void 0:fs(r.pid,500,!1);try{await r}finally{if(o){let i=await o.stop();i>0&&(this.peakMemoryMb=It(i))}}}};import{mkdir as Wb}from"fs/promises";import{dirname as Vb,resolve as Gb}from"path";import{execa as zb}from"execa";import{lock as fl,check as x0}from"proper-lockfile";function hl(n){return Gb(n,".hvigor",".build-lock")}function qb(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function cm(n){let e=Vb(hl(n));if(await Wb(e,{recursive:!0}),process.platform==="win32")try{await zb("attrib",["+h",e])}catch{}}async function Yb(n,e){let t=new AbortController,r=qb(e);await cm(n);let o={lockfilePath:hl(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await fl(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 fl(n,{...o,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function _t(n,e,t){let{release:r,signal:o}=await Yb(n,t);try{return await e(o)}finally{await r()}}async function gs(n,e){let t=new AbortController;await cm(n);let r={lockfilePath:hl(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},o;try{o=await fl(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 ln from"fs";import*as Vn from"path";import Jb from"json5";var Kb=1e3;function ws(n){m(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=Vn.join(n,ut.SYNC_OUTPUT_PATH);if(!ln.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return m(`[ProjectCheck] ${l.reason}`),l}let t=ln.statSync(e).mtimeMs;m(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Xb(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return m(`[ProjectCheck] ${l.reason}`),l}let o=Vn.join(n,ut.OH_PACKAGE_JSON5),i=ys(o,t,"root");if(i.required)return m(`[ProjectCheck] Root check: ${i.reason}`),i;let s=Vn.join(n,ut.BUILD_PROFILE_JSON5),a=ys(s,t,"build-profile");if(a.required)return m(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let d=Vn.join(n,l.srcPath,ut.OH_PACKAGE_JSON5),h=ys(d,t,l.name);if(h.required)return m(`[ProjectCheck] Module '${l.name}' check: ${h.reason}`),h;let w=Vn.join(n,l.srcPath,ut.BUILD_PROFILE_JSON5),v=ys(w,t,l.name);if(v.required)return m(`[ProjectCheck] Module '${l.name}' build-profile check: ${v.reason}`),v}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return m(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function ys(n,e,t){if(!ln.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=ln.statSync(n).mtimeMs;return r-e>Kb?{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 Xb(n){let e=Vn.join(n,ut.BUILD_PROFILE_JSON5);try{let t=ln.readFileSync(e,"utf-8");if(!t.trim())return null;let r=Jb.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 Je from"fs";import*as mt from"path";import*as lm from"util";var gl="";function Ss(n){if(!n||n==="auto"||n==="stdout"||n==="none"){gl="";return}gl=n}function dm(){return gl||(Op()??"")}function vs(n,...e){if(e.length===0)return n;try{return lm.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var f={info(n,...e){g.info(`[lsp] ${vs(n,...e)}`)},warn(n,...e){g.warn(`[lsp] ${vs(n,...e)}`)},error(n,...e){g.error(`[lsp] ${vs(n,...e)}`)},debug(n,...e){g.debug(`[lsp] ${vs(n,...e)}`)}};import*as xo from"fs";import*as No from"os";import*as vr from"path";import Zb 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"},N="2.0";var um=8192,yl=100,pm=.03,mm=.7,Qe=900*1e3,bs="/data/app/sdk.org/sdk_1.0.0";function Ye(n){if(!xo.existsSync(n))return null;try{let e=xo.readFileSync(n,"utf-8");return e.trim()?Zb.parse(e):null}catch{return null}}function Es(n,e){let t=Math.floor(No.totalmem()/1048576),r=Math.floor(t*mm),o,i;e!==void 0&&Number.isFinite(e)&&e>0?(o=e,i=`override(${e})`):(o=um,n>yl&&(o+=(n-yl)*pm*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 pt(n){if(n.startsWith("file:"))return n;try{let e=vr.resolve(n),t=new URL(`file://${e}`).toString();if(No.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 Sr(n){return n&&n.replace(/\\/g,"/")}function V(n){let e=vr.normalize(n).replace(/\\/g,"/");if(No.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function fm(n){return vr.join(n,"build-profile.json5")}var Ft=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=fm(this.projectRoot);try{let t=Ye(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*as hm from"os";import*as gm from"path";import{spawn as Qb}from"child_process";var eE=600*1e3;function tE(n){let e=[],t=[];return n.stdout?.on("data",r=>{e.push(r.toString())}),n.stderr?.on("data",r=>{t.push(r.toString())}),{stdout:e,stderr:t}}function Ps(n){return n.join("")}function nE(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
22
22
|
Output so far:
|
|
23
|
-
`+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function
|
|
23
|
+
`+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function rE(n,e,t){return new Promise(r=>{let o=Qb(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:i,stderr:s}=tE(o),a=setTimeout(()=>{o.kill();let c=[Ps(i),Ps(s)].filter(Boolean).join(`
|
|
24
24
|
`).trim();r({success:!1,output:`Build process timeout after 10 minutes.
|
|
25
25
|
Output so far:
|
|
26
|
-
`+c,exitCode:-1})},
|
|
27
|
-
`).trim()||"";r(
|
|
28
|
-
[ohpm install] Running...`);try{await n.installAll()}catch(l){
|
|
29
|
-
[hvigor sync] Running...`);try{a=await e.sync(t,r)}catch(l){
|
|
26
|
+
`+c,exitCode:-1})},eE);o.on("close",(c,l)=>{clearTimeout(a);let d=[Ps(i),Ps(s)].filter(Boolean).join(`
|
|
27
|
+
`).trim()||"";r(nE(c,l,d))}),o.on("error",c=>{clearTimeout(a),r({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function wl(n,e,t,r,o){let i={...process.env,DEVECO_SDK_HOME:r};return b()&&(i.HVIGOR_USER_HOME=gm.join(hm.homedir(),".hvigor")),await rE([e,[t,...o]],n,i)}var oE=["--sync","-p","product=default","--analyze=normal","--parallel","--incremental","--no-daemon"];async function ym(n,e){try{return(await wl(n,e.nodePath,e.hvigorJsPath,e.sdkPath,oE)).success}catch(t){return f.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}function iE(n){let e=mt.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function sE(n,e){let t=mt.join(n,e.name);return e.isDirectory()?e.name===".cxx"||wm(t):iE(t)}function wm(n){if(!Je.existsSync(n))return!1;try{return Je.readdirSync(n,{withFileTypes:!0}).some(t=>sE(n,t))}catch{}return!1}function Gn(n){try{let t=new Ft(n).getAllModuleInfo(),r=[];for(let o of t){let i=mt.resolve(n,o.srcPath);wm(i)&&r.push(o)}return r}catch(e){throw g.error(`[CppCompile] findCppModules threw: ${e instanceof Error?e.message:String(e)}`),e}}function aE(n){let e=[],r=new Ft(n).getAllModuleInfo();for(let o of r){let i=mt.resolve(n,o.srcPath),s=mt.join(i,".cxx");Je.existsSync(s)&&vm(s,e)}return e}function vm(n,e){try{let t=Je.readdirSync(n,{withFileTypes:!0});for(let r of t){let o=mt.join(n,r.name);r.isDirectory()?vm(o,e):r.name==="compile_commands.json"&&e.push(o)}}catch{}}function cE(n){let e=[];for(let t of n)try{let r=Je.readFileSync(t,"utf8"),o=JSON.parse(r);e.push(...o)}catch{}return e}function lE(n,e){let t=mt.join(n,...Jc.slice(0,-1));Je.mkdirSync(t,{recursive:!0});let r=mt.join(t,"compile_commands.json");Je.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function vl(n){let e=aE(n);if(e.length>0){let t=cE(e);lE(n,t),g.info(`[CppCompile] compile_commands.json generated, ${t.length} compile commands`)}else g.warn("[CppCompile] No compile_commands.json files found")}async function dE(n,e,t){g.info(`[CppCompile] devecoPath: ${e.devecoStudioPath}, sdkPath: ${e.sdkPath}, nodePath: ${e.nodePath},hvigorJsPath:${e.hvigorJsPath}`);for(let r of t){let o=["--mode","module","-p",`module=${r.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"];g.info(`[CppCompile] Running compileNative for module: ${r.name}`);let i=await wl(n,e.nodePath,e.hvigorJsPath,e.sdkPath,o);i.success?g.info(`[CppCompile] compileNative ${r.name} succeeded`):g.warn(`[CppCompile] compileNative ${r.name} failed: ${i.output}`)}}async function Sm(n,e){let t=Gn(n);if(t.length===0){g.info("[CppCompile] No C++ modules found, skipping initialization");return}g.info(`[CppCompile] Found ${t.length} C++ module(s): ${t.map(r=>r.name).join(", ")}`),await dE(n,e,t),vl(n)}function pE(n,e){if(e.product&&n.validateProduct(e.product),e.buildMode&&!n.profile.app.buildModeSet.some(r=>r.name===e.buildMode))throw new Error(`Build mode '${e.buildMode}' not found in project build-profile.json5.`)}function mE(n,e){let t;if(e.modules&&e.modules.length>0)t=e.modules;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 R(`Multiple entry modules found (${i.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`,"Multiple entry modules found."):new R(`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 Lo(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 Oo(n,e){let t=e,r=`${n} failed`;console.error(bm(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 Mo(n,e,t,r,o,i){let s=ws(i);console.log(`
|
|
28
|
+
[ohpm install] Running...`);try{await n.installAll()}catch(l){Oo("ohpm install",l)}let a="";if(s.required){console.log(`
|
|
29
|
+
[hvigor sync] Running...`);try{a=await e.sync(t,r)}catch(l){Oo("hvigor sync",l)}}else console.log(`
|
|
30
30
|
[hvigor sync] Skipped (configurations unchanged)`);console.log(`
|
|
31
|
-
[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){
|
|
32
|
-
Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(
|
|
33
|
-
Failed to merge compile_commands.json: ${e.message}`))}}async function
|
|
34
|
-
`+
|
|
35
|
-
[1/2] Running hvigor clean...`);try{await r.clean()}catch(o){
|
|
36
|
-
[2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(o){
|
|
37
|
-
`+
|
|
31
|
+
[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){Oo("hvigor build",l)}return fE(i),{ohpmMemoryMb:n.peakMemoryMb,syncMemoryMb:a,buildMemoryMb:c}}function fE(n){try{if(Gn(n).length===0)return;vl(n),console.log(Sl(`
|
|
32
|
+
Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(bl(`
|
|
33
|
+
Failed to merge compile_commands.json: ${e.message}`))}}async function Em(n,e){let t=Date.now(),r=!0,o=null;try{await e()}catch(i){r=!1,o=Y(i),console.error(bm(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await I.track(n,i)}}function hE(n){let e={event:A.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 gE(){return{event:A.CommandExecuted,args:["build","clean"]}}async function yE(n){let e=process.cwd(),t=J.discover(e);console.warn(bl("Ensure the project source is trustworthy before proceeding."));let r=await D.new();r.assertJava(),pE(t,n);let o=n.product||"default",i=n.buildMode||"debug",s;if(n.product&&!n.modules)s={type:"product"};else{let d=mE(t,n),h=Lo(t,d);s={type:"modules",modulesToBuild:d,moduleTasks:h}}let a=new cn(r,t.rootDir),c=new Oe(r,t.rootDir),l=await _t(t.rootDir,async()=>Mo(a,c,o,i,s,t.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")});return console.log(`
|
|
34
|
+
`+Sl("Build completed successfully")),{bundleName:t.getBundleName(),ohpmMemoryMb:l.ohpmMemoryMb,syncMemoryMb:l.syncMemoryMb,buildMemoryMb:l.buildMemoryMb}}async function wE(){let n=process.cwd(),e=J.discover(n);console.warn(bl("Ensure the project source is trustworthy before proceeding."));let t=await D.new();t.assertJava();let r=new Oe(t,e.rootDir);return await _t(e.rootDir,async()=>{console.log(`
|
|
35
|
+
[1/2] Running hvigor clean...`);try{await r.clean()}catch(o){Oo("hvigor clean",o)}console.log(`
|
|
36
|
+
[2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(o){Oo("hvigor --stop-daemon",o)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
|
|
37
|
+
`+Sl("Clean completed successfully.")),e.getBundleName()}var Pm=new uE("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=hE(n);await Em(e,async()=>{let t=await yE(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)})});Pm.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{let n=gE();await Em(n,async()=>{n.bundle_name=await wE()})});var Cm=Pm;import{Command as IP}from"commander";import{green as $o,red as AP,yellow as Ms}from"colorette";import*as _s from"path";import{randomUUID as xE}from"crypto";import{execa as NE}from"execa";import{execa as kE}from"execa";import{execFile as vE,spawn as SE}from"child_process";import{promisify as bE}from"util";var EE=bE(vE);function Im(n,e,t){let o=n.replace(/\r\n/g,`
|
|
38
38
|
`).split(`
|
|
39
|
-
`),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
|
|
40
|
-
`)){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"){m(`[DeviceManager] Skipping unauthorized device: ${s}`);continue}t.push({serial:s,status:a})}return t}extractDisplayName(e){let t=e.get("ohos.qemu.hvd.name");if(t)return t;let r=e.get("const.product.name");if(r&&r!=="emulator")return r;let 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
|
|
39
|
+
`),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 Am(n,e,t){let r=n.endsWith("\r")?n.slice(0,-1):n;r.length>0&&t.onData([r],e)}function PE(n,e){return{stdout:n.stdoutChunks.join(""),stderr:n.stderrChunks.join(""),exitCode:e??-1}}function CE(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function IE(n,e,t,r,o){n.stdout?.on("data",i=>{let s=i.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=Im(e.stdoutLineBuffer+s,"stdout",t)}),n.stderr?.on("data",i=>{let s=i.toString();e.stderrChunks.push(s),e.stderrLineBuffer=Im(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,Am(e.stdoutLineBuffer,"stdout",t),Am(e.stderrLineBuffer,"stderr",t),t.onClose(i);let s=PE(e,i);r(s)})}async function zn(n,e=[],t={}){try{let{stdout:r,stderr:o}=await EE(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 Dm(n,e,t){return await new Promise((r,o)=>{let i=SE(n,e,{stdio:["inherit","pipe","pipe"]}),s=CE();IE(i,s,t,r,o)})}function Tm(n){let e=n.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var AE=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],DE=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function br(n){return n?AE.some(e=>e.test(n))?"transient":DE.some(e=>e.test(n))?"fatal":"ok":"ok"}var El=[800,1500,2500];function TE(n){return new Promise(e=>setTimeout(e,n))}async function de(n,e){let t=1+El.length,r={stdout:"",stderr:"",exitCode:-1};for(let o=0;o<t;o++){if(r=await zn(n,e),r.exitCode===0||br(r.stderr)!=="transient"||o>=t-1)return r;m(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${El[o]}ms`),await TE(El[o])}return r}var Rm=/^[\w.-]+$/;async function Cs(n,e,t){if(!Rm.test(t)){m(`Skipping invalid param key: ${JSON.stringify(t)}`);return}let r=["-t",e,"shell","param","get",t];m(`Executing: ${n} ${r.join(" ")}`);let o=await de(n,r);if(o.exitCode!==0)return;let i=o.stdout.trim();if(!(!i||br(i)!=="ok"))return Tm(i)}var Pl="__DEVECO_PARAM_DELIM__";function RE(n,e){let t=new Map,r=n.split(Pl);for(let o=0;o<e.length;o++){let i=(r[o]??"").trim();if(!i||br(i)!=="ok")continue;let s=Tm(i);s&&t.set(e[o],s)}return t}async function Er(n,e,t){let r=t.filter(a=>Rm.test(a)?!0:(m(`Skipping invalid param key: ${JSON.stringify(a)}`),!1));if(r.length===0)return new Map;if(r.length===1){let a=new Map,c=await Cs(n,e,r[0]);return c&&a.set(r[0],c),a}let o=r.map(a=>`param get ${a}`).join(`; echo ${Pl}; `)+`; echo ${Pl}`,i=await de(n,["-t",e,"shell",o]);if(i.exitCode===0){let a=RE(i.stdout,r);if(a.size>0)return a}m(`Batched param fetch failed (exit=${i.exitCode}), falling back to individual calls for ${e}`);let s=new Map;for(let a of r){let c=await Cs(n,e,a);c&&s.set(a,c)}return s}function qn(n){return n.startsWith("127.0.0.1:")}var km=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],ae=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 m(`Executing: ${this.hdcPath} ${e.join(" ")}`),kE(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let r of e.split(`
|
|
40
|
+
`)){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"){m(`[DeviceManager] Skipping unauthorized device: ${s}`);continue}t.push({serial:s,status:a})}return t}extractDisplayName(e){let t=e.get("ohos.qemu.hvd.name");if(t)return t;let r=e.get("const.product.name");if(r&&r!=="emulator")return r;let 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 Er(this.hdcPath,e,[...km]);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 Error(`Multiple devices match "${t}". Use a serial instead:
|
|
41
41
|
`+i.map(s=>` - ${s.name} (${s.device.serial})`).join(`
|
|
42
|
-
`)):new Error(`Device "${t}" not found. Use \`devecocli device list\` to see available targets.`)}return e[0]}async getDeviceDetail(e){let t={serial:e,status:"device"};try{let r=await
|
|
43
|
-
`).map(t=>t.trim()).filter(t=>t.length>0&&t!=="[Empty]")}async isDevEcoStudioRunningViaHdc(e){return(await this.runHdc(["-t",e,"shell","ps -ef | grep com.huawei.devecostudio | grep -v grep"],!1)).trim().length>0}async launchPreview(e,t,r,o,i,s,a,c,l){let h=JSON.stringify({bundleName:t,abilityName:r,moduleName:s,productName:o,productType:i,subProductType:a,instanceId:c,launchDeviceIndex:l,launchFlag:"{}",isCustom:!1,nativeDebuggable:!1,appDebuggable:!1}).replace(/'/g,"'\\''"),w=`aa start -a DevEcoViewerAbility -b com.huawei.devecostudio -m DevEcoViewer --pi instanceId ${c} --ps paramJson '${h}'`;return await this.runHdc(["-t",e,"shell",w])}async forceStopApp(e,t){let r=["-t",e,"shell","aa","force-stop",t];return await this.runHdc(r,!1)}};import El from"fs";import*as Jn from"path";function Mo(n,e){if(!El.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=El.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=Jn.resolve(e),i=new Set,s=[];for(let a of r){let c=Jn.resolve(o,a),l=Jn.isAbsolute(a)?Jn.relative(o,a):a;if(l.startsWith(".."))throw new Error(`File path is outside the project directory: ${a}`);let d=R.isPathContainedWithSymlink(l,o);if(!d.contained){if(!El.existsSync(c))throw new Error(`File not found: ${a}`);let h=d.reason?`; ${d.reason}`:"";throw new Error(`File path is outside the project directory: ${a}${h}`)}i.has(c)||(i.add(c),s.push(c))}return s}import Pl from"fs";import Er from"path";import{execa as LE}from"execa";import Im from"fs";import*as Am from"path";import xE from"json5";function NE(n,e){try{let r=xE.parse(Im.readFileSync(n,"utf-8")).modules?.find(o=>o.name===e);return r?.srcPath?r.srcPath.replace(/^\.\//,""):null}catch(t){return m(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function Dt(n,e){let t=Am.join(n,"build-profile.json5");return Im.existsSync(t)?NE(t,e)??e:e}import*as Dm from"os";async function Tm(n,e,t,r){let o={...process.env,DEVECO_SDK_HOME:n.sdkPath};if(n.javaPath){let c=Er.dirname(n.javaPath);o.PATH=`${c}${Er.delimiter}${process.env.PATH||""}`}b()&&(o.HVIGOR_USER_HOME=Er.join(Dm.homedir(),".hvigor"));let i=[n.hvigorJsPath,"--mode","module","-p",`module=${t.join(",")}@${r}`,"-p",`product=${r}`,"-p","debuggable=true","assembleDevHqf","--analyze=normal","--parallel","--incremental","--no-daemon"];m(`[buildSignedHqf] ${n.nodePath} ${i.join(" ")}`);let s=await LE(n.nodePath,i,{cwd:e,env:o,stdout:"inherit",stderr:"inherit",reject:!1}),a=(s.exitCode??0)|0;if(a===-1)throw new Error("hvigor hot compile produced invalid abc (exit code -1)");if(a!==0)throw new Error(`hvigor assembleDevHqf failed with exit code ${s.exitCode}`);return t.map(c=>ME(e,c,r))}function km(n,e,t){let r=Dt(n,e);return Er.join(n,r,"build",t,"outputs")}function OE(n,e,t){return Er.join(km(n,e,t),`${e}-${t}-signed.hqf`)}function ME(n,e,t){let r=km(n,e,t),o=OE(n,e,t);if(Pl.existsSync(o))return o;let i=Cl(r,"-signed.hqf")??Cl(r,".hqf");if(!i)throw new Error(`Signed hqf not found at ${o} (and no *.hqf under ${r})`);return m(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${i}`),i}function Cl(n,e){if(!Pl.existsSync(n))return null;for(let t of Pl.readdirSync(n,{withFileTypes:!0})){let r=Er.join(n,t.name);if(t.isDirectory()){let o=Cl(r,e);if(o)return o}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import Q from"fs";import*as M from"path";import Il from"json5";var Rm="default",Pr=class n{static writeChangedFileLists(e,t,r,o){let i=t||Rm,s=n.loadBuildProfile(e);if(!s)return{writtenModules:[],skippedFiles:r};let a=s.modules,c=n.filterRunnableModules(e,a);if(c.length===0)return{writtenModules:[],skippedFiles:r};let l=n.buildReverseDependencyMap(e,a),d=n.createCollectors(c),h=n.collectChanges(r,e,a,l,d);return{writtenModules:n.flushCollectors(e,i,c,d,o),skippedFiles:h}}static initEmptyChangedFileLists(e,t,r){let o=t||Rm,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=M.normalize(a),l=n.classifyFile(c,t,r);if(l.fileClass==="unknown"){s.push(c);continue}let d=n.findModuleByFilePath(c,t,r);if(!d){s.push(c);continue}let h=n.resolveTargetModules(d,t,r,o);if(h.length===0){s.push(c);continue}n.dispatchToCollectors(h,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=M.join(e,r,"build",t,"intermediates","patch","default"),s=M.join(i,"changedFileList.json");if(Q.existsSync(s)||(Q.mkdirSync(i,{recursive:!0}),Q.writeFileSync(s,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!o)return;let a=M.join(e,r,"build",t,"intermediates","hotReload"),c=M.join(a,"changedFileList.json");Q.existsSync(c)||(Q.mkdirSync(a,{recursive:!0}),Q.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=M.join(e,"build-profile.json5");if(!Q.existsSync(t))return null;try{let r=Q.readFileSync(t,"utf-8");return Il.parse(r)}catch{return null}}static classifyFile(e,t,r){let o=M.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=M.normalize(e);for(let i of r){let s=M.normalize(M.join(t,i.srcPath)),a=s+M.sep;if(o.startsWith(a)||o===s)return i}return null}static getModuleType(e,t){let r=M.join(e,t,"src","main","module.json5");if(!Q.existsSync(r))return"entry";try{let o=Q.readFileSync(r,"utf-8");return Il.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=M.join(e,t,"oh-package.json5");if(!Q.existsSync(r))return[];try{let o=Q.readFileSync(r,"utf-8"),i=Il.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=M.resolve(e,t,i);return o.find(l=>M.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(h=>h.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=M.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=M.join(e,i,"build",r,"intermediates","hotReload","changedFileList.json"),a=n.readExistingApply(s),c=n.mergeApplyEntries(a,o),l=M.dirname(s);Q.existsSync(l)||Q.mkdirSync(l,{recursive:!0}),Q.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),m(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!Q.existsSync(e))return[];try{let t=Q.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,r,o,i,s){let a=t.replace(/^\.\//,""),c=M.join(e,a,"build",r,"intermediates","patch","default","changedFileList.json"),l=n.readExistingPatch(c),d=M.join(e,a,"src","main","ets"),h=o.map(Y=>n.resolveRelativePathForPatch(Y,d)),w=n.mergeStrings(l.modifiedFiles,h),v=n.mergePatchResources(l.rawFile,i),I=n.mergePatchResources(l.resFile,s),H=M.dirname(c);Q.existsSync(H)||Q.mkdirSync(H,{recursive:!0}),Q.writeFileSync(c,JSON.stringify({resources:{resFile:I,rawFile:v},modifiedFiles:w}),"utf-8"),m(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!Q.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=Q.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 M.relative(M.normalize(t),M.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 _E from"fs";import{randomUUID as FE}from"crypto";import{execa as jE}from"execa";var Cr=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!_E.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}let i=`/data/local/tmp/${FE()}`,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(m(`[InstallHqf] quickfix output: ${i}`),/succe(?:ed|ss)/i.test(i))return console.log("[Apply] hqf installed successfully."),{success:!0,message:"hqf quickfix installed successfully."};let s=`hqf quickfix install failed. Device response: ${i||"(empty)"}. Please try reinstalling the application.`;return console.error(`[Apply] ${s}`),{success:!1,message:s}}async getApiVersion(e){try{let t=await this.runHdc(["-t",e,"shell","param","get","const.ohos.apiversion"],!1),r=parseInt(t.trim(),10);if(!isNaN(r))return console.log(`[InstallHqf] device API version: ${r}`),r}catch{}return 0}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;m(`[InstallHqf] Executing: ${r} ${e.join(" ")}`);try{let{stdout:o}=await jE(r,e,{env:{...process.env}});return o}catch(o){if(t)throw o;return o.stdout||""}}};var $E="6.1.1",Ps=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}toolProvider;projectRoot;async execute(e){await Ft(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion($E);let t=Mo(e.applyFile,this.projectRoot);console.log(`[Apply] Parsed ${t.length} changed file(s)`);let r=this.writeChangeFileList(e,t),o=await this.buildHqf(e,r);await this.stopApp(e),await this.installHqf(e,o),await this.launchApp(e),console.log("[Apply] Apply complete")}writeChangeFileList(e,t){let r=Pr.writeChangedFileLists(this.projectRoot,e.productName,t);if(r.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");return console.log(`[Apply] changeFileList written for: ${r.writtenModules.join(", ")}`),r.writtenModules}async buildHqf(e,t){return m(`[Apply] hvigor assembleDevHqf --no-daemon (modules=${t.join(",")})`),await Tm(this.toolProvider,this.projectRoot,t,e.productName)}async installHqf(e,t){console.log(`[Apply] Installing ${t.length} hqf(s) to ${e.targetDeviceId}`);let o=await new Cr(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 $t(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 $t(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 xm from"fs";import*as B from"path";var Cs=class n{static generate(e,t,r,o){let i=Dt(e,t),s=B.join(e,i),a=B.join(s,"build","config"),c=n.buildConfig(e,s,r,o);xm.mkdirSync(a,{recursive:!0}),xm.writeFileSync(B.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[BuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,o){let i=B.dirname(o.nodePath)+B.sep,s=B.join(t,"build",r),a=B.join(s,"intermediates"),c=B.join(a,"loader_out",r),l=B.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:i,projectProfilePath:B.join(e,"build-profile.json5"),localPropertiesPath:B.join(e,"local.properties"),appResource:B.join(l,"ResourceTable.txt"),cachePath:B.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:B.join(a,"loader",r,"loader.json"),aceModuleJsonPath:B.join(l,"module.json"),aceSoPath:B.join(c,"nativeDependencies.txt"),aceModuleRoot:B.join(t,"src","main","ets"),aceModuleBuild:B.join(c,"ets"),aceProfilePath:B.join(l,"resources","base","profile"),aceSuperVisualPath:B.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:B.join(c,"ets"),changedFileList:B.join(a,"patch","default","changedFileList.json"),patchAbcPath:B.join(a,"patch","default","ets"),removeChangedFileListInSdk:"true"}}}};import Nm from"fs";import*as U from"path";var Is=class n{static generate(e,t,r,o){let i=Dt(e,t),s=U.join(e,i),a=U.join(s,"build","config"),c=n.buildConfig(e,s,r,o);Nm.mkdirSync(a,{recursive:!0}),Nm.writeFileSync(U.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[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 Lm from"crypto";import tt from"fs";import nt from"path";import Om from"os";import{io as HE}from"socket.io-client";var BE=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Ir=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;tt.mkdirSync(nt.dirname(o),{recursive:!0}),tt.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(`
|
|
42
|
+
`)):new Error(`Device "${t}" not found. Use \`devecocli device list\` to see available targets.`)}return e[0]}async getDeviceDetail(e){let t={serial:e,status:"device"};try{let r=await Er(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=b()?!1:qn(e),r,o;try{let i=await Er(this.hdcPath,e,[...km]);r=this.extractDisplayName(i),o=i.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:o}}async ensureWirelessSelfConnection(){if(!b())return{mode:"tcp"};let e=await this.getLocalParam("persist.hdc.mode");if(!e)return{mode:""};if(e!=="tcp")return{mode:e};let t=await this.getLocalParam("persist.hdc.port");if(!t)return{mode:"tcp"};let r=await this.listDevices();if(this.hasDeviceWithPort(r,t))return{mode:"tcp",port:t,autoConnected:!1};let o=`127.0.0.1:${t}`;m(`Executing: ${this.hdcPath} tconn ${o}`);let i=!1;try{await this.executeHdc(["tconn",o]),i=!0}catch(s){m(`hdc tconn ${o} failed: ${s.message}`)}return{mode:"tcp",port:t,autoConnected:i}}async getLocalParam(e){m(`Executing: param get ${e}`);let t=await zn("param",["get",e]);return t.exitCode!==0||!t.stdout||/^Get parameter\b.*fail!/i.test(t.stdout)?"":this.parseLocalParamValue(t.stdout)}parseLocalParamValue(e){let t=e.trim(),r=t.indexOf("=");if(r!==-1)return t.slice(r+1).trim();let o=t.match(/^[\w.]+\s*:\s*(.+)$/);return o?o[1].trim():t}hasDeviceWithPort(e,t){let r=`127.0.0.1:${t}`;return e.some(o=>o.serial===r)}};var jt=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=ae.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;m(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:o}=await NE(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){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/${xE()}`;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){let o=["-t",e,"shell","aa","start","-a",r,"-b",t];return await this.runHdc(o)}async connectTarget(e){await this.runHdc(["tconn",e])}async disconnectTarget(e){await this.runHdc(["tconn",e,"-remove"],!1)}async listRawTargets(){return(await this.runHdc(["list","targets"],!1)).split(`
|
|
43
|
+
`).map(t=>t.trim()).filter(t=>t.length>0&&t!=="[Empty]")}async isDevEcoStudioRunningViaHdc(e){return(await this.runHdc(["-t",e,"shell","ps -ef | grep com.huawei.devecostudio | grep -v grep"],!1)).trim().length>0}async launchPreview(e,t,r,o,i,s,a,c,l){let h=JSON.stringify({bundleName:t,abilityName:r,moduleName:s,productName:o,productType:i,subProductType:a,instanceId:c,launchDeviceIndex:l,launchFlag:"{}",isCustom:!1,nativeDebuggable:!1,appDebuggable:!1}).replace(/'/g,"'\\''"),w=`aa start -a DevEcoViewerAbility -b com.huawei.devecostudio -m DevEcoViewer --pi instanceId ${c} --ps paramJson '${h}'`;return await this.runHdc(["-t",e,"shell",w])}async forceStopApp(e,t){let r=["-t",e,"shell","aa","force-stop",t];return await this.runHdc(r,!1)}};import Cl from"fs";import*as Yn from"path";function _o(n,e){if(!Cl.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=Cl.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=Yn.resolve(e),i=new Set,s=[];for(let a of r){let c=Yn.resolve(o,a),l=Yn.isAbsolute(a)?Yn.relative(o,a):a;if(l.startsWith(".."))throw new Error(`File path is outside the project directory: ${a}`);let d=x.isPathContainedWithSymlink(l,o);if(!d.contained){if(!Cl.existsSync(c))throw new Error(`File not found: ${a}`);let h=d.reason?`; ${d.reason}`:"";throw new Error(`File path is outside the project directory: ${a}${h}`)}i.has(c)||(i.add(c),s.push(c))}return s}import Il from"fs";import Pr from"path";import{execa as ME}from"execa";import xm from"fs";import*as Nm from"path";import OE from"json5";function LE(n,e){try{let r=OE.parse(xm.readFileSync(n,"utf-8")).modules?.find(o=>o.name===e);return r?.srcPath?r.srcPath.replace(/^\.\//,""):null}catch(t){return m(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function At(n,e){let t=Nm.join(n,"build-profile.json5");return xm.existsSync(t)?LE(t,e)??e:e}import*as Om from"os";async function Lm(n,e,t,r){let o={...process.env,DEVECO_SDK_HOME:n.sdkPath};if(n.javaPath){let c=Pr.dirname(n.javaPath);o.PATH=`${c}${Pr.delimiter}${process.env.PATH||""}`}b()&&(o.HVIGOR_USER_HOME=Pr.join(Om.homedir(),".hvigor"));let i=[n.hvigorJsPath,"--mode","module","-p",`module=${t.join(",")}@${r}`,"-p",`product=${r}`,"-p","debuggable=true","assembleDevHqf","--analyze=normal","--parallel","--incremental","--no-daemon"];m(`[buildSignedHqf] ${n.nodePath} ${i.join(" ")}`);let s=await ME(n.nodePath,i,{cwd:e,env:o,stdout:"inherit",stderr:"inherit",reject:!1}),a=(s.exitCode??0)|0;if(a===-1)throw new Error("hvigor hot compile produced invalid abc (exit code -1)");if(a!==0)throw new Error(`hvigor assembleDevHqf failed with exit code ${s.exitCode}`);return t.map(c=>FE(e,c,r))}function Mm(n,e,t){let r=At(n,e);return Pr.join(n,r,"build",t,"outputs")}function _E(n,e,t){return Pr.join(Mm(n,e,t),`${e}-${t}-signed.hqf`)}function FE(n,e,t){let r=Mm(n,e,t),o=_E(n,e,t);if(Il.existsSync(o))return o;let i=Al(r,"-signed.hqf")??Al(r,".hqf");if(!i)throw new Error(`Signed hqf not found at ${o} (and no *.hqf under ${r})`);return m(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${i}`),i}function Al(n,e){if(!Il.existsSync(n))return null;for(let t of Il.readdirSync(n,{withFileTypes:!0})){let r=Pr.join(n,t.name);if(t.isDirectory()){let o=Al(r,e);if(o)return o}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import Z from"fs";import*as M from"path";import Dl from"json5";var _m="default",Cr=class n{static writeChangedFileLists(e,t,r,o){let i=t||_m,s=n.loadBuildProfile(e);if(!s)return{writtenModules:[],skippedFiles:r};let a=s.modules,c=n.filterRunnableModules(e,a);if(c.length===0)return{writtenModules:[],skippedFiles:r};let l=n.buildReverseDependencyMap(e,a),d=n.createCollectors(c),h=n.collectChanges(r,e,a,l,d);return{writtenModules:n.flushCollectors(e,i,c,d,o),skippedFiles:h}}static initEmptyChangedFileLists(e,t,r){let o=t||_m,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=M.normalize(a),l=n.classifyFile(c,t,r);if(l.fileClass==="unknown"){s.push(c);continue}let d=n.findModuleByFilePath(c,t,r);if(!d){s.push(c);continue}let h=n.resolveTargetModules(d,t,r,o);if(h.length===0){s.push(c);continue}n.dispatchToCollectors(h,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=M.join(e,r,"build",t,"intermediates","patch","default"),s=M.join(i,"changedFileList.json");if(Z.existsSync(s)||(Z.mkdirSync(i,{recursive:!0}),Z.writeFileSync(s,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!o)return;let a=M.join(e,r,"build",t,"intermediates","hotReload"),c=M.join(a,"changedFileList.json");Z.existsSync(c)||(Z.mkdirSync(a,{recursive:!0}),Z.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=M.join(e,"build-profile.json5");if(!Z.existsSync(t))return null;try{let r=Z.readFileSync(t,"utf-8");return Dl.parse(r)}catch{return null}}static classifyFile(e,t,r){let o=M.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=M.normalize(e);for(let i of r){let s=M.normalize(M.join(t,i.srcPath)),a=s+M.sep;if(o.startsWith(a)||o===s)return i}return null}static getModuleType(e,t){let r=M.join(e,t,"src","main","module.json5");if(!Z.existsSync(r))return"entry";try{let o=Z.readFileSync(r,"utf-8");return Dl.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=M.join(e,t,"oh-package.json5");if(!Z.existsSync(r))return[];try{let o=Z.readFileSync(r,"utf-8"),i=Dl.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=M.resolve(e,t,i);return o.find(l=>M.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(h=>h.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=M.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=M.join(e,i,"build",r,"intermediates","hotReload","changedFileList.json"),a=n.readExistingApply(s),c=n.mergeApplyEntries(a,o),l=M.dirname(s);Z.existsSync(l)||Z.mkdirSync(l,{recursive:!0}),Z.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),m(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!Z.existsSync(e))return[];try{let t=Z.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,r,o,i,s){let a=t.replace(/^\.\//,""),c=M.join(e,a,"build",r,"intermediates","patch","default","changedFileList.json"),l=n.readExistingPatch(c),d=M.join(e,a,"src","main","ets"),h=o.map(Ve=>n.resolveRelativePathForPatch(Ve,d)),w=n.mergeStrings(l.modifiedFiles,h),v=n.mergePatchResources(l.rawFile,i),T=n.mergePatchResources(l.resFile,s),ne=M.dirname(c);Z.existsSync(ne)||Z.mkdirSync(ne,{recursive:!0}),Z.writeFileSync(c,JSON.stringify({resources:{resFile:T,rawFile:v},modifiedFiles:w}),"utf-8"),m(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!Z.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=Z.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 M.relative(M.normalize(t),M.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 jE from"fs";import{randomUUID as $E}from"crypto";import{execa as HE}from"execa";var Ir=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!jE.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}let i=`/data/local/tmp/${$E()}`,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(m(`[InstallHqf] quickfix output: ${i}`),/succe(?:ed|ss)/i.test(i))return console.log("[Apply] hqf installed successfully."),{success:!0,message:"hqf quickfix installed successfully."};let s=`hqf quickfix install failed. Device response: ${i||"(empty)"}. Please try reinstalling the application.`;return console.error(`[Apply] ${s}`),{success:!1,message:s}}async getApiVersion(e){try{let t=await this.runHdc(["-t",e,"shell","param","get","const.ohos.apiversion"],!1),r=parseInt(t.trim(),10);if(!isNaN(r))return console.log(`[InstallHqf] device API version: ${r}`),r}catch{}return 0}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;m(`[InstallHqf] Executing: ${r} ${e.join(" ")}`);try{let{stdout:o}=await HE(r,e,{env:{...process.env}});return o}catch(o){if(t)throw o;return o.stdout||""}}};var UE="6.1.1",Is=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}toolProvider;projectRoot;async execute(e){await _t(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(UE);let t=_o(e.applyFile,this.projectRoot);console.log(`[Apply] Parsed ${t.length} changed file(s)`);let r=this.writeChangeFileList(e,t),o=await this.buildHqf(e,r);await this.stopApp(e),await this.installHqf(e,o),await this.launchApp(e),console.log("[Apply] Apply complete")}writeChangeFileList(e,t){let r=Cr.writeChangedFileLists(this.projectRoot,e.productName,t);if(r.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");return console.log(`[Apply] changeFileList written for: ${r.writtenModules.join(", ")}`),r.writtenModules}async buildHqf(e,t){return m(`[Apply] hvigor assembleDevHqf --no-daemon (modules=${t.join(",")})`),await Lm(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 Ir(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 jt(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 jt(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 Fm from"fs";import*as H from"path";var As=class n{static generate(e,t,r,o){let i=At(e,t),s=H.join(e,i),a=H.join(s,"build","config"),c=n.buildConfig(e,s,r,o);Fm.mkdirSync(a,{recursive:!0}),Fm.writeFileSync(H.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[BuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,o){let i=H.dirname(o.nodePath)+H.sep,s=H.join(t,"build",r),a=H.join(s,"intermediates"),c=H.join(a,"loader_out",r),l=H.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:i,projectProfilePath:H.join(e,"build-profile.json5"),localPropertiesPath:H.join(e,"local.properties"),appResource:H.join(l,"ResourceTable.txt"),cachePath:H.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:H.join(a,"loader",r,"loader.json"),aceModuleJsonPath:H.join(l,"module.json"),aceSoPath:H.join(c,"nativeDependencies.txt"),aceModuleRoot:H.join(t,"src","main","ets"),aceModuleBuild:H.join(c,"ets"),aceProfilePath:H.join(l,"resources","base","profile"),aceSuperVisualPath:H.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:H.join(c,"ets"),changedFileList:H.join(a,"patch","default","changedFileList.json"),patchAbcPath:H.join(a,"patch","default","ets"),removeChangedFileListInSdk:"true"}}}};import jm from"fs";import*as U from"path";var Ds=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);jm.mkdirSync(a,{recursive:!0}),jm.writeFileSync(U.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[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 $m from"crypto";import et from"fs";import tt from"path";import Hm from"os";import{io as BE}from"socket.io-client";var WE=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Ar=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;et.mkdirSync(tt.dirname(o),{recursive:!0}),et.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(`
|
|
44
44
|
`)?a:a+`
|
|
45
|
-
`),r.length>100&&r.shift())},onWatchResult:s=>{let a=n.extractText(s);if(!a.trim())return;let c=`[WatchResult] ${a}`;console.log(c),
|
|
46
|
-
`].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
|
|
45
|
+
`),r.length>100&&r.shift())},onWatchResult:s=>{let a=n.extractText(s);if(!a.trim())return;let c=`[WatchResult] ${a}`;console.log(c),et.writeFileSync(e,[...r,c+`
|
|
46
|
+
`].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 tt.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=BE(`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=w=>{t()||(r(!0),h(),this.invalidateSocket(),o(new Error(`Socket disconnected: ${w}`)))},s=this.createOutputHandler(),{onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d}=this.getDataHandler(),h=()=>{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:h}}getDataHandler(){let e=n.extractText;return{onWatchLog:s=>{let a=e(s);a.trim()&&process.stdout.write(a+(a.endsWith(`
|
|
47
47
|
`)?"":`
|
|
48
|
-
`))},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(!tt.existsSync(e))return null;try{let t=tt.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=nt.join(t,"fd"),o=nt.join(t,"ac"),i=nt.join(t,"ce"),s=this.readComponents(r),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(BE)]),c=this.readSingleFile(o),l=Lm.pbkdf2Sync(Buffer.from(a).toString(),c,1e4,16,"sha256"),d=this.readSingleFile(i),h=this.aesGcmDecrypt(l,d),w=Buffer.from(e,"hex");return this.aesGcmDecrypt(h,w).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=Lm.createDecipheriv("aes-128-gcm",e,i);return l.setAuthTag(c),Buffer.concat([l.update(a),l.final()])}readComponents(e){let t=tt.readdirSync(e).map(r=>nt.join(e,r)).filter(r=>tt.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=tt.readdirSync(r);if(o.length===0)throw new Error(`No file in ${r}`);return tt.readFileSync(nt.join(r,o[0]))})}readSingleFile(e){let t=tt.readdirSync(e).map(r=>nt.join(e,r)).filter(r=>tt.statSync(r).isFile());if(t.length===0)throw new Error(`No file in ${e}`);return tt.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||nt.join(Om.homedir(),".hvigor");return nt.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||nt.join(Om.homedir(),".hvigor");return nt.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import Fm from"fs";import*as Ht from"path";import{green as ks,yellow as Al}from"colorette";import Kn from"fs";import*as Xn from"path";import UE from"json5";var WE=2e6,VE=1e6,GE="hotreload",As=class n{static generateOrUpdate(e,t,r){let o=n.readAppConfig(e),i=Xn.resolve(e,t),s=Xn.join(i,"patch.json"),a;return Kn.existsSync(s)?(m(`[PatchManager] patch.json found at ${s}, incrementing patchVersionCode`),a=n.readExistingPatch(s),a.app.patchVersionCode+=1):(m(`[PatchManager] patch.json not found, generating new one at ${s}`),a={app:{bundleName:o.bundleName,patchVersionCode:WE,versionCode:o.versionCode},module:{name:r,type:GE}}),n.writePatchJson(s,a),a}static readAppConfig(e){let t=Xn.join(e,"AppScope","app.json5");if(!Kn.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let r=Kn.readFileSync(t,"utf-8"),o=UE.parse(r),i=o?.app?.bundleName;if(!i)throw new Error("bundleName is missing in AppScope/app.json5");let s=o?.app?.versionCode??VE;return{bundleName:i,versionCode:s}}static readExistingPatch(e){let t=Kn.readFileSync(e,"utf-8"),r=JSON.parse(t);if(!r?.app?.patchVersionCode)throw new Error(`Invalid patch.json at ${e}: missing app.patchVersionCode`);return r}static writePatchJson(e,t){let r=Xn.dirname(e);Kn.existsSync(r)||Kn.mkdirSync(r,{recursive:!0});let o=JSON.stringify(t,null,2);Kn.writeFileSync(e,o,"utf-8"),m(`[PatchManager] patch.json written to ${e}`),m(`[PatchManager] Content: ${o}`)}};import ve from"fs";import*as V from"path";import Mm from"crypto";import qE from"json5";import{execa as _m}from"execa";var Ds=class n{static COMPONENT=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]);static DIRS=["fd","ac","ce"];static decryptPwd(e,t,r){if(t.length<32||t.length%2!==0)throw new Error(`Invalid encrypted password for ${r}`);m(`[DecipherUtil] Decrypting ${r}, encrypted length: ${t.length}`);let o=V.resolve(e,"material"),i=n.getKey(o,r),s=new Int8Array(Buffer.from(t,"hex"));return m(`[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=Mm.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=Mm.createDecipheriv("aes-128-gcm",Buffer.from(e),Buffer.from(i));a.setAuthTag(Buffer.from(s));let c=a.update(Buffer.from(t.subarray(4+o,t.length-16))),l=a.final();return Buffer.concat([c,l])}static readFd(e,t){let r=ve.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(ve.statSync(e).isDirectory()){let o=ve.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(ve.readFileSync(V.join(e,o[0])))}return new Int8Array(ve.readFileSync(e))}},Ts=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(ve.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(!ve.existsSync(e))return null;let t=ve.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=Dt(this.projectRoot,e),o=V.join(this.projectRoot,r,"build",t,"outputs","default");return ve.existsSync(o)||ve.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"];m(`[GenSignHqf] Packing: ${s} ${a.join(" ")}`);try{let c=Date.now(),l=await _m(s,a,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] pack (JVM#1): ${Date.now()-c}ms`),l.stdout&&console.log(l.stdout),l.stderr&&console.error(l.stderr),l.exitCode!==0?(console.error(`[HotReload] app_packing_tool failed with exit code ${l.exitCode}`),!1):ve.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;m(`[GenSignHqf] Signing: ${i} ${o.join(" ")}`);try{let s=Date.now(),a=await _m(i,o,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] sign (JVM#2): ${Date.now()-s}ms`),a.stdout&&console.log(a.stdout),a.stderr&&console.error(a.stderr),a.exitCode!==0?this.signFailResult(e,`hqf signing failed with exit code ${a.exitCode}`):ve.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(s){return this.signFailResult(e,`hqf signing failed: ${s.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=Ds.decryptPwd(r,t.storePassword,"storePassword"),i=Ds.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 ve.existsSync(r)?t:null}readSigningConfig(e){let t=V.join(this.projectRoot,"build-profile.json5");if(!ve.existsSync(t))return null;try{let r=ve.readFileSync(t,"utf-8"),o=qE.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(ve.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(ve.existsSync(r))return r;return null}};async function jm(n){let e=Date.now(),t=Dt(n.projectPath,n.moduleName),r=zE(n);console.log(Al("[HotReload] Ensure the project source is trusted before proceeding."));let o=YE(n),i=Mo(r,n.projectPath);console.log(`[HotReload] Parsed ${i.length} changed file(s) from ${n.applyFileName}`),JE(n,i),KE(n,t),await XE(n,o);let s=Ht.join(n.projectPath,t,"patch.json"),a=await QE(n,t,s);return await eP(n,a),console.log(ks("[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 zE(n){if(Ht.basename(n.applyFileName)!==n.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n.applyFileName}`);return Ht.join(n.projectPath,".hvigor",n.applyFileName)}function YE(n){let{projectPath:e,toolProvider:t}=n,r=new Ir(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 JE(n,e){let t=Pr.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(ks(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn(Al(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function KE(n,e){let t=As.generateOrUpdate(n.projectPath,e,n.moduleName);console.log(ks(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function XE(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=ZE(r);throw new Error(`Daemon hot compile exited with code ${o}`+(i?`
|
|
48
|
+
`))},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(!et.existsSync(e))return null;try{let t=et.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=tt.join(t,"fd"),o=tt.join(t,"ac"),i=tt.join(t,"ce"),s=this.readComponents(r),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(WE)]),c=this.readSingleFile(o),l=$m.pbkdf2Sync(Buffer.from(a).toString(),c,1e4,16,"sha256"),d=this.readSingleFile(i),h=this.aesGcmDecrypt(l,d),w=Buffer.from(e,"hex");return this.aesGcmDecrypt(h,w).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=$m.createDecipheriv("aes-128-gcm",e,i);return l.setAuthTag(c),Buffer.concat([l.update(a),l.final()])}readComponents(e){let t=et.readdirSync(e).map(r=>tt.join(e,r)).filter(r=>et.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=et.readdirSync(r);if(o.length===0)throw new Error(`No file in ${r}`);return et.readFileSync(tt.join(r,o[0]))})}readSingleFile(e){let t=et.readdirSync(e).map(r=>tt.join(e,r)).filter(r=>et.statSync(r).isFile());if(t.length===0)throw new Error(`No file in ${e}`);return et.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||tt.join(Hm.homedir(),".hvigor");return tt.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||tt.join(Hm.homedir(),".hvigor");return tt.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import Wm from"fs";import*as $t from"path";import{green as xs,yellow as Tl}from"colorette";import Jn from"fs";import*as Kn from"path";import VE from"json5";var GE=2e6,zE=1e6,qE="hotreload",Ts=class n{static generateOrUpdate(e,t,r){let o=n.readAppConfig(e),i=Kn.resolve(e,t),s=Kn.join(i,"patch.json"),a;return Jn.existsSync(s)?(m(`[PatchManager] patch.json found at ${s}, incrementing patchVersionCode`),a=n.readExistingPatch(s),a.app.patchVersionCode+=1):(m(`[PatchManager] patch.json not found, generating new one at ${s}`),a={app:{bundleName:o.bundleName,patchVersionCode:GE,versionCode:o.versionCode},module:{name:r,type:qE}}),n.writePatchJson(s,a),a}static readAppConfig(e){let t=Kn.join(e,"AppScope","app.json5");if(!Jn.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let r=Jn.readFileSync(t,"utf-8"),o=VE.parse(r),i=o?.app?.bundleName;if(!i)throw new Error("bundleName is missing in AppScope/app.json5");let s=o?.app?.versionCode??zE;return{bundleName:i,versionCode:s}}static readExistingPatch(e){let t=Jn.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=Kn.dirname(e);Jn.existsSync(r)||Jn.mkdirSync(r,{recursive:!0});let o=JSON.stringify(t,null,2);Jn.writeFileSync(e,o,"utf-8"),m(`[PatchManager] patch.json written to ${e}`),m(`[PatchManager] Content: ${o}`)}};import we from"fs";import*as W from"path";import Um from"crypto";import YE from"json5";import{execa as Bm}from"execa";var Rs=class n{static COMPONENT=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]);static DIRS=["fd","ac","ce"];static decryptPwd(e,t,r){if(t.length<32||t.length%2!==0)throw new Error(`Invalid encrypted password for ${r}`);m(`[DecipherUtil] Decrypting ${r}, encrypted length: ${t.length}`);let o=W.resolve(e,"material"),i=n.getKey(o,r),s=new Int8Array(Buffer.from(t,"hex"));return m(`[DecipherUtil] Data length: ${s.length}, key length: ${i.length}`),n.decrypt(i,s).toString("utf-8")}static getKey(e,t){let r=W.resolve(e,n.DIRS[0]),o=n.readFd(r,t),i=n.readDirBytes(W.resolve(e,n.DIRS[1]),t),s=n.getRootKey(o,i,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 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=Um.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=Um.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=we.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=W.join(e,i);o.push(n.readDirBytes(s,t))}return o}static readDirBytes(e,t){if(we.statSync(e).isDirectory()){let o=we.readdirSync(e).filter(i=>i!==".DS_Store");if(o.length!==1)throw new Error(`Expected exactly 1 file in ${e} for ${t}`);return new Int8Array(we.readFileSync(W.join(e,o[0])))}return new Int8Array(we.readFileSync(e))}},ks=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let o=`${W.dirname(e.javaPath)}${W.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=W.join(e,"ets","modules.abc");if(we.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(!we.existsSync(e))return null;let t=we.readdirSync(e,{withFileTypes:!0});for(let r of t){let o=W.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=W.join(this.projectRoot,r,"build",t,"outputs","default");return we.existsSync(o)||we.mkdirSync(o,{recursive:!0}),{unsignedHqfPath:W.join(o,`${e}-default-unsigned.hqf`),signedHqfPath:W.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=W.dirname(t),s=this.toolProvider.javaPath,a=["-jar",o,"--mode","hqf","--json-path",e,"--ets-path",i,"--out-path",r,"--force","true"];m(`[GenSignHqf] Packing: ${s} ${a.join(" ")}`);try{let c=Date.now(),l=await Bm(s,a,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] pack (JVM#1): ${Date.now()-c}ms`),l.stdout&&console.log(l.stdout),l.stderr&&console.error(l.stderr),l.exitCode!==0?(console.error(`[HotReload] app_packing_tool failed with exit code ${l.exitCode}`),!1):we.existsSync(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;m(`[GenSignHqf] Signing: ${i} ${o.join(" ")}`);try{let s=Date.now(),a=await Bm(i,o,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] sign (JVM#2): ${Date.now()-s}ms`),a.stdout&&console.log(a.stdout),a.stderr&&console.error(a.stderr),a.exitCode!==0?this.signFailResult(e,`hqf signing failed with exit code ${a.exitCode}`):we.existsSync(t)?(console.log(`[HotReload] Signed hqf generated: ${t}`),{success:!0,signedHqfPaths:[t],unsignedHqfPath:e,message:"hqf generated and signed successfully."}):this.signFailResult(e,`Signed hqf not generated at ${t}`)}catch(s){return this.signFailResult(e,`hqf signing failed: ${s.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=Rs.decryptPwd(r,t.storePassword,"storePassword"),i=Rs.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=W.resolve(e.storeFile,".."),r=W.join(t,"material");return we.existsSync(r)?t:null}readSigningConfig(e){let t=W.join(this.projectRoot,"build-profile.json5");if(!we.existsSync(t))return null;try{let r=we.readFileSync(t,"utf-8"),o=YE.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=[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(we.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(we.existsSync(r))return r;return null}};async function Vm(n){let e=Date.now(),t=At(n.projectPath,n.moduleName),r=JE(n);console.log(Tl("[HotReload] Ensure the project source is trusted before proceeding."));let o=KE(n),i=_o(r,n.projectPath);console.log(`[HotReload] Parsed ${i.length} changed file(s) from ${n.applyFileName}`),XE(n,i),ZE(n,t),await QE(n,o);let s=$t.join(n.projectPath,t,"patch.json"),a=await tP(n,t,s);return await nP(n,a),console.log(xs("[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 JE(n){if($t.basename(n.applyFileName)!==n.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n.applyFileName}`);return $t.join(n.projectPath,".hvigor",n.applyFileName)}function KE(n){let{projectPath:e,toolProvider:t}=n,r=new Ar(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 XE(n,e){let t=Cr.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(xs(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn(Tl(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function ZE(n,e){let t=Ts.generateOrUpdate(n.projectPath,e,n.moduleName);console.log(xs(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function QE(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=eP(r);throw new Error(`Daemon hot compile exited with code ${o}`+(i?`
|
|
49
49
|
--- compile output (from watch session) ---
|
|
50
|
-
${i}`:""))}}finally{e.disconnect()}console.log(`[Timing] daemon hot compile: ${Date.now()-t}ms`)}function
|
|
51
|
-
`):""}catch{return""}}async function
|
|
50
|
+
${i}`:""))}}finally{e.disconnect()}console.log(`[Timing] daemon hot compile: ${Date.now()-t}ms`)}function eP(n){try{return Wm.existsSync(n)?Wm.readFileSync(n,"utf8").split(/\r?\n/).filter(t=>t.trim()).slice(-40).join(`
|
|
51
|
+
`):""}catch{return""}}async function tP(n,e,t){let r=$t.join(n.projectPath,e,"build",n.productName,"intermediates"),o=[$t.join(r,"hotReload","patchAbcPath"),$t.join(r,"patch","default")],i=Date.now(),s=new ks(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 nP(n,e){let t=Date.now(),o=await new Ir(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 Rl(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 Gm(n,e,t){let r=$t.join(n.rootDir,".hvigor",t),o;try{o=_o(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(Tl(`[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 zm(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 qm(n,e){await new Oe(n,e.rootDir).stopDaemon(),console.log(xs("Hvigor daemon stopped."))}import{execa as Nl}from"execa";import*as Ym from"readline/promises";import{stdin as cP,stdout as lP}from"process";import{green as Dr,red as Ls,yellow as Ol}from"colorette";import Os from"fs";import*as jo from"path";import dP from"json5";var rP=[{productIndex:0,productName:"Pura 90 Pro",productType:"phone",subProductType:"phone"},{productIndex:1,productName:"MatePad 11.5'S",productType:"tablet",subProductType:"tablet"},{productIndex:2,productName:"Mate X7",productType:"phone",subProductType:"foldable"},{productIndex:3,productName:"Pura X",productType:"phone",subProductType:"widefold"},{productIndex:4,productName:"Mate XT",productType:"phone",subProductType:"triplefold"}],Fo={productIndex:0,productName:"phone",productType:"phone",subProductType:"phone"};async function oP(){return[]}async function kl(){let n=await oP();return n.length>0?n:rP}function Ns(n){return n.toLowerCase().replace(/[\s\W]+/g,"")}var iP={phone:"Pura 90 Pro",tablet:"MatePad 11.5'S",pad:"MatePad 11.5'S",fold:"Mate X7",foldable:"Mate X7",widefold:"Pura X",wide:"Pura X",triplefold:"Mate XT",triple:"Mate XT",pura90:"Pura 90 Pro",pura90pro:"Pura 90 Pro",matepad:"MatePad 11.5'S",matex7:"Mate X7",purax:"Pura X",matext:"Mate XT"};function sP(n,e){let t=n.length,r=e.length;if(t===0)return r;if(r===0)return t;let o=new Array(r+1),i=new Array(r+1);for(let s=0;s<=r;s++)o[s]=s;for(let s=1;s<=t;s++){i[0]=s;for(let a=1;a<=r;a++){let c=n[s-1]===e[a-1]?0:1;i[a]=Math.min(o[a]+1,i[a-1]+1,o[a-1]+c)}for(let a=0;a<=r;a++)o[a]=i[a]}return o[r]}function aP(n,e){let t=n.map(i=>({spec:i,dist:sP(e,Ns(i.productName))})),r=t.reduce((i,s)=>Math.min(i,s.dist),1/0);if(r>2)return;let o=t.filter(i=>i.dist===r);return o.length===1?{spec:o[0].spec,matchedName:o[0].spec.productName,fuzzy:!0,matchType:"fuzzy"}:{matchType:"none",ambiguous:o.map(i=>i.spec.productName)}}function xl(n,e){if(/[\u4e00-\u9fff\u3400-\u4dbf\u3040-\u30ff\uac00-\ud7af]/.test(e))return{matchType:"none"};let t=Ns(e);if(t.length===0)return{matchType:"none"};let r=n.find(a=>Ns(a.productName)===t);if(r)return{spec:r,matchedName:r.productName,matchType:"exact"};let o=iP[t];if(o){let a=n.find(c=>c.productName===o);if(a)return{spec:a,matchedName:a.productName,matchType:"alias"}}let i=n.filter(a=>{let c=Ns(a.productName);return c.includes(t)||t.includes(c)});if(i.length===1)return{spec:i[0],matchedName:i[0].productName,matchType:"substring"};if(i.length>1)return{matchType:"none",ambiguous:i.map(a=>a.productName)};let s=aP(n,t);return s||{matchType:"none"}}async function uP(n){for(let e of n){let{stdout:t}=await Nl("tasklist",["/FI",`IMAGENAME eq ${e}`,"/FO","CSV","/NH"],{reject:!1});if(t.toLowerCase().includes(e.toLowerCase()))return!0}return!1}async function pP(){try{let n=qc();if(n==="win32")return uP(["devecostudio64.exe","devecostudio.exe"]);if(n==="darwin"){let{stdout:e}=await Nl("pgrep",["-x","DevEco Studio"],{reject:!1});return e.trim().length>0}if(n==="openharmony"||n==="linux"){let{stdout:e}=await Nl("pgrep",["-f","com.huawei.devecostudio"],{reject:!1});return e.trim().length>0}}catch{}return!1}async function mP(n,e){if(!b()){if(await pP()){console.log("DevEco Studio is already running.");return}throw new Error(`DevEco Studio is not running. The previewer requires DevEco Studio to be running.
|
|
52
52
|
Please start DevEco Studio manually, then retry.`)}if(!n||!e)throw new Error("Internal error: hdcAdapter and targetDeviceId are required for IDE detection on HarmonyOS.");if(await n.isDevEcoStudioRunningViaHdc(e)){console.log("DevEco Studio is already running.");return}throw new Error(`DevEco Studio is not running. The previewer requires DevEco Studio to be running.
|
|
53
|
-
Please start DevEco Studio manually, then retry.`)}async function
|
|
53
|
+
Please start DevEco Studio manually, then retry.`)}async function fP(n,e){let t=await e.listDevices();if(t.length===0)return!1;let r=await e.listDevicesWithName();for(let o of n){if(t.some(s=>s.serial===o))return!0;let i=o.toLowerCase();if(r.some(s=>s.name.toLowerCase()===i))return!0}return!1}async function Jm(n,e){if(!n)return!1;let t=n.split(",").map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0||e&&await fP(t,e))return!1;let r=await kl(),o=r.length>0?r:[Fo];return t.every(i=>xl(o,i).spec!==void 0)}function hP(n,e){if(!n)return[e[0]||Fo];let t=n.split(",").map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0)return[e[0]||Fo];let r=[],o=[];for(let i of t){let s=xl(e,i);if(s.spec)r.push(s.spec),s.matchType==="fuzzy"?console.warn(Ol(` [fuzzy] "${i}" \u2192 ${s.matchedName}`)):(s.matchType==="alias"||s.matchType==="substring")&&console.log(` [${s.matchType}] "${i}" \u2192 ${s.matchedName}`);else{if(s.ambiguous&&s.ambiguous.length>0)throw new Error(`Ambiguous device name "${i}". Candidates:
|
|
54
54
|
`+s.ambiguous.map(a=>` - ${a}`).join(`
|
|
55
55
|
`)+`
|
|
56
56
|
Please specify a more precise name.`);o.push(i)}}if(o.length>0){let i=e.map(s=>s.productName).join(", ");throw new Error(`Device type(s) not found: ${o.join(", ")}
|
|
57
|
-
Available: ${i}`)}return
|
|
57
|
+
Available: ${i}`)}return gP(r)}function gP(n){let e=new Set,t=[];for(let r of n)e.has(r.productName)||(e.add(r.productName),t.push(r));return t}async function yP(n){if(!process.stdin.isTTY)return;console.log(""),console.log("No device connected. To connect to this HarmonyOS device:"),console.log(' 1. Open "Settings \u2192 System \u2192 Developer options \u2192 Wireless debugging"'),console.log(" 2. Enable it and note the port number shown"),console.log(" 3. Enter the port below (or set DEVECO_HDC_PORT env var)"),console.log("");let e=Ym.createInterface({input:cP,output:lP});try{let t=await e.question("Wireless debugging port: ");if(t.trim()){let r=`127.0.0.1:${t.trim()}`;return await n.connectTarget(r),console.log(Dr(`Connected to local device: ${r}`)),r}}catch{}finally{e.close()}}async function wP(n,e){if(e){let i=e.includes(":")?e:`127.0.0.1:${e}`;return await n.connectTarget(i),console.log(`Connected to local device: ${i}`),i}let t=process.env.DEVECO_HDC_PORT;if(t){let i=`127.0.0.1:${t}`;try{return await n.connectTarget(i),console.log(`Connected to local device via DEVECO_HDC_PORT: ${i}`),i}catch{console.warn(Ol(`DEVECO_HDC_PORT=${t} but connect failed, trying other methods...`))}}let r=await n.listRawTargets();if(r.length>0){let i=r[0];return m(`[preview] Found existing target: ${i}`),i}let o=await yP(n);if(o)return o;throw new Error(`Cannot connect to local HarmonyOS device.
|
|
58
58
|
Please either:
|
|
59
59
|
1. Run with --device 127.0.0.1:<port>, or
|
|
60
60
|
2. Set DEVECO_HDC_PORT env var, or
|
|
61
|
-
3. Open wireless debugging in system settings first.`)}async function
|
|
62
|
-
`))}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
|
|
61
|
+
3. Open wireless debugging in system settings first.`)}async function vP(n,e){let t=await n.listDevices();if(t.length===0)throw new Error(b()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device.");if(!e&&t.length>1){let o=await n.listDevicesWithName();throw new Error("Multiple devices found. Please specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+o.map(i=>` - ${i.name} (${i.serial})`).join(`
|
|
62
|
+
`))}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 SP(n){if(!Os.existsSync(n))throw new Error(`app.json5 not found at ${n}`);let e=Os.readFileSync(n,"utf8"),t=dP.parse(e);return t.app?.multiAppMode?(console.log("[multi-preview] app.json5 already has multiAppMode, skipping injection."),()=>{}):(t.app||(t.app={}),t.app.multiAppMode={multiAppModeType:"appClone",maxCount:5},Os.writeFileSync(n,JSON.stringify(t,null,2),"utf8"),console.log(`[multi-preview] Injected multiAppMode into ${jo.basename(n)}`),()=>{Os.writeFileSync(n,e,"utf8"),console.log(`[multi-preview] Restored original ${jo.basename(n)}`)})}async function bP(n){let{options:e,project:t,toolProvider:r,hdcAdapter:o,moduleName:i,isMulti:s,targetDeviceId:a}=n,c=jo.join(t.rootDir,"AppScope","app.json5"),l=s?SP(c):()=>{},d=s?"[multi-preview]":"[preview]";try{let h=e.product||"default",w=e.buildMode||"debug",v="default";if(s||!e.skipBuild){console.log(s?`
|
|
63
63
|
${d} Building with multiAppMode (appClone) for multi-instance preview...`:`
|
|
64
|
-
${d} Building and installing hap for preview...`);let
|
|
65
|
-
Launching DevEco Studio previewer on ${n.targetDeviceId}...`),console.log(` bundleName : ${n.bundleName}`),console.log(` abilityName : ${n.mainAbility}`),console.log(` moduleName : ${n.moduleJsonName}`),console.log(` instanceId : ${n.instanceId}`),console.log(` mode : ${n.isMulti?"multi":"single"}`),console.log(` previewers : ${n.targets.map(e=>e.productName).join(", ")}`)}async function
|
|
66
|
-
[${d+1}/${t.length}] Launching ${h.productName} (${h.productType}/${h.subProductType})...`);try{let v=await e.launchPreview(o,i,s,h.productName,h.productType,a,h.subProductType,c,w),
|
|
67
|
-
`+"\u2500".repeat(50));let e=n.filter(r=>r.success).length,t=n.length-e;console.log(`Previewer launch summary: ${
|
|
68
|
-
`),"Multiple devices found.")}let o=await n.getDeviceInfo(r,e);if(!o)throw new Error("No active devices found.");if(!e){let i=await n.getDeviceName(o.serial);console.log(`Auto-selected device: ${i} (${o.serial})`)}return o.serial}function
|
|
64
|
+
${d} Building and installing hap for preview...`);let ne=new cn(r,t.rootDir),Ve=new Oe(r,t.rootDir),lt=t.collectNonHarDependentModuleList(i).map(Wc=>`${Wc}@${v}`),gp=Lo(t,lt),Bc={type:"modules",modulesToBuild:lt,moduleTasks:gp};await _t(t.rootDir,async()=>{await Mo(ne,Ve,h,w,Bc,t.rootDir)},()=>console.log("Another build is already running. Waiting...")),console.log(Dr(`${d} Build completed.`))}else console.log(`${d} Skipping build (--skip-build), installing existing hap...`);let T=t.findArtifactPath(i,v,!1,h);console.log(`${d} Installing hap to ${a}...`),await o.installApp(a,[T]),console.log(Dr(`${d} Installed hap.`))}finally{l()}}function EP(n){console.log(`
|
|
65
|
+
Launching DevEco Studio previewer on ${n.targetDeviceId}...`),console.log(` bundleName : ${n.bundleName}`),console.log(` abilityName : ${n.mainAbility}`),console.log(` moduleName : ${n.moduleJsonName}`),console.log(` instanceId : ${n.instanceId}`),console.log(` mode : ${n.isMulti?"multi":"single"}`),console.log(` previewers : ${n.targets.map(e=>e.productName).join(", ")}`)}async function PP(n){let{hdcAdapter:e,targets:t,isMulti:r,targetDeviceId:o,bundleName:i,mainAbility:s,moduleJsonName:a,instanceId:c}=n,l=[];for(let d=0;d<t.length;d++){let h=t[d],w=r?d:-1;console.log(`
|
|
66
|
+
[${d+1}/${t.length}] Launching ${h.productName} (${h.productType}/${h.subProductType})...`);try{let v=await e.launchPreview(o,i,s,h.productName,h.productType,a,h.subProductType,c,w),T=/start ability successfully/i.test(v);l.push({name:h.productName,success:T,output:v}),T?console.log(Dr(` \u2713 ${h.productName}: ${v.trim()}`)):console.error(Ls(` \u2717 ${h.productName}: ${v.trim()}`))}catch(v){let T=v.message;l.push({name:h.productName,success:!1,output:T}),console.error(Ls(` \u2717 ${h.productName}: ${T}`))}}return l}function CP(n){console.log(`
|
|
67
|
+
`+"\u2500".repeat(50));let e=n.filter(r=>r.success).length,t=n.length-e;console.log(`Previewer launch summary: ${Dr(String(e))} succeeded, ${t>0?Ls(String(t)):"0"} failed.`);for(let r of n){let o=r.success?Dr("\u2713"):Ls("\u2717");console.log(` ${o} ${r.name}`)}return t===0}async function Km(n,e,t,r,o,i){let s=await kl(),a=s.length>0?s:[Fo],c=hP(n.device,a),l=c.length>1,d;if(b()){let T=(await r.listRawTargets()).find(ne=>ne.includes("127.0.0.1:"));T?(d=T,console.log(`Using self-connected device: ${d}`)):(console.warn(Ol("hdc \u672A\u81EA\u8054\u5230\u672C\u673A\u8BBE\u5907(\u9700\u8981 127.0.0.1:<port>)\u3002\u6B63\u5728\u5C1D\u8BD5\u81EA\u52A8\u8FDE\u63A5...")),d=await wP(r,void 0))}else d=await vP(o,void 0);let h={options:n,project:e,toolProvider:t,hdcAdapter:r,moduleName:i,targetDeviceId:d,isMulti:l,targets:c,bundleName:e.getBundleName(),mainAbility:e.getMainAbility(i,n.ability),moduleJsonName:e.getModuleName(i),instanceId:process.pid};await bP(h),await mP(r,d),EP(h);let w=await PP(h);return CP(w)}function Ll(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 Fs(n,e){let t=await n.ensureWirelessSelfConnection(),r=await n.listDevices();if(r.length===0)throw t.mode?new Error(b()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device."):new Error("No active devices found. To run on the local device, enable wireless debugging: Settings \u2192 System \u2192 Developer options \u2192 Wireless debugging");if(!e&&r.length>1){let i=await n.listDevicesWithName();throw new R("Multiple devices found. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+i.map(s=>` - ${s.name} (${s.serial})`).join(`
|
|
68
|
+
`),"Multiple devices found.")}let o=await n.getDeviceInfo(r,e);if(!o)throw new Error("No active devices found.");if(!e){let i=await n.getDeviceName(o.serial);console.log(`Auto-selected device: ${i} (${o.serial})`)}return o.serial}function Ml(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 R(`Specify module(s) using --module <name> [<name>...].
|
|
69
69
|
Available runnable modules:
|
|
70
70
|
`+t.map(r=>` - ${r.name}`).join(`
|
|
71
|
-
`),"Specify module error.")}function
|
|
72
|
-
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(
|
|
71
|
+
`),"Specify module error.")}function Xm(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 Zm(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(`
|
|
72
|
+
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($o(`
|
|
73
73
|
Application '${t}': ${s}`))}else console.log(`
|
|
74
|
-
Application '${t}' installed successfully (no ability to launch).`)}function
|
|
75
|
-
|
|
76
|
-
${n} is already up to date (v${e}, tag: ${t})`)),await
|
|
77
|
-
New version found: ${i} (current: ${e})`)),console.log(
|
|
78
|
-
`+
|
|
79
|
-
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:
|
|
80
|
-
`).trim(),a=
|
|
81
|
-
`:"";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=
|
|
82
|
-
`).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,t){let r=await this.listEmulators(),o=
|
|
83
|
-
`)}),!await this.waitForEmulatorPresenceByList(t))throw new Error(`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.`)}async waitForEmulatorPresenceByList(e,t=1e4,r=500){let o=Date.now()+t;for(;Date.now()<o;){if((await this.listEmulators()).some(a=>
|
|
84
|
-
The device may be running.`);return await this.runEmulatorChecked(["-delete",i,"-force"],{printOutputOnSuccess:!1}),i}};import{red as
|
|
85
|
-
`)}async function
|
|
86
|
-
`),"Multiple devices connected.")}async function
|
|
74
|
+
Application '${t}' installed successfully (no ability to launch).`)}function DP(n){let e={event:A.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 _l=new IP("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/");b()||_l.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.");_l.action(async n=>{let e=DP(n),t=Date.now(),r=!0,o=null;try{let i=await xP(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=Y(i),console.error(AP(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 TP(n,e,t,r,o){let i=new cn(e,n.rootDir),s=new Oe(e,n.rootDir),a=new Set,c=new Set;for(let{moduleName:v,targetName:T}of t)for(let ne of n.collectNonHarDependentModuleList(v))a.add(`${ne}@${T}`),c.add(ne);let l=[...a],d=Lo(n,l),h={type:"modules",modulesToBuild:l,moduleTasks:d};for(let v of c)As.generate(n.rootDir,v,r,e);let w=await _t(n.rootDir,()=>Mo(i,s,r,o,h,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion..."));return console.log(`
|
|
75
|
+
`+$o("Build completed successfully.")),w}async function RP(n,e,t,r,o){let i=new jt(t),s=ae.from(t),a=r[0]?.moduleName||o[0];await Km(n,e,t,i,s,a)}function kP(n,e){for(let{moduleName:t}of e){let r=n.getModuleType(t);if(r!=="entry"&&r!=="feature"&&r!=="shared")throw new R(`Module '${t}' '${r}' is not runnable. Specify an entry or feature module.`,"Module is not runnable.")}}async function xP(n,e){let t=J.discover(process.cwd());console.warn(Ms("Ensure the project source is trusted before proceeding."));let r=await D.new();if(n.skipBuild||r.assertJava(),e.bundle_name=t.getBundleName(),n.hotreloadApply){await OP(n,t,r);return}if(n.hotreload){await NP(n,t,r);return}if(n.apply){await MP(n,t,r);return}return Qm(n,t,r)}async function NP(n,e,t){if(n.hotreload==="stop"){await qm(t,e);return}let o=Ml(e,n.module).map(Ll),{moduleName:i,targetName:s}=o[0];Rl(n.module,i);let a=new jt(t),c=ae.from(t),l=await Fs(c,n.device),d=l.includes("127.0.0.1")||l.includes("localhost"),h=n.product||"default";e.validateProduct(h);let w=e.getBundleName(),v=Xm(e,o,n.ability);Ds.generate(e.rootDir,i,h,t);let T=new Oe(t,e.rootDir);console.log($o("Ensuring hvigor daemon is running (via --sync --daemon, no hap build)...")),await T.ensureDaemonRunning();let ne=[`${i}@${h}`];for(let lt of e.collectNonHarDependentModuleList(i))ne.includes(`${lt}@${h}`)||ne.push(`${lt}@${h}`);console.log($o("Building hap + starting watch session (socket -> CommonBuild assembleHap --hot-reload-build --watch, kept open)..."));let Ve=new Ar(e.rootDir,t);await Ve.startWatchSession({moduleSpecs:ne,productName:h});let ct=zm(e,i,s,d,h);await Zm(a,l,w,ct,v,!!n.uninstall),console.log($o("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.")),Ve.onSocketDisconnect(()=>{console.log("Daemon disconnected (likely via --hotreload stop). Exiting watch session."),process.exit(0)}),await new Promise(()=>{})}async function OP(n,e,t){let r=n.hotreloadApply;if(!r)throw new Error("hotreload-apply requires --hotreload-apply <fileName> (under .hvigor/)");let o=Ml(e,n.module),{moduleName:i}=Ll(o[0]);Rl(n.module,i);let s=ae.from(t),a=await Fs(s,n.device),c=n.product||"default";e.validateProduct(c);let l=e.getBundleName();Gm(e,i,r);let d=[`${i}@${c}`],h=await Vm({applyFileName:r,projectPath:e.rootDir,moduleName:i,productName:c,bundleName:l,toolProvider:t,targetDeviceId:a,moduleSpecs:d});if(!h.success)throw new Error(h.message)}function LP(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 Qm(n,e,t){let r=Ml(e,n.module),o=r.map(Ll),i=ae.from(t);if(await Jm(n.device,i)){await RP(n,e,t,o,r);return}kP(e,o);let s=new jt(t),a=await Fs(i,n.device),c=a.includes("127.0.0.1")||a.includes("localhost"),l=n.product||"default";e.validateProduct(l);let d=n.buildMode||"debug",h;n.skipBuild||(h=await TP(e,t,o,l,d));let w=LP(e,o,c,l),v=e.getBundleName(),T=Xm(e,o,n.ability);return await Zm(s,a,v,w,T,!!n.uninstall),h}async function MP(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(_s.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let o=_s.join(e.rootDir,".hvigor",r),i=ae.from(t),s=await Fs(i,n.device),a=n.product||"default";e.validateProduct(a);let c=e.getBundleName(),l=e.profile.modules.find(w=>e.getModuleType(w.name)==="entry")?.name,d=l?e.getMainAbility(l,n.ability):n.ability||"EntryAbility",h=new Is(t,e.rootDir);try{await h.execute({applyFile:o,productName:a,targetDeviceId:s,bundleName:c,abilityName:d}),console.log(Ms("[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(w){console.warn(Ms(`[Apply] \u5931\u8D25\uFF1A${w.message}`)),console.warn(Ms("[Apply] \u81EA\u52A8\u56DE\u9000\u5230\u5168\u91CF devecocli run..."))}await Qm(n,e,t)}var ef=_l;import{Command as _P}from"commander";import{green as tf,red as nf,cyan as Fl}from"colorette";import{execa as rf}from"execa";function FP(){return"daily"}function jP(){return process.env.DEVECO_CLI_WRAPPER_NAME?process.env.DEVECO_CLI_WRAPPER_NAME:"@deveco-test/deveco-cli-openharmony-arm64"}function $P(){return process.env.DEVECO_CLI_WRAPPER_VERSION?process.env.DEVECO_CLI_WRAPPER_VERSION:"1.3.11-Test.1"}var HP={event:A.CommandExecuted,args:["update"]};async function jl(n,e,t){let r={duration_ms:Date.now()-n,success:e,error_code:t};await I.track(HP,r).catch(()=>{})}async function UP(n,e,t){let r=Y(t);console.error(nf(`Failed to update ${n}`));let o=t instanceof Error?t.message:"";o&&console.error(nf(o)),await jl(e,!1,r),process.exit(1)}var BP=new _P("update").description("Update deveco-cli to latest").action(async()=>{let n=jP(),e=$P(),t=FP(),r=Date.now();console.log(Fl("Checking for updates..."));try{let{stdout:o}=await rf("npm",["view",n,`dist-tags.${t}`]),i=o.trim();if(!i||i===e){console.log(tf(`
|
|
76
|
+
${n} is already up to date (v${e}, tag: ${t})`)),await jl(r,!0,null);return}console.log(Fl(`
|
|
77
|
+
New version found: ${i} (current: ${e})`)),console.log(Fl(`Updating ${n}...`)),await rf("npm",["install","-g",`${n}@${t}`],{stdio:"inherit"}),console.log(`
|
|
78
|
+
`+tf(`${n} updated successfully to version ${i}.`)),await jl(r,!0,null)}catch(o){await UP(n,r,o)}}),of=BP;import{Command as yC}from"commander";import{execa as $s}from"execa";function Ie(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as WP}from"child_process";var VP=2500;function GP(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 zP(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,VP);n.once("error",d=>c(d.message)),GP(n,l,s,a,c,i)}function sf(n,e,t){return m(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,o)=>{let i=[],s=WP(n,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>i.push(a)),zP(s,i,r,o)})}import*as Tr from"path";function qP(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 YP(n){let e=n.instancePath?.trim();if(e)return Tr.dirname(Tr.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?Tr.dirname(Tr.normalize(t)).replace(/\\/g,"/"):""}function JP(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function af(n,e){return e?[...n,"-bootmode",e]:n}function KP(n,e,t){let r=[af(["-start",n],t)],o=YP(e);if(o)for(let i of JP(e.imageRoot))r.push(af(["-hvd",n,"-path",o,...i],t));return qP(r)}async function cf(n,e,t,r){let o=new Error("No start strategy ran"),i=KP(n,e,r);for(let s of i)try{return await t(s),{ok:!0}}catch(a){o=a}return{ok:!1,lastError:o}}async function $l(n){return(await ae.withHdcPath(n).listDevices()).map(t=>t.serial).filter(qn)}async function Hl(n){let e=await $l(n);return e.length===0?[]:(await Promise.all(e.map(r=>Cs(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function lf(n,e){return(await Hl(n)).includes(e)}import*as kr from"path";import{existsSync as XP,statSync as ZP}from"fs";function Rr(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function QP(n){let e=Rr(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 eC(n){return Rr(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function tC(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=kr.dirname(kr.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let o=kr.join(t,r.name);XP(o)&&ZP(o).isDirectory()&&(r.instancePath=o.replace(/\\/g,"/"))}}function nC(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=eC(t),o=Rr(t,["deviceType","DeviceType","devicetype"]),i=Rr(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:QP(t),path:Rr(t,["path","Path","hvdPath","hvd_path"]),imageRoot:Rr(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 rC(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 df(n){let t=nC(n)??rC(n);return tC(t),t}function Ul(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function oC(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function iC(n){if(!oC(n))return null;let e=Ul(n,["osVersion","OsVersion","OSVersion"]),t=Ul(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=Ul(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function js(n){let e=n.trim();if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let r=[];for(let o of t){if(!o||typeof o!="object")continue;let i=iC(o);i&&r.push(i)}return r}catch{return[]}}function uf(n){let t=js(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var pf=/no images are available/i,sC="7.0.0",aC={foldable:["open","half-open","close"],"2in1_foldable":["open","vertical-open","half-open","close"],triplefold:["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"]};function ft(n){return n.normalize("NFKC").trim().toLowerCase()}function cC(n,e){let t=n.deviceType?.trim(),r=t?aC[ft(t)]:void 0;if(!r)throw new Error(`Fold-state control is not supported for emulator "${n.name}" (device type: ${t||"unknown"}).`);if(!r.includes(e))throw new Error(`Fold state "${e}" is not supported by emulator "${n.name}" (device type: ${t}). Available states: ${r.join(", ")}.`)}function lC(n){let e=n.message||"";return pf.test(e)}function dC(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function Ho(n,e){return`${n} ${e.join(" ")}`.trim()}function uC(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 xr=class n{static supportedControlPaths=new Set;emulatorPath;sdkPath;hdcPath;constructor(e,t,r){this.emulatorPath=e,this.sdkPath=t,this.hdcPath=r}static from(e){return new n(e.emulatorPath,e.sdkPath,e.hdcPath)}async executeEmulator(e){return m(`Executing: ${Ho(this.emulatorPath,e)}`),$s(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return sf(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return df(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let r of t)r.name&&r.deviceType&&e.set(Ie(r.name),r.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),r=Ie(e),o=t.find(a=>Ie(a.name)===r);if(!o)throw new Error(`Emulator "${e}" not found.`);let i=o.name;if(await this.isAlreadyRunning(i,o))return"already-running";await this.assertSystemImageAvailable(o);let s=await cf(i,o,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return"started";if(await this.isAlreadyRunning(i))return"already-running";throw new Error(`Unable to start emulator "${e}". All methods failed.
|
|
79
|
+
Last error: ${s.lastError.message||"unknown"}`)}async isAlreadyRunning(e,t){return t?.isRunning===!0||t===void 0&&(await this.listEmulators()).find(o=>o.name===e)?.isRunning===!0?!0:lf(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=Ie(e),o=t.find(a=>Ie(a.name)===r);if(!o)throw new Error(`Emulator "${e}" 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 R(`Emulator "${e}" not found.`,"Emulator instance not found.");if(!await this.isAlreadyRunning(o.name,o))throw new R(`Emulator "${e}" is not running.`,"Emulator instance is not running.");t.type==="folded-state"&&cC(o,t.state);let i=this.buildControlArgs(o.name,t);m(`[EmulatorManager] control ${uC(t)} -> ${Ho(this.emulatorPath,i)}`),await this.runEmulatorChecked(i,{printOutputOnSuccess:!1})}async assertControlCommandSupported(){let e=this.emulatorPath;if(n.supportedControlPaths.has(e))return;let t=["-version"];m(`Executing: ${Ho(this.emulatorPath,t)}`);let{stdout:r,stderr:o,exitCode:i}=await $s(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(`
|
|
80
|
+
`).trim(),a=dC(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(D.compareVersion(a,sC)<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],{type:o}=t;switch(o){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(`Unsupported emulator control action type: ${o}`)}}async executeEmulatorInherit(e){m(`Executing: ${Ho(this.emulatorPath,e)}`);let{exitCode:t}=await $s(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 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(!lC(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 listDownloadedImageOsVersions(){let e=await this.listEmulatorImages({downloaded:!0});return uf(e)}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}
|
|
81
|
+
`:"";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=js(t),o=ft(e.deviceType),i=ft(e.osVersion);return r.filter(s=>ft(s.deviceType)===o&&(ft(s.osVersion)===i||ft(s.softwareVersion)===i))}async hasDownloadedSystemImage(e,t){let r=await this.listEmulatorImages({downloaded:!0}),o=js(r),i=ft(t),s=e?.trim()?ft(e):void 0;return o.some(a=>ft(a.osVersion)===i||ft(a.softwareVersion)===i?s===void 0?!0:ft(a.deviceType)===s:!1)}async assertSystemImageAvailable(e){let t=e.osVersion?.trim();if(!t)throw new Error("The system image file cannot be found, download it again.");if(!await this.hasDownloadedSystemImage(e.deviceType,t))throw new Error(`The system image file ${t} cannot be found, download it again.`)}async runUninstallImageChecked(e,t){await this.runEmulatorChecked(["-uninstall","-deviceType",e,"-osVersion",t,"-force"],{printOutputOnSuccess:!0,extraReject:[pf]})}async runEmulatorChecked(e,t){m(`Executing: ${Ho(this.emulatorPath,e)}`);let{stdout:r,stderr:o,exitCode:i}=await $s(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(`
|
|
82
|
+
`).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,t){let r=await this.listEmulators(),o=Ie(e),i=r.find(s=>Ie(s.name)===o);if(i)if(t)await this.deleteVirtualDevice(i.name);else throw new Error(`Emulator "${e}" already exists. Use \`--force\` to overwrite.`);return o}async createVirtualDevice(e){let t=await this.checkExistingVirtualDevice(e.name,e.force),r=["-create",e.name,"-deviceType",e.deviceType,"-osVersion",e.osVersion];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(`
|
|
83
|
+
`)}),!await this.waitForEmulatorPresenceByList(t))throw new Error(`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.`)}async waitForEmulatorPresenceByList(e,t=1e4,r=500){let o=Date.now()+t;for(;Date.now()<o;){if((await this.listEmulators()).some(a=>Ie(a.name)===e))return!0;await new Promise(a=>setTimeout(a,r))}return!1}async deleteVirtualDevice(e){let t=await this.listEmulators(),r=Ie(e),o=t.find(s=>Ie(s.name)===r);if(!o)throw new Error(`Emulator "${e}" not found.`);let i=o.name;if(o.isRunning===!0||await this.isAlreadyRunning(i,o))throw new Error(`Failed to delete device: ${i}
|
|
84
|
+
The device may be running.`);return await this.runEmulatorChecked(["-delete",i,"-force"],{printOutputOnSuccess:!1}),i}};import{red as wC,yellow as hf,gray as gf}from"colorette";import vC from"ora";import{green as pC}from"colorette";var mC=[[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]],fC=[[0,31],[127,159],[768,879],[6832,6911],[7616,7679],[8203,8207],[8400,8447],[65024,65039],[65056,65071],[8205,8205]],hC=new RegExp("\x1B\\[([0-9;]*)[a-zA-Z]","g");function mf(n,e){for(let[t,r]of e)if(n>=t&&n<=r)return!0;return!1}function Bl(n){let e=n.replace(hC,""),t=0,r=0;for(;r<e.length;){let o=e.codePointAt(r);if(o===void 0)break;mf(o,fC)||(mf(o,mC)?t+=2:t+=1),r+=o>65535?2:1}return t}function ff(n,e){let t=Bl(n);return n+" ".repeat(Math.max(0,e-t))}function gC(n,e){return n.map((t,r)=>{let o=Bl(t);for(let i of e){let s=i.cells[r]??"";o=Math.max(o,Bl(s))}return o})}function Ht(n,e){let t=gC(n,e),r=[];r.push(n.map((o,i)=>ff(o,t[i])).join(" ")),r.push(t.map(o=>"-".repeat(o)).join(" "));for(let o of e){let i=o.cells.map((s,a)=>ff(s??"",t[a])).join(" ").trimEnd();r.push(o.highlight?pC(i):i)}return r.join(`
|
|
85
|
+
`)}async function yf(n,e){let t=Date.now(),r=!0,o=null;try{await e()}catch(i){r=!1,o=Y(i),console.error(wC(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await I.track(n,i)}}function SC(n,e){if(e.size!==0)for(let t of n){if(!t.isEmulator||!t.name)continue;let r=e.get(Ie(t.name));r&&(t.deviceType=r)}}var bC=["Name","Serial","Kind","Device Type"];function EC(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function PC(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function CC(){console.log(hf(" No active devices.")),console.log(gf(b()?" Connect a USB device with debugging enabled.":" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function Wl(n,e){n||console.log(gf(` To ${e==="list"?"list local devices":"view local device details"}, enable wireless debugging: Settings \u2192 System \u2192 Developer options \u2192 Wireless debugging`))}function IC(n){let t=[...n].sort(PC).map(EC);console.log(Ht(bC,t))}async function AC(n,e){if(b()||!n.some(o=>o.isEmulator)||!e.emulatorPath)return;let r=await xr.from(e).getDeviceTypeByName();SC(n,r)}async function DC(n,e,t){try{let r=await n.ensureWirelessSelfConnection(),o=await n.getConnectedEntries();await AC(o,e),t?.stop(),o.length===0?CC():IC(o),Wl(r.mode,"list")}catch(r){throw new R(`Failed to list devices: ${r.message}`,"Failed to list devices.")}finally{t?.stop()}}async function TC(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 R(r.join(`
|
|
86
|
+
`),"Multiple devices connected.")}async function RC(n,e){let t=await n.ensureWirelessSelfConnection();e||await TC(n,"devecocli device view");let r=await n.listDevices(),o=await n.getDeviceInfo(r,e);if(!o)throw console.log(hf("No connected device found.")),Wl(t.mode,"view"),new R("No connected device found.");let i=await n.getDeviceDetail(o.serial),s=await n.getDeviceName(o.serial);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}`),Wl(t.mode,"view")}async function wf(){try{let n=await D.new();return{manager:ae.from(n),toolProvider:n}}catch(n){throw new R(`Failed to initialize device manager: ${n.message}`,"Failed to initialize device manager.")}}var Vl=new yC("device").description("Manage connected devices");Vl.command("list").description("List all connected devices").action(async()=>{let n={event:A.CommandExecuted,args:["device","list"]};await yf(n,async()=>{let{manager:e,toolProvider:t}=await wf(),r=vC({text:"Querying connected devices\u2026",color:"cyan"}).start();await DC(e,t,r)})});Vl.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").action(async n=>{let e={event:A.CommandExecuted,args:["device","view",...n.target?["--target"]:[]]};await yf(e,async()=>{let{manager:t}=await wf();await RC(t,n.target)})});var vf=Vl;import{Argument as Xl,Command as Zl,Option as Vo}from"commander";import{green as Go,cyan as Or,red as Le,yellow as Dt,gray as Wo}from"colorette";import zC from"ora";import{red as kC}from"colorette";function Sf(n,e){n?n.fail(e):console.error(kC(e)),process.exit(1)}import xC from"readline/promises";import{execa as Ef}from"execa";import*as dn from"fs/promises";import*as zl from"os";import*as Xn from"path";var Gl=`1/4:\r
|
|
87
87
|
---------------------------------------\r
|
|
88
88
|
Statement About HarmonyOS and Privacy\r
|
|
89
89
|
\r
|
|
@@ -1253,13 +1253,13 @@ Part I: Chinese mainland.\r
|
|
|
1253
1253
|
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
|
|
1254
1254
|
\r
|
|
1255
1255
|
Part III: Other countries and regions.\r
|
|
1256
|
-
---------------------------------------\r`;var
|
|
1257
|
-
`),
|
|
1258
|
-
`)}function
|
|
1259
|
-
${t}.`);return
|
|
1260
|
-
`,"utf8"),!0}catch{}return!1}async function
|
|
1256
|
+
---------------------------------------\r`;var NC=new Set,Hs=new Map,ql="HarmonyOS_Software_Service_Agreement",Pf=["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(`
|
|
1257
|
+
`),Cf=Pf,Yl="HarmonyOS_SDK_Agreement";function If(n,e){return`${n}\0${e}`}function Af(){NC.clear(),Hs.clear()}var OC=Pf,nt=class extends Error{constructor(e=OC){super(e),this.name="EmulatorLicenseBlockedError"}};function Df(n,e){return[n??"",e??""].join(`
|
|
1258
|
+
`)}function Tf(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 LC(n){return`Emulator${n.trim()}`}function Rf(n){let e=LC(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 Xn.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return Xn.join(zl.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||Xn.join(zl.homedir(),".cache");return Xn.join(t,"Huawei",e,".emu_config")}async function MC(n,e,t){let r=If(n,e),o=Hs.get(r);if(o!==void 0)return o;let i=await Ef(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=Df(i.stdout,i.stderr).trim();if(i.exitCode!==0||!s)throw new nt(t);return Hs.set(r,s),s}function _C(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function FC(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 jC(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=_C(e.slice(r+1).trim());return{key:o,entry:{value:i,delimiter:t}}}}function $C(n){let e={};for(let t of n.split(/\r?\n/)){let r=jC(t);r&&(e[r.key]=r.entry)}return e}function HC(n){let e=n.trim();if(!e)return{};let t=FC(e);return t||$C(n)}function UC(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function kf(n,e,t,r){let o=await MC(n,e,r),i=Tf(o);if(!i)throw new nt(r);let s=Rf(i),a;try{a=await dn.readFile(s,"utf8")}catch(d){throw d.code==="ENOENT"?new nt(r):d}let l=HC(a)[t];if(!l)throw new nt(r);if(l.delimiter==="=")throw new nt(r);if(!UC(l.value))throw new nt(r)}async function Jl(n,e){await kf(n,e,ql,Cf)}async function Kl(n,e){await kf(n,e,Yl,Cf)}async function BC(n,e){let t=await Ef(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),r=Df(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=If(n,e);return Hs.set(o,r),r}async function xf(n,e){let t=await BC(n,e),r=Tf(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
|
|
1259
|
+
${t}.`);return Rf(r)}function bf(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function WC(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[ql]="agree",r[Yl]="agree",await dn.writeFile(n,`${JSON.stringify(r,null,2)}
|
|
1260
|
+
`,"utf8"),!0}catch{}return!1}async function VC(n,e){let t=ql,r=Yl,o=[{k:t,re:new RegExp(`^\\s*${bf(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${bf(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:h}of o)if(h.test(c)){s.push(`${d}:agree`),a.add(d),l=!0;break}l||s.push(c)}a.has(t)||s.push(`${t}:agree`),a.has(r)||s.push(`${r}:agree`),await dn.writeFile(n,s.join(`
|
|
1261
1261
|
`)+(s.length>0?`
|
|
1262
|
-
`:""),"utf8")}async function
|
|
1262
|
+
`:""),"utf8")}async function Nf(n){await dn.mkdir(Xn.dirname(n),{recursive:!0});let e="";try{e=await dn.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await WC(n,e,t)||await VC(n,e)}async function Of(n,e){return console.log(Gl),0}var GC="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function Lf(n,e){try{return await Jl(n,e),await Kl(n,e),!0}catch(t){if(t instanceof nt)return!1;throw t}}async function Mf(n,e){if(await Lf(n,e))return console.log("Emulator license agreements are already accepted."),0;if(console.log(Gl),!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=xC.createInterface({input:process.stdin,output:process.stdout}),o;try{o=await r.question(GC)}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 xf(n,e);await Nf(s),Af()}catch(s){return console.error(s.message),1}return console.log("Emulator license agreements accepted."),0}async function _f(n,e){if(await Lf(n,e))return console.log("Emulator license agreements are already accepted."),0;try{let t=await xf(n,e);await Nf(t),Af()}catch(t){return console.error(t.message),1}return console.log("Emulator license agreements accepted."),0}var qC=["ohos.qemu.hvd.name","const.product.name","const.product.model"],Ff=["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"],YC=`
|
|
1263
1263
|
Folded state scene mappings:
|
|
1264
1264
|
foldableFold (3):
|
|
1265
1265
|
open Fully expanded state
|
|
@@ -1282,43 +1282,43 @@ Folded state scene mappings:
|
|
|
1282
1282
|
left-half-folded-right-folded
|
|
1283
1283
|
left-expanded-right-half-folded
|
|
1284
1284
|
left-half-folded-right-half-folded
|
|
1285
|
-
`;function zC(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function YC(n){let e=n.trim();if(!xf.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${xf.join(", ")}`);return e}function Lf(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 Of(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&&!JC(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 JC(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function KC(n,e,t,r,o){return Number(Of(n,e,t,r,o))}function XC(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 ZC(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 QC(n,e){let t=o=>o.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(Tt("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(Tt("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(o=>t(o)===r)){console.error(Te("--os-version does not match any downloaded image (exact string required).")),console.log(Tt("Use one of these --os-version values:"));for(let o of e)console.log(` ${o}`);throw new Error(`No downloaded image matches --os-version "${n}".`)}}var eI=["Name","Status","Serial","Device Type","OS Version"];function tI(n,e,t){return{cells:[n.name,t?"running":"stopped",e??"-",n.deviceType??"-",n.osVersion??"-"],highlight:t}}async function nI(n,e){let t=await Promise.all(e.map(async r=>{let o=await br(n,r,GC);return[r,o]}));return new Map(t)}async function rI(n){let e=await Fl(n),t=await nI(n,e);return{serials:e,params:t}}function oI(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 iI(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&&oI(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 sI(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(o=>tI(o.emu,o.serial,o.effectiveRunning))}async function aI(n,e,t){try{let[r,o]=await Promise.all([n.listEmulators(),rI(e)]);if(r.length===0){t?.stop(),console.log(Tt(" No emulator instances found."));return}let i=r.filter(l=>l.isRunning).map(l=>l.name),{productSerialMap:s,hvdSerialMap:a}=iI(o.serials,o.params,i);t?.stop();let c=sI(r,s,a);console.log(Bt(eI,c))}catch(r){ff(t,`Failed to list emulators: ${r.message}`)}}function Mf(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(Te(`Failed to ${t} emulator "${e[o]}": ${s.message}`)),s.stdout&&console.error(Uo(s.stdout)),s.stderr&&console.error(Uo(s.stderr))}return r}var cI=2e3,lI=6e4;async function dI(n,e){let t=Ae(e);return(await jl(n)).some(o=>Ae(o)===t)}async function _f(n,e,t,r=lI,o=cI){let i=Date.now()+r;for(;Date.now()<i;){if(await dI(n,e)===t)return!0;await new Promise(a=>setTimeout(a,o))}return!1}async function uI(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(Tt(`Emulator "${t}" is already running.`));return}console.log(Nr(`Starting emulator "${t}"...`));let o=await _f(e,t,!0);console.log(o?Vo(`Emulator "${t}" started successfully.`):Tt(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function pI(n,e,t){let r=await Promise.allSettled(t.map(i=>uI(n,e,i)));Mf(r,t,"start")&&process.exit(1)}async function Ff(n,e){let t=e.trim();if(!Yn(t))return t;let r=await ae.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 mI(n,e,t){let r=await Ff(e,t);if(console.log(Nr(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(Tt(`Emulator "${r}" is already stopped.`));return}let i=await _f(e,r,!1);console.log(i?Vo(`Emulator "${r}" stopped successfully.`):Tt(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function fI(n,e,t){let r=await Promise.allSettled(t.map(i=>mI(n,e,i)));Mf(r,t,"stop")&&process.exit(1)}async function ot(){try{let n=await A.new();return{manager:Rr.from(n),toolProvider:n}}catch(n){console.error(Te(`Failed to initialize emulator: ${n.message}`)),process.exit(1);return}}async function Ut(n,e){try{let t=zC(n.target),r=e(),{manager:o,toolProvider:i}=await ot(),s=await Ff(i.hdcPath,t);await o.controlEmulator(s,r),console.log(Vo(`Emulator "${t}" operation completed.`))}catch(t){let r=n.target?.trim()||"<unknown>";console.error(Te(`Failed to operate emulator "${r}": ${t.message}`)),process.exit(1)}}function hI(n){let e=[];return $s(e,"longitude",n.longitude,-180,180,8),$s(e,"latitude",n.latitude,-90,90,8),$s(e,"altitude",n.altitude,-1e4,1e4,2),$s(e,"bearing",n.direction,0,359.99,2,"--direction"),Xl(e,"Specify one geolocation option.")}function gI(n){let e=[];return Ho(e,"light",n.lightIntensity,0,1e5,!1,"--light-intensity"),Ho(e,"humidity",n.humidity,0,100,!1),Ho(e,"temperature",n.temperature,-273.1,100,!1),Ho(e,"steps",n.steps,0,1e4,!0),Ho(e,"heartrate",n.heartrate,0,255,!0),Xl(e,"Specify one sensor option.")}function Xl(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 $s(n,e,t,r,o,i,s=`--${e}`){t!==void 0&&n.push({type:"gps",key:e,value:Of(s,t,r,o,i)})}function Ho(n,e,t,r,o,i,s=`--${e}`){if(t===void 0)return;let a=i?Lf(s,t,r,o):KC(s,t,r,o,1);n.push({type:"sensor",key:e,value:a})}function yI(n){let e=[];return n.level!==void 0&&e.push({type:"battery",level:Lf("--level",n.level,1,100)}),n.status!==void 0&&e.push({type:"battery-status",status:n.status==="charging"?1:0}),Xl(e,"Specify --level or --status.")}var Se=new Kl("emulator").description("Manage emulator instances"),wI=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Hs(n){let e=new Wo("--device-type <type>","Emulator device type").choices([...wI]);return n?e.makeOptionMandatory():e}function xr(n,e){for(let t of e)if(t in n)return n[t]}function Bo(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function Nf(n){let e=Bo(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var vI=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],SI="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function jf(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function $f(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let o=r,i=Bo(xr(o,["osVersion","OsVersion","OSVersion","os_version"])),s=Bo(xr(o,["deviceType","DeviceType","device_type"])),a=Nf(xr(o,["downloaded","Downloaded","isDownloaded"])),c=Bo(xr(o,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=Bo(xr(o,["releaseType","ReleaseType","release_type"])),d=Nf(xr(o,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[i,s,c,l,d,a],highlight:e&&a==="true"})}return t}function bI(n){let e=n.trim();if(!e)return!0;let t=jf(e);return t===null?!1:t.length===0?!0:$f(t,!0).length===0}function EI(n,e){let t=n.trim();if(!t)return"";let r=jf(t);if(!r)return n.trimEnd();let o=$f(r,e);return Bt(vI,o)}var Bs=new Kl("image").description("HarmonyOS emulator system images (download, list, remove)");Bs.command("download").description("Download system image").addOption(Hs(!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{manager:e,toolProvider:t}=await ot();try{await Yl(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof rt&&(console.error(Te(r.message)),process.exit(1)),r}n.deviceType?.trim()||(console.error(Te("Error: missing required option '--device-type <type>'")),process.exit(1)),n.osVersion?.trim()||(console.error(Te("Error: misssing required option '--os-version <version>'")),process.exit(1));try{await e.installEmulatorImage({deviceType:n.deviceType.trim(),osVersion:n.osVersion.trim(),force:n.force===!0})}catch(r){console.error(Te(`Failed to download system image: ${r.message}`)),process.exit(1)}});Bs.command("remove").description("Remove a downloaded system image").addOption(Hs(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let{manager:e}=await ot();try{await e.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})}catch(t){console.error(Te(`Failed to remove system image: ${t.message}`)),process.exit(1)}});Bs.command("list").description("List system images").addOption(Hs(!1)).option("--all","List all images (local and remote)").addOption(new Wo("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await ot();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if(bI(r)){console.log(Tt(SI));return}if(n.format==="json"){console.log(r.trimEnd());return}let o=EI(r,n.all===!0);console.log(o)}catch(t){console.error(Te(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});Se.addCommand(Bs);var Us=new Kl("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");Us.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let{toolProvider:n}=await ot(),e=await Df(n.emulatorPath,n.sdkPath);process.exit(e)});Us.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let{toolProvider:n}=await ot(),e=await Rf(n.emulatorPath,n.sdkPath);process.exit(e)});Us.action(async()=>{let{toolProvider:n}=await ot(),e=await kf(n.emulatorPath,n.sdkPath);process.exit(e)});Se.addCommand(Us);Se.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Ut(n,()=>({type:"shake"})));Se.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Ut(n,()=>({type:"power"})));Se.command("rotate").description("Rotate emulator").addOption(new Wo("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Jl("<direction>").choices(["left","right"])).action((n,e)=>Ut(e,()=>({type:"rotation",direction:n})));Se.command("volume").description("Change volume").addOption(new Wo("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Jl("<direction>").choices(["up","down"])).action((n,e)=>Ut(e,()=>({type:"volume",direction:n})));Se.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",qC).action((n,e)=>Ut(e,()=>({type:"folded-state",state:YC(n)})));Se.command("battery").description("Set battery level or charging status").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--level <1-100>","Battery level, SOC (integer 1-100)").addOption(new Wo("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>Ut(n,()=>yI(n)));Se.command("geolocation").description("Inject geographic coordinates and direction").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--longitude <value>","Longitude (-180.0 to 180.0)").option("--latitude <value>","Latitude (-90.0 to 90.0)").option("--altitude <value>","Altitude (-10000.0 to 10000.0)").option("--direction <value>","Heading direction in degrees (0.00 to 359.99)").action(n=>Ut(n,()=>hI(n)));Se.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new Jl("<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 Ut(e,()=>t[n])});Se.command("sensor").description("Inject sensor data").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--light-intensity <value>","Light sensor (0 to 100000)").option("--humidity <value>","Humidity sensor (0 to 100)").option("--temperature <value>","Temperature sensor (-273.1 to 100)").option("--steps <value>","Steps sensor (integer 0 to 10000)").option("--heartrate <value>","Heart rate sensor (integer 0 to 255)").action(n=>Ut(n,()=>gI(n)));Se.command("list").description("List all emulator instances").action(async()=>{let{manager:n,toolProvider:e}=await ot(),t=VC({text:"Listing emulators\u2026",color:"cyan"}).start();await aI(n,e.hdcPath,t)});Se.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await ot();try{await zl(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof rt&&(console.error(Te(r.message)),process.exit(1)),r}n?.length||(console.error(Te("Error: missing required argument 'names'")),process.exit(1)),await pI(e,t.hdcPath,n)});Se.command("stop <names...>").description("Stop one or more emulator instances (by name or serial,e.g.,127.0.0.1:<port>)").action(async n=>{let{manager:e,toolProvider:t}=await ot();n?.length||(console.error(Te("Error: missing required argument 'names'")),process.exit(1)),await fI(e,t.hdcPath,n)});var Hf=Se.command("create <name>").description("Create a local emulator by running emulator -create <name> \u2026. --os-version must match a downloaded image from `emulator image list`.").addOption(Hs(!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");Hf.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
|
|
1286
|
-
${
|
|
1287
|
-
${
|
|
1288
|
-
${
|
|
1289
|
-
`)}});Hf.action(async(n,e)=>{try{XC(n),ZC(e.osVersion);let{manager:t}=await ot(),r=await t.listDownloadedImageOsVersions();QC(e.osVersion,r),console.log(Nr(`Creating emulator "${n}"...`)),await t.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(Vo(`Emulator "${n}" created successfully.`))}catch(t){console.error(Te(`${t.message}`)),process.exit(1)}});Se.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let{manager:e}=await ot();console.log(Nr(`Deleting emulator "${n}"...`));try{let t=await e.deleteVirtualDevice(n);console.log(Vo(`Emulator "${t}" deleted successfully.`))}catch(t){let r=t;console.error(Te(r.message)),r.stdout&&console.error(Uo(r.stdout)),r.stderr&&console.error(Uo(r.stderr)),process.exit(1)}});var Bf=Se;import{Command as VI}from"commander";import{red as rd,cyan as kt}from"colorette";import*as lh from"readline";import*as ah from"crypto";import*as Uf from"http";import*as Wf from"crypto";import{URL as PI}from"url";var Ws=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=Uf.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 PI(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&&Wf.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 Fe from"fs";import*as pn from"path";import{homedir as RI}from"os";var Wt={};NS(Wt,{LocalCrypto:()=>Wt,decryptForLocalStorage:()=>DI,decryptForLocalStorageFromDirectory:()=>TI,encryptForLocalStorage:()=>AI,isEncryptedBlob:()=>kI});import*as ee from"fs";import*as Re from"path";import*as _e from"crypto";import*as Gf from"os";import{homedir as qf}from"os";var ke=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var Go=Bn.ALGORITHM,zf=Bn.IV_LENGTH,qo=Bn.KEY_LENGTH,zo=Bn.KEY_LENGTH,Qn=Bn.KEK_VERSIONS,Vs=process.env.DEVECO_CLI_DATA_DIR||Re.join(qf(),Ce.CONFIG_DIR_NAME,Ce.APP_NAME),Gs=Re.join(qf(),".local","share",Ce.APP_NAME,"keys"),Lr=Re.join(Vs,Ce.KEY_FILE_NAME);function Vf(n){return Gf.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 Zl(n){return Re.join(Gs,`${n}.bin`)}function Yf(){if(!ee.existsSync(Vs))try{ee.mkdirSync(Vs,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new ke(Vf(Vs)):n}if(!ee.existsSync(Gs))try{ee.mkdirSync(Gs,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new ke(Vf(Re.dirname(Gs))):n}}function Jf(){Yf();for(let n of Qn){let e=Zl(n);ee.existsSync(e)||ee.writeFileSync(e,_e.randomBytes(qo),{mode:384})}}function Kf(n){if(!Qn.includes(n))throw new Error(`Invalid kekId: ${n}`);Jf();let e=Zl(n),t=ee.readFileSync(e);if(t.length===qo)return t;let r=_e.randomBytes(qo);return ee.writeFileSync(e,r,{mode:384}),r}function Ql(n,e){let t=_e.randomBytes(zf),r=Kf(e),o=_e.createCipheriv(Go,r,t),i=Buffer.concat([o.update(n),o.final()]),s=o.getAuthTag();return{version:1,algorithm:Go,kekId:e,encryptedDek:i.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function Xf(n,e){return Zf(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function Zf(n,e,t,r){let o=_e.createDecipheriv(Go,e,Buffer.from(t,"base64"));return o.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([o.update(n),o.final()])}function Qf(n,e){return Zf(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function CI(){if(Jf(),ee.existsSync(Lr))return;let n=_e.randomBytes(zo),e=Ql(n,Qn[0]);ee.writeFileSync(Lr,JSON.stringify(e,null,2),{mode:384})}function eh(){CI();let n=JSON.parse(ee.readFileSync(Lr,"utf8")),e=Xf(n,Kf(n.kekId));if(e.length===zo)return e;let t=_e.randomBytes(zo),r=Ql(t,Qn[0]);return ee.writeFileSync(Lr,JSON.stringify(r,null,2),{mode:384}),t}function II(){Yf();for(let t of Qn){let r=Zl(t);ee.existsSync(r)||ee.writeFileSync(r,_e.randomBytes(qo),{mode:384})}if(ee.existsSync(Lr))return;let n=_e.randomBytes(zo),e=Ql(n,Qn[0]);ee.writeFileSync(Lr,JSON.stringify(e,null,2),{mode:384})}function AI(n){let e=eh(),t=_e.randomBytes(zf),r=_e.createCipheriv(Go,e,t),o=Buffer.concat([r.update(n,"utf8"),r.final()]),i=r.getAuthTag();return{version:1,algorithm:Go,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:i.toString("base64"),timeStamp:Date.now()}}function DI(n){try{return Qf(n,eh())}catch{throw II(),new Error("Failed to decrypt local ciphertext")}}function TI(n,e){let t=Re.join(e,Ce.KEY_FILE_NAME),r=JSON.parse(ee.readFileSync(t,"utf8"));if(!Qn.includes(r.kekId))throw new Error(`Invalid kekId: ${r.kekId}`);let o=Re.join(e,"keys",`${r.kekId}.bin`),i=Re.resolve(o),s=Re.resolve(Re.join(e,"keys"));if(!i.startsWith(s+Re.sep)&&i!==s)throw new Error("kekId resolves outside the keys directory");let a=ee.readFileSync(i);if(a.length!==qo)throw new Error("Invalid external root key");let c=Xf(r,a);if(c.length!==zo)throw new Error("Invalid external data encryption key");return Qf(n,c)}function kI(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 gt(){return process.env.DEVECO_CLI_AUTH_SOURCE===Ce.AUTH_SOURCE_DEVECO_CODE}var qs=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR||pn.join(RI(),Ce.CONFIG_DIR_NAME,Ce.APP_NAME);return pn.join(e,Ce.TOKEN_FILE_NAME)}ensureConfigDir(){let e=pn.dirname(this.getLocalTokenFilePath());Fe.existsSync(e)||Fe.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=Wt.encryptForLocalStorage(e);this.ensureConfigDir();let r=this.getLocalTokenFilePath();Fe.writeFileSync(r,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return gt()?this.loadDevecoCodeToken():this.loadLocalJwtToken()}loadDevecoCodeToken(){if(!gt())return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;let t=pn.resolve(e);try{let r=pn.join(t,Ce.TOKEN_FILE_NAME);if(!Fe.existsSync(r))return null;let o=JSON.parse(Fe.readFileSync(r,"utf8"));return Wt.isEncryptedBlob(o)?Wt.decryptForLocalStorageFromDirectory(o,e):null}catch{return null}}async loadLocalJwtToken(){let e=this.getLocalTokenFilePath();try{if(!Fe.existsSync(e))return null;let t=JSON.parse(Fe.readFileSync(e,"utf8"));return Wt.isEncryptedBlob(t)?Wt.decryptForLocalStorage(t):null}catch(t){let r=t.code;return r==="EACCES"||r==="EPERM"||r==="ENOENT"||await this.clearToken(),null}}async clearToken(){if(gt()){m("clearToken: skipped, session managed by DevEco Code");return}let e=this.getLocalTokenFilePath();try{Fe.existsSync(e)&&Fe.unlinkSync(e)}catch(t){throw new Error("Failed to clear token",{cause:t})}}},Vt=new qs;import{exec as xI}from"child_process";import{promisify as NI}from"util";var LI=NI(xI);async function th(n){let e=process.platform,t;switch(e){case"win32":t=`start "" "${n}"`;break;case"darwin":t=`open "${n}"`;break;case"openharmony":console.log("\u65E0\u6CD5\u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668\uFF0C\u8BF7\u624B\u52A8\u590D\u5236\u4EE5\u4E0B\u767B\u5F55\u94FE\u63A5\u5230\u6D4F\u89C8\u5668\u6253\u5F00\uFF1A"),console.log(n);return;default:t=`xdg-open "${n}"`;break}try{await LI(t)}catch(r){throw new Error("Failed to open browser",{cause:r})}}import OI from"axios";import{getProxyForUrl as MI}from"proxy-from-env";function _I(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 ed=class{client;constructor(){let e={timeout:vo.HTTP_TIMEOUT_MS,headers:{"User-Agent":Vi.USER_AGENT,"accept-language":Vi.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=OI.create(e),this.client.interceptors.request.use(t=>{let r=MI(t.url??"");return t.proxy=r?_I(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}
|
|
1290
|
-
${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){return JSON.parse(e.data)}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}}},
|
|
1291
|
-
`)}function qI(){return new Promise(n=>{let e=lh.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}async function zI(n){if(n||!process.stdin.isTTY){console.log(kt(n?"Opening browser for login... (--no-prompt: Enter confirmation skipped)":"Non-interactive terminal: opening browser for login without the Enter confirmation..."));return}console.log(kt("Press Enter to open browser for login (or pass --no-prompt to skip)...")),await qI()}var Yo=new VI("auth").description("Authentication commands (login, logout, status, team)");Yo.command("login").description("Log in to your Huawei Developer account").option("--no-prompt","Open the browser immediately without the interactive Enter confirmation (agents and non-interactive terminals)").action(async n=>{if(gt()){console.log(rd("Login is managed by DevEco Code. Login from DevEco Code instead."));return}let e={event:T.CommandExecuted,args:["auth","login"]};await Ks(e,async()=>{let t=await xe.getUserInfo();if(t){console.log(kt(`Already logged in, User Name:${t.userName}`));return}console.log(kt("Starting login process...")),await zI(n.prompt===!1);let r=await xe.login();console.log(kt(`Login successful. Logged in as ${r.userName}.`))},t=>{throw t instanceof ke||(t instanceof Error?t.message:String(t)).includes("Network connection failed")?t:new Error("Login failed",{cause:t})})});Yo.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(gt()){console.log(rd("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}let n={event:T.CommandExecuted,args:["auth","logout"]};await Ks(n,async()=>{let e=await xe.logout();console.log(e?kt("Logout successful"):kt("Already logged out."))},e=>new Error("Logout failed",{cause:e}))});Yo.command("status").description("Show the currently logged-in user").action(async()=>{let n={event:T.CommandExecuted,args:["auth","status"]};await Ks(n,async()=>{let e=await xe.getUserInfo();if(!e){console.log(kt("Not logged in"));return}console.log(kt(`Current user: ${e.userName}`))},e=>e)});var YI=Yo.command("team").description("Team-related commands");YI.command("list").description("List team accounts the current user has joined").action(async()=>{let n={event:T.CommandExecuted,args:["auth","team","list"]};await Ks(n,async()=>{let e=await mn();console.log(GI(e.teamList))},e=>{if(e instanceof ke){console.log(rd(e.message));return}throw e})});var dh=Yo;import{Command as aA}from"commander";import{green as cA,red as Qo,cyan as Nh,yellow as Lh,dim as Oh}from"colorette";import lA from"p-limit";import JI from"ora";var yt=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=JI(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 uh from"fs";import*as ph from"path";var mh=["DevEco"];async function Xs(){let n=await O.get(ut.TAGS_API_URL),t=Zs(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 KI(n){let e=[],t=ut.DEFAULT_PAGE_SIZE,r=1;for(;;){let o=await O.post(ut.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:r,pageSize:t,tagIds:[n]}}),i=Zs(o,"Skills API");if(e.push(...i.data.list),i.data.list.length<t)break;r++}return e}async function od(n){let e=new Map,t=n.map(o=>KI(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=>!mh.includes(i.name)))}async function XI(n,e){let t=await O.post(ut.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:ut.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return Zs(t,"Skills API").data.list}async function id(n,e){let t=new Map,r=e.map(i=>XI(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=>!mh.includes(s.name)))}function fh(n){let e=[],t=Mt();for(let[,r]of Object.entries(t)){let o=ph.join(r.path,n);uh.existsSync(o)&&e.push(r.displayName)}return e.sort()}function Zs(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=O.parseJson(n);if(t.code!==ut.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function hh(n){let e=`${ut.SKILL_API_BASE}/${n}/checksum`,t=await O.get(e);return Zs(t,"Checksum API").data}import ZI from"adm-zip";import QI from"crypto";import yh from"fs";import le from"path";import{fileURLToPath as eA}from"url";import{red as tA}from"colorette";var qt=yh.promises;function sd(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function gh(n,e){let t=le.resolve(e),r=le.resolve(n),o=le.relative(r,t);if(o.startsWith("..")||le.isAbsolute(o))throw new Error(`Path traversal detected: ${e}.`)}function ad(n){return le.isAbsolute(n)?n:le.resolve(process.cwd(),n)}function nA(n){return QI.createHash("sha256").update(n).digest("hex")}async function rA(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=nA(n),o=e.sha256.toLowerCase();if(r!==o)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function wh(n){let e=`${ut.SKILL_API_BASE}/${n}/install?format=zip`,t=await O.getBinary(e),r=await hh(n);return await rA(t,r),t}async function oA(n,e,t){sd(t);let r=new ZI(n),o=r.getEntries();try{await qt.stat(e)}catch{await qt.mkdir(e,{recursive:!0})}let i=le.join(e,t);gh(e,i);for(let s of o){let a=le.join(i,s.entryName);gh(i,a)}r.extractAllTo(i,!0)}async function cd(n){let e=Mt();if(!e[n])throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(e).join(", ")}`);let r=ye[n];try{return await qt.access(r),!0}catch{return!1}}function ld(n){return Mt()[n].path}function dd(n,e){let r=Mt()[e],o="projectPath"in r?r.projectPath:le.join("."+e,"skills");return le.join(n,o)}async function iA(n,e,t){sd(e);let r=le.join(n,e);try{if(await qt.access(r),t)await qt.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 ud(n,e,t){await oA(n,e,t),console.log(`Skill ${t} installed to ${le.join(e,t)}.`)}async function pd(n,e,t){let r=le.join(e,t);await qt.mkdir(r,{recursive:!0});let o=le.join(r,le.basename(n));await qt.copyFile(n,o),console.log(`Skill ${t} installed to ${r}.`)}function vh(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(tA(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function Mr(n,e,t,r){try{let o=await e(),{shouldSkip:i}=await iA(o,n,r);return i?{success:!0,skipped:!0}:(await t(o),{success:!0})}catch(o){return vh(n,o,"Installation failed")}}async function md(n,e){try{sd(n);let t=await e(),r=le.join(t,n);try{await qt.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await qt.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return vh(n,t,"Removal failed")}}async function Sh(n,e,t,r=!1){return Mr(n,()=>ld(e),o=>ud(t,o,n),r)}async function bh(n,e,t,r=!1){return Mr(n,()=>t,o=>ud(e,o,n),r)}async function Eh(n,e,t,r,o=!1){return Mr(n,()=>dd(t,r),i=>ud(e,i,n),o)}async function Ph(n,e,t,r=!1){return Mr(n,()=>ld(t),o=>pd(e,o,n),r)}async function Ch(n,e,t,r,o=!1){return Mr(n,()=>dd(t,r),i=>pd(e,i,n),o)}async function Ih(n,e,t,r=!1){return Mr(n,()=>t,o=>pd(e,o,n),r)}async function Ah(n,e){return md(n,()=>ld(e))}async function Dh(n,e){return md(n,()=>e)}async function Th(n,e,t){return md(n,()=>dd(e,t))}function kh(){let e=le.dirname(eA(import.meta.url));for(;;){let t=le.join(e,"SKILL.md");if(yh.existsSync(t))return t;let r=le.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import Rh from"fs";import{cyan as sA}from"colorette";async function Jo(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await cd(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function Ko(){let n=[],e=Mt();for(let t of Object.keys(e))await cd(t)&&n.push(t);return n}function Xo(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(sA("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function fn(n,e,t){if(!Rh.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!Rh.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function Zo(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?ad(n):void 0,resolvedProject:e?ad(e):void 0}}async function Qs(n,e,t){let r=[],o=[],i;if(e?i=e:t&&n.agent?o=(await Jo(n.agent)).map(a=>({project:t,agent:a})):t?o=(await Ko()).map(a=>({project:t,agent:a})):n.agent?r=await Jo(n.agent):r=await Ko(),!i&&r.length===0&&o.length===0)throw new Error("No agents found. Install an AI agent (opencode, etc.) or use `--path` for a custom location.");return{agents:r,projectAgents:o,customPath:i}}async function dA(n){let e=await Xs();if(n.all)return(await od(e)).map(r=>r.enName);{let r=(await id(n.skill,e)).find(o=>o.enName===n.skill);if(!r)throw new tr("errorCode",`Skill "${n.skill}" not found`);return[r.enName]}}async function uA(n,e,t,r){let o=[];if(t.customPath){let i=await bh(n,e,t.customPath,r);return o.push(i),o}for(let i of t.agents){let s=await Sh(n,i,e,r);o.push(s)}for(let{project:i,agent:s}of t.projectAgents){let a=await Eh(n,e,i,s,r);o.push(a)}return o}function pA(n){if(n.all&&n.skill)throw new tr("errorCode","`--all` and `--skill` cannot be specified together.");if(!n.all&&!n.skill)throw new tr("errorCode","Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=Zo(n.path,n.project,n.agent);return t&&fn(t,"Project directory",n.force),e&&fn(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}async function mA(n,e,t){let r=await Qs(n,e,t);return{skillNames:await dA(n),targets:r}}async function fA(n,e,t,r){let o=[],i=0,s=n.length,a=lA(5),c=n.map(l=>a(()=>hA(l)));for(let l=0;l<n.length;l++){let d=n[l],h=s>1?` (${l+1}/${s})`:"";r.start(`Installing ${d}${h}...`);let w=await c[l];if(!w.success){r.fail(),console.log(Qo(`${d}: Download failed - ${w.error}`)),o.push({success:!1});continue}i+=w.buffer.length,r.stop();let v=await uA(d,w.buffer,e,t);o.push(...v)}return{results:o,diskBytes:i}}async function hA(n){try{let e=await wh(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 gA(n){let e=new yt;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=pA(n),{skillNames:o,targets:i}=await mA(n,t,r),{results:s,diskBytes:a}=await fA(o,i,n.force||!1,e);return e.stop(),Xo(s),{diskBytes:a,results:s}}catch(t){throw e.stop(),t}}function Mh(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=>yA(s.error)))];return{opTotal:e,opSuccess:t,opFailed:o,opSkipped:r,...i.length>0?{failedErrors:i}:{}}}function yA(n){let e=/^([A-Za-z_][A-Za-z0-9_-]*)/.exec(n.trim());return e?e[1].slice(0,32):"error"}var tr=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function wA(n){let e=n;return n instanceof tr?n.code:e.code??e.name??"UnknownError"}function ta(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 na(n,e,t){let r=Date.now(),o=!0,i=null,s={};try{s=await e()}catch(a){throw o=!1,i=wA(a),a}finally{let a={event:T.SkillOperation,subAction:n,args:t,...s};await D.track(a,{duration_ms:Date.now()-r,success:o,error_code:i})}}function vA(n){return na("add",async()=>{let{diskBytes:e,results:t}=await gA(n);return{diskUsage:At(e),...n.skill?{skillName:n.skill}:{},...Mh(t)}},ta("add",n))}function SA(n){let{resolvedPath:e,resolvedProject:t}=Zo(n.path,n.project,n.agent);return t&&fn(t,"Project directory"),e&&fn(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function bA(n,e){let t=new yt;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:o}=SA(e);t.stop();let i=await EA(e,n,r,o);return t.stop(),Xo(i),i}catch(r){throw t.stop(),r}}function xh(n,e=""){if(n.length===0)throw new tr("errorCode",`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function ea(n,e){let t=[];for(let r of e){let o=r.type==="agent"?await Ah(n,r.agent):await Th(n,r.project,r.agent);t.push(o)}return t}async function EA(n,e,t,r){if(t)return[await Dh(e,t)];if(r&&n.agent){let a=(await Jo(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return ea(e,a)}if(r){let s=await Ko();xh(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return ea(e,a)}if(n.agent){let a=(await Jo(n.agent)).map(c=>({type:"agent",agent:c}));return ea(e,a)}let o=await Ko();xh(o,"or use --path for a custom location.");let i=o.map(s=>({type:"agent",agent:s}));return ea(e,i)}function PA(n,e){if(!e){console.log(n.enName);return}console.log(Nh(n.enName)),console.log(Oh(n.description));let t=fh(n.enName);t.length>0&&console.log(cA(`Installed for: ${t.join(", ")}`)),console.log()}async function CA(n){let e=new yt;try{e.start("Fetching skills...");let t=await Xs(),r=await od(t);if(r.length===0)return e.stop(),console.log(Lh("No skills available.")),{resultTotal:0};e.succeed(`Fetched ${r.length} skills`);for(let o of r)PA(o,n.long===!0);return{resultTotal:r.length}}finally{e.stop()}}async function IA(n){let e=new yt;try{e.start("Searching skills...");let t=await Xs(),r=await id(n,t);if(r.length===0)return console.log(Lh(`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(Nh(o.enName)),console.log(Oh(o.description)),console.log();return{resultTotal:r.length,queryLen:n.length,keyword:n}}finally{e.stop()}}var ei=new aA("skills").description("Manage HarmonyOS skills");ei.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async n=>{try{await na("list",()=>CA(n),ta("list",n))}catch(e){console.error(Qo(e.message)),process.exit(1)}});ei.command("find <keyword>").description("Search skills by keyword").action(async n=>{try{await na("find",()=>IA(n),ta("find"))}catch(e){console.error(Qo(e.message)),process.exit(1)}});ei.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 vA(n)}catch(e){console.error(Qo(e.message)),process.exit(1)}});ei.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 na("remove",async()=>{let e=await bA(n.skill,n);return{skillName:n.skill,...Mh(e)}},ta("remove",n))}catch(e){console.error(Qo(e.message)),process.exit(1)}});var _h=ei;import{Command as DA,InvalidArgumentError as oa}from"commander";import{cyan as ra}from"colorette";function nr(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=Sr(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 fd=[800,1500,2500];function AA(n){return new Promise(e=>setTimeout(e,n))}function Fh(){return b()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device."}var _r=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=ae.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(`
|
|
1292
|
-
`)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let o=t[0];return m(
|
|
1285
|
+
`;function JC(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function KC(n){let e=n.trim();if(!Ff.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${Ff.join(", ")}`);return e}function $f(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 Hf(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&&!XC(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 XC(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function ZC(n,e,t,r,o){return Number(Hf(n,e,t,r,o))}function QC(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 eI(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 tI(n,e){let t=o=>o.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(Dt("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(Dt("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(o=>t(o)===r)){console.error(Le("--os-version does not match any downloaded image (exact string required).")),console.log(Dt("Use one of these --os-version values:"));for(let o of e)console.log(` ${o}`);throw new Error(`No downloaded image matches --os-version "${n}".`)}}var nI=["Name","Status","Serial","Device Type","OS Version"];function rI(n,e,t){return{cells:[n.name,t?"running":"stopped",e??"-",n.deviceType??"-",n.osVersion??"-"],highlight:t}}async function oI(n,e){let t=await Promise.all(e.map(async r=>{let o=await Er(n,r,qC);return[r,o]}));return new Map(t)}async function iI(n){let e=await $l(n),t=await oI(n,e);return{serials:e,params:t}}function sI(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 aI(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&&sI(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 cI(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(o=>rI(o.emu,o.serial,o.effectiveRunning))}async function lI(n,e,t){try{let[r,o]=await Promise.all([n.listEmulators(),iI(e)]);if(r.length===0){t?.stop(),console.log(Dt(" No emulator instances found."));return}let i=r.filter(l=>l.isRunning).map(l=>l.name),{productSerialMap:s,hvdSerialMap:a}=aI(o.serials,o.params,i);t?.stop();let c=cI(r,s,a);console.log(Ht(nI,c))}catch(r){Sf(t,`Failed to list emulators: ${r.message}`)}}function Uf(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(Le(`Failed to ${t} emulator "${e[o]}": ${s.message}`)),s.stdout&&console.error(Wo(s.stdout)),s.stderr&&console.error(Wo(s.stderr))}return r}var dI=2e3,uI=6e4;async function pI(n,e){let t=Ie(e);return(await Hl(n)).some(o=>Ie(o)===t)}async function Bf(n,e,t,r=uI,o=dI){let i=Date.now()+r;for(;Date.now()<i;){if(await pI(n,e)===t)return!0;await new Promise(a=>setTimeout(a,o))}return!1}async function mI(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(Dt(`Emulator "${t}" is already running.`));return}console.log(Or(`Starting emulator "${t}"...`));let o=await Bf(e,t,!0);console.log(o?Go(`Emulator "${t}" started successfully.`):Dt(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function fI(n,e,t){let r=await Promise.allSettled(t.map(i=>mI(n,e,i)));Uf(r,t,"start")&&process.exit(1)}async function Wf(n,e){let t=e.trim();if(!qn(t))return t;let r=await ae.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 hI(n,e,t){let r=await Wf(e,t);if(console.log(Or(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(Dt(`Emulator "${r}" is already stopped.`));return}let i=await Bf(e,r,!1);console.log(i?Go(`Emulator "${r}" stopped successfully.`):Dt(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function gI(n,e,t){let r=await Promise.allSettled(t.map(i=>hI(n,e,i)));Uf(r,t,"stop")&&process.exit(1)}async function rt(){try{let n=await D.new();return{manager:xr.from(n),toolProvider:n}}catch(n){throw new Error(`Failed to initialize emulator: ${n.message}`,{cause:n})}}async function Ut(n,e,t){let r={event:A.CommandExecuted,args:["emulator",t,"--target"]},o=Date.now(),i=!0,s=null;try{let a=JC(n.target),c=e(),{manager:l,toolProvider:d}=await rt(),h=await Wf(d.hdcPath,a);await l.controlEmulator(h,c),console.log(Go(`Emulator "${a}" operation completed.`))}catch(a){i=!1,s=Y(a);let c=n.target?.trim()||"<unknown>";console.error(Le(`Failed to operate emulator "${c}": ${a.message}`)),process.exitCode=1}finally{let a={duration_ms:Date.now()-o,success:i,error_code:s};await I.track(r,a)}}function yI(n){let e=[];return Us(e,"longitude",n.longitude,-180,180,8),Us(e,"latitude",n.latitude,-90,90,8),Us(e,"altitude",n.altitude,-1e4,1e4,2),Us(e,"bearing",n.direction,0,359.99,2,"--direction"),Ql(e,"Specify one geolocation option.")}function wI(n){let e=[];return Uo(e,"light",n.lightIntensity,0,1e5,!1,"--light-intensity"),Uo(e,"humidity",n.humidity,0,100,!1),Uo(e,"temperature",n.temperature,-273.1,100,!1),Uo(e,"steps",n.steps,0,1e4,!0),Uo(e,"heartrate",n.heartrate,0,255,!0),Ql(e,"Specify one sensor option.")}function Ql(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 Us(n,e,t,r,o,i,s=`--${e}`){t!==void 0&&n.push({type:"gps",key:e,value:Hf(s,t,r,o,i)})}function Uo(n,e,t,r,o,i,s=`--${e}`){if(t===void 0)return;let a=i?$f(s,t,r,o):ZC(s,t,r,o,1);n.push({type:"sensor",key:e,value:a})}function vI(n){let e=[];return n.level!==void 0&&e.push({type:"battery",level:$f("--level",n.level,1,100)}),n.status!==void 0&&e.push({type:"battery-status",status:n.status==="charging"?1:0}),Ql(e,"Specify --level or --status.")}var ve=new Zl("emulator").description("Manage emulator instances"),SI=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Bs(n){let e=new Vo("--device-type <type>","Emulator device type").choices([...SI]);return n?e.makeOptionMandatory():e}function Nr(n,e){for(let t of e)if(t in n)return n[t]}function Bo(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function jf(n){let e=Bo(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var bI=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],EI="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function Vf(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function Gf(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let o=r,i=Bo(Nr(o,["osVersion","OsVersion","OSVersion","os_version"])),s=Bo(Nr(o,["deviceType","DeviceType","device_type"])),a=jf(Nr(o,["downloaded","Downloaded","isDownloaded"])),c=Bo(Nr(o,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=Bo(Nr(o,["releaseType","ReleaseType","release_type"])),d=jf(Nr(o,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[i,s,c,l,d,a],highlight:e&&a==="true"})}return t}function PI(n){let e=n.trim();if(!e)return!0;let t=Vf(e);return t===null?!1:t.length===0?!0:Gf(t,!0).length===0}function CI(n,e){let t=n.trim();if(!t)return"";let r=Vf(t);if(!r)return n.trimEnd();let o=Gf(r,e);return Ht(bI,o)}var Ws=new Zl("image").description("HarmonyOS emulator system images (download, list, remove)");Ws.command("download").description("Download system image").addOption(Bs(!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{manager:e,toolProvider:t}=await rt();try{await Kl(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof nt&&(console.error(Le(r.message)),process.exit(1)),r}n.deviceType?.trim()||(console.error(Le("Error: missing required option '--device-type <type>'")),process.exit(1)),n.osVersion?.trim()||(console.error(Le("Error: misssing required option '--os-version <version>'")),process.exit(1));try{await e.installEmulatorImage({deviceType:n.deviceType.trim(),osVersion:n.osVersion.trim(),force:n.force===!0})}catch(r){console.error(Le(`Failed to download system image: ${r.message}`)),process.exit(1)}});Ws.command("remove").description("Remove a downloaded system image").addOption(Bs(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let{manager:e}=await rt();try{await e.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})}catch(t){console.error(Le(`Failed to remove system image: ${t.message}`)),process.exit(1)}});Ws.command("list").description("List system images").addOption(Bs(!1)).option("--all","List all images (local and remote)").addOption(new Vo("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await rt();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if(PI(r)){console.log(Dt(EI));return}if(n.format==="json"){console.log(r.trimEnd());return}let o=CI(r,n.all===!0);console.log(o)}catch(t){console.error(Le(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});ve.addCommand(Ws);var Vs=new Zl("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");Vs.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let{toolProvider:n}=await rt(),e=await Of(n.emulatorPath,n.sdkPath);process.exit(e)});Vs.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let{toolProvider:n}=await rt(),e=await _f(n.emulatorPath,n.sdkPath);process.exit(e)});Vs.action(async()=>{let{toolProvider:n}=await rt(),e=await Mf(n.emulatorPath,n.sdkPath);process.exit(e)});ve.addCommand(Vs);ve.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Ut(n,()=>({type:"shake"}),"shake"));ve.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Ut(n,()=>({type:"power"}),"power"));ve.command("rotate").description("Rotate emulator").addOption(new Vo("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Xl("<direction>").choices(["left","right"])).action((n,e)=>Ut(e,()=>({type:"rotation",direction:n}),"rotate"));ve.command("volume").description("Change volume").addOption(new Vo("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Xl("<direction>").choices(["up","down"])).action((n,e)=>Ut(e,()=>({type:"volume",direction:n}),"volume"));ve.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",YC).action((n,e)=>Ut(e,()=>({type:"folded-state",state:KC(n)}),"fold"));ve.command("battery").description("Set battery level or charging status").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--level <1-100>","Battery level, SOC (integer 1-100)").addOption(new Vo("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>Ut(n,()=>vI(n),"battery"));ve.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=>Ut(n,()=>yI(n),"geolocation"));ve.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new Xl("<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 Ut(e,()=>t[n],"scene")});ve.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=>Ut(n,()=>wI(n),"sensor"));ve.command("list").description("List all emulator instances").action(async()=>{let{manager:n,toolProvider:e}=await rt(),t=zC({text:"Listing emulators\u2026",color:"cyan"}).start();await lI(n,e.hdcPath,t)});ve.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await rt();try{await Jl(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof nt&&(console.error(Le(r.message)),process.exit(1)),r}n?.length||(console.error(Le("Error: missing required argument 'names'")),process.exit(1)),await fI(e,t.hdcPath,n)});ve.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{manager:e,toolProvider:t}=await rt();n?.length||(console.error(Le("Error: missing required argument 'names'")),process.exit(1)),await gI(e,t.hdcPath,n)});var zf=ve.command("create <name>").description("Create a local emulator by running emulator -create <name> \u2026. --os-version must match a downloaded image from `emulator image list`.").addOption(Bs(!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");zf.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
|
|
1286
|
+
${Dt("Tip: ")}${Wo("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
|
|
1287
|
+
${Or('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
|
|
1288
|
+
${Or('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
|
|
1289
|
+
`)}});zf.action(async(n,e)=>{try{QC(n),eI(e.osVersion);let{manager:t}=await rt(),r=await t.listDownloadedImageOsVersions();tI(e.osVersion,r),console.log(Or(`Creating emulator "${n}"...`)),await t.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(Go(`Emulator "${n}" created successfully.`))}catch(t){console.error(Le(`${t.message}`)),process.exit(1)}});ve.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let{manager:e}=await rt();console.log(Or(`Deleting emulator "${n}"...`));try{let t=await e.deleteVirtualDevice(n);console.log(Go(`Emulator "${t}" deleted successfully.`))}catch(t){let r=t;console.error(Le(r.message)),r.stdout&&console.error(Wo(r.stdout)),r.stderr&&console.error(Wo(r.stderr)),process.exit(1)}});var qf=ve;import{Command as zI}from"commander";import{red as id,cyan as Tt}from"colorette";import*as hh from"readline";import*as mh from"crypto";import*as Yf from"http";import*as Jf from"crypto";import{URL as II}from"url";var Gs=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=Yf.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 II(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&&Jf.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 _e from"fs";import*as un from"path";import{homedir as NI}from"os";var Bt={};LS(Bt,{LocalCrypto:()=>Bt,decryptForLocalStorage:()=>RI,decryptForLocalStorageFromDirectory:()=>kI,encryptForLocalStorage:()=>TI,isEncryptedBlob:()=>xI});import*as Q from"fs";import*as Te from"path";import*as Me from"crypto";import*as Xf from"os";import{homedir as Zf}from"os";var De=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var zo=Hn.ALGORITHM,Qf=Hn.IV_LENGTH,qo=Hn.KEY_LENGTH,Yo=Hn.KEY_LENGTH,Zn=Hn.KEK_VERSIONS,zs=process.env.DEVECO_CLI_DATA_DIR||Te.join(Zf(),Pe.CONFIG_DIR_NAME,Pe.APP_NAME),qs=Te.join(Zf(),".local","share",Pe.APP_NAME,"keys"),Lr=Te.join(zs,Pe.KEY_FILE_NAME);function Kf(n){return Xf.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 ed(n){return Te.join(qs,`${n}.bin`)}function eh(){if(!Q.existsSync(zs))try{Q.mkdirSync(zs,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new De(Kf(zs)):n}if(!Q.existsSync(qs))try{Q.mkdirSync(qs,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new De(Kf(Te.dirname(qs))):n}}function th(){eh();for(let n of Zn){let e=ed(n);Q.existsSync(e)||Q.writeFileSync(e,Me.randomBytes(qo),{mode:384})}}function nh(n){if(!Zn.includes(n))throw new Error(`Invalid kekId: ${n}`);th();let e=ed(n),t=Q.readFileSync(e);if(t.length===qo)return t;let r=Me.randomBytes(qo);return Q.writeFileSync(e,r,{mode:384}),r}function td(n,e){let t=Me.randomBytes(Qf),r=nh(e),o=Me.createCipheriv(zo,r,t),i=Buffer.concat([o.update(n),o.final()]),s=o.getAuthTag();return{version:1,algorithm:zo,kekId:e,encryptedDek:i.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function rh(n,e){return oh(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function oh(n,e,t,r){let o=Me.createDecipheriv(zo,e,Buffer.from(t,"base64"));return o.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([o.update(n),o.final()])}function ih(n,e){return oh(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function AI(){if(th(),Q.existsSync(Lr))return;let n=Me.randomBytes(Yo),e=td(n,Zn[0]);Q.writeFileSync(Lr,JSON.stringify(e,null,2),{mode:384})}function sh(){AI();let n=JSON.parse(Q.readFileSync(Lr,"utf8")),e=rh(n,nh(n.kekId));if(e.length===Yo)return e;let t=Me.randomBytes(Yo),r=td(t,Zn[0]);return Q.writeFileSync(Lr,JSON.stringify(r,null,2),{mode:384}),t}function DI(){eh();for(let t of Zn){let r=ed(t);Q.existsSync(r)||Q.writeFileSync(r,Me.randomBytes(qo),{mode:384})}if(Q.existsSync(Lr))return;let n=Me.randomBytes(Yo),e=td(n,Zn[0]);Q.writeFileSync(Lr,JSON.stringify(e,null,2),{mode:384})}function TI(n){let e=sh(),t=Me.randomBytes(Qf),r=Me.createCipheriv(zo,e,t),o=Buffer.concat([r.update(n,"utf8"),r.final()]),i=r.getAuthTag();return{version:1,algorithm:zo,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:i.toString("base64"),timeStamp:Date.now()}}function RI(n){try{return ih(n,sh())}catch{throw DI(),new Error("Failed to decrypt local ciphertext")}}function kI(n,e){let t=Te.join(e,Pe.KEY_FILE_NAME),r=JSON.parse(Q.readFileSync(t,"utf8"));if(!Zn.includes(r.kekId))throw new Error(`Invalid kekId: ${r.kekId}`);let o=Te.join(e,"keys",`${r.kekId}.bin`),i=Te.resolve(o),s=Te.resolve(Te.join(e,"keys"));if(!i.startsWith(s+Te.sep)&&i!==s)throw new Error("kekId resolves outside the keys directory");let a=Q.readFileSync(i);if(a.length!==qo)throw new Error("Invalid external root key");let c=rh(r,a);if(c.length!==Yo)throw new Error("Invalid external data encryption key");return ih(n,c)}function xI(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 ht(){return process.env.DEVECO_CLI_AUTH_SOURCE===Pe.AUTH_SOURCE_DEVECO_CODE}var Ys=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR||un.join(NI(),Pe.CONFIG_DIR_NAME,Pe.APP_NAME);return un.join(e,Pe.TOKEN_FILE_NAME)}ensureConfigDir(){let e=un.dirname(this.getLocalTokenFilePath());_e.existsSync(e)||_e.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=Bt.encryptForLocalStorage(e);this.ensureConfigDir();let r=this.getLocalTokenFilePath();_e.writeFileSync(r,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return ht()?this.loadDevecoCodeToken():this.loadLocalJwtToken()}loadDevecoCodeToken(){if(!ht())return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;let t=un.resolve(e);try{let r=un.join(t,Pe.TOKEN_FILE_NAME);if(!_e.existsSync(r))return null;let o=JSON.parse(_e.readFileSync(r,"utf8"));return Bt.isEncryptedBlob(o)?Bt.decryptForLocalStorageFromDirectory(o,e):null}catch{return null}}async loadLocalJwtToken(){let e=this.getLocalTokenFilePath();try{if(!_e.existsSync(e))return null;let t=JSON.parse(_e.readFileSync(e,"utf8"));return Bt.isEncryptedBlob(t)?Bt.decryptForLocalStorage(t):null}catch(t){let r=t.code;return r==="EACCES"||r==="EPERM"||r==="ENOENT"||await this.clearToken(),null}}async clearToken(){if(ht()){m("clearToken: skipped, session managed by DevEco Code");return}let e=this.getLocalTokenFilePath();try{_e.existsSync(e)&&_e.unlinkSync(e)}catch(t){throw new Error("Failed to clear token",{cause:t})}}},Wt=new Ys;import{exec as OI}from"child_process";import{promisify as LI}from"util";var MI=LI(OI);async function ah(n){let e=process.platform,t;switch(e){case"win32":t=`start "" "${n}"`;break;case"darwin":t=`open "${n}"`;break;case"openharmony":console.log("\u65E0\u6CD5\u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668\uFF0C\u8BF7\u624B\u52A8\u590D\u5236\u4EE5\u4E0B\u767B\u5F55\u94FE\u63A5\u5230\u6D4F\u89C8\u5668\u6253\u5F00\uFF1A"),console.log(n);return;default:t=`xdg-open "${n}"`;break}try{await MI(t)}catch(r){throw new Error("Failed to open browser",{cause:r})}}import _I from"axios";import{getProxyForUrl as FI}from"proxy-from-env";function jI(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 nd=class{client;constructor(){let e={timeout:So.HTTP_TIMEOUT_MS,headers:{"User-Agent":zi.USER_AGENT,"accept-language":zi.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=_I.create(e),this.client.interceptors.request.use(t=>{let r=FI(t.url??"");return t.proxy=r?jI(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}
|
|
1290
|
+
${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){return JSON.parse(e.data)}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 nd;function ch(n){let e=n.split(".");return e.length===3&&e.every(t=>t.length>0)}var Vt={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},Qn={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},Js={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},$I={[Vt.CHINA]:Qn.CHINA,[Vt.RUSSIA]:Qn.RUSSIA,[Vt.EUROPE]:Qn.EUROPE,[Vt.SINGAPORE]:Qn.CHINA},HI={[Js.CHINA]:Vt.CHINA,[Js.SINGAPORE]:Vt.SINGAPORE,[Js.EUROPE]:Vt.EUROPE,[Js.RUSSIA]:Vt.RUSSIA};function lh(n){return $I[n]??Qn.CHINA}function dh(n){return HI[n]??Vt.CHINA}var rd=class{async getJwtToken(e,t,r,o,i){let s=e.split("&")[0],a=dh(t),c={tempToken:s,site:a,version:Pe.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 h=d.data.trim();if(!ch(h))throw new Error("Invalid jwtToken format");return h}},uh=new rd;var od=class{async checkJwtToken(e,t,r=!1){let o={refresh:String(r),jwtToken:e},i=`${t}/${q.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 Wt.loadJwtToken();return t?this.refreshTokenWithToken(t,e):null}async refreshTokenWithToken(e,t){try{let r={refresh:"true",jwtToken:e},o=`${t}/${q.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?(m("jwtToken invalid."),await Wt.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:lh(o.userInfo.nationalCode),isRealName:String(o.userInfo.realName)==="true"}}async fetchUserInfo(e,t){let r=await Wt.loadJwtToken();return r?this.getUserInfoFromJwt(r,e,t):null}},Mr=new od;import UI from"querystring";import{spawn as BI}from"child_process";function ph(n){try{let e=JSON.stringify({signInfo:[{agrType:bo.PRIVACY_ID,country:"CN",language:"zh_CN",isAgree:!0}]}),t=UI.stringify({nsp_svc:"as.user.sign",access_token:n,request:e}),r=BI("curl",["-s","-X","POST",bo.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"?m("Agreement sign reported successfully"):m(`Agreement sign failed: HTTP ${i}`)}).on("error",()=>{})}catch(e){m(`Agreement sign error: ${e.message}`)}}var Ks=class{config;server=null;constructor(e){this.config={...Eo,...e}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}async login(){try{m(`Login started, isDevecoCodeAuth: ${ht()}`);let e=this.generateClientSecret();this.server=new Gs(e,q.CN_LOGIN_URL,this.config.successRedirectUrl,this.config.failedRedirectUrl),await this.server.start(),m(`Local auth server started on port ${this.server.getPort()}`),await this.openLoginPage(this.server.getPort(),e),m("Browser opened for authentication");let t=await this.server.waitForCallback(this.config.timeout);if(m(`Callback received: siteId=${t.siteId}`),t.siteId!=="1")throw new De("Non-China accounts are not supported.");let r=await uh.getJwtToken(t.tempToken,t.siteId,q.CN_LOGIN_URL,this.config.tempTokenCheckUrl,this.config.appId);m("JWT token received");let o=await Mr.getUserInfoFromJwt(r,q.CN_LOGIN_URL);if(!o)throw new De("Login failed: failed to get user info");return m(`User info received: ${o.userName}`),await Wt.saveJwtToken(r),m("JWT token saved"),ph(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 Wt.loadJwtToken();if(!e)return!1;let r=`${q.CN_LOGIN_URL}/${this.config.logoutUrl}?jwtToken=${e}`;try{await L.post(r,{timeout:5e3})}catch{m("Logout: server notification failed, local token cleared")}finally{await Wt.clearToken()}return!0}async getUserInfo(e=!0){return Mr.fetchUserInfo(q.CN_LOGIN_URL,e)}generateClientSecret(){return mh.randomUUID().replace(/-/g,"")}async openLoginPage(e,t){let o=`${q.CN_LOGIN_URL}/${this.config.authUrl}?port=${e}&appid=${this.config.appId}&code=${t}`;await ah(o)}async refreshToken(){return Mr.refreshToken(q.CN_LOGIN_URL)}},Re=new Ks;function VI(){return ht()?"Not logged in. Please login via DevEco Code first.":"Please run `devecocli auth login` first."}function GI(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 Xs=class{config;constructor(e){this.config={...Eo,...e}}updateConfig(e){this.config={...this.config,...e}}async listTeams(){let e=await Mr.fetchUserInfo(q.CN_LOGIN_URL,!0);if(!e)throw new De(VI());let t=await this.fetchTeamList(e.accessToken,e.userId),r=GI(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:Qn.CHINA},timeout:15e3})}catch(i){let s=i.message;throw s.includes("401")?new De("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}},fh=new Xs;async function pn(){return fh.listTeams()}async function Zs(n,e,t){let r=Date.now(),o=!0,i=null;try{await e()}catch(s){o=!1,i=Y(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 qI(n){if(n.length===0)return Tt("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(`
|
|
1291
|
+
`)}function YI(){return new Promise(n=>{let e=hh.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}async function JI(n){if(n||!process.stdin.isTTY){console.log(Tt(n?"Opening browser for login... (--no-prompt: Enter confirmation skipped)":"Non-interactive terminal: opening browser for login without the Enter confirmation..."));return}console.log(Tt("Press Enter to open browser for login (or pass --no-prompt to skip)...")),await YI()}var Jo=new zI("auth").description("Authentication commands (login, logout, status, team)");Jo.command("login").description("Log in to your Huawei Developer account").option("--no-prompt","Open the browser immediately without the interactive Enter confirmation (agents and non-interactive terminals)").action(async n=>{if(ht()){console.log(id("Login is managed by DevEco Code. Login from DevEco Code instead."));return}let e={event:A.CommandExecuted,args:["auth","login"]};await Zs(e,async()=>{let t=await Re.getUserInfo();if(t){console.log(Tt(`Already logged in, User Name:${t.userName}`));return}console.log(Tt("Starting login process...")),await JI(n.prompt===!1);let r=await Re.login();console.log(Tt(`Login successful. Logged in as ${r.userName}.`))},t=>{throw t instanceof De||(t instanceof Error?t.message:String(t)).includes("Network connection failed")?t:new Error("Login failed",{cause:t})})});Jo.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(ht()){console.log(id("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}let n={event:A.CommandExecuted,args:["auth","logout"]};await Zs(n,async()=>{let e=await Re.logout();console.log(e?Tt("Logout successful"):Tt("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:A.CommandExecuted,args:["auth","status"]};await Zs(n,async()=>{let e=await Re.getUserInfo();if(!e){console.log(Tt("Not logged in"));return}console.log(Tt(`Current user: ${e.userName}`))},e=>e)});var KI=Jo.command("team").description("Team-related commands");KI.command("list").description("List team accounts the current user has joined").action(async()=>{let n={event:A.CommandExecuted,args:["auth","team","list"]};await Zs(n,async()=>{let e=await pn();console.log(qI(e.teamList))},e=>{if(e instanceof De){console.log(id(e.message));return}throw e})});var gh=Jo;import{Command as lA}from"commander";import{green as dA,red as ei,cyan as jh,yellow as $h,dim as Hh}from"colorette";import uA from"p-limit";import XI from"ora";var gt=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=XI(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 yh from"fs";import*as wh from"path";var vh=["DevEco"];async function Qs(){let n=await L.get(dt.TAGS_API_URL),t=ea(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 ZI(n){let e=[],t=dt.DEFAULT_PAGE_SIZE,r=1;for(;;){let o=await L.post(dt.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:r,pageSize:t,tagIds:[n]}}),i=ea(o,"Skills API");if(e.push(...i.data.list),i.data.list.length<t)break;r++}return e}async function sd(n){let e=new Map,t=n.map(o=>ZI(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=>!vh.includes(i.name)))}async function QI(n,e){let t=await L.post(dt.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:dt.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return ea(t,"Skills API").data.list}async function ad(n,e){let t=new Map,r=e.map(i=>QI(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=>!vh.includes(s.name)))}function Sh(n){let e=[],t=Lt();for(let[,r]of Object.entries(t)){let o=wh.join(r.path,n);yh.existsSync(o)&&e.push(r.displayName)}return e.sort()}function ea(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=L.parseJson(n);if(t.code!==dt.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function bh(n){let e=`${dt.SKILL_API_BASE}/${n}/checksum`,t=await L.get(e);return ea(t,"Checksum API").data}import eA from"adm-zip";import tA from"crypto";import Ph from"fs";import ce from"path";import{fileURLToPath as nA}from"url";import{red as rA}from"colorette";var Gt=Ph.promises;function cd(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function Eh(n,e){let t=ce.resolve(e),r=ce.resolve(n),o=ce.relative(r,t);if(o.startsWith("..")||ce.isAbsolute(o))throw new Error(`Path traversal detected: ${e}.`)}function ld(n){return ce.isAbsolute(n)?n:ce.resolve(process.cwd(),n)}function oA(n){return tA.createHash("sha256").update(n).digest("hex")}async function iA(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=oA(n),o=e.sha256.toLowerCase();if(r!==o)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function Ch(n){let e=`${dt.SKILL_API_BASE}/${n}/install?format=zip`,t=await L.getBinary(e),r=await bh(n);return await iA(t,r),t}async function sA(n,e,t){cd(t);let r=new eA(n),o=r.getEntries();try{await Gt.stat(e)}catch{await Gt.mkdir(e,{recursive:!0})}let i=ce.join(e,t);Eh(e,i);for(let s of o){let a=ce.join(i,s.entryName);Eh(i,a)}r.extractAllTo(i,!0)}async function dd(n){let e=Lt();if(!e[n])throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(e).join(", ")}`);let r=ge[n];try{return await Gt.access(r),!0}catch{return!1}}function ud(n){return Lt()[n].path}function pd(n,e){let r=Lt()[e],o="projectPath"in r?r.projectPath:ce.join("."+e,"skills");return ce.join(n,o)}async function aA(n,e,t){cd(e);let r=ce.join(n,e);try{if(await Gt.access(r),t)await Gt.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 md(n,e,t){await sA(n,e,t),console.log(`Skill ${t} installed to ${ce.join(e,t)}.`)}async function fd(n,e,t){let r=ce.join(e,t);await Gt.mkdir(r,{recursive:!0});let o=ce.join(r,ce.basename(n));await Gt.copyFile(n,o),console.log(`Skill ${t} installed to ${r}.`)}function Ih(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(rA(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function _r(n,e,t,r){try{let o=await e(),{shouldSkip:i}=await aA(o,n,r);return i?{success:!0,skipped:!0}:(await t(o),{success:!0})}catch(o){return Ih(n,o,"Installation failed")}}async function hd(n,e){try{cd(n);let t=await e(),r=ce.join(t,n);try{await Gt.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await Gt.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return Ih(n,t,"Removal failed")}}async function Ah(n,e,t,r=!1){return _r(n,()=>ud(e),o=>md(t,o,n),r)}async function Dh(n,e,t,r=!1){return _r(n,()=>t,o=>md(e,o,n),r)}async function Th(n,e,t,r,o=!1){return _r(n,()=>pd(t,r),i=>md(e,i,n),o)}async function Rh(n,e,t,r=!1){return _r(n,()=>ud(t),o=>fd(e,o,n),r)}async function kh(n,e,t,r,o=!1){return _r(n,()=>pd(t,r),i=>fd(e,i,n),o)}async function xh(n,e,t,r=!1){return _r(n,()=>t,o=>fd(e,o,n),r)}async function Nh(n,e){return hd(n,()=>ud(e))}async function Oh(n,e){return hd(n,()=>e)}async function Lh(n,e,t){return hd(n,()=>pd(e,t))}function Mh(){let e=ce.dirname(nA(import.meta.url));for(;;){let t=ce.join(e,"SKILL.md");if(Ph.existsSync(t))return t;let r=ce.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import _h from"fs";import{cyan as cA}from"colorette";async function Ko(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await dd(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function Xo(){let n=[],e=Lt();for(let t of Object.keys(e))await dd(t)&&n.push(t);return n}function Zo(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(cA("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function mn(n,e,t){if(!_h.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!_h.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function Qo(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?ld(n):void 0,resolvedProject:e?ld(e):void 0}}async function ta(n,e,t){let r=[],o=[],i;if(e?i=e:t&&n.agent?o=(await Ko(n.agent)).map(a=>({project:t,agent:a})):t?o=(await Xo()).map(a=>({project:t,agent:a})):n.agent?r=await Ko(n.agent):r=await Xo(),!i&&r.length===0&&o.length===0)throw new Error("No agents found. Install an AI agent (opencode, etc.) or use `--path` for a custom location.");return{agents:r,projectAgents:o,customPath:i}}async function pA(n){let e=await Qs();if(n.all)return(await sd(e)).map(r=>r.enName);{let r=(await ad(n.skill,e)).find(o=>o.enName===n.skill);if(!r)throw new er("errorCode",`Skill "${n.skill}" not found`);return[r.enName]}}async function mA(n,e,t,r){let o=[];if(t.customPath){let i=await Dh(n,e,t.customPath,r);return o.push(i),o}for(let i of t.agents){let s=await Ah(n,i,e,r);o.push(s)}for(let{project:i,agent:s}of t.projectAgents){let a=await Th(n,e,i,s,r);o.push(a)}return o}function fA(n){if(n.all&&n.skill)throw new er("errorCode","`--all` and `--skill` cannot be specified together.");if(!n.all&&!n.skill)throw new er("errorCode","Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=Qo(n.path,n.project,n.agent);return t&&mn(t,"Project directory",n.force),e&&mn(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}async function hA(n,e,t){let r=await ta(n,e,t);return{skillNames:await pA(n),targets:r}}async function gA(n,e,t,r){let o=[],i=0,s=n.length,a=uA(5),c=n.map(l=>a(()=>yA(l)));for(let l=0;l<n.length;l++){let d=n[l],h=s>1?` (${l+1}/${s})`:"";r.start(`Installing ${d}${h}...`);let w=await c[l];if(!w.success){r.fail(),console.log(ei(`${d}: Download failed - ${w.error}`)),o.push({success:!1});continue}i+=w.buffer.length,r.stop();let v=await mA(d,w.buffer,e,t);o.push(...v)}return{results:o,diskBytes:i}}async function yA(n){try{let e=await Ch(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 wA(n){let e=new gt;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=fA(n),{skillNames:o,targets:i}=await hA(n,t,r),{results:s,diskBytes:a}=await gA(o,i,n.force||!1,e);return e.stop(),Zo(s),{diskBytes:a,results:s}}catch(t){throw e.stop(),t}}function Uh(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=>vA(s.error)))];return{opTotal:e,opSuccess:t,opFailed:o,opSkipped:r,...i.length>0?{failedErrors:i}:{}}}function vA(n){let e=/^([A-Za-z_][A-Za-z0-9_-]*)/.exec(n.trim());return e?e[1].slice(0,32):"error"}var er=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function SA(n){let e=n;return n instanceof er?n.code:e.code??e.name??"UnknownError"}function ra(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 oa(n,e,t){let r=Date.now(),o=!0,i=null,s={};try{s=await e()}catch(a){throw o=!1,i=SA(a),a}finally{let a={event:A.SkillOperation,subAction:n,args:t,...s};await I.track(a,{duration_ms:Date.now()-r,success:o,error_code:i})}}function bA(n){return oa("add",async()=>{let{diskBytes:e,results:t}=await wA(n);return{diskUsage:It(e),...n.skill?{skillName:n.skill}:{},...Uh(t)}},ra("add",n))}function EA(n){let{resolvedPath:e,resolvedProject:t}=Qo(n.path,n.project,n.agent);return t&&mn(t,"Project directory"),e&&mn(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function PA(n,e){let t=new gt;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:o}=EA(e);t.stop();let i=await CA(e,n,r,o);return t.stop(),Zo(i),i}catch(r){throw t.stop(),r}}function Fh(n,e=""){if(n.length===0)throw new er("errorCode",`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function na(n,e){let t=[];for(let r of e){let o=r.type==="agent"?await Nh(n,r.agent):await Lh(n,r.project,r.agent);t.push(o)}return t}async function CA(n,e,t,r){if(t)return[await Oh(e,t)];if(r&&n.agent){let a=(await Ko(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return na(e,a)}if(r){let s=await Xo();Fh(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return na(e,a)}if(n.agent){let a=(await Ko(n.agent)).map(c=>({type:"agent",agent:c}));return na(e,a)}let o=await Xo();Fh(o,"or use --path for a custom location.");let i=o.map(s=>({type:"agent",agent:s}));return na(e,i)}function IA(n,e){if(!e){console.log(n.enName);return}console.log(jh(n.enName)),console.log(Hh(n.description));let t=Sh(n.enName);t.length>0&&console.log(dA(`Installed for: ${t.join(", ")}`)),console.log()}async function AA(n){let e=new gt;try{e.start("Fetching skills...");let t=await Qs(),r=await sd(t);if(r.length===0)return e.stop(),console.log($h("No skills available.")),{resultTotal:0};e.succeed(`Fetched ${r.length} skills`);for(let o of r)IA(o,n.long===!0);return{resultTotal:r.length}}finally{e.stop()}}async function DA(n){let e=new gt;try{e.start("Searching skills...");let t=await Qs(),r=await ad(n,t);if(r.length===0)return console.log($h(`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(jh(o.enName)),console.log(Hh(o.description)),console.log();return{resultTotal:r.length,queryLen:n.length,keyword:n}}finally{e.stop()}}var ti=new lA("skills").description("Manage HarmonyOS skills");ti.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async n=>{try{await oa("list",()=>AA(n),ra("list",n))}catch(e){console.error(ei(e.message)),process.exit(1)}});ti.command("find <keyword>").description("Search skills by keyword").action(async n=>{try{await oa("find",()=>DA(n),ra("find"))}catch(e){console.error(ei(e.message)),process.exit(1)}});ti.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 bA(n)}catch(e){console.error(ei(e.message)),process.exit(1)}});ti.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 oa("remove",async()=>{let e=await PA(n.skill,n);return{skillName:n.skill,...Uh(e)}},ra("remove",n))}catch(e){console.error(ei(e.message)),process.exit(1)}});var Bh=ti;import{Command as RA,InvalidArgumentError as sa}from"commander";import{cyan as ia}from"colorette";function tr(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=br(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 gd=[800,1500,2500];function TA(n){return new Promise(e=>setTimeout(e,n))}function Wh(){return b()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device."}var Fr=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=ae.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(`
|
|
1292
|
+
`)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let o=t[0];return m(ia(`Using device serial: ${o}`)),o}if(e&&t.includes(e))return m(ia(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let o=this.findDeviceByArg(r,e);if(o)return m(ia(`Using device: ${o.name} (${o.serial})`)),o.serial;let i=this.formatConnectedDeviceList(r);throw new R(`Device '${e}' not found.
|
|
1293
1293
|
Available devices:
|
|
1294
|
-
${i}`,"Device not found.")}if(r.length===1){let o=r[0];return m(
|
|
1294
|
+
${i}`,"Device not found.")}if(r.length===1){let o=r[0];return m(ia(`Using device: ${o.name} (${o.serial})`)),o.serial}throw new R("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(Wh());return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error(Wh());return e}async getPidForBundle(e,t,r){m(`Retrieving PID for bundle ${r}`),x.assertBundleNameStrict(r);let o=await de(e,["-t",t,"shell","pidof",r]),i=tr(o,"Failed to look up PID");if(i)throw i;if(o.exitCode===0&&o.stdout.trim()){let s=o.stdout.trim(),a=s.split(/\s+/)[0]||s;return m(`Found PID for ${r}: ${a}`),a}return m(`No PID found for bundle: ${r}`),null}async resizeHilogBuffer(e,t,r){m(`Setting hilog buffer size to: ${r}`);let o=await de(e,["-t",t,"shell","hilog","-G",r]),i=tr(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&&(x.assertHilogToken(e.tag,"tag"),r.push("-T",e.tag)),e.level&&(x.assertHilogLevel(e.level),r.push("-L",e.level)),e.domain&&(x.assertHilogToken(e.domain,"domain"),r.push("-D",e.domain)),t&&r.push("-P",t),e.keyword&&(x.assertHilogKeyword(e.keyword),r.push("-e",x.quotePosixShellArg(e.keyword))),r.join(" ")}async followHilog(e,t,r,o,i){let a=await Dm(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+gd.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||br(a.stderr)!=="transient"||c>=s-1)return a;m(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${gd[c]}ms`),await TA(gd[c])}return a}async runHilogStreamingCollect(e,t,r){return this.runHilogWithSpawnRetry(e,t,()=>{},o=>{m(`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);m(`Ready to run hilog snapshot command: ${s} ${a.join(" ")}`);let c=await this.runHilogStreamingCollect(s,a,"a hilog snapshot streaming read"),l=tr(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=x.filterLogsByRelativeWindow(c.stdout||c.stderr,r.fromSeconds,r.toSeconds);d=x.getLastLines(d,r.tail),d.trim()&&console.log(d)}async getHilogOnce(e,t,r,o){let[i,s]=this.buildHilogCommand(e,t,r,o);m(`Ready to run hilog command: ${i} ${s.join(" ")}`);let a=await this.runHilogStreamingCollect(i,s,"a single hilog streaming read"),c=tr(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=x.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return d=x.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);m(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${i} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(i,s,this.createFollowLineHandler(),l=>{m(`Spawn error during hilog follow: ${l.message}`)},()=>{}),c=tr(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 R(`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 getCrashLog(e,t){m(`Fetching crash logs from device: ${e}`);let r=this.toolProvider.hdcPath,o=await this.listCrashLogs(r,e,t);if(o.length===0)return t?`No crash logs found for bundle '${t}'.`:"No crash logs found.";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 listCrashLogs(e,t,r){let o=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];m(`Running command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log list streaming read"),s=tr(i,"Failed to list crash logs");if(s)throw s;if(i.exitCode!==0)throw new Error(`Failed to list crash logs: ${i.stderr||i.stdout}`);return m(`Crash logs list output:
|
|
1295
1295
|
${i.stdout}`),this.parseCrashLogFilenames(i.stdout,r)}parseCrashLogFilenames(e,t){return e.split(`
|
|
1296
|
-
`).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return R.assertCrashFilename(r),!0}catch{return!1}}).filter(r=>t?r.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){m(`Fetching latest crash log file: ${r}`);let o=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];m(`Executing command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log streaming read"),s=nr(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{cyan as hd,red as $h}from"colorette";import TA from"ora";function kA(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 RA(n){return{event:T.CommandExecuted,args:kA(n),logType:n.crash?"crash":"common",level:n.level??"ALL",bundleName:n.bundleName??"ALL"}}function xA(n){return n instanceof x?n.traceMessage:n instanceof Error?n.code??n.name:"UnknownError"}async function NA(n,e){let t=Date.now(),r=!0,o=null;try{await e()}catch(i){r=!1,o=xA(i),console.error($h(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await D.track(n,i).catch(()=>{})}}function LA(n){try{return R.parsePositiveInteger(n,"tail")}catch{throw new oa("`tail` must be a positive integer.")}}function jh(n,e){try{return R.parseDurationToSeconds(n,e)}catch{throw new oa(`${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 OA(n){try{return R.assertHilogLevel(n),n}catch{throw new oa("`level` must be one of: D, I, W, E, F.")}}function MA(n){try{return R.assertBundleNameStrict(n),n}catch(e){throw new oa(e.message)}}function _A(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.");R.assertRelativeTimeRange(n.from,n.to)}async function FA(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 jA(n,e,t,r){let o=R.filterLogsByRelativeWindow(n,t,r);return e.tail?R.getLastLines(o,e.tail):o}var $A=new DA("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e($h(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",OA).option("--bundle-name <bundle-name>","Filter by application bundle name",MA).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",LA).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>jh(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>jh(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await NA(RA(n),()=>HA(n))});async function HA(n){let e=TA({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};e.start();try{_A(n);let r=n.from,o=n.to,i=await A.new(),s=new _r(i),a=await s.selectDevice(n.device);if(!a)throw new x("No active devices found.","No active devices found.");m(hd(`deviceId: ${a}`)),m(hd(`type: ${n.crash?"Crash logs":"Common logs"}`)),m(hd("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await FA(s,a,n,r,o);t(),n.crash&&c&&(c=jA(c,n,r,o)),c&&console.log(c)}finally{t()}}var Hh=$A;import ni from"path";import zt from"fs";import wd from"process";import Jh from"os";import{Command as QA}from"commander";import{green as Gh,red as gd,cyan as eD,yellow as qh}from"colorette";import pe from"fs-extra";import $ from"path";import*as Uh from"os";import{fileURLToPath as BA}from"url";var Bh={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"}},UA=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function WA(){let n=import.meta.url,e=BA(n);if(e.includes("dist")){let i=$.dirname(e),s=$.dirname(i);return $.join(s,"templates","application")}let t=$.dirname(e),r=$.dirname(t),o=$.dirname(r);return $.join(o,"templates","application")}function Wh(n,e){pe.mkdirSync(e,{recursive:!0});for(let t of pe.readdirSync(n,{withFileTypes:!0})){let r=$.join(n,t.name),o=$.join(e,t.name);if(t.isDirectory()){Wh(r,o);continue}pe.existsSync(o)||(pe.mkdirSync($.dirname(o),{recursive:!0}),pe.copyFileSync(r,o))}}function ti(n,e){let t=pe.readFileSync(n,"utf-8"),r=t;for(let[o,i]of e)r=r.replaceAll(o,i);r!==t&&pe.writeFileSync(n,r,"utf-8")}function VA(n){if(Bh[n])return Bh[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function GA(n,e){if(e===22)return;let t=VA(e);t&&(ti($.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),ti($.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),ti($.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function qA(n){return UA.filter(t=>!pe.existsSync($.join(n,t))).length===0}function zA(){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 YA(n){return Uh.platform()==="darwin"?$.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):$.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function JA(n,e){let t=YA(e);if(!pe.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=$.join(t,o),a=$.join(n,i);pe.existsSync(s)&&(pe.mkdirSync($.dirname(a),{recursive:!0}),pe.copyFileSync(s,a))}return!0}function KA(n){let e=zA(),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=$.join(n,r);pe.mkdirSync($.dirname(o),{recursive:!0}),pe.writeFileSync(o,e)}}function XA(n,e){e&&JA(n,e)||KA(n)}function ZA(n){let e=[$.join(n,"gitignore.txt"),$.join(n,"entry","gitignore.txt")];for(let t of e)if(pe.existsSync(t)){let r=$.dirname(t);pe.renameSync(t,$.join(r,".gitignore"))}}function Vh(n,e,t,r,o){let i=WA();if(!pe.existsSync(i))throw new Error(`Template directory not found: ${i}`);pe.mkdirSync(n,{recursive:!0}),Wh(i,n),ZA(n),XA(n,o),ti($.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),ti($.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),GA(n,r);let s=qA(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function tD(n){if(n.length<1||n.length>200)throw new me("errorCode",`App name length must be 1-200 characters. Current: ${n.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(n))throw new me("errorCode","Application name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function Kh(n){if(Jh.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function zh(n){if(n.length===0)throw new me("errorCode","Project path cannot be empty.");if(n.length>120)throw new me("errorCode",`Project path cannot exceed 120 characters (current: ${n.length}).`);let e=Jh.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 me("errorCode",`Project path can only contain ${i}.`)}let r=Kh(n);if(/[\u4e00-\u9fff]/.test(r))throw new me("errorCode","Project path cannot contain Chinese characters.");if(r.endsWith("."))throw new me("errorCode","Project path cannot end with a dot (.)")}function nD(n){let e=n,t=ni.parse(n).root;for(;e!==t;){if(zt.existsSync(e))return e;e=ni.dirname(e)}return zt.existsSync(t)?t:null}function Yh(n){let e=nD(n);if(!e)throw new me("errorCode",`No existing parent directory found for '${n}'. Cannot create project directory.`);try{zt.accessSync(e,zt.constants.W_OK)}catch{throw new me("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}let t=ni.join(e,`.deveco_write_test_${Date.now()}`);try{zt.writeFileSync(t,"test"),zt.unlinkSync(t)}catch{throw new me("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}}function rD(n){return`com.example.${n.toLowerCase()}`}function oD(n,e){if(e){let o=Kh(e),i=ni.resolve(o);if(zt.existsSync(i)){if(zt.readdirSync(i).length>0)throw new me("errorCode",`Directory '${i}' is not empty. Cannot create project here.`)}else Yh(i);return i}let t=wd.cwd(),r=ni.join(t,n);if(zt.existsSync(r))throw new me("errorCode",`Directory '${r}' already exists. Cannot create project here.`);return Yh(r),r}function iD(n,e){let t=e?.getMaxApiLevel(),r=23;if(n.apiLevel){let o=Number(n.apiLevel);if(!Number.isInteger(o)||o<17)throw new me("errorCode",`Invalid API version ${n.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(o>t)throw new me("errorCode",`Invalid API version ${n.apiLevel}. Your SDK supports API version 17-${t}`)}else if(o>r)throw new me("errorCode",`Invalid API version ${n.apiLevel}. No SDK detected; default supported range is API 17-${r}.`);return o}return t!==void 0?t:23}async function sD(){try{return await A.new()}catch(n){console.error(qh(`Toolchain not found: ${n.message}`)),console.log(qh("Use placeholder API level instead."));return}}var me=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};async function yd(n,e,t,r){let o={event:T.CommandExecuted,args:["create"],apiLevel:r?.apiLevel??null},i={duration_ms:Date.now()-n,success:e,error_code:t};await D.track(o,i).catch(()=>{})}function aD(n){console.log(`
|
|
1297
|
-
`+
|
|
1298
|
-
Failed to create project.`)),console.error(
|
|
1296
|
+
`).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return x.assertCrashFilename(r),!0}catch{return!1}}).filter(r=>t?r.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){m(`Fetching latest crash log file: ${r}`);let o=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];m(`Executing command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log streaming read"),s=tr(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{cyan as yd,red as Gh}from"colorette";import kA from"ora";function xA(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 NA(n){return{event:A.CommandExecuted,args:xA(n),logType:n.crash?"crash":"common",level:n.level??"ALL",bundleName:n.bundleName??"ALL"}}function OA(n){return n instanceof R?n.traceMessage:n instanceof Error?n.code??n.name:"UnknownError"}async function LA(n,e){let t=Date.now(),r=!0,o=null;try{await e()}catch(i){r=!1,o=OA(i),console.error(Gh(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 MA(n){try{return x.parsePositiveInteger(n,"tail")}catch{throw new sa("`tail` must be a positive integer.")}}function Vh(n,e){try{return x.parseDurationToSeconds(n,e)}catch{throw new sa(`${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 _A(n){try{return x.assertHilogLevel(n),n}catch{throw new sa("`level` must be one of: D, I, W, E, F.")}}function FA(n){try{return x.assertBundleNameStrict(n),n}catch(e){throw new sa(e.message)}}function jA(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.");x.assertRelativeTimeRange(n.from,n.to)}async function $A(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 HA(n,e,t,r){let o=x.filterLogsByRelativeWindow(n,t,r);return e.tail?x.getLastLines(o,e.tail):o}var UA=new RA("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(Gh(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",_A).option("--bundle-name <bundle-name>","Filter by application bundle name",FA).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",MA).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>Vh(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>Vh(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await LA(NA(n),()=>BA(n))});async function BA(n){let e=kA({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};e.start();try{jA(n);let r=n.from,o=n.to,i=await D.new(),s=new Fr(i),a=await s.selectDevice(n.device);if(!a)throw new R("No active devices found.","No active devices found.");m(yd(`deviceId: ${a}`)),m(yd(`type: ${n.crash?"Crash logs":"Common logs"}`)),m(yd("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await $A(s,a,n,r,o);t(),n.crash&&c&&(c=HA(c,n,r,o)),c&&console.log(c)}finally{t()}}var zh=UA;import ri from"path";import zt from"fs";import Sd from"process";import tg from"os";import{Command as tD}from"commander";import{green as Xh,red as wd,cyan as nD,yellow as Zh}from"colorette";import ue from"fs-extra";import $ from"path";import*as Yh from"os";import{fileURLToPath as WA}from"url";var qh={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"}},VA=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function GA(){let n=import.meta.url,e=WA(n);if(e.includes("dist")){let i=$.dirname(e),s=$.dirname(i);return $.join(s,"templates","application")}let t=$.dirname(e),r=$.dirname(t),o=$.dirname(r);return $.join(o,"templates","application")}function Jh(n,e){ue.mkdirSync(e,{recursive:!0});for(let t of ue.readdirSync(n,{withFileTypes:!0})){let r=$.join(n,t.name),o=$.join(e,t.name);if(t.isDirectory()){Jh(r,o);continue}ue.existsSync(o)||(ue.mkdirSync($.dirname(o),{recursive:!0}),ue.copyFileSync(r,o))}}function ni(n,e){let t=ue.readFileSync(n,"utf-8"),r=t;for(let[o,i]of e)r=r.replaceAll(o,i);r!==t&&ue.writeFileSync(n,r,"utf-8")}function zA(n){if(qh[n])return qh[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function qA(n,e){if(e===22)return;let t=zA(e);t&&(ni($.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),ni($.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),ni($.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function YA(n){return VA.filter(t=>!ue.existsSync($.join(n,t))).length===0}function JA(){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 KA(n){return Yh.platform()==="darwin"?$.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):$.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function XA(n,e){let t=KA(e);if(!ue.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=$.join(t,o),a=$.join(n,i);ue.existsSync(s)&&(ue.mkdirSync($.dirname(a),{recursive:!0}),ue.copyFileSync(s,a))}return!0}function ZA(n){let e=JA(),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=$.join(n,r);ue.mkdirSync($.dirname(o),{recursive:!0}),ue.writeFileSync(o,e)}}function QA(n,e){e&&XA(n,e)||ZA(n)}function eD(n){let e=[$.join(n,"gitignore.txt"),$.join(n,"entry","gitignore.txt")];for(let t of e)if(ue.existsSync(t)){let r=$.dirname(t);ue.renameSync(t,$.join(r,".gitignore"))}}function Kh(n,e,t,r,o){let i=GA();if(!ue.existsSync(i))throw new Error(`Template directory not found: ${i}`);ue.mkdirSync(n,{recursive:!0}),Jh(i,n),eD(n),QA(n,o),ni($.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),ni($.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),qA(n,r);let s=YA(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function rD(n){if(n.length<1||n.length>200)throw new pe("errorCode",`App name length must be 1-200 characters. Current: ${n.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(n))throw new pe("errorCode","Application name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function ng(n){if(tg.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function Qh(n){if(n.length===0)throw new pe("errorCode","Project path cannot be empty.");if(n.length>120)throw new pe("errorCode",`Project path cannot exceed 120 characters (current: ${n.length}).`);let e=tg.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 pe("errorCode",`Project path can only contain ${i}.`)}let r=ng(n);if(/[\u4e00-\u9fff]/.test(r))throw new pe("errorCode","Project path cannot contain Chinese characters.");if(r.endsWith("."))throw new pe("errorCode","Project path cannot end with a dot (.)")}function oD(n){let e=n,t=ri.parse(n).root;for(;e!==t;){if(zt.existsSync(e))return e;e=ri.dirname(e)}return zt.existsSync(t)?t:null}function eg(n){let e=oD(n);if(!e)throw new pe("errorCode",`No existing parent directory found for '${n}'. Cannot create project directory.`);try{zt.accessSync(e,zt.constants.W_OK)}catch{throw new pe("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}let t=ri.join(e,`.deveco_write_test_${Date.now()}`);try{zt.writeFileSync(t,"test"),zt.unlinkSync(t)}catch{throw new pe("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}}function iD(n){return`com.example.${n.toLowerCase()}`}function sD(n,e){if(e){let o=ng(e),i=ri.resolve(o);if(zt.existsSync(i)){if(zt.readdirSync(i).length>0)throw new pe("errorCode",`Directory '${i}' is not empty. Cannot create project here.`)}else eg(i);return i}let t=Sd.cwd(),r=ri.join(t,n);if(zt.existsSync(r))throw new pe("errorCode",`Directory '${r}' already exists. Cannot create project here.`);return eg(r),r}function aD(n,e){let t=e?.getMaxApiLevel(),r=23;if(n.apiLevel){let o=Number(n.apiLevel);if(!Number.isInteger(o)||o<17)throw new pe("errorCode",`Invalid API version ${n.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(o>t)throw new pe("errorCode",`Invalid API version ${n.apiLevel}. Your SDK supports API version 17-${t}`)}else if(o>r)throw new pe("errorCode",`Invalid API version ${n.apiLevel}. No SDK detected; default supported range is API 17-${r}.`);return o}return t!==void 0?t:23}async function cD(){try{return await D.new()}catch(n){console.error(Zh(`Toolchain not found: ${n.message}`)),console.log(Zh("Use placeholder API level instead."));return}}var pe=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};async function vd(n,e,t,r){let o={event:A.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 lD(n){console.log(`
|
|
1297
|
+
`+Xh("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(Xh("Template integrity check passed."))}var dD=new tD("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(wd("Error: --app-name is required")),await vd(e,!1,"errorCode",n),Sd.exit(1));let t=n.appName;rD(t);let r=n.bundleName||iD(t);x.assertBundleNameStrict(r),n.projectPath&&Qh(n.projectPath);let o=sD(t,n.projectPath);Qh(o),console.log(nD("Initializing project...")),console.log(`Project path: ${o}`),console.log(`App name: ${t}`),console.log(`Bundle name: ${r}`);let i=await cD(),s=aD(n,i);console.log(`API level: ${s}`);let a=i?.devecoStudioPath,c=Kh(o,t,r,s,a);lD(c),await vd(e,!0,null,n)}catch(t){let r=t,i=t instanceof pe?t.code:r.code??r.name??"UnknownError";console.error(wd(`
|
|
1298
|
+
Failed to create project.`)),console.error(wd(r.message)),await vd(e,!1,i,n),Sd.exit(1)}}),rg=dD;import{Command as yD}from"commander";import{red as wD,cyan as ug}from"colorette";import uD from"fs";import aa from"path";import{cyan as pD}from"colorette";import*as ca from"smol-toml";var jr=uD.promises;async function mD(n){try{let e=await jr.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 fD(n){try{let e=await jr.readFile(n,"utf8");return e.trim()===""?{}:ca.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 hD(n,e){let t=aa.dirname(n);await jr.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await jr.writeFile(n,r,"utf8")}async function gD(n,e){let t=aa.dirname(n);await jr.mkdir(t,{recursive:!0});let r=ca.stringify(e);await jr.writeFile(n,r,"utf8")}function og(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function ig(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 sg(n,e){return n.format==="codex"?fD(e):mD(e)}async function ag(n,e,t){return n.format==="codex"?gD(e,t):hD(e,t)}async function cg(n,e,t=!1){let r=an[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(an).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 sg(r,r.globalConfigPath);if(og(o,r.mcpServersKey,Ct)&&!t)return console.log(`MCP server ${Ct} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let i=us(r,void 0);return ig(o,r.mcpServersKey,Ct,i,t),await ag(r,r.globalConfigPath,o),console.log(`MCP server ${Ct} 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 bd(n,e,t=!1){let r=an[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(an).join(", ")}`};let o=aa.isAbsolute(r.projectConfigPath)?r.projectConfigPath:aa.join(e,r.projectConfigPath);try{let i=await sg(r,o);if(og(i,r.mcpServersKey,Ct)&&!t)return console.log(`MCP server ${Ct} already configured in ${o}.`),{success:!0,skipped:!0,configPath:o,agentName:n,installType:"project"};let s=us(r,e);return ig(i,r.mcpServersKey,Ct,s,t),await ag(r,o,i),console.log(`MCP server ${Ct} 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 lg(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(pD("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 Ed="deveco-cli";async function vD(n,e,t){if(n.customPath)return[await xh(Ed,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>kh(Ed,e,s,a,t.force)),...n.agents.map(s=>()=>Rh(Ed,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 SD(n){return[...new Set([...n.agents,...n.projectAgents.map(({agent:e})=>e)])]}async function dg(n,e,t,r){await I.track(n,{duration_ms:Date.now()-e,success:t,error_code:r}).catch(()=>{})}async function bD(n,e,t,r,o){let i={event:A.SkillConfigOperation,subAction:"install",targetType:r?"path":o?"project":"global",agents:SD(n)},s=Date.now();try{let a=await vD(n,e,t),c=a.every(l=>l.success||l.skipped);return await dg(i,s,c,c?null:"SKILL_INSTALL_FAILED"),a}catch(a){let c=a instanceof Error?a.code??a.name:"UnknownError";throw await dg(i,s,!1,c),a}}async function ED(n,e,t){let r=[];for(let{project:o,agent:i}of n.projectAgents){let s=await bd(i,o,t);r.push(s)}for(let o of n.agents){let i=await bd(o,e,t);r.push(i)}return r}async function PD(n,e){let t=[];for(let r of n){if(!an[r])continue;let i=await cg(r,process.cwd(),e);t.push(i)}return t}async function CD(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,o=n.projectAgents.filter(c=>c.agent!=="qoder"),i=n.agents.filter(c=>c!=="qoder"),s={...n,projectAgents:o,agents:i},a=e?await ED(s,e,r):await PD(s.agents,r);a.length>0&&(console.log(ug("MCP Configuration:")),lg(a))}async function ID(n,e,t){let r={event:A.Init,subAction:"install",targetType:e?"project":"global",agentName:t.agent},o=Date.now(),i=!0,s=null;try{await CD(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 AD(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}=Qo(n.path,n.project,n.agent);t&&mn(t,"Project directory",n.force),e&&mn(e,"Directory",n.force);let r=await ta(n,e,t);if(n.mcp){await ID(r,t,n);return}let o=Mh(),i=await bD(r,o,n,e,t);console.log(),i.length>0&&(console.log(ug("Skill Installation:")),Zo(i))}var DD=new yD("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 AD(n)}catch(e){console.error(wD(e.message)),process.exit(1)}}),pg=DD;import{Command as bT}from"commander";import{McpServer as oT}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as iT}from"@modelcontextprotocol/sdk/server/stdio.js";import*as Sn from"path";import*as Dg from"fs";import{z as fe}from"zod";var la=class{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=>r(o)))}};function Pd(){return new la}import*as je from"fs";import*as me from"path";import{z as Id}from"zod";function mg(n){return"method"in n&&!("id"in n)}import{spawn as TD}from"child_process";import{EventEmitter as RD}from"events";import*as $r from"fs";import*as fg from"path";var fn=class extends RD{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;ensureDirectories(){let t=fg.join(this.config.logPath,"lspLog");return $r.existsSync(t)||$r.mkdirSync(t,{recursive:!0}),$r.existsSync(this.config.indexingDataLocation)||$r.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let r=this.ensureDirectories();f.info(`[LspClient] serverMaxSize=${t}MB`);let o=V(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=this.config.nodePath;f.info(`[LspClient] nodePath: ${s}`),this.process=TD(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
|
|
1299
1299
|
\r
|
|
1300
1300
|
${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this.buffer.indexOf(`\r
|
|
1301
1301
|
\r
|
|
1302
|
-
`);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),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 gn=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)o(t,r),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}`),o(),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 ca=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var $r=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 k(n){return typeof n=="object"&&n!==null}var lg=20*1e3,TD=30*1e3,la=class{client;nextRequestId=1;stopOnce=null;callbacks=new $r;requestCallbacks=new gn;diagnosticMap=new Map;initProgressReset=null;constructor(e){this.client=new hn(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(300),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,et);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 ca(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=TD){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){k(e)&&this.broadcastToClients({jsonrpc:N,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,lg,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${lg}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:N,method:y.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var da=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 Ed(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)}},Ed=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var kD={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"},RD={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"},L={...kD,...RD},yn={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"},dg=new Set([1e3,2e3,3e3,3001]);function xD(n){if(!k(n))return!1;let e=n.textDocument;return k(e)&&typeof e.uri=="string"}function ND(n){return k(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function LD(n){return k(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 ua=class n{client;isInitialized=!1;stopOnce=null;callbacks=new $r;requestCallbacks=new gn;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;constructor(e){this.client=new hn(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:N,method:L.EXIT,params:{}}),yn.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(L.BROADCAST),this.callbacks.register(L.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(L.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(L.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(L.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:N,method:L.INITIALIZED,params:{editors:e}}),yn.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:N,id:0,result:{}}),yn.EMPTY)}sendAsyncRequest(e,t,r,o){if(!k(t)){f.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!xD(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=mt(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:N,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(!ND(r)){f.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:N,method:L.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),L.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!k(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:N,method:L.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),yn.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let o=mt(t);e.textDocument.uri=o,f.info(`[LSP] onAsyncOpenFile, uri: ${o}`);let i=this.diagnosticMap.get(o);i||(i=new da(o),this.diagnosticMap.set(o,i),this.registerDiagnosticTimeout(o,L.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(i.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:N,method:L.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),yn.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=mt(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,L.PUBLISH_DIAGNOSTICS)),f.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:N,method:L.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),yn.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=mt(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:N,method:L.DID_CLOSE,params:{textDocument:{uri:r}}}),yn.DID_CLOSE)}getDiagnosticMessage(e){let t=mt(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,L.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:N,method:L.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 L.MODULE_INIT_FINISH:return f.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(L.MODULE_INIT_FINISH),this.callbacks.unregister(L.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case L.INDEXING_PROGRESS_UPDATE:return f.info(`[LSP] onIndexingProgressUpdate: ${LD(t.params)}`),this.callbacks.invoke(L.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case L.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case L.ON_PACKAGE_CHANGE_FINISH:f.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case L.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case L.ON_ASYNC_HOVER:this.handleAsyncResponse(t,L.HOVER);return;case L.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,L.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case L.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,L.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;k(t)&&k(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:N,method:L.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(!k(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,L.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(dg)&&this.finalizeDiagnostic(t,L.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 ai from"path";import*as wa from"path";var pa=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var ma=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var fa=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var ha=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var ga=class{typeSetting=new fa;parameterNames=new ha};var ya=class{constructor(e,t,r,o){this.rootUri=e;this.lspServerWorkspacePath=G(wa.dirname(t)),this.indexingDataLocation=G(o),this.loggerPath=G(wa.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new pa;gutterIconsSetting=new ma;inlayHintsSetting=new ga;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as ug from"path";var ri=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(G(ug.join(e,"src","main","resources")))}};var OD="OS",Hr=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${OD}`;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 ri(e)):this.buildProfileParam=new ri}toString(){return JSON.stringify(this)}};var Br=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as Ne from"path";import*as Vr from"fs";var va=class{modulePath;dependencies={};dynamicDependencies={}};var rr=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 Ur=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 Yt from"path";import*as Sa from"fs";var Wr=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:pt.OH_PACKAGE_JSON5},oi=`${_.HVIGOR_CACHE}/${_.DEPENDENCY}`,or=`${_.DEPENDENCY}${_.JSON5}`,vq=pt.SYNC_OUTPUT_PATH;var ii=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=Yt.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(!k(e))return r;let o=e[t];if(!k(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 Wr;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=Yt.normalize(Yt.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)),Yt.isAbsolute(s)){r.dependencyPath=i;return}o||(i=Yt.resolve(this.modulePath,s)),Sa.existsSync(i)&&Sa.statSync(i).isDirectory()&&(r.dependencyPath=i)}catch(i){f.error("parser dependency path is invalid",i)}}};import*as si from"fs";import*as wn from"path";import MD from"json5";var ba=class n{projectPath;static FILE_DEPENDENCY_PREFIX="file:";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 wn.join(this.projectPath,_.OH_MODULES_PATH,_.OHPM_PATH,_.LOCK_JSON5_FILE)}readLockFile(e){if(!si.existsSync(e))return f.error("lock file does not exist"),this.clearDependencies(),null;try{let t=si.readFileSync(e,"utf8"),r=MD.parse(t);return r||(f.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return f.error("Error parsing lock.json5:",t),this.clearDependencies(),null}}validateLockFile(e){if(!k(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(!k(e))return t;for(let[r,o]of Object.entries(e)){if(!k(o)){f.error(`${r} value is not json object`);continue}typeof o.storePath=="string"&&t.set(r,o.storePath)}return t}getDependencyList(e,t,r){if(!k(e))return[];for(let[o,i]of Object.entries(e))if(k(i)){let s=typeof i.name=="string"?i.name:"";if(r==="."&&s===""||s===r)return this.getFinalDependencyList(e,t,o)}return[]}getFinalDependencyList(e,t,r){let o=e[r];if(!k(o))return f.error("moduleJsonObject is null"),[];let i=[],s=o[t];if(!k(s))return[];for(let[a,c]of Object.entries(s)){if(!k(c))continue;let l=typeof c.specifier=="string"?c.specifier:"",d=typeof c.version=="string"?c.version:"",h=new Wr;h.name=a,h.version=d.startsWith(n.FILE_DEPENDENCY_PREFIX)?d.substring(n.FILE_DEPENDENCY_PREFIX.length):d,this.parseDependencyPath(h,r,a,l,d);let w=`${a}@${d}`;this.storePathMap.has(w)&&(h.storePath=this.storePathMap.get(w)||""),i.push(h)}return i}parseDependencyPath(e,t,r,o,i){let s=wn.resolve(this.projectPath,wn.join(t,_.OH_MODULES_PATH,r));try{let a=i.startsWith(n.FILE_DEPENDENCY_PREFIX)?i.substring(n.FILE_DEPENDENCY_PREFIX.length):i,c=wn.isAbsolute(a)?a:wn.resolve(this.projectPath,a);si.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",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function pg(n){return k(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var ir=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new jt(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=Ne.join(t,oi),o=Ne.join(r,or);if(!Vr.existsSync(r)||!Vr.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 Ur(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];pg(l)&&(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=Ne.join(r,oi),i=Ne.join(o,or);if(!Vr.existsSync(o)||!Vr.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 Ur(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(!pg(l))continue;let d=l.name;if(s&&!s.has(d))continue;let h=Ne.resolve(this.projectPath,l.srcPath),w=Ne.join(o,d),v=G(h),I=this.buildModuleDependencies(d,v,w,a);I.moduleName=d,t.push(I)}return t}parseSingleModule(e,t,r,o){let i=e.name,s=Ne.resolve(this.projectPath,e.srcPath),a=Ne.join(t,i),c=G(s),l=new Hr(c),d=this.buildModuleDependencies(i,c,a,r);this.parseModuleJson5(c,l);let h=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=i,l.moduleType=i,l.packageName=i,l.moduleDependencies=d,l.moduleJsonParam=new Br(h),o.push(l)}buildModuleDependencies(e,t,r,o){let i=new Ur(this.projectPath,e,t);ii.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 va;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 rr(i);for(let i of e.finalDynamicDependencies)o[i.name]=new rr(i);t.dependencies=r,t.dynamicDependencies=o}parseProjectDependencies(e,t){let r=Ne.join(e,_.OH_PACKAGE_JSON5);if(!Vr.existsSync(r))return;ii.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 ba(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=Ne.join(e,"src","main","module.json5"),o=Je(r);if(!k(o)||!k(o.module))return;let i=o.module;t.permissions=this.parseRequestPermissions(i),t.deviceType=this.parseDeviceTypes(i)}parseRequestPermissions(e){let t=[];if(k(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)k(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=Ne.join(e,"src","main","resources","base","profile","main_pages.json"),r=Je(t);return!k(r)||!Array.isArray(r.src)?[]:r.src.filter(o=>typeof o=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!k(t)||!k(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=Ne.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=Je(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!k(t)||!k(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!k(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=Ne.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!k(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 Ea=class{constructor(e=[]){this.valueSet=e}valueSet};var Gr=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var mg=(P=>(P[P.File=1]="File",P[P.Module=2]="Module",P[P.Namespace=3]="Namespace",P[P.Package=4]="Package",P[P.Class=5]="Class",P[P.Method=6]="Method",P[P.Property=7]="Property",P[P.Field=8]="Field",P[P.Constructor=9]="Constructor",P[P.Enum=10]="Enum",P[P.Interface=11]="Interface",P[P.Function=12]="Function",P[P.Variable=13]="Variable",P[P.Constant=14]="Constant",P[P.String=15]="String",P[P.Number=16]="Number",P[P.Boolean=17]="Boolean",P[P.Array=18]="Array",P[P.Object=19]="Object",P[P.Key=20]="Key",P[P.Null=21]="Null",P[P.EnumMember=22]="EnumMember",P[P.Struct=23]="Struct",P[P.Event=24]="Event",P[P.Operator=25]="Operator",P[P.TypeParameter=26]="TypeParameter",P))(mg||{}),fg=()=>Object.values(mg).filter(n=>typeof n=="number");var Pa=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Ca=class{applyEdit=!0;workspaceEdit=new Pa;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Ea(fg());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Gr;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Ia=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Aa=class{constructor(e=[]){this.valueSet=e}valueSet};var Da=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var hg=(C=>(C[C.Text=1]="Text",C[C.Method=2]="Method",C[C.Function=3]="Function",C[C.Constructor=4]="Constructor",C[C.Field=5]="Field",C[C.Variable=6]="Variable",C[C.Class=7]="Class",C[C.Interface=8]="Interface",C[C.Module=9]="Module",C[C.Property=10]="Property",C[C.Unit=11]="Unit",C[C.Value=12]="Value",C[C.Enum=13]="Enum",C[C.Keyword=14]="Keyword",C[C.Snippet=15]="Snippet",C[C.Color=16]="Color",C[C.File=17]="File",C[C.Reference=18]="Reference",C[C.Folder=19]="Folder",C[C.EnumMember=20]="EnumMember",C[C.Constant=21]="Constant",C[C.Struct=22]="Struct",C[C.Event=23]="Event",C[C.Operator=24]="Operator",C[C.TypeParameter=25]="TypeParameter",C))(hg||{}),gg=()=>Object.values(hg).filter(n=>typeof n=="number");var Ta=class{completionItemKind=new Aa(gg());completionItem=new Da;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var ka=class{synchronization=new Ia;completion=new Ta;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 Gr;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var Ra=class{workspace=new Ca;textDocument=new ka;notebookDocument=null;window=null;general=null;experimental=null};var xa=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var Na=class{messageHandle;get stdHandle(){return this.messageHandle}get legacyHandle(){return this.messageHandle}onAsyncOpenFile(e){this.legacyHandle.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.legacyHandle.closeFile(e,t)}serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];sdkPath;rootUri;nodeMaxOldSpaceSize;nodePath;useStandardProtocol;get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}constructor(e){this.sdkPath=e.sdkPath,this.rootUri=e.workspaceRoot,this.nodeMaxOldSpaceSize=e.nodeMaxOldSpaceSize,this.nodePath=e.nodePath,this.useStandardProtocol=e.useStandardProtocol,this.serverPath=e.useStandardProtocol?ai.resolve(ai.dirname(e.arktsLangServerPath),"standardIndex","index.js"):e.arktsLangServerPath,this.logPath=om(),this.indexLogPath=e.indexLogPath||this.logPath;let t={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath,nodePath:this.nodePath};this.messageHandle=e.useStandardProtocol?new la(t):new ua(t),this.messageHandle.setBroadcastToClients(r=>this.onLspMessage(r))}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=mt(this.rootUri),i=new ya(o,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new ir(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),i.modules=s;let l=Ss(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new xa(o,i,new Ra),this.useStandardProtocol){let d=this.messageHandle;await d.sendInitializeResettable(this.currentParams,et),f.info("[LSP] initialize response received"),d.broadcastToClients({jsonrpc:N,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:N,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((o,i)=>{r.onIndexingProgressUpdate(i),r.onInitializationCompleted(o)},"LSP initialization",et),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=k(r)?r:{};f.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let i={jsonrpc:N,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 ir(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,h)=>{(o.dependencies??={})[d]=this.makeDeleteEntry(d,h)}),this.markAddAndDeleteInDeps(a,l,(d,h)=>{(o.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,h)})}}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 rr({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Hr(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new Br([]),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=vr(ai.join(t,"default/openharmony/ets/build-tools/ets-loader")),o=vr(ai.join(t,"default/openharmony/ets/api")),i=vr(ai.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:N,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:N,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:N,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:N,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:N,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:N,id:e.id,error:{code:-32603,message:t.message}}));break;default:f.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!ag(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 Jt from"fs";import*as je from"path";import{createHash as FD}from"crypto";import{EventEmitter as jD}from"events";var La=class extends jD{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(!Jt.existsSync(t)){f.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Jt.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=je.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=je.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=je.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=je.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=je.join(this.projectRoot,_.OH_PACKAGE_JSON5);Jt.existsSync(r)&&t.push(r);let o=this.parseModulesFromBuildProfile();for(let i of o){let s=je.resolve(this.projectRoot,i.srcPath),a=je.join(s,_.OH_PACKAGE_JSON5);Jt.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return je.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Jt.readFileSync(t,"utf-8");return FD("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=Jt.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:je.basename(t),relativePath:je.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 vn from"fs";import*as wt from"path";import{createHash as $D}from"crypto";import{EventEmitter as HD}from"events";var Oa=class extends HD{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=wt.join(t,oi)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!vn.existsSync(this.depMapDir)){f.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=vn.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 G(wt.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===or)i="dep-map-json";else{let a=o.match(/^([^/]+)\/oh-package\.json5$/);i=a?`module:${a[1]}`:""}if(!i)return;let s=wt.join(this.depMapDir,r);vn.existsSync(s)&&this.scheduleDebouncedFullScan()}stop(){this.dirWatcher&&(this.dirWatcher.close(),this.dirWatcher=null),this.fullScanTimer&&(clearTimeout(this.fullScanTimer),this.fullScanTimer=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.coalesceTimer&&(clearTimeout(this.coalesceTimer),this.coalesceTimer=null),this.pendingTags=[],this.pendingRenames=[],this.contentHashes.clear(),this.initialScanDone=!1,f.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=wt.join(this.depMapDir,_.OH_PACKAGE_JSON5),r=wt.join(this.depMapDir,or),o=this.parseModulesFromDepMap(),i=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...o.map(s=>({path:wt.join(this.depMapDir,s.name,_.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of i){if(!vn.existsSync(s))continue;let c=this.canonicalPath(s),l=this.computeFileHash(s);if(!l)continue;let d=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,l);continue}d!==l&&(this.contentHashes.set(c,l),f.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=wt.join(this.depMapDir,or);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 G(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=wt.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=wt.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=vn.readFileSync(t,"utf-8");return $D("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as BD}from"child_process";var UD=["install","--all"];async function WD(n,e,t,r){return new Promise(o=>{let i=BD(n,e,{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(`
|
|
1302
|
+
`);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),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 hn=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)o(t,r),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}`),o(),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 da=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var Hr=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 k(n){return typeof n=="object"&&n!==null}var hg=20*1e3,kD=30*1e3,ua=class{client;nextRequestId=1;stopOnce=null;callbacks=new Hr;requestCallbacks=new hn;diagnosticMap=new Map;initProgressReset=null;constructor(e){this.client=new fn(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(300),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,Qe);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 da(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=kD){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){k(e)&&this.broadcastToClients({jsonrpc:N,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,hg,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${hg}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:N,method:y.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var pa=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 Cd(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)}},Cd=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var xD={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"},ND={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"},O={...xD,...ND},gn={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"},gg=new Set([1e3,2e3,3e3,3001]);function OD(n){if(!k(n))return!1;let e=n.textDocument;return k(e)&&typeof e.uri=="string"}function LD(n){return k(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function MD(n){return k(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 ma=class n{client;isInitialized=!1;stopOnce=null;callbacks=new Hr;requestCallbacks=new hn;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;constructor(e){this.client=new fn(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:N,method:O.EXIT,params:{}}),gn.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(O.BROADCAST),this.callbacks.register(O.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(O.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(O.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(O.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:N,method:O.INITIALIZED,params:{editors:e}}),gn.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:N,id:0,result:{}}),gn.EMPTY)}sendAsyncRequest(e,t,r,o){if(!k(t)){f.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!OD(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=pt(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:N,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(!LD(r)){f.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:N,method:O.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),O.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!k(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:N,method:O.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),gn.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let o=pt(t);e.textDocument.uri=o,f.info(`[LSP] onAsyncOpenFile, uri: ${o}`);let i=this.diagnosticMap.get(o);i||(i=new pa(o),this.diagnosticMap.set(o,i),this.registerDiagnosticTimeout(o,O.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(i.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:N,method:O.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),gn.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=pt(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,O.PUBLISH_DIAGNOSTICS)),f.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:N,method:O.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),gn.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=pt(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:N,method:O.DID_CLOSE,params:{textDocument:{uri:r}}}),gn.DID_CLOSE)}getDiagnosticMessage(e){let t=pt(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,O.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:N,method:O.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 O.MODULE_INIT_FINISH:return f.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(O.MODULE_INIT_FINISH),this.callbacks.unregister(O.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case O.INDEXING_PROGRESS_UPDATE:return f.info(`[LSP] onIndexingProgressUpdate: ${MD(t.params)}`),this.callbacks.invoke(O.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case O.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case O.ON_PACKAGE_CHANGE_FINISH:f.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case O.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case O.ON_ASYNC_HOVER:this.handleAsyncResponse(t,O.HOVER);return;case O.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,O.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case O.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,O.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;k(t)&&k(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:N,method:O.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(!k(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,O.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(gg)&&this.finalizeDiagnostic(t,O.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 ci from"path";import*as Sa from"path";var fa=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var ha=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var ga=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var ya=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var wa=class{typeSetting=new ga;parameterNames=new ya};var va=class{constructor(e,t,r,o){this.rootUri=e;this.lspServerWorkspacePath=V(Sa.dirname(t)),this.indexingDataLocation=V(o),this.loggerPath=V(Sa.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new fa;gutterIconsSetting=new ha;inlayHintsSetting=new wa;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as yg from"path";var oi=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(yg.join(e,"src","main","resources")))}};var _D="OS",Ur=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${_D}`;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 oi(e)):this.buildProfileParam=new oi}toString(){return JSON.stringify(this)}};var Br=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as ke from"path";import*as Gr from"fs";var ba=class{modulePath;dependencies={};dynamicDependencies={}};var nr=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 Wr=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 qt from"path";import*as Ea from"fs";var Vr=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:ut.OH_PACKAGE_JSON5},ii=`${_.HVIGOR_CACHE}/${_.DEPENDENCY}`,rr=`${_.DEPENDENCY}${_.JSON5}`,dz=ut.SYNC_OUTPUT_PATH;var si=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=qt.join(this.dependencyPath,_.OH_PACKAGE_JSON5),r=Ye(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(!k(e))return r;let o=e[t];if(!k(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 Vr;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=qt.normalize(qt.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)),qt.isAbsolute(s)){r.dependencyPath=i;return}o||(i=qt.resolve(this.modulePath,s)),Ea.existsSync(i)&&Ea.statSync(i).isDirectory()&&(r.dependencyPath=i)}catch(i){f.error("parser dependency path is invalid",i)}}};import*as ai from"fs";import*as yn from"path";import FD from"json5";var Pa=class n{projectPath;static FILE_DEPENDENCY_PREFIX="file:";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 yn.join(this.projectPath,_.OH_MODULES_PATH,_.OHPM_PATH,_.LOCK_JSON5_FILE)}readLockFile(e){if(!ai.existsSync(e))return f.error("lock file does not exist"),this.clearDependencies(),null;try{let t=ai.readFileSync(e,"utf8"),r=FD.parse(t);return r||(f.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return f.error("Error parsing lock.json5:",t),this.clearDependencies(),null}}validateLockFile(e){if(!k(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(!k(e))return t;for(let[r,o]of Object.entries(e)){if(!k(o)){f.error(`${r} value is not json object`);continue}typeof o.storePath=="string"&&t.set(r,o.storePath)}return t}getDependencyList(e,t,r){if(!k(e))return[];for(let[o,i]of Object.entries(e))if(k(i)){let s=typeof i.name=="string"?i.name:"";if(r==="."&&s===""||s===r)return this.getFinalDependencyList(e,t,o)}return[]}getFinalDependencyList(e,t,r){let o=e[r];if(!k(o))return f.error("moduleJsonObject is null"),[];let i=[],s=o[t];if(!k(s))return[];for(let[a,c]of Object.entries(s)){if(!k(c))continue;let l=typeof c.specifier=="string"?c.specifier:"",d=typeof c.version=="string"?c.version:"",h=new Vr;h.name=a,h.version=d.startsWith(n.FILE_DEPENDENCY_PREFIX)?d.substring(n.FILE_DEPENDENCY_PREFIX.length):d,this.parseDependencyPath(h,r,a,l,d);let w=`${a}@${d}`;this.storePathMap.has(w)&&(h.storePath=this.storePathMap.get(w)||""),i.push(h)}return i}parseDependencyPath(e,t,r,o,i){let s=yn.resolve(this.projectPath,yn.join(t,_.OH_MODULES_PATH,r));try{let a=i.startsWith(n.FILE_DEPENDENCY_PREFIX)?i.substring(n.FILE_DEPENDENCY_PREFIX.length):i,c=yn.isAbsolute(a)?a:yn.resolve(this.projectPath,a);ai.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",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function wg(n){return k(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var or=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new Ft(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=ke.join(t,ii),o=ke.join(r,rr);if(!Gr.existsSync(r)||!Gr.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 Wr(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];wg(l)&&(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=ke.join(r,ii),i=ke.join(o,rr);if(!Gr.existsSync(o)||!Gr.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 Wr(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(!wg(l))continue;let d=l.name;if(s&&!s.has(d))continue;let h=ke.resolve(this.projectPath,l.srcPath),w=ke.join(o,d),v=V(h),T=this.buildModuleDependencies(d,v,w,a);T.moduleName=d,t.push(T)}return t}parseSingleModule(e,t,r,o){let i=e.name,s=ke.resolve(this.projectPath,e.srcPath),a=ke.join(t,i),c=V(s),l=new Ur(c),d=this.buildModuleDependencies(i,c,a,r);this.parseModuleJson5(c,l);let h=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=i,l.moduleType=i,l.packageName=i,l.moduleDependencies=d,l.moduleJsonParam=new Br(h),o.push(l)}buildModuleDependencies(e,t,r,o){let i=new Wr(this.projectPath,e,t);si.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 ba;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 nr(i);for(let i of e.finalDynamicDependencies)o[i.name]=new nr(i);t.dependencies=r,t.dynamicDependencies=o}parseProjectDependencies(e,t){let r=ke.join(e,_.OH_PACKAGE_JSON5);if(!Gr.existsSync(r))return;si.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 Pa(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=ke.join(e,"src","main","module.json5"),o=Ye(r);if(!k(o)||!k(o.module))return;let i=o.module;t.permissions=this.parseRequestPermissions(i),t.deviceType=this.parseDeviceTypes(i)}parseRequestPermissions(e){let t=[];if(k(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)k(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=ke.join(e,"src","main","resources","base","profile","main_pages.json"),r=Ye(t);return!k(r)||!Array.isArray(r.src)?[]:r.src.filter(o=>typeof o=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!k(t)||!k(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=ke.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=Ye(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!k(t)||!k(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!k(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=ke.join(this.projectPath,"build-profile.json5");this.buildProfileCache=Ye(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!k(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 Ca=class{constructor(e=[]){this.valueSet=e}valueSet};var zr=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var vg=(P=>(P[P.File=1]="File",P[P.Module=2]="Module",P[P.Namespace=3]="Namespace",P[P.Package=4]="Package",P[P.Class=5]="Class",P[P.Method=6]="Method",P[P.Property=7]="Property",P[P.Field=8]="Field",P[P.Constructor=9]="Constructor",P[P.Enum=10]="Enum",P[P.Interface=11]="Interface",P[P.Function=12]="Function",P[P.Variable=13]="Variable",P[P.Constant=14]="Constant",P[P.String=15]="String",P[P.Number=16]="Number",P[P.Boolean=17]="Boolean",P[P.Array=18]="Array",P[P.Object=19]="Object",P[P.Key=20]="Key",P[P.Null=21]="Null",P[P.EnumMember=22]="EnumMember",P[P.Struct=23]="Struct",P[P.Event=24]="Event",P[P.Operator=25]="Operator",P[P.TypeParameter=26]="TypeParameter",P))(vg||{}),Sg=()=>Object.values(vg).filter(n=>typeof n=="number");var Ia=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Aa=class{applyEdit=!0;workspaceEdit=new Ia;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Ca(Sg());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new zr;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Da=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Ta=class{constructor(e=[]){this.valueSet=e}valueSet};var Ra=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var bg=(C=>(C[C.Text=1]="Text",C[C.Method=2]="Method",C[C.Function=3]="Function",C[C.Constructor=4]="Constructor",C[C.Field=5]="Field",C[C.Variable=6]="Variable",C[C.Class=7]="Class",C[C.Interface=8]="Interface",C[C.Module=9]="Module",C[C.Property=10]="Property",C[C.Unit=11]="Unit",C[C.Value=12]="Value",C[C.Enum=13]="Enum",C[C.Keyword=14]="Keyword",C[C.Snippet=15]="Snippet",C[C.Color=16]="Color",C[C.File=17]="File",C[C.Reference=18]="Reference",C[C.Folder=19]="Folder",C[C.EnumMember=20]="EnumMember",C[C.Constant=21]="Constant",C[C.Struct=22]="Struct",C[C.Event=23]="Event",C[C.Operator=24]="Operator",C[C.TypeParameter=25]="TypeParameter",C))(bg||{}),Eg=()=>Object.values(bg).filter(n=>typeof n=="number");var ka=class{completionItemKind=new Ta(Eg());completionItem=new Ra;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var xa=class{synchronization=new Da;completion=new ka;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 zr;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var Na=class{workspace=new Aa;textDocument=new xa;notebookDocument=null;window=null;general=null;experimental=null};var Oa=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var La=class{messageHandle;get stdHandle(){return this.messageHandle}get legacyHandle(){return this.messageHandle}onAsyncOpenFile(e){this.legacyHandle.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.legacyHandle.closeFile(e,t)}serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];sdkPath;rootUri;nodeMaxOldSpaceSize;nodePath;useStandardProtocol;get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}constructor(e){this.sdkPath=e.sdkPath,this.rootUri=e.workspaceRoot,this.nodeMaxOldSpaceSize=e.nodeMaxOldSpaceSize,this.nodePath=e.nodePath,this.useStandardProtocol=e.useStandardProtocol,this.serverPath=e.useStandardProtocol?ci.resolve(ci.dirname(e.arktsLangServerPath),"standardIndex","index.js"):e.arktsLangServerPath,this.logPath=dm(),this.indexLogPath=e.indexLogPath||this.logPath;let t={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath,nodePath:this.nodePath};this.messageHandle=e.useStandardProtocol?new ua(t):new ma(t),this.messageHandle.setBroadcastToClients(r=>this.onLspMessage(r))}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=pt(this.rootUri),i=new va(o,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new or(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),i.modules=s;let l=Es(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new Oa(o,i,new Na),this.useStandardProtocol){let d=this.messageHandle;await d.sendInitializeResettable(this.currentParams,Qe),f.info("[LSP] initialize response received"),d.broadcastToClients({jsonrpc:N,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:N,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((o,i)=>{r.onIndexingProgressUpdate(i),r.onInitializationCompleted(o)},"LSP initialization",Qe),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=k(r)?r:{};f.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let i={jsonrpc:N,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 or(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,h)=>{(o.dependencies??={})[d]=this.makeDeleteEntry(d,h)}),this.markAddAndDeleteInDeps(a,l,(d,h)=>{(o.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,h)})}}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 nr({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Ur(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new Br([]),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=Sr(ci.join(t,"default/openharmony/ets/build-tools/ets-loader")),o=Sr(ci.join(t,"default/openharmony/ets/api")),i=Sr(ci.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:N,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:N,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:N,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:N,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:N,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:N,id:e.id,error:{code:-32603,message:t.message}}));break;default:f.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!mg(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 Yt from"fs";import*as Fe from"path";import{createHash as $D}from"crypto";import{EventEmitter as HD}from"events";var Ma=class extends HD{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(!Yt.existsSync(t)){f.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Yt.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=Fe.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=Fe.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=Fe.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=Fe.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=Ye(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=Fe.join(this.projectRoot,_.OH_PACKAGE_JSON5);Yt.existsSync(r)&&t.push(r);let o=this.parseModulesFromBuildProfile();for(let i of o){let s=Fe.resolve(this.projectRoot,i.srcPath),a=Fe.join(s,_.OH_PACKAGE_JSON5);Yt.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Fe.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Yt.readFileSync(t,"utf-8");return $D("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=Yt.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:Fe.basename(t),relativePath:Fe.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 wn from"fs";import*as yt from"path";import{createHash as UD}from"crypto";import{EventEmitter as BD}from"events";var _a=class extends BD{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=yt.join(t,ii)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!wn.existsSync(this.depMapDir)){f.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=wn.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 V(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===rr)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);wn.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,rr),o=this.parseModulesFromDepMap(),i=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...o.map(s=>({path:yt.join(this.depMapDir,s.name,_.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of i){if(!wn.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,rr);try{let r=Ye(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 V(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=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=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=wn.readFileSync(t,"utf-8");return UD("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as WD}from"child_process";var VD=["install","--all"];async function GD(n,e,t,r){return new Promise(o=>{let i=WD(n,e,{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(`
|
|
1303
1303
|
`);o({exitCode:c??-1,output:l})}),i.on("error",c=>{let l=[s,a].filter(Boolean).join(`
|
|
1304
1304
|
`);o({exitCode:-1,output:l+`
|
|
1305
|
-
`+c.message})})})}function VD(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>f.info("[ohpm] %s",e))}async function yg(n,e){try{let{exitCode:t,output:r}=await WD(e.nodePath,[e.ohpmJsPath,...UD],n,e.sdkPath);return VD(r),t===0?(f.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(f.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",t),f.error("ohpm \u8F93\u51FA: %s",r),!1)}catch(t){return f.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var wg={UNINITIALIZED:-32099,UNKNOWN:-32e3},ci=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,wg.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,wg.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var qr=class{config;lspProxy=null;configWatcher=null;depMapWatcher=null;isInitialized=!1;lastEditorOpenFiles=[];onMessage=()=>{};onConfigChanged=null;disposeOnce=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){if(f.info("[ArktsLspManager] Received arkts/syncProject"),!e)return f.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let o=r?.skipHvigorSync===!0,i=await fs(e,async()=>await yg(e,t)?o?(f.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await um(e,t)?(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 i.acquired?i.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 Na(this.config);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:N,method:y.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();f.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?ci.uninitialized(t):ci.unknown();this.onMessage({jsonrpc:N,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:N,method:y.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new La(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Oa(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:N,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 GD=10080*60*1e3,qD=7200*60*1e3,zD=120*1e3,zr=class n{manager=null;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;toolProvider;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){this.projectPath=e,this.toolProvider=t,this.nodeMaxOldSpaceSize=r}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:Pd.object({files:Pd.array(Pd.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,devecoPath:t,arktsLangServerPath:r,useStandardProtocol:o}=this.resolveProjectAndDeveco();this.useStandardProtocol=o;let i=ge(e),{logPath:s,indexPath:a}=this.getLogAndIndexPath(i);setImmediate(()=>{Yc(a,GD,"[ArkTS-Check]"),Yc(s,qD,"[ArkTS-Check]")}),ws(s);let c=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,l=Number.isNaN(c)?void 0:c;g.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${l??"undefined \u2192 dynamic formula applies"}`);let d=this.toolProvider.sdkPath;g.info(`ArktsCheck devecoStudioPath: ${t}, sdkPath: ${d}`),this.manager=new qr({sdkPath:d,arktsLangServerPath:r,workspaceRoot:G(i),indexLogPath:a,nodeMaxOldSpaceSize:l,nodePath:this.toolProvider.nodePath,useStandardProtocol:o}),this.manager.setOnMessage(h=>this.handleLspMessage(h)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((h,w)=>{this.initResolve=h,this.initReject=w,this.armInitTimer(et),this.manager.start([]).catch(v=>{let I=v instanceof Error?v:new Error(String(v));this.failInit(I)})})}resolveProjectAndDeveco(){let e=Nt(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.toolProvider.devecoStudioPath??"";g.debug(`DevEco Studio installation path: ${t}`);let r=this.toolProvider.lspServerPath;if(!r)throw new Error("arkts-lang-server path not found");let o=fe.resolve(fe.dirname(r),"standardIndex","index.js"),i=$e.existsSync(o);return g.info(`ArktsCheck protocol: ${i?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${i})`),{harmonyRoot:e,devecoPath:t,arktsLangServerPath:r,useStandardProtocol:i}}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=Wn(e),o=await $e.promises.readFile(e,"utf8"),s=`deveco.apptool.${fe.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){g.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:o,version:++this.documentVersion}});try{g.debug(`textDocument/diagnostic uri=${t}`);let i=await e.diagnostic({textDocument:{uri:t}});return YD(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"))},zD);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});g.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(`
|
|
1306
|
-
`):"\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};g.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 g.error(`handleLspFeature ${e} failed: ${s}`),{content:[{type:"text",text:`${e} failed: ${s}`}],isError:!0}}}async handleWorkspaceSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();g.info(`handleWorkspaceSymbol: query="${e}"`);try{let t=await this.manager.sendFeatureRequest(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 g.error(`handleWorkspaceSymbol failed: ${r}`),{content:[{type:"text",text:`workspaceSymbol failed: ${r}`}],isError:!0}}}async handleWorkspaceSymbolRaw(e){if(!this.initialized)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return g.error(`handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};g.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 g.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};g.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 h=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(h)?l.push(...h):h&&l.push(h)}return{items:a,calls:l}});return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){let o=r instanceof Error?r.message:String(r);return g.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};g.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};g.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};g.info(`handleTypeHierarchy: 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_TYPE_HIERARCHY,{textDocument:{uri:i},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],results:[]};let c=e.direction==="supertypes"?y.SUPERTYPES:y.SUBTYPES,l=[];for(let d of a){let h=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(h)?l.push(...h):h&&l.push(h)}return{items:a,results:l}});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();g.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 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
|
|
1307
|
-
`).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 g.error(`${e} failed: ${r}`),{content:[{type:"text",text:`${e} failed: ${r}`}],isError:!0}}async withOpenFile(e,t){let r=
|
|
1305
|
+
`+c.message})})})}function zD(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>f.info("[ohpm] %s",e))}async function Pg(n,e){try{let{exitCode:t,output:r}=await GD(e.nodePath,[e.ohpmJsPath,...VD],n,e.sdkPath);return zD(r),t===0?(f.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(f.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",t),f.error("ohpm \u8F93\u51FA: %s",r),!1)}catch(t){return f.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var Cg={UNINITIALIZED:-32099,UNKNOWN:-32e3},li=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,Cg.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,Cg.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var qr=class{config;lspProxy=null;configWatcher=null;depMapWatcher=null;isInitialized=!1;lastEditorOpenFiles=[];onMessage=()=>{};onConfigChanged=null;disposeOnce=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){if(f.info("[ArktsLspManager] Received arkts/syncProject"),!e)return f.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let o=r?.skipHvigorSync===!0,i=await gs(e,async()=>await Pg(e,t)?o?(f.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await ym(e,t)?(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 i.acquired?i.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 La(this.config);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:N,method:y.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();f.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?li.uninitialized(t):li.unknown();this.onMessage({jsonrpc:N,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:N,method:y.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Ma(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new _a(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:N,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 qD=10080*60*1e3,YD=7200*60*1e3,JD=120*1e3,Yr=class n{manager=null;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;toolProvider;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){this.projectPath=e,this.toolProvider=t,this.nodeMaxOldSpaceSize=r}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:Id.object({files:Id.array(Id.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,devecoPath:t,arktsLangServerPath:r,useStandardProtocol:o}=this.resolveProjectAndDeveco();this.useStandardProtocol=o;let i=he(e),{logPath:s,indexPath:a}=this.getLogAndIndexPath(i);setImmediate(()=>{Kc(a,qD,"[ArkTS-Check]"),Kc(s,YD,"[ArkTS-Check]")}),Ss(s);let c=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,l=Number.isNaN(c)?void 0:c;g.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${l??"undefined \u2192 dynamic formula applies"}`);let d=this.toolProvider.sdkPath;g.info(`ArktsCheck devecoStudioPath: ${t}, sdkPath: ${d}`),this.manager=new qr({sdkPath:d,arktsLangServerPath:r,workspaceRoot:V(i),indexLogPath:a,nodeMaxOldSpaceSize:l,nodePath:this.toolProvider.nodePath,useStandardProtocol:o}),this.manager.setOnMessage(h=>this.handleLspMessage(h)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((h,w)=>{this.initResolve=h,this.initReject=w,this.armInitTimer(Qe),this.manager.start([]).catch(v=>{let T=v instanceof Error?v:new Error(String(v));this.failInit(T)})})}resolveProjectAndDeveco(){let e=xt(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.toolProvider.devecoStudioPath??"";g.debug(`DevEco Studio installation path: ${t}`);let r=this.toolProvider.lspServerPath;if(!r)throw new Error("arkts-lang-server path not found");let o=me.resolve(me.dirname(r),"standardIndex","index.js"),i=je.existsSync(o);return g.info(`ArktsCheck protocol: ${i?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${i})`),{harmonyRoot:e,devecoPath:t,arktsLangServerPath:r,useStandardProtocol:i}}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=Bn(e),o=await je.promises.readFile(e,"utf8"),s=`deveco.apptool.${me.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){g.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:o,version:++this.documentVersion}});try{g.debug(`textDocument/diagnostic uri=${t}`);let i=await e.diagnostic({textDocument:{uri:t}});return KD(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"))},JD);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});g.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(`
|
|
1306
|
+
`):"\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};g.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 g.error(`handleLspFeature ${e} failed: ${s}`),{content:[{type:"text",text:`${e} failed: ${s}`}],isError:!0}}}async handleWorkspaceSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();g.info(`handleWorkspaceSymbol: query="${e}"`);try{let t=await this.manager.sendFeatureRequest(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 g.error(`handleWorkspaceSymbol failed: ${r}`),{content:[{type:"text",text:`workspaceSymbol failed: ${r}`}],isError:!0}}}async handleWorkspaceSymbolRaw(e){if(!this.initialized)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return g.error(`handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};g.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 g.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};g.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 h=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(h)?l.push(...h):h&&l.push(h)}return{items:a,calls:l}});return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){let o=r instanceof Error?r.message:String(r);return g.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};g.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};g.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};g.info(`handleTypeHierarchy: 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_TYPE_HIERARCHY,{textDocument:{uri:i},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],results:[]};let c=e.direction==="supertypes"?y.SUPERTYPES:y.SUBTYPES,l=[];for(let d of a){let h=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(h)?l.push(...h):h&&l.push(h)}return{items:a,results:l}});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();g.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 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 je.promises.readFile(t,"utf8")).split(`
|
|
1307
|
+
`).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 g.error(`${e} failed: ${r}`),{content:[{type:"text",text:`${e} failed: ${r}`}],isError:!0}}async withOpenFile(e,t){let r=Bn(e),o=await je.promises.readFile(e,"utf8"),s=`deveco.apptool.${me.extname(e).replace(/^\./,"")||"plaintext"}`;g.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=me.isAbsolute(e)?e:me.join(this.projectPath,e);return!je.existsSync(t)||!je.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=this.projectPath,o=[];for(let i of e){let s=me.resolve(me.isAbsolute(i)?i:me.join(r,i));if(!je.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${i}`);continue}if(!je.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 Dp(500);try{let i=await this.checkFile(o);r.push(XD(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(`
|
|
1308
1308
|
`)),t.length>0&&r.push(t.join(`
|
|
1309
1309
|
`));let o=r.join(`
|
|
1310
|
-
`).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){g.warn(`Failed to dispose ArktsLspManager: ${t}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":{this.handleDiagnosticsNotification(t.params);break}case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(
|
|
1311
|
-
`):"No valid C/C++ files"}],isError:!0};this.manager.patchSdkPathInCompileCommands();for(let c of o){await ZD
|
|
1310
|
+
`).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){g.warn(`Failed to dispose ArktsLspManager: ${t}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":{this.handleDiagnosticsNotification(t.params);break}case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(Qe),g.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{g.info("Received arkts/initialized");let o=this.initResolve;this.clearInitHandlers(),o?.();break}case"arkts/initializationFailed":{let i=t.params?.message??"unknown";g.error(`LSP initialization failed: ${i}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${i}`));break}case"workspace/didChangeConfiguration":g.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"){g.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;g.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=me.join(rn(),"ArkTSCheck"),r=me.join(t,"mapping-config.properties"),o=Tp(e,r),i=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=me.join(t,"lsp-log",String(o),i),a=me.join(t,"lsp-index",String(o));return je.mkdirSync(s,{recursive:!0}),je.mkdirSync(a,{recursive:!0}),{logPath:he(s),indexPath:he(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function KD(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 XD(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 vn from"fs";import*as Xr from"path";import{z as Ad}from"zod";function Jr(){return{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}function Fa(n,e){let t=e instanceof Error?e.message:String(e);return g.error(`[CppLsp] ${n} failed: ${t}`),{content:[{type:"text",text:`${n} failed: ${t}`}],isError:!0}}var ZD=500,Kr=class{manager;toolProvider;constructor(e,t){this.manager=e,this.toolProvider=t}static getToolDefinition(){return{name:"check_cpp_files",description:"Perform static syntax checks on the provided C/C++ files and return clangd diagnostics.",inputSchema:Ad.object({files:Ad.array(Ad.string()).describe('List of C/C++ file paths to check, format: ["file1.cpp","file2.hpp",...]')})}}async handleCall(e){if(!this.manager.ready)return Jr();let t=[],r=[],o=this.collectValidFiles(e.files,t);if(o.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
|
|
1311
|
+
`):"No valid C/C++ files"}],isError:!0};this.manager.patchSdkPathInCompileCommands();for(let c of o){await eT(ZD);try{let l=await this.checkFile(c);r.push(QD(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(`
|
|
1312
1312
|
`)),r.length>0&&s.push(r.join(`
|
|
1313
1313
|
`));let a=s.join(`
|
|
1314
|
-
`).trim();return!i&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:i}}async checkFile(e){let t=Wn(e),r=await Sn.promises.readFile(e,"utf8"),o=Xi(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=this.manager.projectRoot,o=[];for(let i of e){let s=Kr.resolve(Kr.isAbsolute(i)?i:Kr.join(r,i));if(!Sn.existsSync(s)){t.push(`File does not exist: ${i}`);continue}if(!Sn.statSync(s).isFile()){t.push(`Not a regular file: ${i}`);continue}if(!Un(s)){t.push(`Not a supported C/C++ file: ${i}`);continue}try{o.push(Sn.realpathSync(s))}catch{o.push(s)}}return o}};function XD(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 ZD(n){return new Promise(e=>setTimeout(e,n))}import*as Zr from"fs";import*as _a from"path";var Xr=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 Yr();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};g.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 Ma(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 g.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return Yr();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};g.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async 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 Ma("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return Yr();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};g.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,i=>this.fetchCallHierarchyResult(i,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return Ma("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=Wn(e),o=await Zr.promises.readFile(e,"utf8"),i=Xi(e);g.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=_a.isAbsolute(e)?e:_a.join(this.manager.projectRoot,e);return!Zr.existsSync(t)||!Zr.statSync(t).isFile()||!Un(t)?null:t}};import{spawn as QD}from"child_process";import*as ja from"fs";import*as vg from"path";var eT=30*1e3,tT=30*1e3,Fa=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new gn;diagnosticWaiters=new Map;lastStartErrorMessage=null;onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}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,nodePath:this.config.nodePath};this.client=new hn(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,et),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}`))},tT);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=${G(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];f.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=QD(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=vr(this.config.workspaceRoot),t=mt(e),r=vg.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"0.4.0"},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=eT){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){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:N,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:N,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:N,method:y.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{ja.existsSync(this.config.logPath)||ja.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)),mt(r)}}catch{}return e}};import*as li from"path";import*as Kt from"fs";var di=class{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 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.patchSdkPathInCompileCommands(),this.proxy.sendFeatureRequest(e,t)}registerDiagnosticCallback(e){return this.proxy?this.proxy.registerDiagnosticCallback(e):Promise.reject(new Error("[ClangdLspManager] LSP not ready"))}patchSdkPathInCompileCommands(){if(!b()||this.config.toolProvider.sourceType==="studio"||process.env.COMMAND_LINE_TOOL_PATH?.trim()===A.OPENHARMONY_STUDIO_ROOT)return;let e=hr(this.projectRoot);if(!Kt.existsSync(e))return;let t=Kt.readFileSync(e,"utf8");if(!t.includes(vs))return;let r=t.replaceAll(vs,this.config.toolProvider.sdkPath);Kt.writeFileSync(e,r,"utf8"),f.info(`[CppCheck] Patched SDK path in compile_commands.json: ${vs} -> ${this.config.toolProvider.sdkPath}`)}static async handleSyncCppProject(e,t){if(f.info("[ClangdLspManager] Received cpp/syncProject"),!e)return f.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or devecoPath is empty"),{status:"failed",reason:"workspaceRoot or devecoPath is empty"};if(qn(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let o=await fs(e,async()=>{try{return await fm(e,t),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}}});return o.acquired?o.result:(f.info("[ClangdLspManager] 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}doStart(){return new Promise((e,t)=>{this.initResolve=e,this.initReject=t,this.armInitTimer(et);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=Nt(this.config.workspaceRoot);this.resolvedRoot=e?ge(e):ge(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();ws(t);let r=this.config.toolProvider.clangdPath;if(!r){let s="clangd executable not found inside DevEco Studio SDK";f.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let o=li.dirname(hr(this.resolvedRoot));try{Kt.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 Fa({clangdPath:r,workspaceRoot:this.resolvedRoot,compileCommandsDir:o,logPath:t,nodePath:this.config.toolProvider.nodePath});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=li.join(on(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=li.join(e,"lsp-log",t);return Kt.mkdirSync(r,{recursive:!0}),ge(r)}catch{return"auto"}}};function Sg(n){let e=gs(n);return f.info(`[SyncGuard] ${e.reason}`),e}var Dd=(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))(Dd||{}),Eg=(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))(Eg||{}),Rt=3,Id=600*1e3,Ad=100,$a=class{server;toolRouter;config;arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";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;constructor(e){this.config=e,Vn(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),g.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",g.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,g.info(`Constructor: using configured path as startPath: '${t}'`));let o=Nt(t);g.info(`Constructor: findHarmonyProject('${t}') => ${o??"null"}`),this.config.projectPath=o??void 0,this.server=new nT({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=bd(),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). 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){g.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=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.config.toolProvider.lspServerPath;if(!e)return g.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=bn.join(bn.dirname(e),"standardIndex","index.js"),r=bg.existsSync(t);return g.info(`ArktsCheck protocol: ${r?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${r})`),r}catch(e){return g.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=R.isPathContainedWithSymlink(i,t);s.contained||(g.warn(`Containment check failed: ${s.reason}`),o.push(s.reason))}return o.length>0?{content:[{type:"text",text:o.join(`
|
|
1315
|
-
`)}],isError:!0}:null}let r=e.filter(o=>
|
|
1316
|
-
`)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(d=>typeof d=="string"):[];if(t.length===0)return g.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>
|
|
1314
|
+
`).trim();return!i&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:i}}async checkFile(e){let t=Bn(e),r=await vn.promises.readFile(e,"utf8"),o=Qi(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=this.manager.projectRoot,o=[];for(let i of e){let s=Xr.resolve(Xr.isAbsolute(i)?i:Xr.join(r,i));if(!vn.existsSync(s)){t.push(`File does not exist: ${i}`);continue}if(!vn.statSync(s).isFile()){t.push(`Not a regular file: ${i}`);continue}if(!Un(s)){t.push(`Not a supported C/C++ file: ${i}`);continue}try{o.push(vn.realpathSync(s))}catch{o.push(s)}}return o}};function QD(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 eT(n){return new Promise(e=>setTimeout(e,n))}import*as Qr from"fs";import*as ja from"path";var Zr=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 Jr();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};g.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 Fa(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 g.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return Jr();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};g.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async 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 Fa("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return Jr();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};g.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,i=>this.fetchCallHierarchyResult(i,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return Fa("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=Bn(e),o=await Qr.promises.readFile(e,"utf8"),i=Qi(e);g.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=ja.isAbsolute(e)?e:ja.join(this.manager.projectRoot,e);return!Qr.existsSync(t)||!Qr.statSync(t).isFile()||!Un(t)?null:t}};import{spawn as tT}from"child_process";import*as Ha from"fs";import*as Ig from"path";var nT=30*1e3,rT=30*1e3,$a=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new hn;diagnosticWaiters=new Map;lastStartErrorMessage=null;onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}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,nodePath:this.config.nodePath};this.client=new fn(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,Qe),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}`))},rT);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=${V(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];f.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=tT(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=Sr(this.config.workspaceRoot),t=pt(e),r=Ig.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.11-Test.1"},rootPath:e,rootUri:t,workspaceFolders:[{uri:t,name:r}],capabilities:this.buildClientCapabilities(),initializationOptions:null}}buildClientCapabilities(){return{textDocument:{synchronization:{didOpen:!0,didChange:!0,didClose:!0,willSave:!1,save:!1},publishDiagnostics:{relatedInformation:!0,versionSupport:!1,tagSupport:{valueSet:[1,2]}},hover:{contentFormat:["markdown","plaintext"]},completion:{contextSupport:!1,completionItemKind:{valueSet:[]}},signatureHelp:{signatureInformation:{documentationFormat:["markdown","plaintext"]}},references:{},declaration:{linkSupport:!0},definition:{linkSupport:!0},implementation:{linkSupport:!0},documentSymbol:{hierarchicalDocumentSymbolSupport:!0,symbolKind:{valueSet:[]}},callHierarchy:{dynamicRegistration:!1}},workspace:{symbol:{symbolKind:{valueSet:[]}},configuration:!1,didChangeWatchedFiles:{dynamicRegistration:!1}}}}sendLspRequest(e,t,r=nT){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){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:N,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:N,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:N,method:y.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{Ha.existsSync(this.config.logPath)||Ha.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)),pt(r)}}catch{}return e}};import*as di from"path";import*as Jt from"fs";var ui=class{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 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.patchSdkPathInCompileCommands(),this.proxy.sendFeatureRequest(e,t)}registerDiagnosticCallback(e){return this.proxy?this.proxy.registerDiagnosticCallback(e):Promise.reject(new Error("[ClangdLspManager] LSP not ready"))}patchSdkPathInCompileCommands(){if(!b()||this.config.toolProvider.sourceType==="studio"||process.env.COMMAND_LINE_TOOL_PATH?.trim()===D.OPENHARMONY_STUDIO_ROOT)return;let e=gr(this.projectRoot);if(!Jt.existsSync(e))return;let t=Jt.readFileSync(e,"utf8");if(!t.includes(bs))return;let r=t.replaceAll(bs,this.config.toolProvider.sdkPath);Jt.writeFileSync(e,r,"utf8"),f.info(`[CppCheck] Patched SDK path in compile_commands.json: ${bs} -> ${this.config.toolProvider.sdkPath}`)}static async handleSyncCppProject(e,t){if(f.info("[ClangdLspManager] Received cpp/syncProject"),!e)return f.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or devecoPath is empty"),{status:"failed",reason:"workspaceRoot or devecoPath is empty"};if(Gn(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let o=await gs(e,async()=>{try{return await Sm(e,t),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}}});return o.acquired?o.result:(f.info("[ClangdLspManager] 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}doStart(){return new Promise((e,t)=>{this.initResolve=e,this.initReject=t,this.armInitTimer(Qe);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=xt(this.config.workspaceRoot);this.resolvedRoot=e?he(e):he(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();Ss(t);let r=this.config.toolProvider.clangdPath;if(!r){let s="clangd executable not found inside DevEco Studio SDK";f.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let o=di.dirname(gr(this.resolvedRoot));try{Jt.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 $a({clangdPath:r,workspaceRoot:this.resolvedRoot,compileCommandsDir:o,logPath:t,nodePath:this.config.toolProvider.nodePath});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=di.join(rn(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=di.join(e,"lsp-log",t);return Jt.mkdirSync(r,{recursive:!0}),he(r)}catch{return"auto"}}};function Ag(n){let e=ws(n);return f.info(`[SyncGuard] ${e.reason}`),e}var Rd=(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))(Rd||{}),Tg=(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))(Tg||{}),Rt=3,Dd=600*1e3,Td=100,Ua=class{server;toolRouter;config;arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";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;constructor(e){this.config=e,Wn(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),g.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",g.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,g.info(`Constructor: using configured path as startPath: '${t}'`));let o=xt(t);g.info(`Constructor: findHarmonyProject('${t}') => ${o??"null"}`),this.config.projectPath=o??void 0,this.server=new oT({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=Pd(),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). 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:fe.object({target:fe.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:fe.object({files:fe.array(fe.string()).min(1).describe("List of source file paths to check, relative to the project root (absolute paths within the project are also accepted). Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}registerLspFeatureTools(){if(!this.standardProtocolAvailable){g.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=fe.object({file:fe.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:fe.number().describe("Line number (0-based)"),character:fe.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:fe.object({query:fe.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:fe.object({file:fe.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:fe.object({file:fe.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:fe.number().describe("Line number (0-based)"),character:fe.number().describe("Character offset in the line (0-based)"),direction:fe.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.config.toolProvider.lspServerPath;if(!e)return g.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=Sn.join(Sn.dirname(e),"standardIndex","index.js"),r=Dg.existsSync(t);return g.info(`ArktsCheck protocol: ${r?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${r})`),r}catch(e){return g.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=x.isPathContainedWithSymlink(i,t);s.contained||(g.warn(`Containment check failed: ${s.reason}`),o.push(s.reason))}return o.length>0?{content:[{type:"text",text:o.join(`
|
|
1315
|
+
`)}],isError:!0}:null}let r=e.filter(o=>Sn.isAbsolute(o));return r.length>0?(g.warn(`Absolute paths rejected (no project root): ${r.join(", ")}`),{content:[{type:"text",text:r.map(o=>`Absolute path is not allowed: ${o}`).join(`
|
|
1316
|
+
`)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(d=>typeof d=="string"):[];if(t.length===0)return g.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>Td)return g.warn(`check tool called with ${t.length} files (max: ${Td})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${Td}.`}],isError:!0};let{etsFiles:r,cppFiles:o,unsupported:i}=sT(t);i.length>0&&g.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(`
|
|
1317
1317
|
`),s.join(`
|
|
1318
1318
|
`)].filter(d=>d.trim().length>0).join(`
|
|
1319
|
-
`).trim()||"No diagnostics collected"}],isError:c}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return g.warn(`ArkTS check rejected: project is ${Dd[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return g.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 g.error(`ArkTS check: unknown project state ${this.projectState}, files: ${e.join(", ")}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],isError:!0}}}async handleLspFeatureCall(e,t){let r=t.file,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 g.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){g.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(r)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),i,o)}catch(a){g.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}/${Rt})`;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}/${Rt})`;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 g.warn(`ArkTS ${e} rejected: project is ${Dd[this.projectState]}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return g.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 g.error(`ArkTS ${e}: unknown project state ${this.projectState}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],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"),g.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(g.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(g.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=Rt?(g.error(`Init retry limit reached (${this.initRetryCount}/${Rt}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${Rt}). Ask the user to investigate and confirm \`ohpm install\` + \`hvigor\` sync succeed manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],isError:!0}):(g.info(`Error check: auto-retrying (${this.initRetryCount}/${Rt})`),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 g.warn(`C++ ${e} rejected: C++ project is ${Eg[this.cppProjectState]}`),{content:[{type:"text",text:"C++ project is syncing (compileNative), please retry in 25 seconds"}],isError:!0};case 3:return g.warn(`C++ ${e} rejected: clangd is initializing`),{content:[{type:"text",text:"C++ LSP (clangd) is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleCppErrorCheck();case 4:return this.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};default:return g.error(`C++ ${e}: unknown C++ project state ${this.cppProjectState}`),{content:[{type:"text",text:`Unknown C++ project state: ${this.cppProjectState}`}],isError:!0}}}async routeLspRequest(e,t,r){return e.endsWith(".ets")?this.routeArktsRequest(t,r):Un(e)?this.routeCppRequest(t,r):{content:[{type:"text",text:`Unsupported file type: ${e} (only .ets and C/C++ source/header files are supported)`}],isError:!0}}async handleCppIdleCheck(){if(this.ensureCppProjectReady(),this.config.projectPath){let e;return this.cppSyncSkippedDueToLock?(e=`Another build process is running, C++ sync deferred (waiting ${this.cppSyncSkipStartedAt>0?Math.round((Date.now()-this.cppSyncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,this.cppSyncSkippedDueToLock=!1):e="C++ project detected, syncing (compileNative), please retry in 25 seconds",g.info(`C++ idle check: project '${this.config.projectPath}', triggering C++ init`),{content:[{type:"text",text:e}],isError:!0}}return{content:[{type:"text",text:"No HarmonyOS project detected for C++ tools."}],isError:!0}}async handleCppErrorCheck(){return this.cppInitRetryCount>=Rt?(g.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${Rt}), will not auto-retry`),{content:[{type:"text",text:`C++ project initialization failed repeatedly (auto-retry exhausted: ${this.cppInitRetryCount}/${Rt}). Ask the user to investigate and confirm \`hvigor compileNative\` succeeds manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],isError:!0}):(g.info(`C++ error check: auto-retrying (${this.cppInitRetryCount}/${Rt})`),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(`
|
|
1320
|
-
`);o&&(e.isError?t.push(o):r.push(o))}async handleRestartCall(e){let t=e.target,r=t==="cpp"?"cpp":t==="arkts"?"arkts":"all";return 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){g.info(`[restart] resetting tools + state, re-init (target=${e})`),(e==="arkts"||e==="all")&&this.restartArkts(),(e==="cpp"||e==="all")&&this.restartCpp()}restartArkts(){this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(e=>g.warn("Failed to shutdown ArktsCheckTool during restart:",e)),this.arktsCheckTool=null),this.initRetryCount=0,this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.configChangedTriggeredResync=!1,this.initPromise?(this.needsReinit=!0,g.info("[restart] ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(e=>g.warn("Failed to re-init ArkTS project during restart:",e)))}restartCpp(){this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(e=>g.warn("Failed to dispose ClangdLspManager during restart:",e)),this.cppLspManager=null),this.cppInitRetryCount=0,this.cppHasNoCppCode=!1,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitPromise?(this.cppNeedsReinit=!0,g.info("[restart] C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>g.warn("Failed to re-init C++ project during restart:",e)))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{g.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(t=>{g.warn("Failed to dispose ClangdLspManager during setProjectPath:",t)}),this.cppLspManager=null),this.initPromise?(this.needsReinit=!0,g.info("Project path changed while ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{g.warn("Failed to re-init project after setProjectPath:",t)})),this.cppInitPromise?(this.cppNeedsReinit=!0,g.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=>{g.warn("Failed to re-init C++ project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new rT;if(await this.server.connect(e),g.info("devecocli-mcp-server started"),!this.config.debug){let t=Ap();t&&g.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=Nt(t);r?(g.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):g.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?g.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):g.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{g.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return g.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return g.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){g.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,g.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{g.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{g.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{g.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?Nt(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=Nt(this.originalProjectPath),t&&g.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&await this.ensureProjectSynced()){this.ensureCppProjectReady().catch(e=>{g.warn("Background C++ project init failed:",e)}),this.projectState=3,this.arktsCheckTool=new zr(this.config.projectPath,this.config.toolProvider,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{g.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,g.info("Project fully initialized, check tool is available")}catch(e){g.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=Sg(e),r=!t.required;return g.info(`Sync check: skipHvigor=${r}, reason=${t.reason}`),this.runSync(e,{skipHvigorSync:r})}async runSync(e,t){this.projectState=2,g.info("Starting project sync...");let r=await qr.handleSyncProject(e,this.config.toolProvider,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>=Id?(g.error(`Sync skipped for ${i}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(g.warn(`Sync skipped: ${r.reason}, resetting to IDLE for retry (elapsed ${i}s / ${Id/1e3}s)`),this.projectState=0,!1)}case"failed":return g.error(`Project sync failed: ${r.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return g.error(`Project sync: unknown status ${r.status}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}async ensureCppProjectReady(){if(!this.cppInitPromise){this.cppInitPromise=this.doEnsureCppProjectReady();try{await this.cppInitPromise}finally{this.cppInitPromise=null}this.cppNeedsReinit&&(this.cppNeedsReinit=!1,this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>{g.warn("Failed to re-init C++ project after cppNeedsReinit:",e)}))}}async doEnsureCppProjectReady(){let e=this.config.projectPath;if(!e){g.info("[Cpp] No project path, skipping C++ init");return}this.cppProjectState=1;let t=qn(e);if(t.length===0){g.info('[Cpp] No C++ modules found, C++ tools will return "no C++ code"'),this.cppHasNoCppCode=!0,this.cppProjectState=4,this.cppInitRetryCount=0;return}if(this.cppHasNoCppCode=!1,g.info(`[Cpp] Found ${t.length} C++ module(s): ${t.map(r=>r.name).join(", ")}`),!!await this.runSyncCpp(e)){this.cppProjectState=3,this.cppLspManager=new di({workspaceRoot:e,toolProvider:this.config.toolProvider});try{await this.cppLspManager.start(),this.cppCheckTool=new Jr(this.cppLspManager,this.config.toolProvider),this.cppLspTool=new Xr(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,g.info("[Cpp] C++ project fully initialized, C++ tools are available")}catch(r){g.error("[Cpp] C++ LSP initialization failed:",r),this.cppLspManager&&this.cppLspManager.dispose().catch(()=>{}),this.cppLspManager=null,this.cppCheckTool=null,this.cppLspTool=null,this.cppInitRetryCount++,this.cppProjectState=5}}}async runSyncCpp(e){this.cppProjectState=2,g.info("[Cpp] Starting C++ project sync (compileNative)...");let t=await di.handleSyncCppProject(e,this.config.toolProvider);switch(t.status){case"success":return this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,!0;case"skipped":{this.cppSyncSkippedDueToLock=!0,this.cppSyncSkipStartedAt===0&&(this.cppSyncSkipStartedAt=Date.now());let r=Date.now()-this.cppSyncSkipStartedAt,o=Math.round(r/1e3);return r>=Id?(g.error(`[Cpp] C++ sync skipped for ${o}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(g.warn(`[Cpp] C++ sync skipped: ${t.reason}, resetting to IDLE_CPP for retry (elapsed ${o}s)`),this.cppProjectState=0,!1)}case"failed":return g.error(`[Cpp] C++ project sync failed: ${t.reason}`),this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitRetryCount++,this.cppProjectState=5,!1}return!1}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppLspManager&&await this.cppLspManager.dispose(),this.cppCheckTool=null,this.cppLspTool=null;try{await this.server.close()}catch(e){g.warn("Failed to close MCP server connection:",e)}g.info("devecocli-mcp-server stopped"),Ip(),Cp()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function oT(n){let e=[],t=[],r=[];for(let o of n)bn.extname(o).toLowerCase()===".ets"?e.push(o):Un(o)?t.push(o):r.push(o);return{etsFiles:e,cppFiles:t,unsupported:r}}function Td(n){return new $a(n)}import*as kd from"fs";import*as En from"path";import{spawn as iT}from"child_process";async function Pg(n){Vn(!1);let{serverPath:e,logPath:t,projectPath:r,serverMaxSize:o}=await cT(n),i=uT(e,t,r,n.toolProvider,o);g.info("ace-server started, bridging stdio (initialize is left to the client)"),mT(i),await aT(i.pid??null,sT("--arkts",n))}function sT(n,e){return[n,...e.projectPath?["--project-path"]:[],...e.autoDetect?["--auto-detect"]:[]]}async function aT(n,e){let t="unknown";if(n!==null){let o=await ko(n);o!==null&&(t=At(Number(o)*1024))}let r={event:T.ServeLsp,args:e,lspMemory:t};await D.track(r)}async function cT(n){b()||n.toolProvider.require({clt:!1});let e;if(n.projectPath)e=ge(En.resolve(n.projectPath)),g.info(`projectPath=specified ('${e}'), no search`);else if(n.autoDetect){let a=Ki(process.cwd());e=ge(a??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${a??"null, fallback to cwd"}`)}else e=ge(process.cwd()),g.info(`projectPath=cwd ('${e}'), no search (pass --auto-detect to search subdirs)`);let t=n.toolProvider.sdkPath,r=n.toolProvider.lspServerPath;r||(g.error("ace-server not found in DevEco Studio installation."),process.exit(1));let o=En.resolve(En.dirname(r),"standardIndex","index.js"),i=En.join(on(),"lsp-server",String(Date.now()));kd.mkdirSync(i,{recursive:!0});let s=lT(e,t);return g.info(`projectPath=${e}, sdkPath=${t}, serverPath=${o}, logPath=${i}, serverMaxSize=${s}MB`),{projectPath:e,serverPath:o,logPath:i,serverMaxSize:s}}function lT(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=dT(n,e),s=Ss(i,o);return g.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${i}, override=${o??"none"})`),s}function dT(n,e){try{let t=[];return new ir(n,e).getAllDependencyMap(t).status==="OK"?t.length:new jt(n).getAllModuleInfo().length}catch{return 0}}function uT(n,e,t,r,o){let i=En.join(e,"lspLog");kd.mkdirSync(i,{recursive:!0});let s=pT(n,i,t,r.sdkPath,o),a=r.nodePath;return g.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),iT(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function pT(n,e,t,r,o){let i=G(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=${G(t)}`,`--sdkPath=${G(r)}`]}function mT(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{g.error(`[ace-server] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{g.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as Cg from"fs";import*as sr from"path";import{spawn as fT}from"child_process";async function Ig(n){Vn(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await hT(n),o=sr.join(t,"compile_commands.json");Cg.existsSync(o)||g.warn(`compile_commands.json not found at ${o}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let i=gT(e,t,r);g.info("clangd started, bridging stdio (initialize is left to the client)"),wT(i)}async function hT(n){let e;if(n.projectPath)e=ge(sr.resolve(n.projectPath)),g.info(`projectPath=specified ('${e}'), no search`);else if(n.autoDetect){let i=Ki(process.cwd());e=ge(i??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${i??"null, fallback to cwd"}`)}else e=ge(sr.resolve(process.cwd())),g.info(`projectPath=cwd ('${e}'), no search (pass --auto-detect to search subdirs)`);let t=n.toolProvider.clangdPath;t||(g.error("clangd not found in DevEco Studio SDK. Expected at <deveco>/sdk/default/openharmony/native/llvm/bin/clangd"),process.exit(1));let r=hr(e),o=sr.dirname(r);return g.info(`projectPath=${e}, clangdPath=${t}, compileCommandsDir=${o}`),{projectPath:e,clangdPath:t,compileCommandsDir:o}}function gT(n,e,t){let r=yT(e);return g.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),fT(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function yT(n){return[`--compile-commands-dir=${G(n)}`,"--log=info","--pch-storage=memory"]}function wT(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{g.error(`[clangd] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{g.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function ST(){let n=process.env.PROJECT_PATH||"",e=process.env.NODE_MAX_OLD_SPACE_SIZE,t=process.env.DEBUG==="true"||process.env.DEBUG==="1",r=await A.new();b()||r.require({clt:!1});let i=Td({toolProvider:r,projectPath:n,nodeMaxOldSpaceSize:e,debug:t}),s=async()=>{await i.shutdown(),process.exit(0)};process.once("SIGINT",s),process.once("SIGTERM",s),process.platform==="win32"&&process.once("SIGBREAK",s);try{await i.start()}catch(a){console.error("Failed to start MCP server:",a),process.exit(1)}}var Rd=new vT("serve").description("Host bundled auxiliary protocol servers");Rd.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await ST()});Rd.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));let e=await A.new();n.arkts?await Pg({toolProvider:e,projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await Ig({toolProvider:e,projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var Ag=Rd;import{Command as Ex,InvalidArgumentError as Su}from"commander";import{red as Px,dim as Cx}from"colorette";import*as He from"fs";import*as po from"path";import cx from"proper-lockfile";import Lw from"ora";import*as vt from"fs";import*as Si from"path";var Pn=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],ar={"harmonyos-guides":"\u5F00\u53D1\u6307\u5357","harmonyos-references":"API\u53C2\u8003","best-practices":"\u6700\u4F73\u5B9E\u8DF5","harmonyos-faqs":"FAQ","harmonyos-releases":"\u7248\u672C\u8BF4\u660E","harmonyos-roadmap":"\u53D8\u66F4\u9884\u544A"};var Qr="1.9.1",MK=48*1024*1024,Dg=280,Tg=6,kg=100,Rg=3,xg=28,xd=10,Ng=/API参考|APIReference/i,ui=200,Lg=12,Og=4,Nd=8,Mg=6,Ha=700,Ld=250,Od=400,_g=1320,Fg=120,jg=450,$g=250,Hg=500,Bg=480,Ug=80,Wg=200,Vg=60,Gg=200,qg=40,zg=200,Yg=200,Jg=40,eo=500,Kg=Object.fromEntries(Pn.map((n,e)=>[ar[n],e])),Cn=Object.fromEntries(Pn.map((n,e)=>[n,e]));import*as pi from"fs";import*as F from"path";import{fileURLToPath as ey}from"url";import*as In from"fs";import*as Xg from"path";import{homedir as bT}from"os";var ET="deveco-cli",Md,cr=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function PT(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&as(n)!==""}function Zg(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":as(n))||Xg.join(bT(),".local","share",ET);try{return cs(t)}catch(r){throw new cr(r instanceof Error?r.message:String(r))}}async function Qg(){let n=Zg();await In.promises.mkdir(n,{recursive:!0});let e;try{e=await In.promises.realpath(n)}catch(r){throw new cr(`DEVECO_CLI_DATA_DIR is not usable: ${r instanceof Error?r.message:String(r)}`)}if(!(await In.promises.stat(e)).isDirectory())throw new cr("DEVECO_CLI_DATA_DIR must be a writable directory.");return Md=e,e}function Ba(n){let e=Xt();return PT()?[`Data directory (DEVECO_CLI_DATA_DIR): ${e}`,"If you changed this in System Environment Variables, open a new terminal and retry.",`Log file: ${n}`]:[`Data directory (default): ${e}`,"To use a custom location, set DEVECO_CLI_DATA_DIR and open a new terminal.",`Log file: ${n}`]}function Xt(){if(Md!==void 0)return Md;let n=Zg();try{if(In.existsSync(n))return In.realpathSync(n)}catch{}return n}var CT="docs";function to(){return F.join(Xt(),CT)}function oe(){return F.join(to(),".index")}function Ua(){return F.join(oe(),"build.lock")}function mi(){return F.join(oe(),"build-status.json")}function no(){return F.join(oe(),"build-meta.json")}function lr(){return F.join(oe(),"search.db")}function fi(){return F.join(oe(),"sqlite-backend.json")}function hi(){return F.join(oe(),"jieba-backend.json")}function Zt(){return F.join(oe(),".tmp")}function IT(){return F.join(Xt(),"logs")}function ro(){return F.join(IT(),"doc-init.log")}function AT(n,e){let t=e;for(;!t.endsWith(`${F.sep}dist`)&&t!==F.dirname(t);)t=F.dirname(t);return t}function ty(n,e){return F.dirname(AT(n,e))}function ny(){let n=ey(import.meta.url),e=F.dirname(n);return n.includes(`${F.sep}dist${F.sep}`)?ty(n,e):F.join(e,"..","..","..")}function DT(...n){let e=ey(import.meta.url),t=F.dirname(e);return e.includes(`${F.sep}dist${F.sep}`)?[F.join(ty(e,t),...n)]:[F.join(t,"..","..","..",...n)]}function ry(...n){let e=ny(),t=pi.realpathSync(e);for(let r of DT(...n))try{let o=pi.lstatSync(r);if(o.isSymbolicLink()||!o.isFile())throw new Error(`Unsafe documentation package asset: ${n.join("/")} must be a regular file.`);let i=pi.realpathSync(r);if(!il(i,t))throw new Error(`Unsafe documentation package asset: ${n.join("/")} is outside the package.`);return i}catch(o){if(o.code!=="ENOENT")throw o}return null}function An(){return ry("docs.zip")}function _d(){return ry("index.zip")}function oy(){return F.join(ny(),"index","data")}import*as Qt from"fs";import*as dr from"path";var en=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Wa=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function iy(n){return n instanceof Wa}var Fd=null;function jd(n){Fd=n}function $d(){if(Fd)return Fd;let n=oe();if(en.every(o=>Qt.existsSync(dr.join(n,o))))return n;let t=oy();if(en.every(o=>Qt.existsSync(dr.join(t,o))))return t;throw new Wa("Lexicon files not found. Install the documentation index first (index.zip).")}function sy(){$d()}function ur(n){let e=dr.join($d(),n);return Qt.readFileSync(e,"utf-8")}function ay(n,e){return Qt.readFileSync(dr.join(e,n),"utf-8")}async function cy(n,e=$d()){await Qt.promises.mkdir(n,{recursive:!0});for(let t of en){let r=dr.join(e,t),o=dr.join(n,t);await Qt.promises.copyFile(r,o)}}import*as Va from"fs";import*as ly from"path";import*as dy from"yauzl";var gi=null;function TT(n){return new Promise((e,t)=>{dy.open(n,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(r,o)=>{if(r||!o){t(r??new Error(`Failed to open zip: ${n}`));return}e(o)})})}function kT(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function RT(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",o=>{let i=kT(o);i.endsWith("/")||e.set(i,o),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function xT(){gi?.zipfile.close(),gi=null}async function NT(n){let e=ly.resolve(n),t=await Va.promises.stat(e),r=gi;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;xT();let o=await TT(e),i=await RT(o);return gi={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:o,entries:i,readChain:Promise.resolve()},gi}function LT(n,e){return new Promise((t,r)=>{n.openReadStream(e,(o,i)=>{if(o||!i){r(o??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];i.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),i.on("end",()=>{t(Buffer.concat(s))}),i.on("error",r)})})}async function OT(n,e){let t=n.readChain,r;n.readChain=new Promise(o=>{r=o}),await t;try{return await LT(n.zipfile,e)}finally{r()}}function MT(n){let e=n.replace(/\\/g,"/").replace(/\.md$/,"");if(e.split("/").includes(".."))throw new Error("Invalid document ID: path traversal is not allowed.");return[`docs/${e}.md`,`${e}.md`,`docs/${e}`,e]}function _T(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function uy(n){let e=An();if(!e)throw new Error("docs.zip not found");let t=await NT(e),r=_T(t.entries,MT(n));if(!r)throw new Error(`Document not found: ${n}`);return(await OT(t,r)).toString("utf-8")}function Hd(){let n=An();return n!==null&&Va.existsSync(n)}import*as be from"fs";import*as tn from"path";import py from"adm-zip";import*as yi from"fs";import*as qa from"path";var Ga=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function wi(n){return n instanceof cr||n instanceof Ga||n instanceof Error&&(n.name==="CliDataDirError"||n.name==="DocPathSafetyError")}function Wd(n){return new Ga(n)}function FT(){return Ct(Xt())}function Ud(n,e,t){let r=ss(n,e);if(r===null)throw Wd(`${t} resolves outside the data directory.`);return r}async function Bd(n,e){await yi.promises.mkdir(n,{recursive:!0});let t=Ud(n,e,"directory");if(!(await yi.promises.stat(t)).isDirectory())throw Wd("path must be a directory.")}function vi(n){let e=FT();try{let t=Ud(n,e,"file");if(!yi.statSync(t).isFile())throw Wd("path must be a regular file.")}catch(t){if(t.code==="ENOENT"){Ud(qa.dirname(n),e,"file parent");return}throw t}}async function oo(n={}){let e=n.mode??"write",t=await Qg();await Bd(to(),t),await Bd(oe(),t),e==="write"&&await Bd(Zt(),t);for(let r of[lr(),no(),mi(),Ua(),hi(),fi(),...en.map(o=>qa.join(oe(),o))])vi(r)}var Vd=["search.db","build-meta.json",...en],jT=["corpus.json","corpus-offsets.json","orama.dpack"];async function $T(n){for(let e of jT)await be.promises.rm(tn.join(n,e),{force:!0})}async function HT(n){let e=await be.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await be.promises.rm(tn.join(n,t.name),{recursive:!0,force:!0})}function my(n){let t=new py(n).getEntry("build-meta.json");if(!t)throw new Error("index.zip is missing build-meta.json");return JSON.parse(t.getData().toString("utf-8"))}async function BT(n){let e=oe();await be.promises.mkdir(e,{recursive:!0});for(let t of Vd){let r=tn.join(e,t);await be.promises.rm(r,{force:!0}),await be.promises.rename(tn.join(n,t),r)}await $T(e),await be.promises.rm(Zt(),{recursive:!0,force:!0})}function fy(n){let e=_d();if(!e)return!1;try{let t=my(e);return t.indexVersion===Qr&&t.docsZipSha256===n&&t.segmentCount>0}catch{return!1}}async function hy(n){await oo({mode:"write"});let e=_d();if(!e)throw new Error("index.zip not found");let t=my(e);if(t.docsZipSha256!==n)throw new Error("Bundled index.zip does not match docs.zip. Rebuild index.zip with npm run build:index.");if(t.segmentCount<=0)throw new Error("Bundled index.zip is empty");let r=Zt();await be.promises.rm(r,{recursive:!0,force:!0}),await be.promises.mkdir(r,{recursive:!0});let o=new py(e);for(let s of Vd){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await be.promises.writeFile(tn.join(r,s),a.getData())}let i=JSON.parse(await be.promises.readFile(tn.join(r,"build-meta.json"),"utf-8"));if(!be.existsSync(tn.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await BT(r),await be.promises.mkdir(to(),{recursive:!0}),await HT(to()),i}async function gy(){await be.promises.rm(Zt(),{recursive:!0,force:!0});let n=oe();for(let e of Vd)await be.promises.rm(tn.join(n,e),{force:!0})}import{createHash as yy}from"crypto";import*as wy from"fs";async function za(n){return new Promise((e,t)=>{let r=yy("sha256"),o=wy.createReadStream(n);o.on("data",i=>r.update(i)),o.on("error",t),o.on("end",()=>e(r.digest("hex")))})}function vy(n){return yy("sha256").update(n,"utf8").digest("hex")}var Gd=null;function UT(){let n=ur("harmonyos-synonyms.json");return JSON.parse(n)}function WT(n){let e=new Map;for(let t of n){let r=t.map(o=>o.trim()).filter(Boolean);for(let o of r){let i=r.filter(s=>s!==o);e.set(o.toLowerCase(),i),o!==o.toLowerCase()&&e.set(o,i)}}return e}function VT(){let n=WT(UT()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function GT(){return Gd||(Gd=VT()),Gd}function qd(n,e){let t=GT(),r=n.split(/\s+/).filter(Boolean),o=new Set,i=Number.isFinite(e)?e:r.length;for(let s=0;s<r.length&&o.size<i;s+=1){let a=r[s];o.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(o.size>=i)break;o.add(l)}}return[...o].join(" ")}function Sy(n,e){let t=e?ay(n,e):ur(n);return vy(t)}function Ya(n){return Sy("harmonyos-synonyms.json",n)}function Ja(n){return Sy("harmonyos-terms.txt",n)}var qT={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function Ka(){try{let n=await vt.promises.readFile(mi(),"utf-8");return JSON.parse(n)}catch{return{...qT}}}async function zd(n){let e=mi();await vt.promises.mkdir(Si.dirname(e),{recursive:!0}),await vt.promises.writeFile(e,JSON.stringify(n,null,2))}function by(n){let e=Date.now();return{state:"extracting",phase:1,phaseLabel:"Extracting documentation",current:0,total:0,message:n,startedAt:e,updatedAt:e,error:null}}async function Dn(n){let t={...await Ka(),...n,updatedAt:Date.now()};return await zd(t),t}async function Yd(){let n=An();return n?za(n):null}async function Jd(){try{let n=await vt.promises.readFile(no(),"utf-8");return JSON.parse(n)}catch{return null}}async function Xa(n=!1){if(n)return"no-index";let e=await Jd();if(!e||e.segmentCount===0)return"no-index";let t=await Yd();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==Qr?"engine-upgraded":e.termsHash!==Ja()?"terms-changed":e.synonymsHash!==Ya()?"synonyms-changed":null}function bi(){if(!Hd()||!vt.existsSync(lr())||!vt.existsSync(no()))return!1;let n=Si.dirname(lr());if(!en.every(e=>vt.existsSync(Si.join(n,e))))return!1;try{let e=vt.readFileSync(no(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function Kd(n=!1){return n?!0:Hd()?bi()?await Xa()!==null:!0:!1}async function Ey(){let n=await Ka();return["installing","indexing","persisting"].includes(n.state)}import*as uo from"fs";import*as Rn from"path";import JR from"adm-zip";var Py=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),Xd=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),Cy=new Set(["a","an","and","api","app","application","arkts","arkui","for","get","harmonyos","how","in","oh","ohos","on","or","set","the","to","use","using","what","when","where","which","with","without","data","file","main","model","name","network","stage","system","type","user"]),Iy=new Set(["ability","extension","module","service","context","options","config","info","event","code","state","type","data","request","response","client","server","handler","helper","utils","factory","builder","listener","callback","observer","provider","consumer","delegate","adapter","driver","buffer","stream","channel","session","task","worker","controller","component","container","attribute","descriptor","modifier","validator","parser","formatter","encoder","decoder","filter","converter","generator","iterator","dispatcher","resolver","scanner","tracker","monitor","scheduler","renderer","loader","subscriber","proxy","button","surface","stack","heap","map","set","array","list"]);var zT=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,YT=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,JT=/[A-Z][a-zA-Z0-9]{2,}/g,KT=/@[A-Z][a-zA-Z0-9]*/g,XT=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,Ay=6,ZT=/^[a-z][a-z0-9]{2,}$/,QT=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,ek=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,tk=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,nk=/^[A-Z][a-zA-Z0-9]+$/;function rk(n){return`"${n.replace(/"/g,'""')}"`}function Pi(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(rk).join(` ${e} `)}function Ei(n){return Pi(n,"OR")}function Dy(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?Ei([...t,...r]):`(${Ei(t)}) AND (${Ei(r)})`}function Ci(n){return ek.test(n)}function Ty(n){return tk.test(n)&&n.length>=Ay}function ok(n){return nk.test(n)}function Ii(n){return Ci(n)||Ty(n)||ok(n)}function ik(n){let e=n.trim().toLowerCase();return Iy.has(e)?!1:Py.has(e)}function sk(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function Za(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function Zd(n){return[...n.matchAll(zT)].map(e=>e[0])}function Qd(n,e=Ay){let t=[];for(let r of n.matchAll(YT))r[0].length>=e&&t.push(r[0]);return t}function io(n){return n.filter(e=>{let t=e.toLowerCase();return!n.some(r=>{if(r===e)return!1;let o=r.toLowerCase();return o.length>t.length&&o.endsWith(t)&&t.length>=4})})}function St(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function ak(n){let e=new Set;St(e,n);let t=Za(n);return t&&St(e,t),io([...e])}function Qa(n){if(Ci(n))return ak(n);let e=new Set;return St(e,n),io([...e])}function ec(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(QT);if(!t)return null;let r=t[1].toLowerCase(),o=t[2].toLowerCase();if(!ZT.test(r)||Cy.has(r)||!ik(o))return null;let i=sk(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function eu(n){let e=ec(n.trim());return!e||e.second!=="manager"?null:e}function ck(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function ky(n){let e=n.trim(),t=eu(e);if(t&&Xd.has(t.first))return!0;if(Ty(e)){let r=ck(e);return r!==null&&Xd.has(r)}return!1}function tu(n,e,t){let r=t.toLowerCase(),o=new RegExp(`@ohos\\.[^\\s(]*${t}`,"i");for(let i of[n,e])if(i&&(i.toLowerCase().includes(r)||o.test(i)))return!0;return!1}function nu(n){let e=n.trim();if(Ii(e))return Qa(e);let t=new Set;for(let r of Zd(n)){St(t,r);let o=Za(r);o&&St(t,o)}for(let r of Qd(n))St(t,r);for(let r of n.matchAll(KT))t.add(r[0]);for(let r of n.matchAll(XT))t.add(r[0]);for(let r of n.matchAll(JT))r[0].length>=4&&t.add(r[0]);return io([...t])}function Ry(n){let e=n.trim();if(Ii(e))return Qa(e);let t=new Set,r=ec(e);r&&St(t,r.camelCase);for(let o of nu(e))t.add(o);for(let o of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let i=o[0];i!==i.toLowerCase()&&t.add(i)}return io([...t])}function xy(n){return Ii(n)}var te={pureApiSymbol:/^[A-Z][a-zA-Z0-9]+$/,stageModelExact:/^Stage\s*模型$/i,stageModelEnglishExact:/^stage\s+model$/i,stageModel:/Stage\s*模型/i,stageModelEntryPage:/Stage\s*模型.*EntryAbility.*(页面|新页面)/,declarePermissionBoost:/声明.*权限|应用权限.*声明|如何声明应用权限/,declarePermissionCatalog:/如何声明应用权限/,declarePermissionTokens:/如何声明应用权限|声明应用权限/,uiAbilityLifecycleBoost:/UIAbility.*生命周期|生命周期.*UIAbility|UIAblity/i,uiAbilityLifecycleCatalog:/UIAblity.*生命周期|UIAbility.*生命周期/i,entryAbilityPage:/EntryAbility.*(页面|启动|跳转|新页面)/,stateDecoratorBoost:/@State|@Prop|@Link|@Provide|@Consume/,stateDecoratorCatalog:/@State\s*装饰器|@Prop\s*装饰器|@Link\s*装饰器/,stateManagement:/状态管理原理/,routerRoute:/Router\s+路由/,dialogPopupExact:/^Dialog\s+弹窗$/,dialogPopupBoost:/Dialog\s+弹窗/};function Ny(n){return te.pureApiSymbol.test(n.trim())}function Ai(n){let e=n.trim();return te.stageModelExact.test(e)||te.stageModelEnglishExact.test(e)}function Ly(n){let e=[];return Ai(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),te.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),te.stageModelEntryPage.test(n)&&e.push("\u9875\u9762\u8DEF\u7531","pushUrl"),/UIAblity|UIAbility/.test(n)&&/生命周期/.test(n)&&e.push("UIAbility\u7EC4\u4EF6\u751F\u547D\u5468\u671F"),e}function Oy(n){return Ai(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var lk=[{matches:n=>te.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>Ai(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!Ai(n)&&te.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>te.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>te.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>te.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>te.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>te.routerRoute.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:1.4},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]},{matches:n=>te.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function dk(n,e){for(let{catalog:t,multiplier:r}of e){let o=Cn[t];n.set(o,(n.get(o)??1)*r)}}function My(n,e){for(let t of lk)t.matches(n)&&dk(e,t.weights)}function _y(n,e){if(e!==void 0)return!1;let t=n.trim();return Ci(t)||te.pureApiSymbol.test(t)||ky(t)}function Fy(n){let e=n.trim();if(Ci(e)||te.pureApiSymbol.test(e))return"harmonyos-references";if(Ai(e)||te.uiAbilityLifecycleCatalog.test(e)||te.stateDecoratorCatalog.test(e)||te.stateManagement.test(e)||te.declarePermissionCatalog.test(e)||te.stageModelEntryPage.test(e)||te.routerRoute.test(e)||te.dialogPopupExact.test(e))return"harmonyos-guides"}import*as so from"fs";import*as $y from"path";var tc=null,ru=null,ou=null;function uk(){return so.existsSync(hi())}function pk(n){let e=hi(),t={backend:"jieba-wasm",reason:"native-jieba-load-failed",message:n,createdAt:new Date().toISOString()};so.mkdirSync($y.dirname(e),{recursive:!0}),vi(e),so.writeFileSync(e,JSON.stringify(t,null,2))}function mk(){if(tc)return tc;let n=ur("harmonyos-stopwords.txt");return tc=new Set(n.split(`
|
|
1321
|
-
`).map(e=>e.trim()).filter(Boolean)),
|
|
1319
|
+
`).trim()||"No diagnostics collected"}],isError:c}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return g.warn(`ArkTS check rejected: project is ${Rd[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return g.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 g.error(`ArkTS check: unknown project state ${this.projectState}, files: ${e.join(", ")}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],isError:!0}}}async handleLspFeatureCall(e,t){let r=t.file,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 g.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){g.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(r)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),i,o)}catch(a){g.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}/${Rt})`;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}/${Rt})`;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 g.warn(`ArkTS ${e} rejected: project is ${Rd[this.projectState]}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return g.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 g.error(`ArkTS ${e}: unknown project state ${this.projectState}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],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"),g.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(g.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(g.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=Rt?(g.error(`Init retry limit reached (${this.initRetryCount}/${Rt}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${Rt}). Ask the user to investigate and confirm \`ohpm install\` + \`hvigor\` sync succeed manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],isError:!0}):(g.info(`Error check: auto-retrying (${this.initRetryCount}/${Rt})`),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 g.warn(`C++ ${e} rejected: C++ project is ${Tg[this.cppProjectState]}`),{content:[{type:"text",text:"C++ project is syncing (compileNative), please retry in 25 seconds"}],isError:!0};case 3:return g.warn(`C++ ${e} rejected: clangd is initializing`),{content:[{type:"text",text:"C++ LSP (clangd) is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleCppErrorCheck();case 4:return this.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};default:return g.error(`C++ ${e}: unknown C++ project state ${this.cppProjectState}`),{content:[{type:"text",text:`Unknown C++ project state: ${this.cppProjectState}`}],isError:!0}}}async routeLspRequest(e,t,r){return e.endsWith(".ets")?this.routeArktsRequest(t,r):Un(e)?this.routeCppRequest(t,r):{content:[{type:"text",text:`Unsupported file type: ${e} (only .ets and C/C++ source/header files are supported)`}],isError:!0}}async handleCppIdleCheck(){if(this.ensureCppProjectReady(),this.config.projectPath){let e;return this.cppSyncSkippedDueToLock?(e=`Another build process is running, C++ sync deferred (waiting ${this.cppSyncSkipStartedAt>0?Math.round((Date.now()-this.cppSyncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,this.cppSyncSkippedDueToLock=!1):e="C++ project detected, syncing (compileNative), please retry in 25 seconds",g.info(`C++ idle check: project '${this.config.projectPath}', triggering C++ init`),{content:[{type:"text",text:e}],isError:!0}}return{content:[{type:"text",text:"No HarmonyOS project detected for C++ tools."}],isError:!0}}async handleCppErrorCheck(){return this.cppInitRetryCount>=Rt?(g.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${Rt}), will not auto-retry`),{content:[{type:"text",text:`C++ project initialization failed repeatedly (auto-retry exhausted: ${this.cppInitRetryCount}/${Rt}). Ask the user to investigate and confirm \`hvigor compileNative\` succeeds manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],isError:!0}):(g.info(`C++ error check: auto-retrying (${this.cppInitRetryCount}/${Rt})`),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(`
|
|
1320
|
+
`);o&&(e.isError?t.push(o):r.push(o))}async handleRestartCall(e){let t=e.target,r=t==="cpp"?"cpp":t==="arkts"?"arkts":"all";return 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){g.info(`[restart] resetting tools + state, re-init (target=${e})`),(e==="arkts"||e==="all")&&this.restartArkts(),(e==="cpp"||e==="all")&&this.restartCpp()}restartArkts(){this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(e=>g.warn("Failed to shutdown ArktsCheckTool during restart:",e)),this.arktsCheckTool=null),this.initRetryCount=0,this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.configChangedTriggeredResync=!1,this.initPromise?(this.needsReinit=!0,g.info("[restart] ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(e=>g.warn("Failed to re-init ArkTS project during restart:",e)))}restartCpp(){this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(e=>g.warn("Failed to dispose ClangdLspManager during restart:",e)),this.cppLspManager=null),this.cppInitRetryCount=0,this.cppHasNoCppCode=!1,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitPromise?(this.cppNeedsReinit=!0,g.info("[restart] C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>g.warn("Failed to re-init C++ project during restart:",e)))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{g.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(t=>{g.warn("Failed to dispose ClangdLspManager during setProjectPath:",t)}),this.cppLspManager=null),this.initPromise?(this.needsReinit=!0,g.info("Project path changed while ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{g.warn("Failed to re-init project after setProjectPath:",t)})),this.cppInitPromise?(this.cppNeedsReinit=!0,g.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=>{g.warn("Failed to re-init C++ project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new iT;if(await this.server.connect(e),g.info("devecocli-mcp-server started"),!this.config.debug){let t=Np();t&&g.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=xt(t);r?(g.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):g.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?g.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):g.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{g.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return g.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return g.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){g.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,g.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{g.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{g.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{g.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?xt(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=xt(this.originalProjectPath),t&&g.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&await this.ensureProjectSynced()){this.ensureCppProjectReady().catch(e=>{g.warn("Background C++ project init failed:",e)}),this.projectState=3,this.arktsCheckTool=new Yr(this.config.projectPath,this.config.toolProvider,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{g.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,g.info("Project fully initialized, check tool is available")}catch(e){g.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=Ag(e),r=!t.required;return g.info(`Sync check: skipHvigor=${r}, reason=${t.reason}`),this.runSync(e,{skipHvigorSync:r})}async runSync(e,t){this.projectState=2,g.info("Starting project sync...");let r=await qr.handleSyncProject(e,this.config.toolProvider,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>=Dd?(g.error(`Sync skipped for ${i}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(g.warn(`Sync skipped: ${r.reason}, resetting to IDLE for retry (elapsed ${i}s / ${Dd/1e3}s)`),this.projectState=0,!1)}case"failed":return g.error(`Project sync failed: ${r.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return g.error(`Project sync: unknown status ${r.status}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}async ensureCppProjectReady(){if(!this.cppInitPromise){this.cppInitPromise=this.doEnsureCppProjectReady();try{await this.cppInitPromise}finally{this.cppInitPromise=null}this.cppNeedsReinit&&(this.cppNeedsReinit=!1,this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>{g.warn("Failed to re-init C++ project after cppNeedsReinit:",e)}))}}async doEnsureCppProjectReady(){let e=this.config.projectPath;if(!e){g.info("[Cpp] No project path, skipping C++ init");return}this.cppProjectState=1;let t=Gn(e);if(t.length===0){g.info('[Cpp] No C++ modules found, C++ tools will return "no C++ code"'),this.cppHasNoCppCode=!0,this.cppProjectState=4,this.cppInitRetryCount=0;return}if(this.cppHasNoCppCode=!1,g.info(`[Cpp] Found ${t.length} C++ module(s): ${t.map(r=>r.name).join(", ")}`),!!await this.runSyncCpp(e)){this.cppProjectState=3,this.cppLspManager=new ui({workspaceRoot:e,toolProvider:this.config.toolProvider});try{await this.cppLspManager.start(),this.cppCheckTool=new Kr(this.cppLspManager,this.config.toolProvider),this.cppLspTool=new Zr(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,g.info("[Cpp] C++ project fully initialized, C++ tools are available")}catch(r){g.error("[Cpp] C++ LSP initialization failed:",r),this.cppLspManager&&this.cppLspManager.dispose().catch(()=>{}),this.cppLspManager=null,this.cppCheckTool=null,this.cppLspTool=null,this.cppInitRetryCount++,this.cppProjectState=5}}}async runSyncCpp(e){this.cppProjectState=2,g.info("[Cpp] Starting C++ project sync (compileNative)...");let t=await ui.handleSyncCppProject(e,this.config.toolProvider);switch(t.status){case"success":return this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,!0;case"skipped":{this.cppSyncSkippedDueToLock=!0,this.cppSyncSkipStartedAt===0&&(this.cppSyncSkipStartedAt=Date.now());let r=Date.now()-this.cppSyncSkipStartedAt,o=Math.round(r/1e3);return r>=Dd?(g.error(`[Cpp] C++ sync skipped for ${o}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(g.warn(`[Cpp] C++ sync skipped: ${t.reason}, resetting to IDLE_CPP for retry (elapsed ${o}s)`),this.cppProjectState=0,!1)}case"failed":return g.error(`[Cpp] C++ project sync failed: ${t.reason}`),this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitRetryCount++,this.cppProjectState=5,!1}return!1}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppLspManager&&await this.cppLspManager.dispose(),this.cppCheckTool=null,this.cppLspTool=null;try{await this.server.close()}catch(e){g.warn("Failed to close MCP server connection:",e)}g.info("devecocli-mcp-server stopped"),xp(),kp()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function sT(n){let e=[],t=[],r=[];for(let o of n)Sn.extname(o).toLowerCase()===".ets"?e.push(o):Un(o)?t.push(o):r.push(o);return{etsFiles:e,cppFiles:t,unsupported:r}}function kd(n){return new Ua(n)}import*as xd from"fs";import*as bn from"path";import{spawn as aT}from"child_process";async function Rg(n){Wn(!1);let{serverPath:e,logPath:t,projectPath:r,serverMaxSize:o}=await dT(n),i=mT(e,t,r,n.toolProvider,o);g.info("ace-server started, bridging stdio (initialize is left to the client)"),hT(i),await lT(i.pid??null,cT("--arkts",n))}function cT(n,e){return[n,...e.projectPath?["--project-path"]:[],...e.autoDetect?["--auto-detect"]:[]]}async function lT(n,e){let t="unknown";if(n!==null){let o=await ko(n);o!==null&&(t=It(Number(o)*1024))}let r={event:A.ServeLsp,args:e,lspMemory:t};await I.track(r)}async function dT(n){b()||n.toolProvider.require({clt:!1});let e;if(n.projectPath)e=he(bn.resolve(n.projectPath)),g.info(`projectPath=specified ('${e}'), no search`);else if(n.autoDetect){let a=Zi(process.cwd());e=he(a??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${a??"null, fallback to cwd"}`)}else e=he(process.cwd()),g.info(`projectPath=cwd ('${e}'), no search (pass --auto-detect to search subdirs)`);let t=n.toolProvider.sdkPath,r=n.toolProvider.lspServerPath;r||(g.error("ace-server not found in DevEco Studio installation."),process.exit(1));let o=bn.resolve(bn.dirname(r),"standardIndex","index.js"),i=bn.join(rn(),"lsp-server",String(Date.now()));xd.mkdirSync(i,{recursive:!0});let s=uT(e,t);return g.info(`projectPath=${e}, sdkPath=${t}, serverPath=${o}, logPath=${i}, serverMaxSize=${s}MB`),{projectPath:e,serverPath:o,logPath:i,serverMaxSize:s}}function uT(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=pT(n,e),s=Es(i,o);return g.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${i}, override=${o??"none"})`),s}function pT(n,e){try{let t=[];return new or(n,e).getAllDependencyMap(t).status==="OK"?t.length:new Ft(n).getAllModuleInfo().length}catch{return 0}}function mT(n,e,t,r,o){let i=bn.join(e,"lspLog");xd.mkdirSync(i,{recursive:!0});let s=fT(n,i,t,r.sdkPath,o),a=r.nodePath;return g.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),aT(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function fT(n,e,t,r,o){let i=V(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=${V(t)}`,`--sdkPath=${V(r)}`]}function hT(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{g.error(`[ace-server] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{g.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as kg from"fs";import*as ir from"path";import{spawn as gT}from"child_process";async function xg(n){Wn(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await yT(n),o=ir.join(t,"compile_commands.json");kg.existsSync(o)||g.warn(`compile_commands.json not found at ${o}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let i=wT(e,t,r);g.info("clangd started, bridging stdio (initialize is left to the client)"),ST(i)}async function yT(n){let e;if(n.projectPath)e=he(ir.resolve(n.projectPath)),g.info(`projectPath=specified ('${e}'), no search`);else if(n.autoDetect){let i=Zi(process.cwd());e=he(i??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${i??"null, fallback to cwd"}`)}else e=he(ir.resolve(process.cwd())),g.info(`projectPath=cwd ('${e}'), no search (pass --auto-detect to search subdirs)`);let t=n.toolProvider.clangdPath;t||(g.error("clangd not found in DevEco Studio SDK. Expected at <deveco>/sdk/default/openharmony/native/llvm/bin/clangd"),process.exit(1));let r=gr(e),o=ir.dirname(r);return g.info(`projectPath=${e}, clangdPath=${t}, compileCommandsDir=${o}`),{projectPath:e,clangdPath:t,compileCommandsDir:o}}function wT(n,e,t){let r=vT(e);return g.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),gT(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function vT(n){return[`--compile-commands-dir=${V(n)}`,"--log=info","--pch-storage=memory"]}function ST(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{g.error(`[clangd] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{g.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function ET(){let n=process.env.PROJECT_PATH||"",e=process.env.NODE_MAX_OLD_SPACE_SIZE,t=process.env.DEBUG==="true"||process.env.DEBUG==="1",r=await D.new();b()||r.require({clt:!1});let i=kd({toolProvider:r,projectPath:n,nodeMaxOldSpaceSize:e,debug:t}),s=async()=>{await i.shutdown(),process.exit(0)};process.once("SIGINT",s),process.once("SIGTERM",s),process.platform==="win32"&&process.once("SIGBREAK",s);try{await i.start()}catch(a){console.error("Failed to start MCP server:",a),process.exit(1)}}var Nd=new bT("serve").description("Host bundled auxiliary protocol servers");Nd.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await ET()});Nd.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));let e=await D.new();n.arkts?await Rg({toolProvider:e,projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await xg({toolProvider:e,projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var Ng=Nd;import{Command as Cx,InvalidArgumentError as Eu}from"commander";import{red as Ix,dim as Ax}from"colorette";import*as $e from"fs";import*as mo from"path";import dx from"proper-lockfile";import $w from"ora";import*as wt from"fs";import*as bi from"path";var En=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],sr={"harmonyos-guides":"\u5F00\u53D1\u6307\u5357","harmonyos-references":"API\u53C2\u8003","best-practices":"\u6700\u4F73\u5B9E\u8DF5","harmonyos-faqs":"FAQ","harmonyos-releases":"\u7248\u672C\u8BF4\u660E","harmonyos-roadmap":"\u53D8\u66F4\u9884\u544A"};var eo="1.9.1",AK=48*1024*1024,Og=280,Lg=6,Mg=100,_g=3,Fg=28,Od=10,jg=/API参考|APIReference/i,pi=200,$g=12,Hg=4,Ld=8,Ug=6,Ba=700,Md=250,_d=400,Bg=1320,Wg=120,Vg=450,Gg=250,zg=500,qg=480,Yg=80,Jg=200,Kg=60,Xg=200,Zg=40,Qg=200,ey=200,ty=40,to=500,ny=Object.fromEntries(En.map((n,e)=>[sr[n],e])),Pn=Object.fromEntries(En.map((n,e)=>[n,e]));import*as mi from"fs";import*as F from"path";import{fileURLToPath as sy}from"url";import*as Cn from"fs";import*as ry from"path";import{homedir as PT}from"os";var CT="deveco-cli",Fd,ar=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function IT(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&ls(n)!==""}function oy(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":ls(n))||ry.join(PT(),".local","share",CT);try{return ds(t)}catch(r){throw new ar(r instanceof Error?r.message:String(r))}}async function iy(){let n=oy();await Cn.promises.mkdir(n,{recursive:!0});let e;try{e=await Cn.promises.realpath(n)}catch(r){throw new ar(`DEVECO_CLI_DATA_DIR is not usable: ${r instanceof Error?r.message:String(r)}`)}if(!(await Cn.promises.stat(e)).isDirectory())throw new ar("DEVECO_CLI_DATA_DIR must be a writable directory.");return Fd=e,e}function Wa(n){let e=Kt();return IT()?[`Data directory (DEVECO_CLI_DATA_DIR): ${e}`,"If you changed this in System Environment Variables, open a new terminal and retry.",`Log file: ${n}`]:[`Data directory (default): ${e}`,"To use a custom location, set DEVECO_CLI_DATA_DIR and open a new terminal.",`Log file: ${n}`]}function Kt(){if(Fd!==void 0)return Fd;let n=oy();try{if(Cn.existsSync(n))return Cn.realpathSync(n)}catch{}return n}var AT="docs";function no(){return F.join(Kt(),AT)}function oe(){return F.join(no(),".index")}function Va(){return F.join(oe(),"build.lock")}function fi(){return F.join(oe(),"build-status.json")}function ro(){return F.join(oe(),"build-meta.json")}function cr(){return F.join(oe(),"search.db")}function hi(){return F.join(oe(),"sqlite-backend.json")}function gi(){return F.join(oe(),"jieba-backend.json")}function Xt(){return F.join(oe(),".tmp")}function DT(){return F.join(Kt(),"logs")}function oo(){return F.join(DT(),"doc-init.log")}function TT(n,e){let t=e;for(;!t.endsWith(`${F.sep}dist`)&&t!==F.dirname(t);)t=F.dirname(t);return t}function ay(n,e){return F.dirname(TT(n,e))}function cy(){let n=sy(import.meta.url),e=F.dirname(n);return n.includes(`${F.sep}dist${F.sep}`)?ay(n,e):F.join(e,"..","..","..")}function RT(...n){let e=sy(import.meta.url),t=F.dirname(e);return e.includes(`${F.sep}dist${F.sep}`)?[F.join(ay(e,t),...n)]:[F.join(t,"..","..","..",...n)]}function ly(...n){let e=cy(),t=mi.realpathSync(e);for(let r of RT(...n))try{let o=mi.lstatSync(r);if(o.isSymbolicLink()||!o.isFile())throw new Error(`Unsafe documentation package asset: ${n.join("/")} must be a regular file.`);let i=mi.realpathSync(r);if(!al(i,t))throw new Error(`Unsafe documentation package asset: ${n.join("/")} is outside the package.`);return i}catch(o){if(o.code!=="ENOENT")throw o}return null}function In(){return ly("docs.zip")}function jd(){return ly("index.zip")}function dy(){return F.join(cy(),"index","data")}import*as Zt from"fs";import*as lr from"path";var Qt=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Ga=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function uy(n){return n instanceof Ga}var $d=null;function Hd(n){$d=n}function Ud(){if($d)return $d;let n=oe();if(Qt.every(o=>Zt.existsSync(lr.join(n,o))))return n;let t=dy();if(Qt.every(o=>Zt.existsSync(lr.join(t,o))))return t;throw new Ga("Lexicon files not found. Install the documentation index first (index.zip).")}function py(){Ud()}function dr(n){let e=lr.join(Ud(),n);return Zt.readFileSync(e,"utf-8")}function my(n,e){return Zt.readFileSync(lr.join(e,n),"utf-8")}async function fy(n,e=Ud()){await Zt.promises.mkdir(n,{recursive:!0});for(let t of Qt){let r=lr.join(e,t),o=lr.join(n,t);await Zt.promises.copyFile(r,o)}}import*as za from"fs";import*as hy from"path";import*as gy from"yauzl";var yi=null;function kT(n){return new Promise((e,t)=>{gy.open(n,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(r,o)=>{if(r||!o){t(r??new Error(`Failed to open zip: ${n}`));return}e(o)})})}function xT(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function NT(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",o=>{let i=xT(o);i.endsWith("/")||e.set(i,o),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function OT(){yi?.zipfile.close(),yi=null}async function LT(n){let e=hy.resolve(n),t=await za.promises.stat(e),r=yi;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;OT();let o=await kT(e),i=await NT(o);return yi={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:o,entries:i,readChain:Promise.resolve()},yi}function MT(n,e){return new Promise((t,r)=>{n.openReadStream(e,(o,i)=>{if(o||!i){r(o??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];i.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),i.on("end",()=>{t(Buffer.concat(s))}),i.on("error",r)})})}async function _T(n,e){let t=n.readChain,r;n.readChain=new Promise(o=>{r=o}),await t;try{return await MT(n.zipfile,e)}finally{r()}}function FT(n){let e=n.replace(/\\/g,"/").replace(/\.md$/,"");if(e.split("/").includes(".."))throw new Error("Invalid document ID: path traversal is not allowed.");return[`docs/${e}.md`,`${e}.md`,`docs/${e}`,e]}function jT(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function yy(n){let e=In();if(!e)throw new Error("docs.zip not found");let t=await LT(e),r=jT(t.entries,FT(n));if(!r)throw new Error(`Document not found: ${n}`);return(await _T(t,r)).toString("utf-8")}function Bd(){let n=In();return n!==null&&za.existsSync(n)}import*as Se from"fs";import*as en from"path";import wy from"adm-zip";import*as wi from"fs";import*as Ya from"path";var qa=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function vi(n){return n instanceof ar||n instanceof qa||n instanceof Error&&(n.name==="CliDataDirError"||n.name==="DocPathSafetyError")}function Gd(n){return new qa(n)}function $T(){return Pt(Kt())}function Vd(n,e,t){let r=cs(n,e);if(r===null)throw Gd(`${t} resolves outside the data directory.`);return r}async function Wd(n,e){await wi.promises.mkdir(n,{recursive:!0});let t=Vd(n,e,"directory");if(!(await wi.promises.stat(t)).isDirectory())throw Gd("path must be a directory.")}function Si(n){let e=$T();try{let t=Vd(n,e,"file");if(!wi.statSync(t).isFile())throw Gd("path must be a regular file.")}catch(t){if(t.code==="ENOENT"){Vd(Ya.dirname(n),e,"file parent");return}throw t}}async function io(n={}){let e=n.mode??"write",t=await iy();await Wd(no(),t),await Wd(oe(),t),e==="write"&&await Wd(Xt(),t);for(let r of[cr(),ro(),fi(),Va(),gi(),hi(),...Qt.map(o=>Ya.join(oe(),o))])Si(r)}var zd=["search.db","build-meta.json",...Qt],HT=["corpus.json","corpus-offsets.json","orama.dpack"];async function UT(n){for(let e of HT)await Se.promises.rm(en.join(n,e),{force:!0})}async function BT(n){let e=await Se.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await Se.promises.rm(en.join(n,t.name),{recursive:!0,force:!0})}function vy(n){let t=new wy(n).getEntry("build-meta.json");if(!t)throw new Error("index.zip is missing build-meta.json");return JSON.parse(t.getData().toString("utf-8"))}async function WT(n){let e=oe();await Se.promises.mkdir(e,{recursive:!0});for(let t of zd){let r=en.join(e,t);await Se.promises.rm(r,{force:!0}),await Se.promises.rename(en.join(n,t),r)}await UT(e),await Se.promises.rm(Xt(),{recursive:!0,force:!0})}function Sy(n){let e=jd();if(!e)return!1;try{let t=vy(e);return t.indexVersion===eo&&t.docsZipSha256===n&&t.segmentCount>0}catch{return!1}}async function by(n){await io({mode:"write"});let e=jd();if(!e)throw new Error("index.zip not found");let t=vy(e);if(t.docsZipSha256!==n)throw new Error("Bundled index.zip does not match docs.zip. Rebuild index.zip with npm run build:index.");if(t.segmentCount<=0)throw new Error("Bundled index.zip is empty");let r=Xt();await Se.promises.rm(r,{recursive:!0,force:!0}),await Se.promises.mkdir(r,{recursive:!0});let o=new wy(e);for(let s of zd){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await Se.promises.writeFile(en.join(r,s),a.getData())}let i=JSON.parse(await Se.promises.readFile(en.join(r,"build-meta.json"),"utf-8"));if(!Se.existsSync(en.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await WT(r),await Se.promises.mkdir(no(),{recursive:!0}),await BT(no()),i}async function Ey(){await Se.promises.rm(Xt(),{recursive:!0,force:!0});let n=oe();for(let e of zd)await Se.promises.rm(en.join(n,e),{force:!0})}import{createHash as Py}from"crypto";import*as Cy from"fs";async function Ja(n){return new Promise((e,t)=>{let r=Py("sha256"),o=Cy.createReadStream(n);o.on("data",i=>r.update(i)),o.on("error",t),o.on("end",()=>e(r.digest("hex")))})}function Iy(n){return Py("sha256").update(n,"utf8").digest("hex")}var qd=null;function VT(){let n=dr("harmonyos-synonyms.json");return JSON.parse(n)}function GT(n){let e=new Map;for(let t of n){let r=t.map(o=>o.trim()).filter(Boolean);for(let o of r){let i=r.filter(s=>s!==o);e.set(o.toLowerCase(),i),o!==o.toLowerCase()&&e.set(o,i)}}return e}function zT(){let n=GT(VT()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function qT(){return qd||(qd=zT()),qd}function Yd(n,e){let t=qT(),r=n.split(/\s+/).filter(Boolean),o=new Set,i=Number.isFinite(e)?e:r.length;for(let s=0;s<r.length&&o.size<i;s+=1){let a=r[s];o.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(o.size>=i)break;o.add(l)}}return[...o].join(" ")}function Ay(n,e){let t=e?my(n,e):dr(n);return Iy(t)}function Ka(n){return Ay("harmonyos-synonyms.json",n)}function Xa(n){return Ay("harmonyos-terms.txt",n)}var YT={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function Za(){try{let n=await wt.promises.readFile(fi(),"utf-8");return JSON.parse(n)}catch{return{...YT}}}async function Jd(n){let e=fi();await wt.promises.mkdir(bi.dirname(e),{recursive:!0}),await wt.promises.writeFile(e,JSON.stringify(n,null,2))}function Dy(n){let e=Date.now();return{state:"extracting",phase:1,phaseLabel:"Extracting documentation",current:0,total:0,message:n,startedAt:e,updatedAt:e,error:null}}async function An(n){let t={...await Za(),...n,updatedAt:Date.now()};return await Jd(t),t}async function Kd(){let n=In();return n?Ja(n):null}async function Xd(){try{let n=await wt.promises.readFile(ro(),"utf-8");return JSON.parse(n)}catch{return null}}async function Qa(n=!1){if(n)return"no-index";let e=await Xd();if(!e||e.segmentCount===0)return"no-index";let t=await Kd();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==eo?"engine-upgraded":e.termsHash!==Xa()?"terms-changed":e.synonymsHash!==Ka()?"synonyms-changed":null}function Ei(){if(!Bd()||!wt.existsSync(cr())||!wt.existsSync(ro()))return!1;let n=bi.dirname(cr());if(!Qt.every(e=>wt.existsSync(bi.join(n,e))))return!1;try{let e=wt.readFileSync(ro(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function Zd(n=!1){return n?!0:Bd()?Ei()?await Qa()!==null:!0:!1}async function Ty(){let n=await Za();return["installing","indexing","persisting"].includes(n.state)}import*as po from"fs";import*as Rn from"path";import Xk from"adm-zip";var Ry=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),Qd=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),ky=new Set(["a","an","and","api","app","application","arkts","arkui","for","get","harmonyos","how","in","oh","ohos","on","or","set","the","to","use","using","what","when","where","which","with","without","data","file","main","model","name","network","stage","system","type","user"]),xy=new Set(["ability","extension","module","service","context","options","config","info","event","code","state","type","data","request","response","client","server","handler","helper","utils","factory","builder","listener","callback","observer","provider","consumer","delegate","adapter","driver","buffer","stream","channel","session","task","worker","controller","component","container","attribute","descriptor","modifier","validator","parser","formatter","encoder","decoder","filter","converter","generator","iterator","dispatcher","resolver","scanner","tracker","monitor","scheduler","renderer","loader","subscriber","proxy","button","surface","stack","heap","map","set","array","list"]);var JT=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,KT=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,XT=/[A-Z][a-zA-Z0-9]{2,}/g,ZT=/@[A-Z][a-zA-Z0-9]*/g,QT=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,Ny=6,eR=/^[a-z][a-z0-9]{2,}$/,tR=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,nR=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,rR=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,oR=/^[A-Z][a-zA-Z0-9]+$/;function iR(n){return`"${n.replace(/"/g,'""')}"`}function Ci(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(iR).join(` ${e} `)}function Pi(n){return Ci(n,"OR")}function Oy(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?Pi([...t,...r]):`(${Pi(t)}) AND (${Pi(r)})`}function Ii(n){return nR.test(n)}function Ly(n){return rR.test(n)&&n.length>=Ny}function sR(n){return oR.test(n)}function Ai(n){return Ii(n)||Ly(n)||sR(n)}function aR(n){let e=n.trim().toLowerCase();return xy.has(e)?!1:Ry.has(e)}function cR(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function ec(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function eu(n){return[...n.matchAll(JT)].map(e=>e[0])}function tu(n,e=Ny){let t=[];for(let r of n.matchAll(KT))r[0].length>=e&&t.push(r[0]);return t}function so(n){return n.filter(e=>{let t=e.toLowerCase();return!n.some(r=>{if(r===e)return!1;let o=r.toLowerCase();return o.length>t.length&&o.endsWith(t)&&t.length>=4})})}function vt(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function lR(n){let e=new Set;vt(e,n);let t=ec(n);return t&&vt(e,t),so([...e])}function tc(n){if(Ii(n))return lR(n);let e=new Set;return vt(e,n),so([...e])}function nc(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(tR);if(!t)return null;let r=t[1].toLowerCase(),o=t[2].toLowerCase();if(!eR.test(r)||ky.has(r)||!aR(o))return null;let i=cR(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function nu(n){let e=nc(n.trim());return!e||e.second!=="manager"?null:e}function dR(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function My(n){let e=n.trim(),t=nu(e);if(t&&Qd.has(t.first))return!0;if(Ly(e)){let r=dR(e);return r!==null&&Qd.has(r)}return!1}function ru(n,e,t){let r=t.toLowerCase(),o=new RegExp(`@ohos\\.[^\\s(]*${t}`,"i");for(let i of[n,e])if(i&&(i.toLowerCase().includes(r)||o.test(i)))return!0;return!1}function ou(n){let e=n.trim();if(Ai(e))return tc(e);let t=new Set;for(let r of eu(n)){vt(t,r);let o=ec(r);o&&vt(t,o)}for(let r of tu(n))vt(t,r);for(let r of n.matchAll(ZT))t.add(r[0]);for(let r of n.matchAll(QT))t.add(r[0]);for(let r of n.matchAll(XT))r[0].length>=4&&t.add(r[0]);return so([...t])}function _y(n){let e=n.trim();if(Ai(e))return tc(e);let t=new Set,r=nc(e);r&&vt(t,r.camelCase);for(let o of ou(e))t.add(o);for(let o of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let i=o[0];i!==i.toLowerCase()&&t.add(i)}return so([...t])}function Fy(n){return Ai(n)}var ee={pureApiSymbol:/^[A-Z][a-zA-Z0-9]+$/,stageModelExact:/^Stage\s*模型$/i,stageModelEnglishExact:/^stage\s+model$/i,stageModel:/Stage\s*模型/i,stageModelEntryPage:/Stage\s*模型.*EntryAbility.*(页面|新页面)/,declarePermissionBoost:/声明.*权限|应用权限.*声明|如何声明应用权限/,declarePermissionCatalog:/如何声明应用权限/,declarePermissionTokens:/如何声明应用权限|声明应用权限/,uiAbilityLifecycleBoost:/UIAbility.*生命周期|生命周期.*UIAbility|UIAblity/i,uiAbilityLifecycleCatalog:/UIAblity.*生命周期|UIAbility.*生命周期/i,entryAbilityPage:/EntryAbility.*(页面|启动|跳转|新页面)/,stateDecoratorBoost:/@State|@Prop|@Link|@Provide|@Consume/,stateDecoratorCatalog:/@State\s*装饰器|@Prop\s*装饰器|@Link\s*装饰器/,stateManagement:/状态管理原理/,routerRoute:/Router\s+路由/,dialogPopupExact:/^Dialog\s+弹窗$/,dialogPopupBoost:/Dialog\s+弹窗/};function jy(n){return ee.pureApiSymbol.test(n.trim())}function Di(n){let e=n.trim();return ee.stageModelExact.test(e)||ee.stageModelEnglishExact.test(e)}function $y(n){let e=[];return Di(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),ee.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),ee.stageModelEntryPage.test(n)&&e.push("\u9875\u9762\u8DEF\u7531","pushUrl"),/UIAblity|UIAbility/.test(n)&&/生命周期/.test(n)&&e.push("UIAbility\u7EC4\u4EF6\u751F\u547D\u5468\u671F"),e}function Hy(n){return Di(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var uR=[{matches:n=>ee.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>Di(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!Di(n)&&ee.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>ee.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>ee.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>ee.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>ee.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>ee.routerRoute.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:1.4},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]},{matches:n=>ee.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function pR(n,e){for(let{catalog:t,multiplier:r}of e){let o=Pn[t];n.set(o,(n.get(o)??1)*r)}}function Uy(n,e){for(let t of uR)t.matches(n)&&pR(e,t.weights)}function By(n,e){if(e!==void 0)return!1;let t=n.trim();return Ii(t)||ee.pureApiSymbol.test(t)||My(t)}function Wy(n){let e=n.trim();if(Ii(e)||ee.pureApiSymbol.test(e))return"harmonyos-references";if(Di(e)||ee.uiAbilityLifecycleCatalog.test(e)||ee.stateDecoratorCatalog.test(e)||ee.stateManagement.test(e)||ee.declarePermissionCatalog.test(e)||ee.stageModelEntryPage.test(e)||ee.routerRoute.test(e)||ee.dialogPopupExact.test(e))return"harmonyos-guides"}import*as ao from"fs";import*as Gy from"path";var rc=null,iu=null,su=null;function mR(){return ao.existsSync(gi())}function fR(n){let e=gi(),t={backend:"jieba-wasm",reason:"native-jieba-load-failed",message:n,createdAt:new Date().toISOString()};ao.mkdirSync(Gy.dirname(e),{recursive:!0}),Si(e),ao.writeFileSync(e,JSON.stringify(t,null,2))}function hR(){if(rc)return rc;let n=dr("harmonyos-stopwords.txt");return rc=new Set(n.split(`
|
|
1321
|
+
`).map(e=>e.trim()).filter(Boolean)),rc}function gR(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t]?.trim();if(!r)continue;let o=n[t+1]?.trim();if(r==="@"&&o&&/^[A-Z][a-zA-Z0-9]*$/.test(o)){e.push(`@${o}`),t+=1;continue}e.push(r)}return e}function zy(n){let e=hR(),t=[];for(let r of gR(n)){let o=r.trim();!o||e.has(o)||(t.push(o.toLowerCase()),/[A-Z]/.test(o)&&/[a-zA-Z]/.test(o)&&t.push(o))}return t}async function qy(n){let{dict:e}=await import("@node-rs/jieba/dict.js"),t=n.withDict(e),r=dr("harmonyos-terms.txt");return t.loadDict(Buffer.from(r,"utf-8")),t}async function yR(){let{Jieba:n}=await import("@node-rs/jieba");return qy(n)}async function Vy(){let{Jieba:n}=await import("@node-rs/jieba-wasm32-wasi");return qy(n)}async function wR(){let n=await import("jieba-wasm"),e=dr("harmonyos-terms.txt");return n.with_dict(e),{cut:n.cut,cutForSearch:n.cut_for_search}}async function vR(){if(b())return wR();if(mR())return Vy();try{let e=await yR();return m("doc-index: using @node-rs/jieba backend"),e}catch(e){let t=e instanceof Error?e.message:String(e);fR(t),m(`doc-index: @node-rs/jieba unavailable (${t}); falling back to wasm32-wasi`)}let n=await Vy();return m("doc-index: using @node-rs/jieba-wasm32-wasi backend"),n}async function Dn(){return iu||(su||(su=vR().then(n=>(iu=n,n))),su)}async function SR(n){let e=await Dn();return zy(e.cutForSearch(n,!0))}async function Yy(n){let e=await Dn();return zy(e.cut(n,!0))}async function oc(n,e){let t=n.trim();if(!t||e<=0)return"";let r=(await SR(t)).join(" ");return r.length<=e?r:r.slice(0,e)}async function bR(n,e){let t=[];for(let o of n){let i=o.trim();i&&(t.push(i.toLowerCase()),/[A-Z]/.test(i)&&t.push(i))}let r=[...new Set(t)].join(" ");return r.length<=e?r:r.slice(0,e)}async function ic(n){let e=!!n.sectionTitle.trim(),t=n.titleTokens.trim(),r=e?qg:Bg,o=e?Jg:Vg,i=e?await bR(n.apiSymbols,o):await oc(n.apiSymbols.join(" "),o),a=(await Promise.all([oc(t,e?Yg:Wg),Promise.resolve(i),oc(n.headingsText,e?Kg:Gg),oc(n.bodySample,e?Xg:zg)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}function ER(n){return n.join(" ").replace(/\s+/g," ").trim().slice(0,pi)}function au(n,e){let t=new Set,r=[];for(let o of[...n,...e]){let i=o.toLowerCase();if(!(!o||t.has(i))&&(t.add(i),r.push(o),r.length>=$g))break}return r}function PR(n){return n.length>=2&&n.length<=Hg}function CR(n,e){let t=Yd(n,Ld),r=t.split(/\s+/).filter(Boolean),o=[e.first,...r.filter(a=>a!==e.second),e.lower,e.camelCase],i=[e.second,e.lower,e.camelCase],s=au(o,i);return{rawQuery:n,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:Oy(o,i)}}function IR(n,e){let t=au(tc(e),[]);return{rawQuery:n,expandedQuery:n,tokens:t,preferAnd:!1,ftsMatch:Pi(t)}}async function Jy(n){let e=ER(n),t=e.trim(),r=Hy(t);if(r)return{rawQuery:e,expandedQuery:r.expandedQuery,tokens:r.tokens,preferAnd:!1};let o=nc(t);if(o)return CR(e,o);if(Ai(t))return IR(e,t);let i=$y(e),s=[...ou(e),...i],c=Fy(t)?e:Yd(e,Ld),l=await Yy(c),d=au(s,l);return{rawQuery:e,expandedQuery:c,tokens:d,preferAnd:i.length===0&&PR(d)}}var Ky=["harmonyos-releases","harmonyos-roadmap"],AR=new Set(Ky.map(n=>Pn[n])),DR=Ky.map(n=>`${sr[n]}/`);function TR(n){return AR.has(n)}function RR(n){return DR.some(e=>n.startsWith(e))}function Xy(n){let e=[],t=[];for(let r of n)TR(r.catalog_id)?t.push(r):e.push(r);return[...e,...t]}function Zy(n){let e=[],t=[];for(let r of n)RR(r.documentId)?t.push(r):e.push(r);return[...e,...t]}var kR=[{pattern:/@ohos\./i,catalog:"harmonyos-references",multiplier:1.5},{pattern:/@[A-Z][a-zA-Z]+/,catalog:"harmonyos-guides",multiplier:1.35},{pattern:/(如何|怎么|怎样|步骤)/,catalog:"harmonyos-guides",multiplier:1.45},{pattern:/(生命周期|原理|概述|什么是|模型|介绍)/,catalog:"harmonyos-guides",multiplier:1.35},{pattern:/(报错|失败|错误|异常|排查)/,catalog:"harmonyos-guides",multiplier:1.25},{pattern:/(报错|失败|FAQ)/i,catalog:"harmonyos-faqs",multiplier:1.2},{pattern:/(构建|签名|打包|发布|上架|应用市场|hvigor|ohpm)/i,catalog:"harmonyos-guides",multiplier:1.3},{pattern:/(行为变更|changelog|升级|适配|版本说明)/i,catalog:"harmonyos-releases",multiplier:1.3},{pattern:/(路由|弹窗|手势|页面|权限|装饰器)/,catalog:"harmonyos-guides",multiplier:1.25,skipForPureApiSymbol:!0}];function Ti(n,e,t){let r=Pn[e];n.set(r,(n.get(r)??1)*t)}function xR(n,e){let t=n.trim(),r=/[\u4e00-\u9fff]/.test(t),o=/\b[A-Z][a-zA-Z0-9]{2,}\b/.test(t),i=/\b[a-z][a-zA-Z0-9]{3,}\b/.test(t);if(r&&(o||i)){Ti(e,"harmonyos-guides",1.45),Ti(e,"harmonyos-references",1.35);return}(o||i)&&Ti(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&Ti(e,"harmonyos-references",1.75)}function Qy(n){let e=new Map,t=n.trim();if(!t)return e;let r=jy(t);xR(t,e),Uy(t,e);for(let o of kR)o.pattern.test(t)&&(o.skipForPureApiSymbol&&r||Ti(e,o.catalog,o.multiplier));return e}function ew(n){return Wy(n)}import*as lo from"fs";import*as cw from"path";var NR=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function tw(n,e){let t=-1;for(let r of NR){let o=n.lastIndexOf(r);o>t&&(t=o)}return t>=e?t:-1}function nw(n,e){let t=n.trim();if(t.length<=e)return{text:t,excerptTruncated:!1};let r=t.slice(0,e),o=tw(r,e-20),i=o>=0?o:e;return{text:t.slice(0,i).trimEnd(),excerptTruncated:!0}}function rw(n,e,t={}){let{maxLen:r=ey,contextChars:o=ty,excerptTruncated:i=!1}=t,s=n.replace(/\s+/g," ").trim();if(!s)return"";if(s.length<=r)return i?`${s}...`:s;let a=e.split(/\s+/).map(Ve=>Ve.trim()).filter(Boolean),c=0;for(let Ve of a){let ct=s.toLowerCase().indexOf(Ve.toLowerCase());if(ct>=0){c=ct;break}}let l=Math.max(0,c-o),d=Math.min(s.length,l+r),h=s.slice(l,d),w=tw(h,r-25);w>=0&&(d=l+w);let v=s.slice(l,d).trim(),T=l>0?"...":"",ne=d<s.length||i?"...":"";return`${T}${v}${ne}`}var OR=`
|
|
1322
1322
|
SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
|
|
1323
1323
|
d.catalog_id, bm25(segments_fts) AS bm25
|
|
1324
1324
|
FROM segments_fts
|
|
@@ -1327,7 +1327,7 @@ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this
|
|
|
1327
1327
|
WHERE segments_fts MATCH ?
|
|
1328
1328
|
ORDER BY bm25(segments_fts)
|
|
1329
1329
|
LIMIT ?
|
|
1330
|
-
`,
|
|
1330
|
+
`,LR=`
|
|
1331
1331
|
SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
|
|
1332
1332
|
d.catalog_id, bm25(segments_fts) AS bm25
|
|
1333
1333
|
FROM segments_fts
|
|
@@ -1336,7 +1336,7 @@ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this
|
|
|
1336
1336
|
WHERE segments_fts MATCH ? AND d.catalog_id = ?
|
|
1337
1337
|
ORDER BY bm25(segments_fts)
|
|
1338
1338
|
LIMIT ?
|
|
1339
|
-
`,
|
|
1339
|
+
`,MR=3.5,_R=1.4,FR=4,jR=1.8,$R=1.35,HR=3.5,UR=1.8,BR=120,ow=6;function lu(n){return n.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function WR(n){return n.split(/[^\p{L}\p{N}@.]+/u).map(lu).filter(e=>e.length>=2)}function VR(n,e){return e.length>1&&e.every(t=>n.includes(t))}function GR(n){return/^[a-z0-9]{1,4}$/.test(n.trim().toLowerCase())}function zR(n,e){return n===e?HR:n.startsWith(e)||n.includes(`@ohos.${e}`)?UR:1}function qR(n,e){let t=lu(e);if(t.length<2)return 1;let r=lu(n.doc_title);if(GR(e))return zR(r,t);if(r.includes(t))return FR;if(t.length>=ow&&r.includes(t.slice(0,ow)))return jR;let o=WR(e);return VR(r,o)?$R:1}function YR(n,e){return e<=1?n:n<0?n*e:n/e}function sc(n,e,t,r){let o=n.bm25/(e.get(n.catalog_id)??1);return o=YR(o,qR(n,t)),r&&ru(n.doc_title,n.section_title,r)&&(o/=MR,n.catalog_id===Pn["harmonyos-references"]&&(o/=_R)),o}function cu(n,e,t,r){return n.reduce((o,i)=>sc(i,e,t,r)<sc(o,e,t,r)?i:o)}function JR(n,e){return e.some(t=>n.section_title.includes(t)||n.doc_title.includes(t))}function KR(n,e,t,r,o){if(o){let i=n.filter(s=>ru(s.doc_title,s.section_title,o));if(i.length>0)return cu(i,t,r,o)}if(e.length>0){let i=n.filter(s=>JR(s,e));if(i.length>0)return cu(i,t,r,o)}return cu(n,t,r,o)}function iw(n,e,t,r,o){let i=Qy(e),s=_y(e),c=nu(e)?.camelCase,l=new Map;for(let v of n){let T=l.get(v.document_id)??[];T.push(v),l.set(v.document_id,T)}let d=[];for(let v of l.values())d.push(KR(v,s,i,t,c));let h=d.sort((v,T)=>sc(v,i,t,c)-sc(T,i,t,c));return(o?Xy(h):h).slice(0,r)}function ac(n,e,t,r,o,i){let s=e?Pn[e]:void 0,a=Math.max(t,t*Ug,BR),c=s===void 0?n.all(OR,r,a):n.all(LR,r,s,a);return(s===void 0?iw(c,i,o,t,!0):iw(c,i,o,t,!1)).map(d=>({title:d.doc_title,documentId:d.document_id,sectionTitle:d.section_title||void 0,snippet:rw(d.lead_text,o,{excerptTruncated:!!d.excerpt_truncated})}))}var cc=`
|
|
1340
1340
|
CREATE TABLE documents (
|
|
1341
1341
|
id INTEGER PRIMARY KEY,
|
|
1342
1342
|
document_id TEXT NOT NULL UNIQUE,
|
|
@@ -1374,59 +1374,56 @@ CREATE TRIGGER segments_au AFTER UPDATE ON segments BEGIN
|
|
|
1374
1374
|
END;
|
|
1375
1375
|
|
|
1376
1376
|
CREATE INDEX segments_doc_id_idx ON segments(doc_id);
|
|
1377
|
-
`;var
|
|
1377
|
+
`;var co=null,du=null;function XR(){co?.close(),co=null,du=null}function ZR(n,e){if(co&&du===e)return co;co?.close();let t=new n(e,{readonly:!0,fileMustExist:!0});return co=t,du=e,t.pragma("mmap_size = 268435456"),t.pragma("cache_size = -8000"),t.pragma("query_only = ON"),t}function QR(n,e){let t=new n(e);return t.pragma("journal_mode = OFF"),t.pragma("synchronous = OFF"),t.pragma("temp_store = MEMORY"),t.exec(cc),t}function ek(n,e,t){let r=e.get(t.documentId);if(r!==void 0)return r;let i=n.prepare("SELECT id FROM documents WHERE document_id = ?").get(t.documentId);if(i)return e.set(t.documentId,i.id),i.id;let a=n.prepare(`
|
|
1378
1378
|
INSERT INTO documents(document_id, catalog_id, doc_title)
|
|
1379
1379
|
VALUES (?, ?, ?)
|
|
1380
|
-
`).run(t.documentId,t.catalogId,t.docTitle),c=Number(a.lastInsertRowid);return e.set(t.documentId,c),c}async function
|
|
1380
|
+
`).run(t.documentId,t.catalogId,t.docTitle),c=Number(a.lastInsertRowid);return e.set(t.documentId,c),c}async function tk(n,e,t,r){await Dn();let o=QR(n,e),i=new Map,s=o.prepare(`
|
|
1381
1381
|
INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated)
|
|
1382
1382
|
VALUES (?, ?, ?, ?, ?)
|
|
1383
|
-
`),a=t.length;for(let c=0;c<a;c+=eo){let l=t.slice(c,c+eo),d=await Promise.all(l.map(async w=>({source:w,searchText:await rc(w)})));o.transaction(w=>{for(let v of w){let I=Zk(o,i,v.source);s.run(I,v.source.sectionTitle,v.source.leadText,v.searchText,v.source.excerptTruncated?1:0)}})(d),await r?.(Math.min(c+l.length,a),a)}o.exec("ANALYZE"),o.exec("VACUUM"),o.close()}function eR(n,e,t,r,o,i,s){let a=Kk(n,e);return ic({all(c,...l){return a.prepare(c).all(...l)}},t,r,o,i,s)}async function ew(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:Jk,buildSearchIndex:(t,r,o)=>Qk(e,t,r,o),searchIndex:(t,r,o,i,s,a,c)=>Promise.resolve(eR(e,i,r,o,s,a,c))}}import{readFile as tR,stat as nR,writeFile as rR}from"fs/promises";var lu=null,kn=null;async function du(){return lu||(lu=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),lu}function oR(n){return{all(e,...t){let r=n.prepare(e);t.length>0&&r.bind(t);let o=[];for(;r.step();)o.push(r.get({}));return r.finalize(),o}}}async function iR(n){let e=await nR(n);if(kn&&kn.dbPath===n&&kn.mtimeMs===e.mtimeMs)return kn.db;kn?.db.close();let t=await du(),r=t.capi,o=t.wasm,i=new Uint8Array(await tR(n)),s=o.allocFromTypedArray(i),a=new t.oo1.DB(":memory:"),c=a.pointer;if(c===void 0)throw new Error("sqlite3_deserialize: database pointer is undefined");let l=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE;return r.sqlite3_deserialize(c,"main",s,i.byteLength,i.byteLength,l),kn={dbPath:n,mtimeMs:e.mtimeMs,db:a},a}function tw(){kn?.db.close(),kn=null}async function sR(n,e,t,r){n.exec("BEGIN");for(let o of r){let i=t(o.source);e.bind([i,o.source.sectionTitle,o.source.leadText,o.searchText,o.source.excerptTruncated?1:0]),e.step(),e.reset()}n.exec("COMMIT")}function aR(n,e,t){return r=>{let o=e.get(r.documentId);if(o!==void 0)return o;let i=n.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(i!=null){let a=Number(i);return e.set(r.documentId,a),a}t.bind([r.documentId,r.catalogId,r.docTitle]),t.step(),t.reset();let s=Number(n.selectValue("SELECT last_insert_rowid()"));return e.set(r.documentId,s),s}}async function cR(n,e,t){await Tn();let r=await du(),o=new r.oo1.DB(":memory:","c");o.exec(sc);let i=new Map,s=o.prepare("INSERT INTO documents(document_id, catalog_id, doc_title) VALUES (?, ?, ?)"),a=o.prepare("INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated) VALUES (?, ?, ?, ?, ?)"),c=aR(o,i,s),l=e.length;for(let h=0;h<l;h+=eo){let w=e.slice(h,h+eo),v=await Promise.all(w.map(async I=>({source:I,searchText:await rc(I)})));await sR(o,a,c,v),await t?.(Math.min(h+w.length,l),l)}o.exec("ANALYZE");let d=r.capi.sqlite3_js_db_export(o);await rR(n,d),o.close(),tw()}async function lR(n,e,t,r,o,i){let s=await iR(n);return ic(oR(s),e,t,r,o,i)}async function uu(){return await du(),{kind:"sqlite-wasm",resetCache:tw,buildSearchIndex:cR,searchIndex:(n,e,t,r,o,i,s)=>lR(r,e,t,o,i,s)}}var ac=null,pu=null;function dR(){return co.existsSync(fi())}function uR(n){let e=fi(),t={backend:"sqlite-wasm",reason:"better-sqlite3-load-failed",message:n,createdAt:new Date().toISOString()};co.mkdirSync(nw.dirname(e),{recursive:!0}),vi(e),co.writeFileSync(e,JSON.stringify(t,null,2))}async function pR(){if(dR())return uu();try{let n=await ew();return m("doc-index: using better-sqlite3 SQLite backend"),n}catch(n){let e=n instanceof Error?n.message:String(n);uR(e),m(`doc-index: better-sqlite3 unavailable (${e}); falling back to sqlite-wasm`)}return uu()}async function Ti(){return ac||(ac=pR().then(n=>(pu=n,n))),ac}function rw(){pu?.resetCache(),ac=null,pu=null}async function mR(n,e,t,r,o,i,s){let a=await Ti(),c=s??lr();return a.searchIndex(n,e,t,c,r,o,i)}function lo(){rw()}async function iw(n,e,t){await(await Ti()).buildSearchIndex(n,e,t)}function sw(n,e,t){let r=new Set,o=[];for(let i of[...n,...e])if(!r.has(i.documentId)&&(r.add(i.documentId),o.push(i),o.length>=t))break;return o}function cc(n,e,t,r,o,i){return mR(n,e,t,o,r.expandedQuery,r.rawQuery,i)}async function fR(n,e,t,r,o){let i=await cc(n,e,t,r,Pi(r.tokens,"AND"),o);if(i.length>=t)return i;let s=await cc(n,e,t,r,Pi(r.tokens,"OR"),o);return sw(i,s,t)}async function mu(n,e,t,r,o){return r.ftsMatch?cc(n,e,t,r,r.ftsMatch,o):r.preferAnd?fR(n,e,t,r,o):cc(n,e,t,r,Pi(r.tokens,"OR"),o)}async function hR(n,e,t,r){let o=await mu(n,"harmonyos-references",e,t,r);if(o.length>=e)return o;let i=await mu(n,void 0,e,t,r);return sw(o,i,e)}function ow(n,e){return e!==void 0?n:qy(n)}async function fu(n,e,t=20,r){let o=await Wy(n);if(_y(o.rawQuery,e)){let a=await hR(n,t,o,r);return ow(a,e)}let i=e??Yy(o.rawQuery),s=await mu(n,i,t,o,r);return ow(s,e)}import{unified as fw}from"unified";import hw from"remark-parse";import gw from"remark-gfm";import{toString as dc}from"mdast-util-to-string";var gR=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,yR=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,wR=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,vR=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,SR=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function lc(n){let e=n.trim(),t=e.match(vR);return t?t[1]:e}function bR(n){let e=n.match(gR);if(!e)return;let t=lc(e[1].trim());return{displayTitle:n,symbolName:t,searchExtras:[t,e[3]]}}function ER(n){let e=lc(n.replace(/\([^)]*\)$/,""));if(/^[A-Z][A-Za-z0-9]*$/.test(e))return{displayTitle:n,symbolName:e,searchExtras:[e]};if(/^[A-Z][A-Za-z0-9]*(\([^)]*\))?$/.test(n))return{displayTitle:n,symbolName:e,searchExtras:[e]}}function ki(n){let e=n.trim();return e?bR(e)??(()=>{let t=e.match(yR);if(t){let r=t[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let t=e.match(wR);if(!t)return;let r=t[1].trim(),o=t[2].trim();return{displayTitle:e,symbolName:o,searchExtras:[r,o]}})()??ER(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function PR(n){if(n.length<2||n.length>36||SR.test(n))return!1;let e=[...n.replace(/\s/g,"")];return e.length===0?!1:e.filter(r=>new RegExp("\\p{Script=Han}","u").test(r)).length/e.length>=.4}function aw(n){for(let e of n){let t=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(PR(t))return t}return""}function cw(n,e,t){let r=[n,...t.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var CR=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,Ri=/@[A-Z][a-zA-Z]+/g,IR=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,AR=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,DR=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,TR=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),kR=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),RR=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function yw(n,e){let t=new Set,r=[n,...e];for(let o of r){for(let i of Zd(o)){St(t,i);let s=Za(i);s&&St(t,s)}for(let i of Qd(o))St(t,i);for(let i of o.matchAll(CR)){let s=i[0];xR(s)&&t.add(s)}for(let i of o.matchAll(Ri))t.add(i[0])}return io([...t])}function xR(n){let e=n.trim();if(!e||Ri.test(e))return!!e;if(e.includes(".")){let t=e.split(".")[0]??"";return RR.has(t)?!1:/^[A-Z]/.test(t)}return TR.has(e)?!1:kR.has(e)?!0:e.length<=3?!1:/^[A-Z][a-z]+[A-Z]/.test(e)?!0:e.length>=6&&/^[A-Z][A-Za-z0-9]+$/.test(e)}function lw(n){let e=n.trim();return!!(!e||DR.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function ww(n,e){let t=e.jsonTitle?.trim(),r=MR(n,"").trim(),o=e.fileName.trim();return t&&!lw(t)?t:r&&!lw(r)?r:t||r||o}function vw(n){return IR.test(n.trim())}function hu(n){let e=n.trim().replace(/\([^)]*\)$/,""),t=lc(e);return AR.test(t)}function uc(n){let e=n.trim();return e?Ri.test(e)||vw(e)||hu(e)?!0:!!ki(e).symbolName:!1}function NR(n){let e=n.trim();return!(!e||vw(e)||hu(e))}function LR(n){let e=new Set,t=[];for(let r of n){let o=r.trim();!NR(o)||e.has(o)||(e.add(o),t.push(o))}return t}function dw(n){if(!n.includes("."))return 0;let e=n.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function OR(n,e){let t=dw(n)-dw(e);return t!==0?t:n.localeCompare(e)}function Sw(n,e=[]){let t=[...new Set(e.map(i=>i.trim()).filter(Boolean))],r=new Set(t),o=[...new Set(n.map(i=>i.trim()).filter(Boolean))].filter(i=>!r.has(i));return o.sort(OR),[...t,...o].slice(0,qg)}function pc(n){return n.replace(/\s+/g," ").trim()}function uw(n){return n.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function MR(n,e=""){let t=n.split(/\r?\n/),r=0;for(;r<t.length&&!t[r].trim();)r+=1;if(r>=t.length)return e;let o=uw(t[r].trim()),i=o.match(/^#+\s+(.+)$/);if(i)return uw(i[1].trim());if(r+1<t.length){let s=t[r+1].trim();if(/^=+$/.test(s)||/^-+$/.test(s))return o}return o||e}function bw(n){let e=pc(n.join(" "));if(e.length<=Ha)return e;let t=e.slice(0,Ha);return e.length<=Ha+Ld?t:`${t} ${e.slice(-Ld)}`}function _R(n){let e=LR(n).join(" ");return e.length<=Od?e:e.slice(0,Od)}function Ew(n){let e=pc(n),{text:t,excerptTruncated:r}=Ky(e,zg);return{leadText:t,excerptTruncated:r}}function FR(n,e){let{leadText:t,excerptTruncated:r}=Ew(n);return{leadText:t,excerptTruncated:r||!!e.trim()}}function Pw(n,e){if(n.type==="code"){e.codeBlocks.push(n.value??"");return}if("children"in n&&Array.isArray(n.children)){for(let r of n.children)Pw(r,e);return}let t=pc(dc(n));t&&e.bodyParts.push(t)}function jR(n){let e=fw().use(hw).use(gw).parse(n),t=[],r=null,o=()=>{r&&((r.sectionTitle||r.bodyParts.length||r.codeBlocks.length)&&t.push(r),r=null)},i=()=>{r||(r={sectionTitle:"",bodyParts:[],codeBlocks:[]})};for(let s of e.children){if(s.type==="heading"){let a=s,c=dc(a).trim();if(a.depth>=4&&c&&uc(c)){o(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}i(),c&&r.bodyParts.push(c);continue}i(),Pw(s,r)}return o(),t.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:t}function $R(n){return Ng.test(n)}function HR(n){return n.filter(e=>e.sectionTitle&&uc(e.sectionTitle)).length}function BR(n){return{sectionTitle:n.map(e=>e.sectionTitle.trim()).join(" | "),bodyParts:n.flatMap(e=>e.bodyParts).slice(0,40),codeBlocks:n.flatMap(e=>e.codeBlocks).slice(0,8)}}function pw(n){let e=n.trim();return!e||Ri.test(e)?Ri.test(e):/对象说明$|枚举说明$/.test(e)?!0:hu(e)}function UR(n){let e=n.filter(h=>!h.sectionTitle||!uc(h.sectionTitle)),t=n.filter(h=>h.sectionTitle&&uc(h.sectionTitle)),r=t.filter(h=>pw(h.sectionTitle)),o=t.filter(h=>!pw(h.sectionTitle)),i=Math.max(0,xg-r.length),s=o.slice(0,i),a=o.slice(i),c=a.filter(h=>mw(h.sectionTitle)),l=a.filter(h=>!mw(h.sectionTitle)),d=[];for(let h=0;h<l.length;h+=xd)d.push(BR(l.slice(h,h+xd)));return[...e,...r,...s,...c,...d]}function WR(n,e,t){let r=n.split(/\r?\n/).length,o=HR(e);return o===0?!1:$R(t)?r>=kg&&o>=Rg:r>=Dg&&o>=Tg}var VR=/^\[h2\][A-Za-z]/;function mw(n){return VR.test(n.trim())}function Cw(n){if(!n.includes(" | ")){let t=ki(n);return t.symbolName?[t.symbolName]:[]}let e=[];for(let t of n.split(" | ")){let r=ki(t.trim()).symbolName;r&&e.push(r)}return e}function GR(n,e,t,r){let o=Cw(n),i=yw(t,r);return e.symbolName&&i.push(e.symbolName),Sw([...o,...i],o)}function qR(n,e){let t=bw(n.bodyParts),r=n.sectionTitle.trim(),o=ki(r),i=aw(n.bodyParts),s=cw(r,i,o),a=Cw(r),c=r?a.length>0?`${e.docTitle} ${a.join(" ")}`:`${e.docTitle} ${o.symbolName??r}`:e.docTitle,l=[e.docTitle,s,...n.bodyParts].join(" "),{leadText:d,excerptTruncated:h}=FR(t,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:GR(r,o,l,n.codeBlocks),bodySample:t,leadText:d,excerptTruncated:h}}function Iw(n,e){for(let t of n){if(t.type==="heading"){let o=dc(t).trim();o&&e.headings.push(o);continue}if(t.type==="code"){e.codeBlocks.push(t.value??"");continue}if("children"in t&&Array.isArray(t.children)){Iw(t.children,e);continue}let r=pc(dc(t));r&&e.bodyParts.push(r)}}function zR(n){let e=fw().use(hw).use(gw).parse(n),t={headings:[],bodyParts:[],codeBlocks:[]};return Iw(e.children,t),t}function YR(n,e){let t=zR(n),r=e.docTitle?.trim()||e.documentId,o=bw(t.bodyParts),i=[r,...t.headings,o].join(" "),{leadText:s,excerptTruncated:a}=Ew(o);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:_R(t.headings),apiSymbols:Sw(yw(i,t.codeBlocks)),bodySample:o,leadText:s,excerptTruncated:a}}function Aw(n,e){let t=e.docTitle?.trim()||e.documentId,r=jR(n);return WR(n,r,e.documentId)?UR(r).filter(o=>o.sectionTitle||o.bodyParts.length>0||o.codeBlocks.length>0).map(o=>qR(o,{...e,docTitle:t})):[YR(n,{...e,docTitle:t})]}function Dw(n){let e=n.split("/");if(e[0]==="docs"&&(e=e.slice(1)),e.length<2)return null;let t=Kg[e[0]];if(t===void 0)return null;let r=e[e.length-1].replace(/\.md$/,"");return e[e.length-1]=r,{documentId:e.join("/"),catalogId:t,docTitle:r}}function Tw(n,e,t){let r=ww(n,{jsonTitle:e,fileName:t.docTitle});return Aw(n,{...t,docTitle:r})}function KR(n){return n.getEntries().filter(e=>e.isDirectory||!e.entryName.endsWith(".md")?!1:e.entryName.split("/").every(t=>!t.startsWith(".")))}function XR(n,e){let t=n.getEntry(e.replace(/\.md$/,".json"));if(t)try{return JSON.parse(t.getData().toString("utf-8")).title?.trim()||void 0}catch{return}}function ZR(n){let e=new JR(n),t=[];for(let r of KR(e)){let o=Dw(r.entryName);o&&t.push(...Tw(r.getData().toString("utf-8"),XR(e,r.entryName),o))}return t}async function QR(n){let e=[];async function t(r){let o=await uo.promises.readdir(r,{withFileTypes:!0});for(let i of o){if(i.name.startsWith("."))continue;let s=Rn.join(r,i.name);i.isDirectory()?await t(s):i.isFile()&&i.name.endsWith(".md")&&e.push(s)}}return await t(n),e}async function ex(n){let e=n.replace(/\.md$/,".json");try{let t=await uo.promises.readFile(e,"utf-8");return JSON.parse(t).title?.trim()||void 0}catch{return}}async function tx(n){let e=[];for(let t of await QR(n)){let r=Rn.relative(n,t).split(Rn.sep).join("/"),o=Dw(r);if(!o)continue;let i=await uo.promises.readFile(t,"utf-8");e.push(...Tw(i,await ex(t),o))}return e}async function nx(n){return"docsZipPath"in n?ZR(n.docsZipPath):tx(n.docsDir)}async function rx(n,e,t){let r=Rn.join(e,"search.db");return await iw(r,n,async(o,i)=>{await t?.({current:o,total:i,message:`Building search index\u2026 ${o.toLocaleString()} / ${i.toLocaleString()} segments`})}),n.length}function ox(n,e){return{indexVersion:Qr,docsZipSha256:n.docsZipSha256,termsHash:n.termsHash,synonymsHash:n.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:n.builtBy}}async function kw(n){n.lexiconDir&&jd(n.lexiconDir);try{let e=await nx(n);await n.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await uo.promises.mkdir(n.tmpDir,{recursive:!0});let t=await rx(e,n.tmpDir,n.onProgress),r=ox(n,t);return await uo.promises.writeFile(Rn.join(n.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await cy(n.tmpDir),r}finally{n.lexiconDir&&jd(null)}}var xi=class extends Error{constructor(e){super(e),this.name="NativeDepsError"}};function ix(){let n=ro(),e=oe();return["Documentation search index is not installed yet.","",...Ba(n),`Index directory: ${e}`,"","Try:"," 1. Wait a moment and run the docs command again (postinstall may still be running)"," 2. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 3. Check the log file above for setup errors"].join(`
|
|
1384
|
-
`)}function
|
|
1385
|
-
`)}function
|
|
1386
|
-
`)}async function
|
|
1383
|
+
`),a=t.length;for(let c=0;c<a;c+=to){let l=t.slice(c,c+to),d=await Promise.all(l.map(async w=>({source:w,searchText:await ic(w)})));o.transaction(w=>{for(let v of w){let T=ek(o,i,v.source);s.run(T,v.source.sectionTitle,v.source.leadText,v.searchText,v.source.excerptTruncated?1:0)}})(d),await r?.(Math.min(c+l.length,a),a)}o.exec("ANALYZE"),o.exec("VACUUM"),o.close()}function nk(n,e,t,r,o,i,s){let a=ZR(n,e);return ac({all(c,...l){return a.prepare(c).all(...l)}},t,r,o,i,s)}async function sw(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:XR,buildSearchIndex:(t,r,o)=>tk(e,t,r,o),searchIndex:(t,r,o,i,s,a,c)=>Promise.resolve(nk(e,i,r,o,s,a,c))}}import{readFile as rk,stat as ok,writeFile as ik}from"fs/promises";var uu=null,Tn=null;async function pu(){return uu||(uu=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),uu}function sk(n){return{all(e,...t){let r=n.prepare(e);t.length>0&&r.bind(t);let o=[];for(;r.step();)o.push(r.get({}));return r.finalize(),o}}}async function ak(n){let e=await ok(n);if(Tn&&Tn.dbPath===n&&Tn.mtimeMs===e.mtimeMs)return Tn.db;Tn?.db.close();let t=await pu(),r=t.capi,o=t.wasm,i=new Uint8Array(await rk(n)),s=o.allocFromTypedArray(i),a=new t.oo1.DB(":memory:"),c=a.pointer;if(c===void 0)throw new Error("sqlite3_deserialize: database pointer is undefined");let l=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE;return r.sqlite3_deserialize(c,"main",s,i.byteLength,i.byteLength,l),Tn={dbPath:n,mtimeMs:e.mtimeMs,db:a},a}function aw(){Tn?.db.close(),Tn=null}async function ck(n,e,t,r){n.exec("BEGIN");for(let o of r){let i=t(o.source);e.bind([i,o.source.sectionTitle,o.source.leadText,o.searchText,o.source.excerptTruncated?1:0]),e.step(),e.reset()}n.exec("COMMIT")}function lk(n,e,t){return r=>{let o=e.get(r.documentId);if(o!==void 0)return o;let i=n.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(i!=null){let a=Number(i);return e.set(r.documentId,a),a}t.bind([r.documentId,r.catalogId,r.docTitle]),t.step(),t.reset();let s=Number(n.selectValue("SELECT last_insert_rowid()"));return e.set(r.documentId,s),s}}async function dk(n,e,t){await Dn();let r=await pu(),o=new r.oo1.DB(":memory:","c");o.exec(cc);let i=new Map,s=o.prepare("INSERT INTO documents(document_id, catalog_id, doc_title) VALUES (?, ?, ?)"),a=o.prepare("INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated) VALUES (?, ?, ?, ?, ?)"),c=lk(o,i,s),l=e.length;for(let h=0;h<l;h+=to){let w=e.slice(h,h+to),v=await Promise.all(w.map(async T=>({source:T,searchText:await ic(T)})));await ck(o,a,c,v),await t?.(Math.min(h+w.length,l),l)}o.exec("ANALYZE");let d=r.capi.sqlite3_js_db_export(o);await ik(n,d),o.close(),aw()}async function uk(n,e,t,r,o,i){let s=await ak(n);return ac(sk(s),e,t,r,o,i)}async function mu(){return await pu(),{kind:"sqlite-wasm",resetCache:aw,buildSearchIndex:dk,searchIndex:(n,e,t,r,o,i,s)=>uk(r,e,t,o,i,s)}}var lc=null,fu=null;function pk(){return lo.existsSync(hi())}function mk(n){let e=hi(),t={backend:"sqlite-wasm",reason:"better-sqlite3-load-failed",message:n,createdAt:new Date().toISOString()};lo.mkdirSync(cw.dirname(e),{recursive:!0}),Si(e),lo.writeFileSync(e,JSON.stringify(t,null,2))}async function fk(){if(pk())return mu();try{let n=await sw();return m("doc-index: using better-sqlite3 SQLite backend"),n}catch(n){let e=n instanceof Error?n.message:String(n);mk(e),m(`doc-index: better-sqlite3 unavailable (${e}); falling back to sqlite-wasm`)}return mu()}async function Ri(){return lc||(lc=fk().then(n=>(fu=n,n))),lc}function lw(){fu?.resetCache(),lc=null,fu=null}async function hk(n,e,t,r,o,i,s){let a=await Ri(),c=s??cr();return a.searchIndex(n,e,t,c,r,o,i)}function uo(){lw()}async function uw(n,e,t){await(await Ri()).buildSearchIndex(n,e,t)}function pw(n,e,t){let r=new Set,o=[];for(let i of[...n,...e])if(!r.has(i.documentId)&&(r.add(i.documentId),o.push(i),o.length>=t))break;return o}function dc(n,e,t,r,o,i){return hk(n,e,t,o,r.expandedQuery,r.rawQuery,i)}async function gk(n,e,t,r,o){let i=await dc(n,e,t,r,Ci(r.tokens,"AND"),o);if(i.length>=t)return i;let s=await dc(n,e,t,r,Ci(r.tokens,"OR"),o);return pw(i,s,t)}async function hu(n,e,t,r,o){return r.ftsMatch?dc(n,e,t,r,r.ftsMatch,o):r.preferAnd?gk(n,e,t,r,o):dc(n,e,t,r,Ci(r.tokens,"OR"),o)}async function yk(n,e,t,r){let o=await hu(n,"harmonyos-references",e,t,r);if(o.length>=e)return o;let i=await hu(n,void 0,e,t,r);return pw(o,i,e)}function dw(n,e){return e!==void 0?n:Zy(n)}async function gu(n,e,t=20,r){let o=await Jy(n);if(By(o.rawQuery,e)){let a=await yk(n,t,o,r);return dw(a,e)}let i=e??ew(o.rawQuery),s=await hu(n,i,t,o,r);return dw(s,e)}import{unified as Sw}from"unified";import bw from"remark-parse";import Ew from"remark-gfm";import{toString as pc}from"mdast-util-to-string";var wk=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,vk=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,Sk=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,bk=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,Ek=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function uc(n){let e=n.trim(),t=e.match(bk);return t?t[1]:e}function Pk(n){let e=n.match(wk);if(!e)return;let t=uc(e[1].trim());return{displayTitle:n,symbolName:t,searchExtras:[t,e[3]]}}function Ck(n){let e=uc(n.replace(/\([^)]*\)$/,""));if(/^[A-Z][A-Za-z0-9]*$/.test(e))return{displayTitle:n,symbolName:e,searchExtras:[e]};if(/^[A-Z][A-Za-z0-9]*(\([^)]*\))?$/.test(n))return{displayTitle:n,symbolName:e,searchExtras:[e]}}function ki(n){let e=n.trim();return e?Pk(e)??(()=>{let t=e.match(vk);if(t){let r=t[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let t=e.match(Sk);if(!t)return;let r=t[1].trim(),o=t[2].trim();return{displayTitle:e,symbolName:o,searchExtras:[r,o]}})()??Ck(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function Ik(n){if(n.length<2||n.length>36||Ek.test(n))return!1;let e=[...n.replace(/\s/g,"")];return e.length===0?!1:e.filter(r=>new RegExp("\\p{Script=Han}","u").test(r)).length/e.length>=.4}function mw(n){for(let e of n){let t=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(Ik(t))return t}return""}function fw(n,e,t){let r=[n,...t.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var Ak=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,xi=/@[A-Z][a-zA-Z]+/g,Dk=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,Tk=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,Rk=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,kk=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),xk=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),Nk=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function Pw(n,e){let t=new Set,r=[n,...e];for(let o of r){for(let i of eu(o)){vt(t,i);let s=ec(i);s&&vt(t,s)}for(let i of tu(o))vt(t,i);for(let i of o.matchAll(Ak)){let s=i[0];Ok(s)&&t.add(s)}for(let i of o.matchAll(xi))t.add(i[0])}return so([...t])}function Ok(n){let e=n.trim();if(!e||xi.test(e))return!!e;if(e.includes(".")){let t=e.split(".")[0]??"";return Nk.has(t)?!1:/^[A-Z]/.test(t)}return kk.has(e)?!1:xk.has(e)?!0:e.length<=3?!1:/^[A-Z][a-z]+[A-Z]/.test(e)?!0:e.length>=6&&/^[A-Z][A-Za-z0-9]+$/.test(e)}function hw(n){let e=n.trim();return!!(!e||Rk.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function Cw(n,e){let t=e.jsonTitle?.trim(),r=Fk(n,"").trim(),o=e.fileName.trim();return t&&!hw(t)?t:r&&!hw(r)?r:t||r||o}function Iw(n){return Dk.test(n.trim())}function yu(n){let e=n.trim().replace(/\([^)]*\)$/,""),t=uc(e);return Tk.test(t)}function mc(n){let e=n.trim();return e?xi.test(e)||Iw(e)||yu(e)?!0:!!ki(e).symbolName:!1}function Lk(n){let e=n.trim();return!(!e||Iw(e)||yu(e))}function Mk(n){let e=new Set,t=[];for(let r of n){let o=r.trim();!Lk(o)||e.has(o)||(e.add(o),t.push(o))}return t}function gw(n){if(!n.includes("."))return 0;let e=n.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function _k(n,e){let t=gw(n)-gw(e);return t!==0?t:n.localeCompare(e)}function Aw(n,e=[]){let t=[...new Set(e.map(i=>i.trim()).filter(Boolean))],r=new Set(t),o=[...new Set(n.map(i=>i.trim()).filter(Boolean))].filter(i=>!r.has(i));return o.sort(_k),[...t,...o].slice(0,Zg)}function fc(n){return n.replace(/\s+/g," ").trim()}function yw(n){return n.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function Fk(n,e=""){let t=n.split(/\r?\n/),r=0;for(;r<t.length&&!t[r].trim();)r+=1;if(r>=t.length)return e;let o=yw(t[r].trim()),i=o.match(/^#+\s+(.+)$/);if(i)return yw(i[1].trim());if(r+1<t.length){let s=t[r+1].trim();if(/^=+$/.test(s)||/^-+$/.test(s))return o}return o||e}function Dw(n){let e=fc(n.join(" "));if(e.length<=Ba)return e;let t=e.slice(0,Ba);return e.length<=Ba+Md?t:`${t} ${e.slice(-Md)}`}function jk(n){let e=Mk(n).join(" ");return e.length<=_d?e:e.slice(0,_d)}function Tw(n){let e=fc(n),{text:t,excerptTruncated:r}=nw(e,Qg);return{leadText:t,excerptTruncated:r}}function $k(n,e){let{leadText:t,excerptTruncated:r}=Tw(n);return{leadText:t,excerptTruncated:r||!!e.trim()}}function Rw(n,e){if(n.type==="code"){e.codeBlocks.push(n.value??"");return}if("children"in n&&Array.isArray(n.children)){for(let r of n.children)Rw(r,e);return}let t=fc(pc(n));t&&e.bodyParts.push(t)}function Hk(n){let e=Sw().use(bw).use(Ew).parse(n),t=[],r=null,o=()=>{r&&((r.sectionTitle||r.bodyParts.length||r.codeBlocks.length)&&t.push(r),r=null)},i=()=>{r||(r={sectionTitle:"",bodyParts:[],codeBlocks:[]})};for(let s of e.children){if(s.type==="heading"){let a=s,c=pc(a).trim();if(a.depth>=4&&c&&mc(c)){o(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}i(),c&&r.bodyParts.push(c);continue}i(),Rw(s,r)}return o(),t.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:t}function Uk(n){return jg.test(n)}function Bk(n){return n.filter(e=>e.sectionTitle&&mc(e.sectionTitle)).length}function Wk(n){return{sectionTitle:n.map(e=>e.sectionTitle.trim()).join(" | "),bodyParts:n.flatMap(e=>e.bodyParts).slice(0,40),codeBlocks:n.flatMap(e=>e.codeBlocks).slice(0,8)}}function ww(n){let e=n.trim();return!e||xi.test(e)?xi.test(e):/对象说明$|枚举说明$/.test(e)?!0:yu(e)}function Vk(n){let e=n.filter(h=>!h.sectionTitle||!mc(h.sectionTitle)),t=n.filter(h=>h.sectionTitle&&mc(h.sectionTitle)),r=t.filter(h=>ww(h.sectionTitle)),o=t.filter(h=>!ww(h.sectionTitle)),i=Math.max(0,Fg-r.length),s=o.slice(0,i),a=o.slice(i),c=a.filter(h=>vw(h.sectionTitle)),l=a.filter(h=>!vw(h.sectionTitle)),d=[];for(let h=0;h<l.length;h+=Od)d.push(Wk(l.slice(h,h+Od)));return[...e,...r,...s,...c,...d]}function Gk(n,e,t){let r=n.split(/\r?\n/).length,o=Bk(e);return o===0?!1:Uk(t)?r>=Mg&&o>=_g:r>=Og&&o>=Lg}var zk=/^\[h2\][A-Za-z]/;function vw(n){return zk.test(n.trim())}function kw(n){if(!n.includes(" | ")){let t=ki(n);return t.symbolName?[t.symbolName]:[]}let e=[];for(let t of n.split(" | ")){let r=ki(t.trim()).symbolName;r&&e.push(r)}return e}function qk(n,e,t,r){let o=kw(n),i=Pw(t,r);return e.symbolName&&i.push(e.symbolName),Aw([...o,...i],o)}function Yk(n,e){let t=Dw(n.bodyParts),r=n.sectionTitle.trim(),o=ki(r),i=mw(n.bodyParts),s=fw(r,i,o),a=kw(r),c=r?a.length>0?`${e.docTitle} ${a.join(" ")}`:`${e.docTitle} ${o.symbolName??r}`:e.docTitle,l=[e.docTitle,s,...n.bodyParts].join(" "),{leadText:d,excerptTruncated:h}=$k(t,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:qk(r,o,l,n.codeBlocks),bodySample:t,leadText:d,excerptTruncated:h}}function xw(n,e){for(let t of n){if(t.type==="heading"){let o=pc(t).trim();o&&e.headings.push(o);continue}if(t.type==="code"){e.codeBlocks.push(t.value??"");continue}if("children"in t&&Array.isArray(t.children)){xw(t.children,e);continue}let r=fc(pc(t));r&&e.bodyParts.push(r)}}function Jk(n){let e=Sw().use(bw).use(Ew).parse(n),t={headings:[],bodyParts:[],codeBlocks:[]};return xw(e.children,t),t}function Kk(n,e){let t=Jk(n),r=e.docTitle?.trim()||e.documentId,o=Dw(t.bodyParts),i=[r,...t.headings,o].join(" "),{leadText:s,excerptTruncated:a}=Tw(o);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:jk(t.headings),apiSymbols:Aw(Pw(i,t.codeBlocks)),bodySample:o,leadText:s,excerptTruncated:a}}function Nw(n,e){let t=e.docTitle?.trim()||e.documentId,r=Hk(n);return Gk(n,r,e.documentId)?Vk(r).filter(o=>o.sectionTitle||o.bodyParts.length>0||o.codeBlocks.length>0).map(o=>Yk(o,{...e,docTitle:t})):[Kk(n,{...e,docTitle:t})]}function Ow(n){let e=n.split("/");if(e[0]==="docs"&&(e=e.slice(1)),e.length<2)return null;let t=ny[e[0]];if(t===void 0)return null;let r=e[e.length-1].replace(/\.md$/,"");return e[e.length-1]=r,{documentId:e.join("/"),catalogId:t,docTitle:r}}function Lw(n,e,t){let r=Cw(n,{jsonTitle:e,fileName:t.docTitle});return Nw(n,{...t,docTitle:r})}function Zk(n){return n.getEntries().filter(e=>e.isDirectory||!e.entryName.endsWith(".md")?!1:e.entryName.split("/").every(t=>!t.startsWith(".")))}function Qk(n,e){let t=n.getEntry(e.replace(/\.md$/,".json"));if(t)try{return JSON.parse(t.getData().toString("utf-8")).title?.trim()||void 0}catch{return}}function ex(n){let e=new Xk(n),t=[];for(let r of Zk(e)){let o=Ow(r.entryName);o&&t.push(...Lw(r.getData().toString("utf-8"),Qk(e,r.entryName),o))}return t}async function tx(n){let e=[];async function t(r){let o=await po.promises.readdir(r,{withFileTypes:!0});for(let i of o){if(i.name.startsWith("."))continue;let s=Rn.join(r,i.name);i.isDirectory()?await t(s):i.isFile()&&i.name.endsWith(".md")&&e.push(s)}}return await t(n),e}async function nx(n){let e=n.replace(/\.md$/,".json");try{let t=await po.promises.readFile(e,"utf-8");return JSON.parse(t).title?.trim()||void 0}catch{return}}async function rx(n){let e=[];for(let t of await tx(n)){let r=Rn.relative(n,t).split(Rn.sep).join("/"),o=Ow(r);if(!o)continue;let i=await po.promises.readFile(t,"utf-8");e.push(...Lw(i,await nx(t),o))}return e}async function ox(n){return"docsZipPath"in n?ex(n.docsZipPath):rx(n.docsDir)}async function ix(n,e,t){let r=Rn.join(e,"search.db");return await uw(r,n,async(o,i)=>{await t?.({current:o,total:i,message:`Building search index\u2026 ${o.toLocaleString()} / ${i.toLocaleString()} segments`})}),n.length}function sx(n,e){return{indexVersion:eo,docsZipSha256:n.docsZipSha256,termsHash:n.termsHash,synonymsHash:n.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:n.builtBy}}async function Mw(n){n.lexiconDir&&Hd(n.lexiconDir);try{let e=await ox(n);await n.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await po.promises.mkdir(n.tmpDir,{recursive:!0});let t=await ix(e,n.tmpDir,n.onProgress),r=sx(n,t);return await po.promises.writeFile(Rn.join(n.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await fy(n.tmpDir),r}finally{n.lexiconDir&&Hd(null)}}var Ni=class extends Error{constructor(e){super(e),this.name="NativeDepsError"}};function ax(){let n=oo(),e=oe();return["Documentation search index is not installed yet.","",...Wa(n),`Index directory: ${e}`,"","Try:"," 1. Wait a moment and run the docs command again (postinstall may still be running)"," 2. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 3. Check the log file above for setup errors"].join(`
|
|
1384
|
+
`)}function cx(){let n=oo();return[`Chinese tokenizer (${b()?"jieba-wasm":"@node-rs/jieba"}) failed to load.`,"",`Node.js: ${process.version} (required: >=18)`,"",...Wa(n),"","Try:"," 1. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 2. Use Node.js 18 or newer",b()?" 3. Verify jieba-wasm package is installed (WASM backend for OpenHarmony)":" 3. Configure npm registry/proxy if your network blocks optional platform packages"].join(`
|
|
1385
|
+
`)}function lx(n){let e=oo();return[n,"",...Wa(e)].join(`
|
|
1386
|
+
`)}async function _w(){try{py()}catch(n){throw uy(n)?new Ni(`${ax()}
|
|
1387
1387
|
|
|
1388
|
-
Detail: ${n.message}`):n}try{await
|
|
1388
|
+
Detail: ${n.message}`):n}try{await Dn()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Ni(`${cx()}
|
|
1389
1389
|
|
|
1390
|
-
Detail: ${e}`)}try{await
|
|
1391
|
-
`)}async function
|
|
1392
|
-
`),t=e.findIndex(s=>s.trimStart().startsWith("WindowName"));if(t===-1)return[];let r=[];for(let s=t+1;s<e.length;s++){let a=e[s].trim();if(!a||/^-+$/.test(a)||a.startsWith("Focus window")||a.startsWith("total window"))break;let c=a.split(/\s+/);if(c.length<5)continue;let l=c[0],d=Number(c[1]),h=Number(c[2]),w=Number(c[3]),v=Number(c[4]);Number.isFinite(w)&&Number.isFinite(d)&&Number.isFinite(h)&&r.push({id:w,name:l,pid:h,displayId:d,type:v})}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
|
|
1390
|
+
Detail: ${e}`)}try{await Ri()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Ni(lx(e))}}var wu=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function ux(n){return new Promise(e=>setTimeout(e,n))}async function Hw(n){let e=oo();await $e.promises.mkdir(mo.dirname(e),{recursive:!0}),await $e.promises.appendFile(e,`${new Date().toISOString()} ${n}
|
|
1391
|
+
`)}async function px(){await io({mode:"write"});let n=oe(),e=Xt(),t=await $e.promises.readdir(e);for(let r of t){let o=mo.join(n,r);await $e.promises.rm(o,{force:!0}),await $e.promises.rename(mo.join(e,r),o)}await $e.promises.rm(e,{recursive:!0,force:!0}),await $e.promises.rm(mo.join(n,"orama.dpack"),{force:!0})}async function Fw(n,e,t){e?.start(t),await An({state:"installing",phase:1,phaseLabel:"Installing index",message:t}),await by(n),uo(),e&&(e.text="Documentation index installed.")}async function mx(n,e){try{return await Fw(n,e,"Installing documentation index\u2026"),await vu(e),!0}catch(t){if(vi(t))throw t}try{return await Ey(),uo(),await Fw(n,e,"Retrying documentation index install\u2026"),await vu(e),!0}catch(t){if(vi(t))throw t;let r=t instanceof Error?t.message:String(t);return await Hw(`Bundled index install failed; falling back to local rebuild: ${r}`),!1}}async function fx(n,e,t){let r=In();if(!r)throw new Error("docs.zip not found");let o=Xt();await $e.promises.mkdir(oe(),{recursive:!0}),await $e.promises.rm(o,{recursive:!0,force:!0}),t?.start("Building search index\u2026"),await An({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"}),await Mw({docsZipPath:r,tmpDir:o,docsZipSha256:e,termsHash:Xa(),synonymsHash:Ka(),builtBy:n.builtBy??"doc-init",onProgress:async i=>{t&&(t.text=i.message),await An({state:"indexing",current:i.current,total:i.total,message:i.message})}}),await An({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await px(),uo()}async function vu(n){await An({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function hx(n){let e=await Xd(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await An({state:"done",message:t,error:null})}async function gx(n,e){let t=n instanceof Error?n.message:String(n);throw await An({state:"error",error:t}),await Hw(`ERROR: ${t}`),e?.fail(t),n}async function yx(){let n=oe();await $e.promises.mkdir(n,{recursive:!0});let e=Va();return $e.existsSync(e)||await $e.promises.writeFile(e,"","utf-8"),e}async function wx(){let n=await yx();return dx.lock(n,{stale:1800*1e3})}async function vx(){let n=In(),e=(n?await Ja(n):null)??await Kd();if(!e)throw new Error("docs.zip not found");return e}async function Sx(n,e){let t=await vx(),r=n.force||await Zd(n.force),o=await Qa(n.force);if(!r&&!o&&Ei()){await hx(e);return}!n.force&&Sy(t)&&await mx(t,e)||(await fx(n,t,e),await vu(e))}var Oi=class{static async run(e={}){let t=e.background??!1,o=e.quiet??t?void 0:$w({text:"Checking documentation\u2026",color:"cyan"}),i;try{e.assumeStorageSafe||await io({mode:"write"}),i=await wx(),await Jd(Dy("Starting documentation setup\u2026")),await Sx(e,o)}catch(s){throw i&&await gx(s,o),s}finally{i&&await i()}}};async function bx(n){for(;;){let e=await Za();if(e.state==="done"&&Ei())return;if(e.state==="error")throw new wu("build-failed",e.error??"Documentation setup failed. Try your docs command again in a moment.");n.text=e.message||"Documentation is being prepared\u2026",await ux(500)}}async function jw(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await Oi.run({builtBy:"doc-init",force:e,quiet:!0})}async function Ex(){let n=await Qa()!==null;if(Ei()&&!n)return;let e=$w({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await Ty()){await bx(e),e.succeed("Documentation ready.");return}if(await Zd()){await jw(e),e.succeed("Documentation ready.");return}await jw(e,!0),e.succeed("Documentation ready.")}catch(t){throw e.fail(t.message),t}}async function Li(){await io({mode:"read"}),await Ex(),await _w()}function Px(n){let e=n instanceof Error?n.message:String(n);return/file is not a database|database disk image is malformed|SQLITE_CORRUPT/i.test(e)}var Su=class{async search(e,t,r=20){await Li();try{return await gu(e,t,r)}catch(o){if(!Px(o))throw o;return uo(),await Oi.run({builtBy:"doc-init",force:!0,quiet:!0,assumeStorageSafe:!0}),gu(e,t,r)}}async readDocument(e){return await Li(),yy(e)}},bu=new Su;function Bw(...n){return e=>{if(!n.includes(e))throw new Eu(`Allowed values: ${n.join(", ")}`);return e}}function Dx(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new Eu("Must be a positive integer.");return e}var Tx=Bw("json","default"),Rx=Bw("json","default");function kx(n){let e=n instanceof Error?n.message:String(n);return vi(n)?e:/\b(EACCES|EPERM|ENOSPC|ENOTDIR|ELOOP)\b/.test(e)?"Documentation data directory is unavailable. Check DEVECO_CLI_DATA_DIR and retry.":e}async function Pu(n,e){let t=Date.now();try{let r=await e();return await Uw(n,Date.now()-t,!0,null),r}catch(r){let o=r instanceof Error?r.code??r.name:"UnknownError";throw await Uw(n,Date.now()-t,!1,o),r}}async function Uw(n,e,t,r){await I.track(n,{duration_ms:e,success:t,error_code:r}).catch(()=>{})}function Cu(n){console.error(Ix(kx(n))),process.exitCode=1}var hc=new Cx("docs").description("Search and read HarmonyOS documentation from local docs directory");hc.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",Nx,"all").option("--format <fmt>","Output format (default, json)",Tx,"default").option("--limit <n>","Max number of results",Dx,20).action(async(n,e)=>{let t={event:A.DocOperation,subAction:"search",keywords:n,queryLen:n.join(" ").length,catalog:e.catalog??"all"};try{await Pu(t,async()=>{let r=xx(n),o=e.catalog&&e.catalog!=="all"?e.catalog:void 0,i=await bu.search(r,o,e.limit);e.format==="json"?console.log(JSON.stringify(i,null,2)):Ox(i)})}catch(r){Cu(r)}});hc.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{let e=n.trim(),t={event:A.DocOperation,subAction:"read",documentId:e};try{await Pu(t,async()=>{if(!e)throw new Error("Document ID cannot be empty.");let r=await bu.readDocument(e);console.log(r)})}catch(r){Cu(r)}});hc.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",Rx,"default").action(async n=>{let e={event:A.DocOperation,subAction:"catalog",fmt:n.format??"default"};try{await Pu(e,async()=>{if(await Li(),n.format==="json"){let t=En.map(r=>({name:r,title:sr[r]}));console.log(JSON.stringify(t,null,2))}else for(let t of En)console.log(` ${t.padEnd(20)} ${Ax(sr[t])}`)})}catch(t){Cu(t)}});function xx(n){let e=n.map(r=>r.trim()).filter(Boolean);if(e.length===0)throw new Error("Keywords cannot be empty.");if(e.join(" ").length>pi)throw new Error(`Query exceeds ${pi} characters.`);return e}function Nx(n){if(n==="all")return"all";if(!En.includes(n))throw new Eu(`Invalid catalog "${n}". Allowed: all, ${En.join(", ")}`);return n}function Ox(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 Ww=hc;import{Command as HN}from"commander";import{Command as Gx,InvalidArgumentError as zx,Option as Au}from"commander";import{readFileSync as Mx,unlinkSync as _x}from"fs";import{tmpdir as Fx}from"os";import{join as jx}from"path";var tn=class{constructor(e,t){this.hdcPath=e;this.serial=t}hdcPath;serial;async listWindows(e){let t=await this.fetchDump(),r=Lx(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"];m(`Executing: ${this.hdcPath} ${e.join(" ")}`);let t=await de(this.hdcPath,e);if(t.exitCode!==0)throw new Error(`Failed to query windows: ${(t.stderr||t.stdout).trim()}`);return t.stdout}};function Lx(n){let e=n.split(`
|
|
1392
|
+
`),t=e.findIndex(s=>s.trimStart().startsWith("WindowName"));if(t===-1)return[];let r=[];for(let s=t+1;s<e.length;s++){let a=e[s].trim();if(!a||/^-+$/.test(a)||a.startsWith("Focus window")||a.startsWith("total window"))break;let c=a.split(/\s+/);if(c.length<5)continue;let l=c[0],d=Number(c[1]),h=Number(c[2]),w=Number(c[3]),v=Number(c[4]);Number.isFinite(w)&&Number.isFinite(d)&&Number.isFinite(h)&&r.push({id:w,name:l,pid:h,displayId:d,type:v})}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 Vw(n){if(!(!n||n==="HitTestMode.Default"))return n.startsWith("HitTestMode.")?n.slice(12):n}function Mi(n){if(!(n==null||n==="")){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1}}function Gw(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 zw(n){return n.originalText||void 0}function fo(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 qw(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 w={...o,children:[]};if(a?t.push(w):i.children.push(w),d=w,e>0&&s+1>=e)continue}if(process.env.DEVECO_CLI_DEBUG){let w=o.type?o.id?`${o.type}#${o.id}`:o.type:"#";m(`collapse ${w} depth=${s} -> ${a?"root":c?"collapsed":"emitted"}`)}let h=l?s+1:s;for(let w=o.children.length-1;w>=0;w--)r.push({current:o.children[w],parent:d,depth:h})}return t}function $x(n){let e=Mx(n,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function Hx(n){return n.attributes??{}}function gc(n,e,t){let r=Hx(n),o={id:r.id||void 0,type:r.type||void 0,text:zw(r),bounds:Gw(r.bounds),clickable:Mi(r.clickable)||void 0,longClickable:Mi(r.longClickable)||void 0,scrollable:Mi(r.scrollable)||void 0,checkable:Mi(r.checkable)||void 0,hitTestBehavior:Vw(r.hitTestBehavior),children:[]};return e>0&&t+1>=e||n.children&&(o.children=n.children.map(i=>gc(i,e,t+1))),o}function Ux(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 Error(`Window '${e}' not found. Available windows: ${o||"none"}`)}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 ur=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),m(`Executing: ${this.hdcPath} ${i.join(" ")}`);let s=await de(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=jx(Fx(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,r),$x(r)}finally{await this.cleanupDumpArtifacts(e,r,t)}}async recvDumpFile(e,t,r){let o=["-t",e,"file","recv",t,r];m(`Executing: ${this.hdcPath} ${o.join(" ")}`);let i=await de(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{m(`Removing local dump file: ${t}`),_x(t)}catch(i){m(`Failed to clean local dump file ${t}: ${i.message}`)}let o=["-t",e,"shell","rm","-f",r];m(`Executing: ${this.hdcPath} ${o.join(" ")}`),await de(this.hdcPath,o).catch(i=>{m(`Failed to clean remote dump file ${r}: ${i.message}`)})}async dumpRawNodes(e,t,r){let i=await new tn(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=Ux(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=>gc(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:gc(s,t,0)})}return o}async dumpCollapsedTree(e,t,r,o){return(await this.dumpRawNodes(e,r,o)).flatMap(s=>qw(gc(s,0,0),t))}};var yc={left:"0",right:"1",up:"2",down:"3"};function xe(n,e){let t=Number(n);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function Iu(n,e){n!==void 0&&xe(n,e)}function Yw(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function wc(n,e){if(n!==void 0&&n.length===0)throw new Error(`${e} must not be empty`)}function _i(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 Jw(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function Kw(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 ho(n,e,t,r,o=!0){Yw(n,e),wc(t,"--id"),Iu(n,"x"),Iu(e,"y"),Jw(r),Kw(n!==void 0,!!t,!!r,o)}async function kn(n,e){let r=await new Fr(n).selectDevice(e);if(!r)throw new Error("No device selected. Use `devecocli device list` to see targets.");return r}async function kt(n){let e=await D.new(),t=await kn(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function go(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 tn(n,e).listWindows({all:!0}),c=new ur(n);return Bx(c,e,a,o,i)}async function Bx(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 Error(`Window "${o}" is on display ${i.displayId}. The current command only supports operations on the primary display.`);let s=await n.dumpFullTree(e,0,o,!1);return Vx(s,r)}return Wx(n,e,t,r)}async function Wx(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 fo([c],r))s.push({node:l,displayId:a});if(s.length===0)throw new Error(`Node "${r}" not found.`);if(s.length>1)throw new Error(`Multiple nodes found with id "${r}".`);if(s[0].displayId!==0)throw new Error(`Node "${r}" is on display ${s[0].displayId}. The current command only supports operations on the primary display.`);return Xw(s[0].node,r)}function Vx(n,e){let t=fo(n,e);if(t.length===0)throw new Error(`Node "${e}" not found.`);if(t.length>1)throw new Error(`Multiple nodes found with id "${e}".`);return Xw(t[0],e)}function Xw(n,e){let t=n.bounds;if(!t)throw new Error(`Node "${e}" has no bounds.`);let[r,o,i,s]=t;return{x:Math.ceil((r+i)/2),y:Math.ceil((o+s)/2)}}async function ot(n,e,t){let r=["-t",e,"shell",t.join(" ")];m(`Executing: ${n} ${r.join(" ")}`);let o=await de(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 qx from"ora";function Yx(n){let e=parseInt(n,10);if(!Number.isInteger(e)||e<0||String(e)!==n.trim())throw new zx("depth must be a non-negative integer");return e}function Jx(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 Zw(n,e=0){let t=[],r=" ".repeat(e);for(let o of n)t.push(`${r}${Jx(o)}`),o.children.length>0&&t.push(...Zw(o.children,e+1).split(`
|
|
1393
1393
|
`));return t.join(`
|
|
1394
|
-
`)}function
|
|
1395
|
-
`).trim()}function
|
|
1394
|
+
`)}function Kx(n){if(n.allWindows&&n.window)throw new Error("--all-windows and --window are mutually exclusive.")}function Xx(n,e){let t=fo(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 Zx(n,e){return e.id?Xx(n,e.id):e.format==="json"?JSON.stringify(n,null,2):Zw(n)}async function Qx(n){Kx(n);let e=qx({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let o=await D.new(),i=await kn(o,n.device),s=new ur(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=Zx(t,n);return console.log(r),Buffer.byteLength(r,"utf8")}function eN(n){return{event:A.CommandExecuted,args:["ui","layout",...n.device?["--device"]:[]],mode:n.mode,outputSize:0}}async function tN(n){let e=eN(n),t=Date.now(),r=!0,o=null;try{e.outputSize=await Qx(n)}catch(i){throw r=!1,o=Y(i),i}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await I.track(e,i)}}var Qw=new Gx("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 Au("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(Yx).default(0)).addOption(new Au("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new Au("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async n=>{await tN(n)});import{Command as nN,Option as rN}from"commander";import{yellow as oN}from"colorette";import iN from"ora";var sN=["Id","Name","Pid","DisplayId","Focused"];function aN(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(Ht(sN,t))}async function cN(n){let e=iN({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let r=await D.new(),o=await kn(r,n.device);t=await new tn(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(oN(" No windows found."));return}aN(t,n.format)}function lN(n){let e=[];return n.device&&e.push("--device"),n.format!=="default"&&e.push("--format"),n.all&&e.push("--all"),{event:A.CommandExecuted,args:["ui","window","list",...e]}}async function dN(n){let e=lN(n),t=Date.now(),r=!0,o=null;try{await cN(n)}catch(i){throw r=!1,o=Y(i),i}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await I.track(e,i)}}var Du=new nN("window").description("Manage device windows");Du.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new rN("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async n=>{await dN(n)});import{Command as uN}from"commander";import He from"fs";import it from"path";import{randomUUID as pN}from"crypto";import{green as mN}from"colorette";function fN(n){return{event:A.CommandExecuted,args:["ui","screenshot",...n.device?["--device"]:[]]}}function hN(){return String(Date.now())}function ev(n){let e;try{e=He.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{He.accessSync(n,He.constants.W_OK|He.constants.X_OK)}catch(t){throw new Error(`Screenshot directory is not writable: ${n}`,{cause:t})}}function tv(n,e){try{throw He.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 gN(n){if(!n?.trim())throw new Error("--path is required.");let e=n.trim(),t=it.resolve(e);try{if(He.statSync(t).isDirectory()){ev(t);let o=it.join(t,`screenshot-${hN()}.png`);return tv(o,t),o}}catch(o){if(o.code!=="ENOENT")throw o}if(it.extname(t).toLowerCase()!==".png")throw new Error(`Screenshot path must be an existing directory or a PNG file: ${t}`);let r=it.dirname(t);return ev(r),tv(t,r),t}function nv(n){if(!He.existsSync(n))throw new Error(`Screenshot file was not created: ${n}`);let e=He.statSync(n);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${n}`);let t=He.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 yN(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 wN(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}function vN(n,e){try{He.copyFileSync(n,e,He.constants.COPYFILE_EXCL)}catch(t){throw t.code==="EEXIST"?new Error(`Screenshot file already exists: ${e}`,{cause:t}):t}nv(e)}function SN(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 bN(n){let e=["-t",n.serial,"shell","ls","-l",n.remotePath];m(`Executing: ${n.hdcPath} ${e.join(" ")}`);let t=await de(n.hdcPath,e);return t.exitCode===0?SN(t.stdout):void 0}function EN(n){return[n.stdout,n.stderr].filter(Boolean).join(`
|
|
1395
|
+
`).trim()}function PN(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 CN(n,e){let t=yN(n,e);m(`Executing: ${n.hdcPath} ${t.join(" ")}`);let r=await de(n.hdcPath,t),o=await bN(n);return{created:o!==void 0&&o>0,output:EN(r)}}async function IN(n){let e="";for(let t of[void 0,"png"]){let r=await CN(n,t);if(r.created)return;if(n.display!==void 0&&PN(r.output))throw new Error(`Screenshot was not created on device: ${n.remotePath}.
|
|
1396
1396
|
snapshot_display output:
|
|
1397
1397
|
${r.output}`);r.output&&(e=r.output)}throw new Error(e?`Screenshot was not created on device: ${n.remotePath}.
|
|
1398
1398
|
snapshot_display output:
|
|
1399
|
-
${e}`:`Screenshot was not created on device: ${n.remotePath}.`)}function
|
|
1399
|
+
${e}`:`Screenshot was not created on device: ${n.remotePath}.`)}function rv(n){try{return nv(n),!0}catch{return!1}}function ov(n){let e=[];for(let t of He.readdirSync(n,{withFileTypes:!0})){let r=it.join(n,t.name);if(t.isDirectory()){e.push(...ov(r));continue}t.isFile()&&rv(r)&&e.push(r)}return e}function AN(n,e){let t=it.join(n,it.basename(e));if(rv(t))return t;let r=ov(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}async function Tu(n,e,t){let r=["-t",n.serial,"file","recv",n.remotePath,t];m(`Executing: ${n.hdcPath} ${r.join(" ")}`);let o=await de(n.hdcPath,r);return o.exitCode!==0&&m(`hdc file recv failed: ${o.stderr||o.stdout||`exit code ${o.exitCode}`}`),AN(e,n.remotePath)}async function DN(n){let e=He.mkdtempSync(it.join(it.dirname(n.localPath),".devecocli-screenshot-"));try{let t=await Tu(n,e,it.join(e,it.basename(n.remotePath)))??await Tu(n,e,e)??await Tu(n,e,it.join(e,"screenshot.png"));if(!t)throw new Error(`Screenshot file was not created in ${e}.`);vN(t,n.localPath)}finally{He.rmSync(e,{recursive:!0,force:!0})}}async function TN(n){let e=["-t",n.serial,"shell","rm","-f",n.remotePath];m(`Executing: ${n.hdcPath} ${e.join(" ")}`),await de(n.hdcPath,e)}async function RN(n){try{await IN(n),await DN(n)}finally{await TN(n)}}async function kN(n){let e=fN(n),t=Date.now(),r=!0,o=null;try{let i=gN(n.path),s=n.display!==void 0?wN(n.display):void 0;if(n.device!==void 0&&!n.device.trim())throw new Error("--device must not be empty.");let a=await D.new(),c=await kn(a,n.device),l=`/data/local/tmp/devecocli-${pN()}.png`;await RN({hdcPath:a.hdcPath,serial:c,localPath:i,remotePath:l,display:s}),console.log(mN(`Screenshot saved to ${i}`))}catch(i){throw r=!1,o=Y(i),i}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await I.track(e,i)}}var iv=new uN("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(kN);import{Command as xn}from"commander";function Nn(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:A.CommandExecuted,args:["ui",n,...t]}}function xN(n){let t=`"$(printf '%s' '${Buffer.from(n,"utf8").toString("base64")}' | base64 -d)"`;return m(`escapeShellText: ${n} -> ${t}`),t}async function On(n,e,t,r){let o=new gt;o.start(n);let i=Date.now(),s=!0,a=null;try{await r(o)}catch(c){throw o.stop(),s=!1,a=Y(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 NN(n,e,t){let r=Nn("click",t);await On("Executing click...","click failed",r,async o=>{ho(n,e,t.id,t.window);let{hdcPath:i,deviceId:s}=await kt(t.device),{x:a,y:c}=await go(i,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await ot(i,s,["uitest","uiInput","click",String(a),String(c)]),o.succeed(`click at (${a}, ${c})`)})}async function ON(n,e,t){let r=Nn("doubleclick",t);await On("Executing doubleclick...","doubleclick failed",r,async o=>{ho(n,e,t.id,t.window);let{hdcPath:i,deviceId:s}=await kt(t.device),{x:a,y:c}=await go(i,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await ot(i,s,["uitest","uiInput","doubleClick",String(a),String(c)]),o.succeed(`doubleclick at (${a}, ${c})`)})}async function LN(n,e,t){let r=Nn("longclick",t);await On("Executing longclick...","longclick failed",r,async o=>{ho(n,e,t.id,t.window);let{hdcPath:i,deviceId:s}=await kt(t.device),{x:a,y:c}=await go(i,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await ot(i,s,["uitest","uiInput","longClick",String(a),String(c)]),o.succeed(`longclick at (${a}, ${c})`)})}async function MN(n,e,t,r,o){let i=Nn("swipe",o);await On("Executing swipe...","swipe failed",i,async s=>{xe(n,"x1"),xe(e,"y1"),xe(t,"x2"),xe(r,"y2");let a=_i(o.speed),{hdcPath:c,deviceId:l}=await kt(o.device),d=["uitest","uiInput","swipe",n,e,t,r];a&&d.push(a),await ot(c,l,d),s.succeed(`swipe from (${n}, ${e}) to (${t}, ${r})`)})}async function _N(n,e,t,r,o){let i=Nn("fling",o);await On("Executing fling...","fling failed",i,async s=>{xe(n,"x1"),xe(e,"y1"),xe(t,"x2"),xe(r,"y2");let a=_i(o.speed),{hdcPath:c,deviceId:l}=await kt(o.device),d=["uitest","uiInput","fling",n,e,t,r];a&&d.push(a),await ot(c,l,d),s.succeed(`fling from (${n}, ${e}) to (${t}, ${r})`)})}async function FN(n,e,t,r,o){let i=Nn("drag",o);await On("Executing drag...","drag failed",i,async s=>{xe(n,"x1"),xe(e,"y1"),xe(t,"x2"),xe(r,"y2");let a=_i(o.speed),{hdcPath:c,deviceId:l}=await kt(o.device),d=["uitest","uiInput","drag",n,e,t,r];a&&d.push(a),await ot(c,l,d),s.succeed(`drag from (${n}, ${e}) to (${t}, ${r})`)})}async function jN(n,e){let t=Nn("dircfling",e);await On("Executing dircfling...","dircfling failed",t,async r=>{let o=yc[n];if(o===void 0)throw new Error(`Invalid direction "${n}". Valid values: ${Object.keys(yc).join(", ")}`);let{hdcPath:i,deviceId:s}=await kt(e.device);await ot(i,s,["uitest","uiInput","dircFling",o]),r.succeed(`dircfling ${n}`)})}async function $N(n,e,t,r){let o=Nn("text",r);await On("Executing text input...","input failed",o,async i=>{ho(e,t,r.id,r.window,!1),wc(n,"text");let{hdcPath:s,deviceId:a}=await kt(r.device),c=xN(n);if(e!==void 0)await ot(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 go(s,a,void 0,void 0,r.id,r.window);await ot(s,a,["uitest","uiInput","inputText",`${l}`,`${d}`,c]),i.succeed(`input ${n} at (${l}, ${d})`)}else await ot(s,a,["uitest","uiInput","text",c]),i.succeed(`input ${n}`)})}var sv=new xn("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(NN),av=new xn("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(ON),cv=new xn("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(LN),lv=new xn("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(MN),dv=new xn("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(_N),uv=new xn("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(FN),pv=new xn("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action(jN),mv=new xn("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($N);var st=new HN("ui").description("Inspect and interact with UI on a connected device");st.addCommand(Qw);st.addCommand(Du);st.addCommand(iv);st.addCommand(sv);st.addCommand(av);st.addCommand(cv);st.addCommand(lv);st.addCommand(dv);st.addCommand(uv);st.addCommand(pv);st.addCommand(mv);var fv=st;import{Command as IL}from"commander";import{execa as cO}from"execa";import nn from"fs";import*as Nu from"os";import*as G from"path";var UN=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),BN=/\r/g,WN=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,VN=/^<+\s*/,GN=/\s*>+$/,zN=[/^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\.$/];function Ru(n){if(!n)return"";let e=n.replace(UN,"").replace(BN,`
|
|
1400
1400
|
`).split(`
|
|
1401
|
-
`).map(t=>t.trimEnd()).filter(t=>
|
|
1401
|
+
`).map(t=>t.trimEnd()).filter(t=>YN(t));return e.length>0?`${e.join(`
|
|
1402
1402
|
`)}
|
|
1403
|
-
`:""}function
|
|
1403
|
+
`:""}function wv(n){let e=Ru(n).trim();if(!e)return{jsonText:void 0,diagnostics:""};if(vv(e))return{jsonText:e,diagnostics:""};let t=JN(e);if(!t)return{jsonText:void 0,diagnostics:`${e}
|
|
1404
1404
|
`};let r=[e.slice(0,t.start).trim(),e.slice(t.end).trim()].filter(Boolean).join(`
|
|
1405
1405
|
`);return{jsonText:e.slice(t.start,t.end),diagnostics:r?`${r}
|
|
1406
|
-
`:""}}function
|
|
1407
|
-
${
|
|
1408
|
-
`;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[
|
|
1406
|
+
`:""}}function qN(n){return WN.test(n.trim())}function YN(n){let e=n.trim();return!!e&&!qN(e)&&!zN.some(t=>t.test(e))}function vv(n){try{return JSON.parse(n),!0}catch{return!1}}function JN(n){for(let e=0;e<n.length;e++){if(n[e]!=="["&&n[e]!=="{")continue;let t=KN(n,e);if(t)return t}}function KN(n,e){for(let t=n.length;t>e;t--){let r=n[t-1];if(r!=="]"&&r!=="}")continue;let o=n.slice(e,t);if(vv(o))return{start:e,end:t}}}var hv=["Error","Warning","Suggestion","Info","Off","Unknown"];function Sv(n){let e=ku(n);return{issues:eO(e),summary:XN(n,e)}}function XN(n,e){let t=nO(e);return{filesChecked:rO(n).size,issues:e.length,errors:t.get("Error")??0,warnings:t.get("Warning")??0,suggestions:t.get("Suggestion")??0}}function ku(n,e=""){if(Array.isArray(n))return n.flatMap(i=>ku(i,e));if(!bv(n))return[];let t=Fi(n,["filePath","file","path"])??e,r=ZN(n,t);if(r.length>0)return r;let o=QN(n,t);return o?[o]:[]}function ZN(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=>ku(s,e));if(i.length>0)return i}}return[]}function QN(n,e){let t=Fi(n,["message","description","desc","detail"])??"",r=aO(Fi(n,["rule","ruleId","ruleName"])),o=iO(n,["severity","level"]),i=Fi(n,["filePath","file","path"])??e;if(!(!t&&!r&&o==="Unknown"))return{file:i,line:yv(n,["line","reportLine"]),column:yv(n,["column","reportColumn"]),severity:o,rule:r,message:t}}function eO(n){return[...n].sort((e,t)=>{let r=gv(e.severity)-gv(t.severity);return r===0?tO(e,t):r})}function tO(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 nO(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 rO(n){let e=new Set;return xu(e,n,""),e}function xu(n,e,t){if(Array.isArray(e)){for(let o of e)xu(n,o,t);return}if(!bv(e))return;let r=Fi(e,["filePath","file","path"])??t;r&&n.add(r),oO(n,e,r)}function oO(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)xu(n,s,t)}}function iO(n,e){for(let t of e){let r=n[t];if(typeof r=="string"||typeof r=="number")return sO(r)}return"Unknown"}function sO(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 aO(n){let e=n?.normalize("NFKC").trim();if(e)return e.replace(VN,"").replace(GN,"").toLowerCase()}function gv(n){let e=hv.indexOf(n);return e===-1?hv.length:e}function Fi(n,e){for(let t of e){let r=n[t];if(typeof r=="string")return r}}function yv(n,e){for(let t of e){let r=n[t];if(typeof r=="number")return r}}function bv(n){return typeof n=="object"&&n!==null}var Ev="deveco-codelinter-",Pv=[".ets",".ts",".js"],ji=class n{resolution;cwd;constructor(e,t){this.resolution=n.resolveWithToolProvider(e),this.cwd=t}static resolveProjectRoot(e){try{return J.discover(e).rootDir}catch{return e}}async check(e){let t=nn.mkdtempSync(G.join(Nu.tmpdir(),Ev)),r=G.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),c=await this.run(a),l=wv(c.stdout),d=l.diagnostics+Ru(c.stderr);try{let h=this.readJsonReport(r,l.jsonText);return{exitCode:c.exitCode,diagnostics:d,report:Sv(h)}}catch(h){return{exitCode:c.exitCode,diagnostics:d,reportError:h}}}finally{this.removeTempDir(t)}}resolveLintTarget(e,t){let r=e?G.resolve(this.cwd,e):t,o=this.resolveRealPath(r,"Lint path"),i=nn.statSync(o);if(!i.isFile()&&!i.isDirectory())throw new Error(`Lint path must be a file or directory: ${r}`);if(i.isFile()){let a=G.extname(o).toLowerCase();if(!Pv.some(l=>l===a))throw new Error(`Unsupported lint file extension "${a||"<none>"}": ${o}. Supported extensions: ${Pv.join(", ")}.`)}let s=this.discoverProjectRoot(o,i.isDirectory());if(e!==void 0&&s===void 0)throw new Error(`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?G.resolve(this.cwd,e):G.join(t.projectRoot??this.cwd,"code-linter.json5"),o=this.resolveRealPath(r,"`--config-path`");if(!nn.statSync(o).isFile())throw new Error(`--config-path must point to a file: ${r}`);if(t.projectRoot){let i=this.discoverProjectRoot(o,!1);if(i===void 0||G.relative(t.projectRoot,i)!=="")throw new Error(`\`--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:G.dirname(e);try{return nn.realpathSync(J.discover(r).rootDir)}catch{return}}resolveRealPath(e,t){try{return nn.realpathSync(e)}catch(r){throw new Error(`${t} does not exist or cannot be resolved: ${e}`,{cause:r})}}buildNativeArgs(e,t,r,o){let i=["--config",r];return e.fix&&i.push("--fix"),e.incremental&&i.push("--incremental"),i.push("--product",e.product,"--format","json","--output",o,t),i}async run(e){let t=[...this.resolution.argsPrefix,...e],r=this.resolution.workingDirectory??this.cwd;this.prepareRuntimeDirectories(),m(`Executing: ${this.resolution.command} ${t.join(" ")}`),m(`[CodelinterAdapter] Working directory: ${r}`);let o=await cO(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??[])try{nn.mkdirSync(e,{recursive:!0})}catch(t){m(`[CodelinterAdapter] Skipping runtime directory ${e}: ${t.message}`)}}readJsonReport(e,t){let o=(nn.existsSync(e)?nn.readFileSync(e,"utf-8").trim():void 0)||t?.trim();if(!o)throw new Error("Native JSON report was not generated.");return JSON.parse(o)}removeTempDir(e){let t=G.resolve(e),r=G.resolve(Nu.tmpdir());!(t.startsWith(`${r}${G.sep}`)||t===r)||!G.basename(t).startsWith(Ev)||nn.rmSync(t,{recursive:!0,force:!0})}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={command:e.nodePath,argsPrefix:[o,i],env:{...process.env,PATH:[...s,process.env.PATH||""].join(G.delimiter),DEVECO_SDK_HOME:i}};return t==="command-line-tools"&&(c.workingDirectory=r,c.runtimeDirectories=[n.getResultDirectory(o)]),m(`[CodelinterAdapter] Selected ${a} entry: ${o}`),c}static getPathEntries(e,t){let r=[G.dirname(e.nodePath)];return t==="ide"&&e.javaPath&&r.unshift(G.dirname(e.javaPath)),r}static getResultDirectory(e){return G.resolve(e,"..","linter","result")}static getSource(e){return e.sourceType==="studio"?"ide":"command-line-tools"}};import{red as Sc,yellow as vO}from"colorette";import{Argument as SO,Command as bO,InvalidArgumentError as Mn}from"commander";import Hi from"fs";import*as Ue from"path";import*as $i from"path";var Cv="n/a",Iv=/\\/g,lO=/\|/g,dO=/\r?\n/g;function Av(n,e){if(n.issues.length===0)return`No defects found.
|
|
1407
|
+
${Ou(n.summary)}
|
|
1408
|
+
`;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[pO(t),Ou(n.summary)];return e!==void 0&&t.length<n.issues.length&&r.push(uO(n.issues.length,t.length)),`${r.join(`
|
|
1409
1409
|
`)}
|
|
1410
|
-
`}function
|
|
1411
|
-
`)}function
|
|
1412
|
-
`)}function
|
|
1413
|
-
`}function
|
|
1414
|
-
`)}function
|
|
1415
|
-
`))}}var
|
|
1416
|
-
`?(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
|
|
1410
|
+
`}function Dv(n,e){return[Ou(n.summary),`Full report: ${Lu(e)}`,""].join(`
|
|
1411
|
+
`)}function Tv(n){let e=["# CodeLinter report",""];return n.issues.length===0?e.push("No defects found.",""):e.push(...mO(n.issues),""),e.push("## Summary","",...hO(n.summary),""),e.join(`
|
|
1412
|
+
`)}function Rv(n){return`${JSON.stringify(n,null,2)}
|
|
1413
|
+
`}function Ou(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 uO(n,e){return`Showing ${at(e)} of ${at(n)} issues. Use --output-path <path> to write all results.`}function pO(n){let e=["No","File","Line","Column","Severity","Rule","Message"],t=n.map((r,o)=>({cells:yO(r,o+1)}));return["CodeLinter report","",Ht(e,t)].join(`
|
|
1414
|
+
`)}function mO(n){let e=["| No | File | Line | Column | Severity | Rule | Message |","| ---: | --- | ---: | ---: | --- | --- | --- |"];for(let[t,r]of n.entries())e.push(fO(r,t+1));return e}function fO(n,e){return`| ${[String(e),Lu(Ln(n.file)),vc(n.line),vc(n.column),Ln(n.severity),Ln(n.rule),Ln(n.message)].map(gO).join(" | ")} |`}function hO(n){return[`- Issues: ${at(n.issues)}`,`- Errors: ${at(n.errors)}`,`- Warnings: ${at(n.warnings)}`,`- Suggestions: ${at(n.suggestions)}`,`- Files checked: ${at(n.filesChecked)}`]}function gO(n){return n.replace(Iv,"\\\\").replace(lO,"\\|").replace(dO,"<br>")}function yO(n,e){return[String(e),Lu(Ln(wO(n.file))),vc(n.line),vc(n.column),Ln(n.severity),Ln(n.rule),Ln(n.message)]}function wO(n){if(!$i.isAbsolute(n))return n;let e=$i.relative(process.cwd(),n);return!e||e.startsWith("..")||$i.isAbsolute(e)?n:e}function Lu(n){return n.replace(Iv,"/")}function Ln(n){let e=n?.trim();return e||Cv}function vc(n){return n===void 0?Cv:String(n)}function at(n){return n.toLocaleString("en-US")}var Mu=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function EO(n){let e=n;return n instanceof Mu?n.code:e.code??e.name??"UnknownError"}async function kv(n,e,t,r){let o=await ko(process.pid),i=o!==null?It(Number(o)*1024):"unknown",s={event:A.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 PO=/^-?\d+$/;function _u(){return new bO("lint").description("Run DevEco Code Linter checks for TS/ArkTS code").addArgument(new SO("[path]","File or directory to lint").argParser(TO)).option("--fix","Auto-fix fixable code issues").option("--incremental","Only check uncommitted files").option("--config-path <path>","Path to lint configuration file",IO).option("--product <product>","Product name defined in build-profile.json5",AO,"default").option("--format <format>","Report format (choices: default, json)",CO,"default").option("--output-path <path>","Complete report file or directory",DO).option("--limit <number>","Maximum terminal issues to display when --output-path is omitted",RO).action(async(n,e)=>{await kO(n,e)})}function CO(n){if(n==="default"||n==="json")return n;throw new Mn("Invalid --format. Expected one of: default, json.")}function IO(n){Fu(n,"--config-path");let e=Ue.extname(n).toLowerCase();if(e!==".json"&&e!==".json5")throw new Mn("`--config-path` must point to a .json or .json5 file.");return n}function AO(n){return xv(n,"product"),n}function DO(n){return Fu(n,"--output-path"),n}function TO(n){return Fu(n,"path"),n}function RO(n){if(xv(n,"limit"),!PO.test(n))throw new Mn("`--limit` must be a positive integer.");let e=Number.parseInt(n,10);if(e<=0||!Number.isSafeInteger(e))throw new Mn("`--limit` must be an integer greater than 0.");return e}function xv(n,e){if(n.trim().length===0||Lv(n))throw new Mn(`Invalid --${e} value.`)}function Fu(n,e){let t=`\`${e}\``;if(n.length===0||Lv(n))throw new Mn(`${t} must be a non-empty path without control characters.`)}async function kO(n,e){let t=Date.now(),r=["check","lint"];try{let o=process.cwd(),i=MO(e.outputPath,e.format,o);e.fix&&console.warn(vO("Running codelinter with --fix. Ensure your project source is trusted."));let s=await xO(n,e,o);HO(s.diagnostics),process.exitCode=OO(s,i,e.format,e.limit,o),await kv(t,!0,null,r)}catch(o){let i=EO(o);throw await kv(t,!1,i,r),o}}async function xO(n,e,t){let r=await D.new(),o=new ji(r,t);return NO(o,{lintPath:n,configPath:e.configPath,product:e.product,fix:e.fix,incremental:e.incremental})}async function NO(n,e){let t=new gt;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 OO(n,e,t,r,o){if(!n.report)return console.error(Sc("Failed to generate Code Linter report.")),console.error(Sc(n.reportError?.message??"Native JSON report was not generated.")),n.exitCode===0?1:n.exitCode;try{if(e){LO(e,t,n.report);let i=Ov(e,o);process.stdout.write(Dv(n.report,i))}else process.stdout.write(Av(n.report,r));return n.exitCode}catch(i){return console.error(Sc("Failed to generate Code Linter report.")),console.error(Sc(i.message)),n.exitCode===0?1:n.exitCode}}function LO(n,e,t){Hi.mkdirSync(Ue.dirname(n),{recursive:!0});let r=e==="json"?Rv(t):Tv(t);try{Hi.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 MO(n,e,t){if(!n)return;let r=jO(n,t),o=FO(n,r),i=o?Ue.join(r,$O(e)):r;if(o||_O(n,e),Hi.existsSync(i))throw new Mn(`Output file already exists: ${Ov(i,t)}`);return i}function _O(n,e){let t=Nv(e);if(Ue.extname(n).toLowerCase()!==t)throw new Mn(`--output-path must use the ${t} extension for --format ${e}.`)}function FO(n,e){return Hi.existsSync(e)?Hi.statSync(e).isDirectory():n.endsWith("/")||n.endsWith("\\")||Ue.extname(n)===""}function jO(n,e){return Ue.resolve(e,n)}function $O(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}${Nv(n)}`}function Nv(n){return n==="json"?".json":".md"}function Ov(n,e){let t=Ue.relative(e,n);return t&&!t.startsWith("..")&&!Ue.isAbsolute(t)?t:n}function HO(n){n&&process.stderr.write(n)}function Lv(n){for(let e of n){let t=e.charCodeAt(0);if(t<=31||t===127)return!0}return!1}import{Command as UO,InvalidArgumentError as jv}from"commander";import*as z from"path";import*as ju from"os";import{readdirSync as BO,existsSync as bc,readFileSync as WO,unlinkSync as VO,copyFileSync as $v,writeFileSync as Hv}from"fs";import{execa as GO}from"execa";import{cyan as be,yellow as Uv}from"colorette";import zO from"ora";var Mv=["default","csv","json"];function Bv(n){if(Mv.includes(n))return n;throw new jv(`--format must be one of: ${Mv.join(", ")} (got "${n}")`)}function qO(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new jv(`--limit must be a positive integer (got "${n}")`);return e}function YO(n){return[...n].sort((e,t)=>{let r=_v(e),o=_v(t);return r.apiVersion-o.apiVersion||r.suffix.localeCompare(o.suffix)})}function _v(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 Wv(n){let t=BO(n,{withFileTypes:!0}).filter(r=>r.isFile()&&r.name.toLowerCase().endsWith(".json")).map(r=>r.name.slice(0,-5));return YO(t)}function JO(n){let e=process.argv;for(let t=0;t<e.length;t+=1){let r=e[t],o;if(r==="--format"&&t+1<e.length?o=e[t+1]:r.startsWith("--format=")&&(o=r.slice(9)),o!==void 0){let i=Bv(o);return i==="default"?"csv":i}}return n}async function KO(n){let e=await D.new(),{apiChangeDir:t}=e.getApiscanPaths();m(be(`[compat:versions] apiChangeDir: "${t}"`));let r=Wv(t);if(n==="json")console.log(JSON.stringify({versions:r,count:r.length},null,2));else{if(r.length===0){console.log("No SDK versions available.");return}console.log(r.join(`
|
|
1415
|
+
`))}}var Fv=new Set([".ets",".c",".cpp"]);function XO(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 Error(`Module ${r.map(s=>`"${s}"`).join(", ")} ${i} not defined in build-profile.json5. Available modules: ${o}.`)}function ZO(n){for(let e of n){let t=z.resolve(e);if(!bc(t))throw new Error(`File "${e}" does not exist.`);let r=z.extname(t).toLowerCase();if(!Fv.has(r)){let o=Array.from(Fv).join(", ");throw new Error(`Unsupported file extension "${r}" for "${e}". Supported: ${o}.`)}}}function QO(n){let e=[],t=[];for(let r of n)z.extname(r).toLowerCase()===".ets"?e.push(r):t.push(r);return{arkTs:e,cpp:t}}function eL(n){let e=[],t=[],r="",o=!1,i=0;for(;i<n.length;){let s=n[i];o?{field:r,inQuotes:o,i}=tL(n,i,s,r,o):s==='"'?(o=!0,i+=1):s===","?(t.push(r),r="",i+=1):s===`
|
|
1416
|
+
`?(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 tL(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 nL(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 rL(n){let e=WO(n,"utf8"),t=e.startsWith("\uFEFF")?e.slice(1):e,r=eL(t);if(r.length<2)return[];let[o,...i]=r;return nL(o,i)}function oL(n,e){let t=n.match(/CSV saved to:\s*([^\r\n]+\.csv)/);if(!t)return null;let r=t[1].trim();return z.isAbsolute(r)?r:z.join(e,r)}function iL(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(be("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 sL(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(be(`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(Uv(` ... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function aL(n,e){let t=n.slice(0,e),r=n.length-t.length;console.log(),console.log(JSON.stringify({count:n.length,records:t},null,2)),r>0&&console.log(Uv(`... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function cL(n,e){let t=[];for(let r of e){let o=n.profile.modules.find(i=>i.name===r);if(!o)throw new Error(`Module "${r}" not found in build-profile.json5.`);t.push(z.resolve(n.rootDir,o.srcPath))}return t}function lL(n,e,t,r){if(!r.sourceVersion||!r.targetVersion)throw new Error("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}=QO(e),a=d=>z.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=cL(t,r.modules);o.push("--modulePaths",i.join(","))}else o.push("--projectPath",t.rootDir);return o.push("--outputPath",ju.tmpdir()),o}async function dL(n,e){let t=z.dirname(e[0]);try{let o=(await GO(n.nodePath,e,{cwd:t,stdin:"ignore",stdout:"pipe",stderr:"inherit"})).stdout;return process.env.DEVECO_CLI_DEBUG&&(console.log(be("[compat:check] === scan stdout ===")),process.stdout.write(o),o.endsWith(`
|
|
1417
1417
|
`)||process.stdout.write(`
|
|
1418
|
-
`),console.log(
|
|
1418
|
+
`),console.log(be("[compat:check] === end stdout ==="))),o}catch(r){let o=r;process.env.DEVECO_CLI_DEBUG&&o.stdout&&(console.log(be("[compat:check] === scan stdout (on error) ===")),process.stdout.write(o.stdout),o.stdout.endsWith(`
|
|
1419
1419
|
`)||process.stdout.write(`
|
|
1420
|
-
`),console.log(
|
|
1421
|
-
${o.stderr}`:""));throw o.stdout&&(i.stdout=o.stdout),i}}function
|
|
1422
|
-
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 Error(`--target-version "${n.targetVersion}" must be later than --source-version "${n.sourceVersion}". Run \`devecocli compat versions\` to see the available order.`)}}function
|
|
1423
|
-
`}function wO(n,e,t,r){r===".csv"?Lv(n,t):Ov(t,jv(e),"utf8"),m(Ee(`[compat:check] saved report: "${t}"`))}function vO(n,e,t,r){if(r==="json"){let i=z.basename(n,".csv"),s=z.join(t,`${i}.json`);return Ov(s,jv(e),"utf8"),m(Ee(`[compat:check] saved report: "${s}"`)),s}let o=z.join(t,z.basename(n));return Lv(n,o),m(Ee(`[compat:check] saved report: "${o}"`)),o}async function SO(n,e){let t=new Me(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 Error(`hvigorw compileNative failed (module=${r??"<project>"}): `+o.message,{cause:o})}}async function bO(n,e){lO(n,e);let t=K.discover(process.cwd());e.modules&&e.modules.length>0&&JL(t,e.modules),n.length>0&&KL(n);let r=await A.new(),{apiChangeDir:o,scriptPath:i}=r.getApiscanPaths();m(Ee(`[compat:check] script: "${i}"`));let s=Fv(o);dO(e,s),e.outputPath&&m(Ee(`[compat:check] outputPath: "${e.outputPath}"`));let a=gO(e.outputPath,e.format);return m(Ee(`[compat:check] outputTarget: ${a.kind}`)),yO(a),{project:t,scriptPath:i,target:a,toolProvider:r}}async function EO(n,e){let{project:t,scriptPath:r,target:o,toolProvider:i}=await bO(n,e),s=VL({text:"Running compatibility check...",color:"cyan"}).start();try{await SO(i,e);let a=aO(r,n,t,e);pO(r,a);let c=await cO(i,a),l=nO(c,_u.tmpdir());if(!l)throw new Error("Scanner output format unexpected: missing report path.");m(Ee(`[compat:check] tmp csv: "${l}"`));let d=tO(l),h=null;if(o.kind==="file")wO(l,d,o.filePath,o.ext),h=o.filePath;else if(o.kind==="dir")h=vO(l,d,o.dirPath,e.format);else if(o.kind!=="none")throw new Error(`Unexpected output target kind: ${o.kind}`);mO(l),s.stop(),uO(d,h,e.format,e.limit,o.kind)}catch(a){throw s.fail("Compatibility check failed"),a}}var Fu=new $L("compat").description("Compatibility checking utilities.");Fu.description("Check source code compatibility against a target SDK version. By default, performs a project-level scan; pass positional `files...` for file-level scanning; pass `--modules` for module-level scanning.").arguments("[files...]").option("--source-version <version>","Current project SDK version (required; use `compat versions` to list available versions). On zsh, quote the value because version strings contain parentheses; run `compat versions` first to copy a real example.").option("--target-version <version>","Target SDK version (required; use `compat versions` to list available versions). On zsh, quote the value because version strings contain parentheses; run `compat versions` first to copy a real example.").option("--modules <modules...>","Modules to check (default: all modules in the project). Mutually exclusive with positional file arguments.").option("--format <format>",'Output format: "json" or "default" (text) for console; "csv", "json", or "default" for file output (--output-path). "csv" requires --output-path.',_v,"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)",GL,100).action(async(n,e)=>{await EO(n,e)});Fu.command("versions").description("List all available target SDK versions for compatibility checking").action(async()=>{let n=zL("csv");await YL(n)});var $v=Fu;var Hv=new PO("check").description("Run DevEco project checks").addCommand(Ou());b()||Hv.addCommand($v);var Bv=Hv;import{Command as R_}from"commander";import{green as sp,red as x_}from"colorette";import ap from"fs";import TS from"path";import N_ from"json5";import{readFileSync as KO}from"fs";import{join as CO}from"path";var ie={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"},We={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:CO(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},Pe={SUCCESS_MARKER:'"code":0',SQUARE_BRACKETS:"[]",OPENPROXY_BLOCKED_URL:"Openproxy_Blocked_URL_list",CERT_LIMIT_CODE:"205389872",USER_NOT_HARMONY_CODE:"205389904",DEVICE_EXCEEDS_LIMIT_CODE:"205389859",DEVICE_NAME_REPEAT_CODE:"205389857",PROVISION_EXCEEDS_LIMIT_CODE:"205389938",PROVISION_NAME_REPEAT_CODE:"205389830"},bt={FORBIDDEN:403,UNAUTHORIZED:401},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."},ne={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.",JAVA_PLATFORM_UNSUPPORTED:"Java environment not found (Windows/macOS/Linux only).",JAVA_REQUIRED:"Java runtime is required to run hvigor.Set JAVA_HOME or add Java to PATH.",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 Sc(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function ju(n){let e=n.replace(We.TEAM_ID_INVALID_CHARS,"");return`${We.CERT_NAME_PREFIX}${e}.cer`}function go(n,e,t){if(n===bt.FORBIDDEN)return e===Pe.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN);if(n===bt.UNAUTHORIZED)return new Error(E.ERR_UNAUTHORIZED);if(t.includes(Pe.USER_NOT_HARMONY_CODE))return new Error(E.ERR_USER_NOT_HARMONY);if(t.includes(Pe.CERT_LIMIT_CODE))return new Error(E.ERR_CERT_LIMIT_REACHED);let r=IO(t);return new Error(r??E.ERR_DOWNLOAD_CER)}function IO(n){let e=Uv(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?Uv(t):t;if(r&&typeof r=="object"){let o=r.msg;if(typeof o=="string"&&o.trim()!=="")return o}return null}function Uv(n){try{return JSON.parse(n)}catch{return null}}function $u(n){return JSON.parse(n)}async function Wv(n){let e=`${ie.BASE_URL}${ie.CERT_LIST_PATH}`,t=await O.postAllowFailure(e,{headers:Sc(n)});if(t.statusCode!==200)throw go(t.statusCode,t.statusText,t.data);return $u(t.data)?.certList??[]}async function bc(n,e){return(await Wv(n)).find(r=>r.certName===e)??null}async function Hu(n,e){let t=`${ie.BASE_URL}${ie.CERT_DELETE_PATH}`,r=await O.deleteAllowFailure(t,{headers:Sc(n),params:{certIds:[e]}});if(r.statusCode!==200)throw go(r.statusCode,r.statusText,r.data);return $u(r.data)?.ret?.code===0}async function Bu(n,e,t){let r=`${ie.BASE_URL}${ie.CERT_ADD_PATH}`,o={csr:e,certName:t,certType:We.CERT_TYPE_DEBUG},i=await O.postAllowFailure(r,{headers:Sc(n),params:o});if(i.statusCode!==200)throw go(i.statusCode,i.statusText,i.data);if(!i.data.includes(Pe.SUCCESS_MARKER))throw go(void 0,i.statusText,i.data)}async function Uu(n,e){let t=`${ie.BASE_URL}${ie.CERT_DOWNLOAD_URL_PATH}`,r=await O.postAllowFailure(t,{headers:Sc(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw go(r.statusCode,r.statusText,r.data);return $u(r.data)?.urlsInfo?.[0]?.newUrl??null}import{mkdirSync as AO,writeFileSync as DO,existsSync as TO}from"fs";import{dirname as kO}from"path";async function Hi(n,e){let{statusCode:t,statusText:r,buffer:o}=await O.getBinaryAllowFailure(n,{timeout:We.DOWNLOAD_CONNECT_TIMEOUT_MS});if(t!==200)throw t===bt.FORBIDDEN&&r===Pe.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_DOWNLOAD_CER);let i=kO(e);TO(i)||AO(i,{recursive:!0}),DO(e,o)}import zO from"fs/promises";import{readFileSync as YO}from"fs";import Ec from"path";import qv from"crypto";import RO from"os";import Bi from"fs/promises";var zv={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},Vv=["ECC","RSA"],Gv=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],xO={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},NO=8,Wu=64,LO=/[\\:*?"<>|=-]/g,Et={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function OO(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>Wu)throw new Error(`The length of keyAlias cannot exceed ${Wu}`);if(!Vv.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${Vv.join(" / ")}`);let e=xO[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function MO(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(!Gv.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${Gv.join(" / ")}`)}function _O(n){return qv.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function FO(n){let e=n?.trim()??"";return e&&e.replace(LO,"_").slice(0,Wu)||Et.productName}async function Yv(){let n=await A.new(),e=n.javaPath;if(!e&&!b())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=b()?"hap-sign-tool":"hap-sign-tool.jar",o=Ec.join(t,"default","openharmony","toolchains","lib",r);try{await Bi.access(o)}catch(i){throw new Error(`${r} not found: ${o}`,{cause:i})}return{javaPath:e,toolPath:o}}async function jO(n){let{javaPath:e,toolPath:t}=await Yv(),r=[zv.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=>["-keyPwd","-keystorePwd"].includes(i)?`${i} ******`:i);return f.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),b()?[t,...r]:[e,"-jar",t,...r]}async function $O(n){let{javaPath:e,toolPath:t}=await Yv(),r=[zv.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=>["-keyPwd","-keystorePwd"].includes(i)?`${i} ******`:i);return f.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),b()?[t,...r]:[e,"-jar",t,...r]}async function HO(n){f.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),OO(n);let e=await jO(n),t=await zn(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 BO(n){f.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),MO(n);let e=await $O(n),t=await zn(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 UO(n=NO){return qv.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function WO(){let n=RO.homedir();try{await Bi.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=Ec.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 f.info(`\u7B7E\u540D\u914D\u7F6E\u76EE\u5F55\u5C31\u7EEA\uFF1A${e}`),e}async function De(n,e,t){let r=FO(n),o=Ec.basename(e),i=_O(e),s=`${r}_${o}_${i}=.${t}`,a=await WO();return Ec.join(a,s)}function VO(n){let e;try{e=K.discover(n).rootDir}catch(t){throw new Error(`Current directory ${n} is not a valid project root`,{cause:t})}return e}async function GO(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 qO(n){try{await Bi.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function Vu(n,e,t){let r=process.cwd(),o=VO(r);await GO(o),f.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${o}`);let i=UO(),s=await De(n??"",o,"p12"),a=await De(n??"",o,"csr");return console.log("Start generating p12"),await HO({keyAlias:e?.keyAlias??Et.keyAlias,keyPwd:i,keyAlg:e?.keyAlg??Et.keyAlg,keySize:e?.keySize??Et.keySize,keystoreFile:s,keystorePwd:i}),await qO(s),console.log("Start generating csr"),await BO({subject:t?.subject??Et.csrSubject,outFile:a,keyAlias:t?.keyAlias??Et.keyAlias,keyPwd:i,signAlg:t?.signAlg??Et.signAlg,keystoreFile:s,keystorePwd:i}),{p12FilePath:s,csrFilePath:a,keyPwd:i,keyAlias:e?.keyAlias??Et.keyAlias}}var JO=["p12","cer","csr","p7b"];async function Gu(n,e){for(let t of JO){let r=await De(n,e,t);await zO.rm(r,{force:!0})}}function qu(n){let e;try{e=YO(n,"utf-8")}catch{throw new Error(E.ERR_CERT_INVALIDATE)}if(!We.CERT_PATTERN.test(e))throw new Error(E.ERR_CERT_INVALIDATE)}async function Jv(n,e){return{certPath:await De(n,e,"cer"),csrPath:await De(n,e,"csr"),p12Path:await De(n,e,"p12"),profilePath:await De(n,e,"p7b")}}async function zu(n,e){let t=e??"",r=K.discover(process.cwd()).rootDir;await Gu(t,r);let o=ju(n.teamId),i=await bc(n,o);if(i&&!await Hu(n,i.id))throw new Error(E.ERR_DOWNLOAD_CER);let s=await Vu(e),a;try{a=KO(s.csrFilePath,"utf-8")}catch{throw new Error(E.ERR_READ_CSR)}console.log("Start generating certificate"),await Bu(n,a,o);let c=await bc(n,o);if(!c)throw new Error(E.ERR_DOWNLOAD_CER);let l=await Uu(n,c.certObjectId);if(!l)throw new Error(E.ERR_DOWNLOAD_CER);let d=await De(t,r,"cer");await Hi(l,d),qu(d);let h=await De(t,r,"p7b");return{p12FilePath:s.p12FilePath,csrFilePath:s.csrFilePath,cerFilePath:d,profileFilePath:h,certId:c.id,keyAlias:s.keyAlias,keyPwd:s.keyPwd,storePassword:s.keyPwd}}import Nc from"crypto";import $n from"fs";import*as lS from"path";import wM from"json5";import{execa as aS}from"execa";import*as dS from"pkijs";import{createCipheriv as XO,createDecipheriv as ZO,pbkdf2Sync as QO,randomBytes as Xu}from"crypto";import{promises as fr}from"fs";import{dirname as eM,join as Pt}from"path";var Pc=3,Ui=16,tM=1e4,Kv="material",nM=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),eS="aes-128-gcm",mr=12,Cc=16,_n=4;function Yu(n){return new Uint8Array(Xu(n))}function rM(n){return Xu(n).toString("hex")}function oM(...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 Xv(n,e,t=tM,r=Ui){let o=[...n,nM],i=oM(...o),s=Buffer.from(i).toString("utf8"),a=Buffer.from(s,"utf8"),c=QO(a,e,t,r,"sha256");return new Uint8Array(c)}function Zv(n,e){let t=Xu(mr),r=XO(eS,n,t),o=Buffer.concat([r.update(e),r.final()]),i=r.getAuthTag(),s=Buffer.concat([o,i]),a=s.length,c=Buffer.alloc(_n+mr+s.length);return c.writeUInt32BE(a,0),t.copy(c,_n),s.copy(c,_n+mr),c}function Qv(n,e){if(e.length<_n+mr+Cc)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(_n,_n+mr),o=e.subarray(_n+mr,_n+mr+t);if(o.length<Cc)throw new Error("Ciphertext too short for auth tag");let i=o.subarray(0,o.length-Cc),s=o.subarray(o.length-Cc),a=ZO(eS,n,r);return a.setAuthTag(s),Buffer.concat([a.update(i),a.final()])}async function iM(n){try{await fr.rm(n,{recursive:!0,force:!0})}catch{}}async function Ju(n){let e=await fr.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 fr.readFile(Pt(n,t[0]))}async function Ku(n,e){let t=rM(Ui),r=Pt(n,t);return await fr.writeFile(r,e),t}var Fn=class{static async generateMaterial(e){let t=Pt(e,Kv);await iM(t);let r=Pt(t,"ac"),o=Pt(t,"ce");await fr.mkdir(r,{recursive:!0}),await fr.mkdir(o,{recursive:!0});for(let d=0;d<Pc;d++)await fr.mkdir(Pt(t,"fd",String(d)),{recursive:!0});let i=Yu(Ui),s=[];for(let d=0;d<Pc;d++)s.push(Yu(Ui));let a=Yu(Ui),c=Xv(s,i),l=Zv(c,a);await Ku(r,i),await Ku(o,l);for(let d=0;d<Pc;d++){let h=Pt(t,"fd",String(d));await Ku(h,s[d])}return a}static async readMaterial(e){let t=Pt(e,Kv),r=Pt(t,"ac"),o=new Uint8Array(await Ju(r)),i=[];for(let d=0;d<Pc;d++){let h=Pt(t,"fd",String(d)),w=await Ju(h);i.push(new Uint8Array(w))}let s=Pt(t,"ce"),a=await Ju(s),c=Xv(i,o),l=Qv(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t=eM(e);try{return await this.readMaterial(t)}catch{return await this.generateMaterial(t)}}static async encryptedPassword(e,t){let r=await this.getStoreKey(t),o=Buffer.from(e,"utf8");return Zv(r,o).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),o=Buffer.from(e,"hex");return Qv(r,o).toString("utf8")}};import iS from"fs";import Rc from"path";import uM from"json5";import*as Ic from"fs";import*as tS from"path";function Ac(n){let e=tS.resolve(n);if(!Ic.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=Ic.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 wo from"fs";import*as Ve from"path";import{debuglog as yo}from"util";var nS={"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 sM(n){return Object.prototype.hasOwnProperty.call(nS,n)}function Dc(n){if(sM(n))return nS[n]}var rS={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as aM}from"url";var kc=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 Tc(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function oS(n){return n==null||n.length===0}function cM(n){return!oS(n)}function Zu(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function lM(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 dM(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 jn=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=Ve.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=Ve.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=Ve.join(t.sdkPath,"default","sdk-pkg.json"),a=Ac(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=Ve.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(wo.existsSync(e))return wo.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=aM(e);if(t.includes("dist")){let s=Ve.dirname(t),a=Ve.dirname(s);return Ve.join(a,"src","resources")}let r=Ve.dirname(t),o=Ve.dirname(r),i=Ve.dirname(o);return Ve.join(i,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{yo("read builtin acl permission failed.");return}if(r!==void 0)try{let o=JSON.parse(r),s=(Array.isArray(o)?o:Tc(o)?Object.values(o):[]).filter(Tc).map(a=>new kc(a));s.forEach(a=>{let c=a.permissionInsteadName;cM(c)&&(a.permissionInsteadName=Dc(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(o){yo(`failed to parse aclPermissionsInfo.json: ${o}`)}}static initAclPermissionFromSDK(e,t,r){let o=this.parsePermissionDefinitionFile(e);o&&o.forEach(i=>{if(!Tc(i))return;let s=i,a=Zu(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(oS(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||Zu(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||Zu(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:lM(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let o=new kc;o.permissionName=t;let i=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;o.permissionDisplayName=i;let s=dM(r,this.ACL_SINCE_KEY);o.minSupportApiLevel=String(s),this.handleInsteadName(o,i),e.add(o)}static parsePermissionDefinitionFile(e){let t=Ve.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!wo.existsSync(t))return;let r;try{r=wo.readFileSync(t,"utf-8")}catch(s){yo(`failed to load permissionDefinitions.json: ${s}`);return}let o;try{let s=JSON.parse(r);if(!Tc(s)){yo("json object is null");return}o=s}catch(s){yo(`failed to parse permissionDefinitions.json: ${s}`);return}let i=o[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(i)){yo("definePermissions is not an array");return}return i}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=Dc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=Dc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function xc(n,e){let t=new Set,r=new Set;jn.handleSpecificAclPermissions(),jn.initAclPermission(n,e);for(let o of n.profile.modules){let i=sS(o,n,e,r,Rc.join("src","main"));for(let a of i)t.add(a);let s=sS(o,n,e,r,Rc.join("src","ohosTest"));for(let a of s)t.add(a)}return pM(r),t}function pM(n){if(n.size>0)throw new Error(rS.DUPLICATE_PERMISSION)}function sS(n,e,t,r,o){let i=fM(e.rootDir,n,o);if(i==null)return new Set;let s=[];for(let w of i){if(typeof w!="object"||w===null)continue;let v=mM(w,"name");v&&s.push(v)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=Rc.join(t.sdkPath,"default","sdk-pkg.json"),l=Ac(c),d=jn.getAclPermissionInfos(e),h=new Set(Array.from(d).filter(w=>{let v=Number(w.minSupportApiLevel);return Number.isFinite(v)&&v<=l}).map(w=>w.permissionName));for(let w of Array.from(a))h.has(w)||a.delete(w);return a}function mM(n,e){let t=n[e];return typeof t=="string"?t:""}function fM(n,e,t){let r=Rc.join(n,e.srcPath,t,"module.json5"),o=hM(r);if(o==null)return null;let i=gM(o,"module");return i==null?null:yM(i,"requestPermissions")}function hM(n){try{if(!iS.existsSync(n))return null;let e=iS.readFileSync(n,"utf-8");return uM.parse(e)}catch{return null}}function gM(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 yM(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}function vM(n){let e=Buffer.from(n,"utf8"),t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var ep=class{async verifyStorePassword(e,t){try{let r=$n.readFileSync(e);return await dS.PFX.fromBER(r).parseInternalValues({password:vM(t),checkIntegrity:!0}),!0}catch{return!1}}getLocalCerFingerprints(e){let r=$n.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(o=>this.formatFp(new Nc.X509Certificate(o).fingerprint256));try{return[this.formatFp(new Nc.X509Certificate($n.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let o=$n.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let i of o)try{let s=new Nc.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 SM(n){let e=$n.readFileSync(n,"utf-8"),t=bM(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let o=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:Qu(o["bundle-name"]),expiryDate:EM(r?.validity?.["not-after"]),cerFingerprintInProfile:PM(Qu(o["development-certificate"])),deviceUdidsInProfile:CM(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:IM(r?.acls?.["allowed-acls"]),teamIdInProfile:Qu(o["developer-id"])}}function bM(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 EM(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function PM(n){if(!n)return null;try{let t=new Nc.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function CM(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 IM(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 Qu(n){return typeof n=="string"?n:null}var Wi=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.#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=K.discover(process.cwd()),a=s.rootDir,[c,l]=await Promise.all([AM(i,a),TM(t.hdcPath)]),d=null;if(cS(c).allExist)try{d=SM(c.profileFile)}catch{}return{force:r,teamId:o,productName:i,projectPath:a,materialPaths:c,bundleName:s.getBundleName(),deviceUdids:l,storePassword:await DM(a,i,c.storeFile),localAclPermissions:[...xc(s,t)].sort(),hapSignTool:new ep,profileInfo:d}}static#t(e){return e.force?(m("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:Xe({force:!0})}):null}static#n(e){let t=cS(e.materialPaths);return t.allExist?null:(m(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:Xe({allFilesExist:!1,missingFiles:t.missing})})}static#r(e){return(e.profileInfo?.rawContent??"").trim().length>0?null:(m("[reGenerateSign] profile content is empty"),{shouldRegenerate:!0,reason:"Profile file content is empty",checkDetails:Xe({allFilesExist:!0,profileContentNotEmpty:!1})})}static#o(e){let t=e.profileInfo?.expiryDate;return!t||t>=new Date?null:(m(`[reGenerateSign] profile expired at ${t.toISOString()}`),{shouldRegenerate:!0,reason:`Profile expired at ${t.toISOString()}`,checkDetails:Xe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#i(e){let t=e.profileInfo?.bundleNameInProfile;return t&&t===e.bundleName?null:(m(`[reGenerateSign] bundleName mismatch \u2014 current=${e.bundleName}, profile=${t}`),{shouldRegenerate:!0,reason:`bundleName mismatch: current=${e.bundleName}, in profile=${t}`,checkDetails:Xe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!1})})}static#s(e){let t=e.profileInfo?.teamIdInProfile;return t&&t===e.teamId?null:(m(`[reGenerateSign] teamId mismatch \u2014 current=${e.teamId}, profile=${t}`),{shouldRegenerate:!0,reason:`teamId mismatch: current=${e.teamId}, in profile=${t}`,checkDetails:Xe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=RM(e.profileInfo?.deviceUdidsInProfile??[],e.deviceUdids);return t.allPresent?null:(m(`[reGenerateSign] missing device UDIDs: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Device UDID(s) not in profile: ${t.missing.join(", ")}`,checkDetails:Xe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return xM(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(m("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:Xe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!1})})}static#l(e){let t=e.hapSignTool.getLocalCerFingerprints(e.materialPaths.cerFile),r=e.profileInfo?.cerFingerprintInProfile;return r&&t.includes(r)?null:(m("[reGenerateSign] certificate mismatch"),{shouldRegenerate:!0,reason:"Certificate mismatch between profile and local .cer file",checkDetails:Xe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!1})})}static#d(e){let t=e.profileInfo?.cerFingerprintInProfile,r=e.hapSignTool.getLocalCerExpiry(e.materialPaths.cerFile,t);return!r||r>=new Date?null:(m(`[reGenerateSign] local certificate expired at ${r.toISOString()}`),{shouldRegenerate:!0,reason:`Local certificate expired at ${r.toISOString()}`,checkDetails:Xe({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?await e.hapSignTool.verifyStorePassword(e.materialPaths.storeFile,e.storePassword)?null:(m("[reGenerateSign] keystore password verification failed"),{shouldRegenerate:!0,reason:"Keystore password verification failed (storeFile may be corrupted or password changed)",checkDetails:Xe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})}):(m("[reGenerateSign] no stored keystore password"),{shouldRegenerate:!0,reason:"No stored keystore password available for verification",checkDetails:Xe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})})}static#p(){return m("[reGenerateSign] all checks passed \u2014 skip regeneration"),{shouldRegenerate:!1,reason:"",checkDetails:Xe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function AM(n,e){let[t,r,o,i]=await Promise.all([De(n,e,"p12"),De(n,e,"csr"),De(n,e,"cer"),De(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:o,profileFile:i}}async function DM(n,e,t){let r=lS.join(n,"build-profile.json5");if(!$n.existsSync(r))return;let o;try{o=wM.parse($n.readFileSync(r,"utf-8"))}catch{return}let a=(o?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await Fn.decryptPassword(a,t)}catch{return}}async function TM(n){m(`Executing: ${n} list targets`);let{stdout:e}=await aS(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let o of e.split(`
|
|
1424
|
-
`)){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{m(`Executing: ${n} -t ${o} shell bm get -u`);let{stdout:i}=await
|
|
1425
|
-
`);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
|
|
1426
|
-
`)){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
|
|
1427
|
-
`);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 _M(n,e){let{stdout:t}=await np(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return FM(t)}function FM(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 Hn from"fs";import{Buffer as Oc}from"buffer";import{createHash as YM,createPrivateKey as JM,createPublicKey as KM,X509Certificate as rp}from"crypto";import*as Ge from"pkijs";import{createDecipheriv as jM,createHash as $M}from"crypto";var HM="1.2.840.113549.1.12.1.3",BM="1.2.840.113549.1.12.1.4";function UM(n){let e=new Uint8Array(n.length*2+2),t=new DataView(e.buffer);for(let r=0;r<n.length;r++)t.setUint16(r*2,n.charCodeAt(r),!1);return t.setUint16(n.length*2,0,!1),e}function yS(n,e){let t=new Uint8Array(e*Math.ceil(n.length/e));for(let r=0;r<t.length;r++)t[r]=n[r%n.length];return t}function WM(n,e,t,r,o){let i=Math.ceil(r/t)+Math.ceil(o/t),s=new Uint8Array(i*t);for(let a=0;a<i;a++){let c=Array.from(n.slice(a*t,(a+1)*t)),l=511;for(let d=t-1;d>=0;d--)l>>=8,l+=e[d]+(c[d]||0),c[d]=l&255;s.set(c,a*t)}return s}function wS(n,e,t,r,o){let a=new Uint8Array(64).fill(n),c=yS(t,64),l=yS(e,64),d=new Uint8Array(c.length+l.length);d.set(c),d.set(l,c.length);let h=Math.ceil(o/20),w=new Uint8Array(h*20);for(let v=0;v<h;v++){let I=Buffer.alloc(a.length+d.length);I.set(a),I.set(d,a.length);for(let Y=0;Y<r;Y++)I=$M("sha1").update(I).digest();w.set(I.subarray(0,20),v*20);let H=new Uint8Array(64);for(let Y=0;Y<64;Y++)H[Y]=I[Y%I.length];d=WM(d,H,64,t.length,e.length)}return w.subarray(0,o)}function VM(n){try{let t=n?.valueBlock?.value;if(!t||t.length<2)return null;let r=t[0]?.valueBlock?.valueHex,o=t[1]?.valueBlock?.valueDec;return!r||typeof o!="number"?null:{salt:new Uint8Array(r),iterations:o}}catch{return null}}function GM(n){switch(n){case HM:return{cipherName:"des-ede3-cbc",keyLen:24,ivLen:8};case BM:return{cipherName:"des-ede-cbc",keyLen:16,ivLen:8};default:return null}}function qM(n){let e=n.encryptedContent;if(!e)return null;let t=e.getValue?.()??e.valueBlock?.valueHex;return t?new Uint8Array(t):null}function zM(n){let e=n.encryptedContentInfo;if(!e)return null;let t=GM(e.contentEncryptionAlgorithm.algorithmId);if(!t)return null;let r=VM(e.contentEncryptionAlgorithm.algorithmParams);if(!r)return null;let o=qM(e);return o?{config:t,salt:r.salt,iterations:r.iterations,ciphertext:o}:null}function vS(n,e){let t=zM(n);if(!t)return null;let r=UM(e),o=wS(1,r,t.salt,t.iterations,t.config.keyLen),i=wS(2,r,t.salt,t.iterations,t.config.ivLen);try{let s=jM(t.config.cipherName,Buffer.from(o),Buffer.from(i)),a=Buffer.concat([s.update(Buffer.from(t.ciphertext)),s.final()]);return new Uint8Array(a)}catch(s){throw new Error(`${t.config.cipherName} decryption failed: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}async function ES(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=`${ie.BASE_URL}${ie.PROVISION_ADD_TEST_PATH}`,h=XM(t,r),w=await QM(n,d,a||[],r,s,h,i||[]);if(!w||!w.profileInfo||!w.profileInfo.provisionFileUrl)throw m("add provision failed, the provision file url is null"),new Error(E.ADD_PROFILE_FAIL);let v=w.profileInfo,H=(await r_(n,v.provisionFileUrl)).urlList,Y=w.profileInfo.id;if(H&&H.length>0){let lt=await Jv(t,o),dt=lt.profilePath;if(!await o_(H,dt))throw await SS(n,Y),new Error(E.ERROR_WHILE_DOWNLOAD_PROFILE);if(await SS(n,Y),Hn.existsSync(lt.certPath)&&Hn.existsSync(dt)&&Hn.existsSync(lt.p12Path)){let Hc=Hn.readFileSync(lt.certPath,"utf8"),Bc=Hn.readFileSync(dt,"utf8");return await i_(Bc,Hc,lt.p12Path,c,l)||n_(dt),dt}}throw new Error(E.ADD_PROFILE_FAIL)}function XM(n,e){let t=n?`${n}_`:"";return`${ZM(`${t}${e}_${e}`)}`}function ZM(n){return YM("sha256").update(n).digest("hex").substring(0,16)}async function QM(n,e,t,r,o,i,s){e_(r);let a=ip(n),c={certList:t,packageName:r,deviceList:o,provisionName:i};s.length&&(c.aclPermissionList=s);let l=await O.postAllowFailure(e,{headers:a,params:c});if(!l)throw m("add provision failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw op(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw m(`add provision fail: ${l.data}`),t_(l.data,i),new Error(d.ret?.msg||E.ADD_PROFILE_FAIL);let h=d.provisionFileUrl;return{profileInfo:{id:d.id,name:i,provisionFileUrl:h}}}function op(n,e,t){return n===bt.FORBIDDEN?e===Pe.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN):n===bt.UNAUTHORIZED?new Error(E.ERR_UNAUTHORIZED):t.includes(Pe.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(E.TEST_PROVISION_EXCEEDS_LIMIT):new Error(E.ADD_PROFILE_FAIL)}function e_(n){if(!n||n.trim().length===0)throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!We.BUNDLE_NAME_REGEX.test(n))throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function t_(n,e){if(n.includes(Pe.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(E.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(Pe.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(E.PROFILE_NAME_REPEAT)}async function SS(n,e){if(!e||e.trim().length===0)return;let t=`${ie.BASE_URL}${ie.PROVISION_DELETE_PATH}?id=${e}`,r=await O.deleteAllowFailure(t,{headers:ip(n)});if(r.statusCode!==200)throw op(r.statusCode,r.statusText,r.data);let o=JSON.parse(r.data);(!o||!o.ret||o.ret.code!==0)&&m(`delete provision failed: ${r.data}`)}function n_(...n){for(let e of n)try{Hn.existsSync(e)&&Hn.unlinkSync(e)}catch(t){m(`delete local sign file error: ${t.message}`)}}async function r_(n,e){let t=`${ie.BASE_URL}${ie.CERT_DOWNLOAD_URL_PATH}`,r=ip(n),o={sourceUrls:e},i=await O.postAllowFailure(t,{headers:r,params:o});if(!i)throw m("get download list failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(i.statusCode!==200)throw op(i.statusCode,i.statusText,i.data);let s=JSON.parse(i.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw m("download: The application does not exist"),new Error(s.ret?.msg||E.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function o_(n,e){if(!n||n.length===0)return!1;let t=n[0].newUrl;return await Hi(t,e),!0}async function i_(n,e,t,r,o){return s_(n,e),r=r||We.TARGET_FRIENDLY_NAME,o=o||"",await a_(e,t,r,o),!0}function s_(n,e){if(e.lastIndexOf(We.CERT_BEGIN_HEADER)<0)throw new Error(E.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(We.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}async function a_(n,e,t,r){let o=n.matchAll(We.CERTIFICATE_PATTERN_GLOBAL),i=[],s=new Date;for(let c of o)try{let l=c[0],d=c_(l),h=new Date(d.validFrom),w=new Date(d.validTo);if(s<h||s>w){let v=`Certificate is not valid, Valid from ${h} to ${w}`;throw console.warn(`checkCertificateInValidityPeriod: ${v}`),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(!await S_(e,t,r,i))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function c_(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new rp(t);let r=Oc.from(t,"base64");return new rp(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}var l_="1.2.840.113549.1.9.20",d_="1.2.840.113549.1.12.10.1.3",u_="1.2.840.113549.1.12.10.1.2",p_="1.2.840.113549.1.7.1",m_="1.2.840.113549.1.7.6";function f_(n){let e=Oc.from(n,"utf8"),t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}function bS(n){let e=new DataView(n),t="";for(let o=0;o+1<n.byteLength;o+=2)t+=String.fromCharCode(e.getUint16(o,!1));let r=t.length;for(;r>0&&t.charCodeAt(r-1)===0;)r--;return t.substring(0,r)}function PS(n){if(n){for(let e of n)if(e.type===l_&&e.values.length>0){let t=e.values[0];if(t&&typeof t.value=="string")return t.value;if(t?.valueBlock&&typeof t.valueBlock.value=="string")return t.valueBlock.value;let r=t?.valueBlock?.valueHex;if(r instanceof ArrayBuffer)return bS(r);let o=t?.valueBlock?.valueHexView;if(o instanceof Uint8Array){let i=new ArrayBuffer(o.byteLength);return new Uint8Array(i).set(o),bS(i)}}}}function h_(n){if(!(n instanceof Ge.CertBag))return null;let e=n.parsedValue;if(!(e instanceof Ge.Certificate))return null;try{let t=e.toSchema().toBER(!1),r=new rp(Oc.from(t));return r.publicKey?r.publicKey.export({type:"spki",format:"der"}):null}catch(t){return m(`Failed to parse cert from CertBag: ${t}`),null}}function g_(n,e,t){for(let r of n){if(r.bagId!==d_)continue;let o=PS(r.bagAttributes);if(!o||o.toLowerCase()!==e.toLowerCase())continue;let i=h_(r.bagValue);if(!i)continue;if(t.some(a=>{let c=a.publicKey.export({type:"spki",format:"der"});return i.equals(c)}))return!0}return!1}function y_(n,e,t,r){for(let o of n){if(o.bagId!==u_)continue;let i=PS(o.bagAttributes);if(!(!i||i.toLowerCase()!==e.toLowerCase()))try{let s=o.bagValue;if(!(s instanceof Ge.PKCS8ShroudedKeyBag))continue;let a=s.toSchema().toBER(!1),c=Oc.from(a).toString("base64"),d=`-----BEGIN ENCRYPTED PRIVATE KEY-----
|
|
1428
|
-
${(c.match(/.{1,64}/g)??[c]).join(`
|
|
1429
|
-
`)}
|
|
1430
|
-
-----END ENCRYPTED PRIVATE KEY-----`,h=JM({key:d,format:"pem",passphrase:r}),v=KM(h).export({type:"spki",format:"der"});if(t.some(H=>{let Y=H.publicKey.export({type:"spki",format:"der"});return v.equals(Y)}))return!0}catch{}}return!1}async function w_(n,e,t){let r=new Ge.EncryptedData({schema:n.content});try{let o=await r.decrypt({password:e});return Ge.SafeContents.fromBER(o).safeBags}catch(o){try{let i=vS(r,t);if(i){let s=new ArrayBuffer(i.byteLength);return new Uint8Array(s).set(i),Ge.SafeContents.fromBER(s).safeBags}}catch{}m(`SafeContent decrypt failed: pkijs=${o instanceof Error?o.message:String(o)}`)}return[]}async function v_(n,e,t){if(n.contentType===p_)try{let r=n.content;if(typeof r.getValue=="function"){let o=r.getValue();return Ge.SafeContents.fromBER(o).safeBags}}catch(r){m(`data SafeContent parse error: ${r instanceof Error?r.message:String(r)}`)}else if(n.contentType===m_)return w_(n,e,t);return[]}async function S_(n,e,t,r){try{let o=Hn.readFileSync(n),i=f_(t),s=Ge.PFX.fromBER(o);await s.parseInternalValues({password:i,checkIntegrity:!0});let a=s.parsedValue?.authenticatedSafe;if(!a)return!1;let c=[];for(let l of a.safeContents){let d=await v_(l,i,t);c.push(...d)}return c.length===0?!1:g_(c,e,r)?!0:y_(c,e,r,t)}catch(o){let i=o instanceof Error?o.message:String(o);return m(`Failed to process P12 file: ${n}, error: ${i}`),!1}}function ip(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var IS="https://developer.huawei.com",b_={"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"},E_="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function P_(n){let e=b_[n];return e?`${IS}${e}`:void 0}function C_(){return`${IS}${E_}`}var I_={"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 CS(n,e){return(I_[n]??n).replace(/\{(\d+)\}/g,(r,o)=>String(e[Number(o)]??""))}function A_(n){return Array.from(n).join(", ")}function AS(n,e){if(n.size===0)return;let t=jn.getAclPermissionInfos(e),r=new Set;for(let h of t)n.has(h.permissionName)&&r.add(h);for(let h of r){let w=P_(h.permissionName);w!=null&&(h.permissionHelpUrlKey=w)}let o=new Set;for(let h of r)o.add(h.permissionDisplayName);let i=new Set;for(let h of r)if(h.permissionHelpUrlKey!=null){let w=h.permissionInsteadName??h.permissionDisplayName;i.add(`${w} (${h.permissionHelpUrlKey})`)}let s=C_(),a=CS("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=i.size>0?Array.from(i).join(", ")+".":"",d=CS("acl.permissions.warn",[A_(o),l,c]);console.log(d)}var Mc=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=K.discover(process.cwd()),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Project.discover() failed: ${t.message}`),e(ne.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Product validation failed: ${r.message}`),t(`Product "${e}" not found.Check the product property in the build-profile.json5 file.`)}}checkBundleName(e,t){try{return this._project.getBundleName(),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] BundleName check failed: ${r.message}`),t(`bundleName was not found under product "${e}".Check the bundleName configuration.`)}}checkAtomicService(){return this._project.isAtomicService()?{passed:!1,message:ne.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import D_ from"fs";import DS from"path";var _c=class{constructor(e){this.toolProvider=e}toolProvider;checkJava(e){try{return this.toolProvider.assertJava(),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Java check failed: ${t.message}`),e(ne.JAVA_PLATFORM_UNSUPPORTED)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=b()?"hap-sign-tool":"hap-sign-tool.jar",o=DS.join(t,"default","openharmony","toolchains","lib",r);if(!D_.existsSync(o)){let i=DS.join("sdk","default","openharmony","toolchains","lib",r);return e(`${r} not found.Check whether ${i} exists.`)}return{passed:!0,message:""}}};var Fc=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await xe.getUserInfo()}catch(e){return m(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await xe.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(ne.LOGIN_REQUIRED)}catch(t){return m(`[EnvCheck] Login check failed: ${t.message}`),e(ne.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(ne.TEAM_INFO_FAILED);try{if((await mn()).teamList.length>0)return{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Team API error: ${r.message}`),e(ne.TEAM_INFO_FAILED)}return m("[EnvCheck] No teams found for current user"),e(ne.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(ne.REALNAME_REQUIRED):t.isRealName!==!0?(m("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(ne.REALNAME_REQUIRED)):{passed:!0,message:""}:e(ne.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let o=await mn();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 m(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(o){return m(`[EnvCheck] Team ID check failed: ${o.message}`),{passed:!1,message:`team-id for ${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(ne.REGION_CHINA_ONLY):{passed:!0,message:""}:(m("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(ne.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function T_(n){try{let{teamList:e}=await mn();if(e.length>0)return e[0].id}catch(e){m(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function k_(n){let e=await xe.getUserInfo(),t=await xe.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await T_(e.userId);if(!r)throw new Error("No team found");let o={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await Lc(o)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var jc=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t){try{let r=await k_(t);if(r.length>0)return m(`[EnvCheck] Scenario 4 Device check: ${r.length} device(s) found in AGC cloud, skipping local device check`),{passed:!0,message:""};m("[EnvCheck] Scenario 4 Device check: no cloud devices found, falling back to local hdc");let i=await ae.from(this.toolProvider).listDevices();return i.length===0?(m("[EnvCheck] Scenario 4 Device check: no local devices found"),e(ne.DEVICE_MISSING)):i.some(a=>Yn(a.serial))?{passed:!0,message:""}:(m("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(ne.DEVICE_MISSING))}catch(r){return m(`[EnvCheck] Scenario 4 Device check failed: ${r.message}`),e(ne.DEVICE_DETECT_FAILED)}}};var $c=class{projectChecker=new Mc;toolchainChecker=null;authChecker=new Fc;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 _c(e),this.deviceChecker=new jc(e),!0}catch(e){throw m(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(ne.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 m(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};function L_(n){if(ap.existsSync(n)){let e=ap.readFileSync(n,"utf-8");return N_.parse(e)}return{app:{signingConfigs:[],products:[]}}}function O_(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function M_(n){if(n.keyPwd===n.storePassword){let r=await Fn.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await Fn.encryptedPassword(n.keyPwd,n.p12FilePath),t=await Fn.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function __(n,e,t){let r=TS.join(n,"build-profile.json5"),o=L_(r);O_(o);let i=t??"default",{keyPassword:s,storePassword:a}=await M_(e),c={name:i,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:Et.signAlg,storeFile:e.p12FilePath,storePassword:a}},l=o.app?.signingConfigs?.findIndex(h=>h.name===i);l!==void 0&&l>=0?o.app.signingConfigs[l]=c:o.app.signingConfigs.push(c);let d=o.app?.products?.findIndex(h=>h.name===i);d!==void 0&&d>=0?o.app.products[d].signingConfig=i:o.app.products.push({name:i,signingConfig:i}),ap.writeFileSync(r,JSON.stringify(o,null,2),"utf-8")}async function F_(n){let e=await xe.getUserInfo(),t=await xe.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 j_(n){let e=n.product||"default";await new $c().preflight({productName:e,teamId:n.teamId}),console.log("Executing signature generate command");let r=await F_(n),o=await A.new(),{shouldRegenerate:i}=await Wi.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product},o);if(!i){console.log(sp("Signature generation completed successfully."));return}await $_(n,r,o),console.log(sp("Signature generation completed successfully."))}async function $_(n,e,t){let r=await zu(e,n.product),o=H_(n,e,r,t);o.allDeviceIds=await pS(e,t.hdcPath),await ES(e,o);let i=K.discover(process.cwd()).rootDir;await __(i,r,n.product??"default"),console.log(sp(`Signing config written to ${TS.join(i,"build-profile.json5")}`))}function H_(n,e,t,r){let o=process.cwd(),i=K.discover(o),s=xc(i,r);return AS(s,i),{productName:n.product||"default",bundleName:i.getBundleName(),projectPath:i.rootDir,teamId:e.teamId,force:n.force||!1,aclPermissionList:[...s],certIds:[t.certId],keyAlias:t.keyAlias,keyPwd:t.keyPwd}}var kS=new R_("signature").description("Generate application signature.");kS.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:T.CommandExecuted,args:["signature","generate",...n.force?["--force"]:[],...n.teamId?["--team-id"]:[],...n.product?["--product"]:[]]},t=Date.now(),r=!0,o=null;try{await j_(n)}catch(i){r=!1,o=ce(i),console.error(x_(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await D.track(e,i)}});var RS=kS;if(!Qe())try{D.init(lp.join(Xt(),"TraceLogData")),D.startScheduler()}catch(n){g.error(`[telemetry] init failed: ${n instanceof Error?n.message:String(n)}`)}(async()=>{if(!Qe())try{let n=await A.new();D.setSourceType(n.sourceType);let e=n.readVersion();e&&(n.sourceType==="clt"?D.setCltVersion(e):D.setStudioVersion(e))}catch(n){g.error(`[telemetry] toolchain info failed: ${n instanceof Error?n.message:String(n)}`)}})();de.name("devecocli").description(`HarmonyOS application development command line tool
|
|
1420
|
+
`),console.log(be("[compat:check] === end stdout ===")));let i=new Error(`Compatibility scan failed: ${o.message}`+(o.stderr?`
|
|
1421
|
+
${o.stderr}`:""));throw o.stdout&&(i.stdout=o.stdout),i}}function uL(n,e){if(n.length>0&&e.modules&&e.modules.length>0)throw new Error("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 Error("--source-version is required.");if(!e.targetVersion)throw new Error("--target-version is required.");if(!e.outputPath&&e.format==="csv")throw new Error("--format csv requires --output-path. For console output, use --format json or --format default (or omit the flag).")}function pL(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 Error(`${t.join(" and ")} ${r} not in the available SDK version list.
|
|
1422
|
+
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 Error(`--target-version "${n.targetVersion}" must be later than --source-version "${n.sourceVersion}". Run \`devecocli compat versions\` to see the available order.`)}}function mL(n,e,t,r,o){o==="none"&&(t==="json"?aL(n,r):sL(n,r)),iL(n,e)}function fL(n,e){let t=z.dirname(n),r=z.basename(n),o=e.slice(1).map(i=>i.startsWith("--")?i:`"${i}"`).join(" ");m(be(`[compat:check] command: cd "${t}" && node "${r}" ${o}`))}function hL(n){try{VO(n),m(be(`[compat:check] cleaned up tmp report: "${n}"`))}catch(e){m(be(`[compat:check] failed to clean up tmp report: ${e.message}`))}}var gL=[".csv",".json"];function yL(n){return gL.includes(n.toLowerCase())}function wL(n,e){if(!n)return{kind:"none"};let t=z.extname(n).toLowerCase();if(!yL(t))return{kind:"dir",dirPath:z.resolve(n)};if(t===".csv"&&!(e==="default"||e==="csv")||t===".json"&&e!=="json")throw new Error(`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:z.resolve(n),ext:t}}function vL(n){if(n.kind==="file"){if(bc(n.filePath))throw new Error(`Target file "${n.filePath}" already exists. Remove it first, or choose a different --output-path.`);let e=z.dirname(n.filePath);if(!bc(e))throw new Error(`Target directory "${e}" does not exist. Create it first, or choose a different --output-path.`)}else if(n.kind==="dir"&&!bc(n.dirPath))throw new Error(`Target directory "${n.dirPath}" does not exist. Create it first, or choose a different --output-path.`)}function Vv(n){return JSON.stringify({count:n.length,records:n},null,2)+`
|
|
1423
|
+
`}function SL(n,e,t,r){r===".csv"?$v(n,t):Hv(t,Vv(e),"utf8"),m(be(`[compat:check] saved report: "${t}"`))}function bL(n,e,t,r){if(r==="json"){let i=z.basename(n,".csv"),s=z.join(t,`${i}.json`);return Hv(s,Vv(e),"utf8"),m(be(`[compat:check] saved report: "${s}"`)),s}let o=z.join(t,z.basename(n));return $v(n,o),m(be(`[compat:check] saved report: "${o}"`)),o}async function EL(n,e){let t=new Oe(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 Error(`hvigorw compileNative failed (module=${r??"<project>"}): `+o.message,{cause:o})}}async function PL(n,e){uL(n,e);let t=J.discover(process.cwd());e.modules&&e.modules.length>0&&XO(t,e.modules),n.length>0&&ZO(n);let r=await D.new(),{apiChangeDir:o,scriptPath:i}=r.getApiscanPaths();m(be(`[compat:check] script: "${i}"`));let s=Wv(o);pL(e,s),e.outputPath&&m(be(`[compat:check] outputPath: "${e.outputPath}"`));let a=wL(e.outputPath,e.format);return m(be(`[compat:check] outputTarget: ${a.kind}`)),vL(a),{project:t,scriptPath:i,target:a,toolProvider:r}}async function CL(n,e){let{project:t,scriptPath:r,target:o,toolProvider:i}=await PL(n,e),s=zO({text:"Running compatibility check...",color:"cyan"}).start();try{await EL(i,e);let a=lL(r,n,t,e);fL(r,a);let c=await dL(i,a),l=oL(c,ju.tmpdir());if(!l)throw new Error("Scanner output format unexpected: missing report path.");m(be(`[compat:check] tmp csv: "${l}"`));let d=rL(l),h=null;if(o.kind==="file")SL(l,d,o.filePath,o.ext),h=o.filePath;else if(o.kind==="dir")h=bL(l,d,o.dirPath,e.format);else if(o.kind!=="none")throw new Error(`Unexpected output target kind: ${o.kind}`);hL(l),s.stop(),mL(d,h,e.format,e.limit,o.kind)}catch(a){throw s.fail("Compatibility check failed"),a}}var $u=new UO("compat").description("Compatibility checking utilities.");$u.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.',Bv,"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)",qO,100).action(async(n,e)=>{await CL(n,e)});$u.command("versions").description("List all available target SDK versions for compatibility checking").action(async()=>{let n=JO("csv");await KO(n)});var Gv=$u;var zv=new IL("check").description("Run DevEco project checks").addCommand(_u());b()||zv.addCommand(Gv);var qv=zv;import{Command as w_}from"commander";import{green as pp,red as v_}from"colorette";import mp from"fs";import kS from"path";import S_ from"json5";var Ec={liteWearable:"1",wearable:"2",tv:"3",phone:"4"},Yv=Object.keys(Ec),AL="phone",DL=/^[A-F0-9]+$/,Hu=64;function Jv(n){let e=[];for(let t of n)for(let r of t.split(","))e.push({value:r.trim(),position:e.length+1});return e}function TL(n){let e=n.lastIndexOf(":");return e<0?{udid:n.trim(),type:null}:{udid:n.slice(0,e).trim(),type:n.slice(e+1).trim()}}function RL(n,e){if(!n)throw new Error(`Invalid --udid value #${e.position}: "${e.value}" \u2014 missing UDID before ":<type>".`);let t=n.toUpperCase();if(!DL.test(t))throw new Error(`Invalid --udid value #${e.position}: "${e.value}" \u2014 expected hexadecimal characters only.`);if(t.length!==Hu)throw new Error(`Invalid --udid value #${e.position}: "${e.value}" \u2014 expected ${Hu} hexadecimal characters, got ${t.length}.`);return t}function kL(n,e){if(n===null)return;let t=Yv.find(r=>r.toLowerCase()===n.toLowerCase());if(!t)throw new Error(`Invalid device type "${n}" in --udid value #${e.position}. Valid types: ${Yv.join(", ")}.`);return t}function Uu(n){let e=[],t=new Set;for(let r of Jv(n)){if(!r.value)throw new Error(`Invalid --udid value #${r.position}: empty. Provide a ${Hu}-character hexadecimal UDID.`);let{udid:o,type:i}=TL(r.value),s=RL(o,r),a=kL(i,r);if(t.has(s)){m(`[manualDevice] duplicate --udid ignored: ${s}`);continue}t.add(s),e.push({udid:s,type:a})}return e}function Bu(n){let e=new Set;for(let t of Jv(n))t.value&&e.add(t.value.toUpperCase());return e.size}function Ui(n){return[...new Set(n.map(e=>e.trim().toUpperCase()).filter(Boolean))]}function Wu(n,e){let t=new Map;for(let r of n){let o=r.udid.toUpperCase();!o||t.has(o)||t.set(o,{udid:o,type:r.type,source:"detected",typeInferred:!1})}for(let r of e){let o=t.get(r.udid);if(o){r.type&&r.type!==o.type&&console.log(`Note: device ${r.udid} is connected locally; its type is read from the device (${o.type}). The type given in --udid was ignored.`);continue}t.set(r.udid,{udid:r.udid,type:r.type??AL,source:"manual",typeInferred:r.type===void 0})}return[...t.values()]}import{readFileSync as rM}from"fs";import{join as xL}from"path";var ie={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"},Be={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:xL(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},Ee={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"},St={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."},te={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.",JAVA_PLATFORM_UNSUPPORTED:"Java environment not found (Windows/macOS/Linux only).",JAVA_REQUIRED:"Java runtime is required to run hvigor.Set JAVA_HOME or add Java to PATH.",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 Pc(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function Vu(n){let e=n.replace(Be.TEAM_ID_INVALID_CHARS,"");return`${Be.CERT_NAME_PREFIX}${e}.cer`}function yo(n,e,t){if(n===St.FORBIDDEN)return e===Ee.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN);if(n===St.UNAUTHORIZED)return new Error(E.ERR_UNAUTHORIZED);if(t.includes(Ee.USER_NOT_HARMONY_CODE))return new Error(E.ERR_USER_NOT_HARMONY);if(t.includes(Ee.CERT_LIMIT_CODE))return new Error(E.ERR_CERT_LIMIT_REACHED);let r=NL(t);return new Error(r??E.ERR_DOWNLOAD_CER)}function NL(n){let e=Kv(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?Kv(t):t;if(r&&typeof r=="object"){let o=r.msg;if(typeof o=="string"&&o.trim()!=="")return o}return null}function Kv(n){try{return JSON.parse(n)}catch{return null}}function Gu(n){return JSON.parse(n)}async function Xv(n){let e=`${ie.BASE_URL}${ie.CERT_LIST_PATH}`,t=await L.postAllowFailure(e,{headers:Pc(n)});if(t.statusCode!==200)throw yo(t.statusCode,t.statusText,t.data);return Gu(t.data)?.certList??[]}async function Cc(n,e){return(await Xv(n)).find(r=>r.certName===e)??null}async function zu(n,e){let t=`${ie.BASE_URL}${ie.CERT_DELETE_PATH}`,r=await L.deleteAllowFailure(t,{headers:Pc(n),params:{certIds:[e]}});if(r.statusCode!==200)throw yo(r.statusCode,r.statusText,r.data);return Gu(r.data)?.ret?.code===0}async function qu(n,e,t){let r=`${ie.BASE_URL}${ie.CERT_ADD_PATH}`,o={csr:e,certName:t,certType:Be.CERT_TYPE_DEBUG},i=await L.postAllowFailure(r,{headers:Pc(n),params:o});if(i.statusCode!==200)throw yo(i.statusCode,i.statusText,i.data);if(!i.data.includes(Ee.SUCCESS_MARKER))throw yo(void 0,i.statusText,i.data)}async function Yu(n,e){let t=`${ie.BASE_URL}${ie.CERT_DOWNLOAD_URL_PATH}`,r=await L.postAllowFailure(t,{headers:Pc(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw yo(r.statusCode,r.statusText,r.data);return Gu(r.data)?.urlsInfo?.[0]?.newUrl??null}import{mkdirSync as OL,writeFileSync as LL,existsSync as ML}from"fs";import{dirname as _L}from"path";async function Bi(n,e){let{statusCode:t,statusText:r,buffer:o}=await L.getBinaryAllowFailure(n,{timeout:Be.DOWNLOAD_CONNECT_TIMEOUT_MS});if(t!==200)throw t===St.FORBIDDEN&&r===Ee.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_DOWNLOAD_CER);let i=_L(e);ML(i)||OL(i,{recursive:!0}),LL(e,o)}import eM from"fs/promises";import{readFileSync as tM}from"fs";import Ic from"path";import eS from"crypto";import FL from"os";import Wi from"fs/promises";var tS={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},Zv=["ECC","RSA"],Qv=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],jL={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},$L=8,Ju=64,HL=/[\\:*?"<>|=-]/g,bt={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function UL(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>Ju)throw new Error(`The length of keyAlias cannot exceed ${Ju}`);if(!Zv.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${Zv.join(" / ")}`);let e=jL[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function BL(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(!Qv.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${Qv.join(" / ")}`)}function WL(n){return eS.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function VL(n){let e=n?.trim()??"";return e&&e.replace(HL,"_").slice(0,Ju)||bt.productName}async function nS(){let n=await D.new(),e=n.javaPath;if(!e&&!b())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=b()?"hap-sign-tool":"hap-sign-tool.jar",o=Ic.join(t,"default","openharmony","toolchains","lib",r);try{await Wi.access(o)}catch(i){throw new Error(`${r} not found: ${o}`,{cause:i})}return{javaPath:e,toolPath:o}}async function GL(n){let{javaPath:e,toolPath:t}=await nS(),r=[tS.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=>["-keyPwd","-keystorePwd"].includes(i)?`${i} ******`:i);return f.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),b()?[t,...r]:[e,"-jar",t,...r]}async function zL(n){let{javaPath:e,toolPath:t}=await nS(),r=[tS.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=>["-keyPwd","-keystorePwd"].includes(i)?`${i} ******`:i);return f.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),b()?[t,...r]:[e,"-jar",t,...r]}async function qL(n){f.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),UL(n);let e=await GL(n),t=await zn(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 YL(n){f.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),BL(n);let e=await zL(n),t=await zn(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 JL(n=$L){return eS.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function KL(){let n=FL.homedir();try{await Wi.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=Ic.join(n,".ohos","config");try{await Wi.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 Ae(n,e,t){let r=VL(n),o=Ic.basename(e),i=WL(e),s=`${r}_${o}_${i}=.${t}`,a=await KL();return Ic.join(a,s)}function XL(n){let e;try{e=J.discover(n).rootDir}catch(t){throw new Error(`Current directory ${n} is not a valid project root`,{cause:t})}return e}async function ZL(n){try{await Wi.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function QL(n){try{await Wi.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function Ku(n,e,t){let r=process.cwd(),o=XL(r);await ZL(o),f.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${o}`);let i=JL(),s=await Ae(n??"",o,"p12"),a=await Ae(n??"",o,"csr");return console.log("Start generating p12"),await qL({keyAlias:e?.keyAlias??bt.keyAlias,keyPwd:i,keyAlg:e?.keyAlg??bt.keyAlg,keySize:e?.keySize??bt.keySize,keystoreFile:s,keystorePwd:i}),await QL(s),console.log("Start generating csr"),await YL({subject:t?.subject??bt.csrSubject,outFile:a,keyAlias:t?.keyAlias??bt.keyAlias,keyPwd:i,signAlg:t?.signAlg??bt.signAlg,keystoreFile:s,keystorePwd:i}),{p12FilePath:s,csrFilePath:a,keyPwd:i,keyAlias:e?.keyAlias??bt.keyAlias}}var nM=["p12","cer","csr","p7b"];async function Xu(n,e){for(let t of nM){let r=await Ae(n,e,t);await eM.rm(r,{force:!0})}}function Zu(n){let e;try{e=tM(n,"utf-8")}catch{throw new Error(E.ERR_CERT_INVALIDATE)}if(!Be.CERT_PATTERN.test(e))throw new Error(E.ERR_CERT_INVALIDATE)}async function rS(n,e){return{certPath:await Ae(n,e,"cer"),csrPath:await Ae(n,e,"csr"),p12Path:await Ae(n,e,"p12"),profilePath:await Ae(n,e,"p7b")}}async function Qu(n,e){let t=e??"",r=J.discover(process.cwd()).rootDir;await Xu(t,r);let o=Vu(n.teamId),i=await Cc(n,o);if(i&&!await zu(n,i.id))throw new Error(E.ERR_DOWNLOAD_CER);let s=await Ku(e),a;try{a=rM(s.csrFilePath,"utf-8")}catch{throw new Error(E.ERR_READ_CSR)}console.log("Start generating certificate"),await qu(n,a,o);let c=await Cc(n,o);if(!c)throw new Error(E.ERR_DOWNLOAD_CER);let l=await Yu(n,c.certObjectId);if(!l)throw new Error(E.ERR_DOWNLOAD_CER);let d=await Ae(t,r,"cer");await Bi(l,d),Zu(d);let h=await Ae(t,r,"p7b");return{p12FilePath:s.p12FilePath,csrFilePath:s.csrFilePath,cerFilePath:d,profileFilePath:h,certId:c.id,keyAlias:s.keyAlias,keyPwd:s.keyPwd,storePassword:s.keyPwd}}import Mc from"crypto";import $n from"fs";import*as wS from"path";import IM from"json5";import{execa as hS}from"execa";import gS from"node-forge";import{createCipheriv as oM,createDecipheriv as iM,pbkdf2Sync as sM,randomBytes as rp}from"crypto";import{promises as mr}from"fs";import{dirname as aM,join as Et}from"path";var Ac=3,Vi=16,cM=1e4,oS="material",lM=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),cS="aes-128-gcm",pr=12,Dc=16,_n=4;function ep(n){return new Uint8Array(rp(n))}function dM(n){return rp(n).toString("hex")}function uM(...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 iS(n,e,t=cM,r=Vi){let o=[...n,lM],i=uM(...o),s=Buffer.from(i).toString("utf8"),a=Buffer.from(s,"utf8"),c=sM(a,e,t,r,"sha256");return new Uint8Array(c)}function sS(n,e){let t=rp(pr),r=oM(cS,n,t),o=Buffer.concat([r.update(e),r.final()]),i=r.getAuthTag(),s=Buffer.concat([o,i]),a=s.length,c=Buffer.alloc(_n+pr+s.length);return c.writeUInt32BE(a,0),t.copy(c,_n),s.copy(c,_n+pr),c}function aS(n,e){if(e.length<_n+pr+Dc)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(_n,_n+pr),o=e.subarray(_n+pr,_n+pr+t);if(o.length<Dc)throw new Error("Ciphertext too short for auth tag");let i=o.subarray(0,o.length-Dc),s=o.subarray(o.length-Dc),a=iM(cS,n,r);return a.setAuthTag(s),Buffer.concat([a.update(i),a.final()])}async function pM(n){try{await mr.rm(n,{recursive:!0,force:!0})}catch{}}async function tp(n){let e=await mr.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 mr.readFile(Et(n,t[0]))}async function np(n,e){let t=dM(Vi),r=Et(n,t);return await mr.writeFile(r,e),t}var Fn=class{static async generateMaterial(e){let t=Et(e,oS);await pM(t);let r=Et(t,"ac"),o=Et(t,"ce");await mr.mkdir(r,{recursive:!0}),await mr.mkdir(o,{recursive:!0});for(let d=0;d<Ac;d++)await mr.mkdir(Et(t,"fd",String(d)),{recursive:!0});let i=ep(Vi),s=[];for(let d=0;d<Ac;d++)s.push(ep(Vi));let a=ep(Vi),c=iS(s,i),l=sS(c,a);await np(r,i),await np(o,l);for(let d=0;d<Ac;d++){let h=Et(t,"fd",String(d));await np(h,s[d])}return a}static async readMaterial(e){let t=Et(e,oS),r=Et(t,"ac"),o=new Uint8Array(await tp(r)),i=[];for(let d=0;d<Ac;d++){let h=Et(t,"fd",String(d)),w=await tp(h);i.push(new Uint8Array(w))}let s=Et(t,"ce"),a=await tp(s),c=iS(i,o),l=aS(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t=aM(e);try{return await this.readMaterial(t)}catch{return await this.generateMaterial(t)}}static async encryptedPassword(e,t){let r=await this.getStoreKey(t),o=Buffer.from(e,"utf8");return sS(r,o).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),o=Buffer.from(e,"hex");return aS(r,o).toString("utf8")}};import mS from"fs";import Oc from"path";import wM from"json5";import*as Tc from"fs";import*as lS from"path";function Rc(n){let e=lS.resolve(n);if(!Tc.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=Tc.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 vo from"fs";import*as We from"path";import{debuglog as wo}from"util";var dS={"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 mM(n){return Object.prototype.hasOwnProperty.call(dS,n)}function kc(n){if(mM(n))return dS[n]}var uS={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as fM}from"url";var Nc=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 xc(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function pS(n){return n==null||n.length===0}function hM(n){return!pS(n)}function op(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function gM(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 yM(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 jn=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=We.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=We.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=We.join(t.sdkPath,"default","sdk-pkg.json"),a=Rc(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=We.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(vo.existsSync(e))return vo.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=fM(e);if(t.includes("dist")){let s=We.dirname(t),a=We.dirname(s);return We.join(a,"src","resources")}let r=We.dirname(t),o=We.dirname(r),i=We.dirname(o);return We.join(i,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{wo("read builtin acl permission failed.");return}if(r!==void 0)try{let o=JSON.parse(r),s=(Array.isArray(o)?o:xc(o)?Object.values(o):[]).filter(xc).map(a=>new Nc(a));s.forEach(a=>{let c=a.permissionInsteadName;hM(c)&&(a.permissionInsteadName=kc(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(o){wo(`failed to parse aclPermissionsInfo.json: ${o}`)}}static initAclPermissionFromSDK(e,t,r){let o=this.parsePermissionDefinitionFile(e);o&&o.forEach(i=>{if(!xc(i))return;let s=i,a=op(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(pS(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||op(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||op(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:gM(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let o=new Nc;o.permissionName=t;let i=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;o.permissionDisplayName=i;let s=yM(r,this.ACL_SINCE_KEY);o.minSupportApiLevel=String(s),this.handleInsteadName(o,i),e.add(o)}static parsePermissionDefinitionFile(e){let t=We.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!vo.existsSync(t))return;let r;try{r=vo.readFileSync(t,"utf-8")}catch(s){wo(`failed to load permissionDefinitions.json: ${s}`);return}let o;try{let s=JSON.parse(r);if(!xc(s)){wo("json object is null");return}o=s}catch(s){wo(`failed to parse permissionDefinitions.json: ${s}`);return}let i=o[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(i)){wo("definePermissions is not an array");return}return i}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=kc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=kc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function Lc(n,e){let t=new Set,r=new Set;jn.handleSpecificAclPermissions(),jn.initAclPermission(n,e);for(let o of n.profile.modules){let i=fS(o,n,e,r,Oc.join("src","main"));for(let a of i)t.add(a);let s=fS(o,n,e,r,Oc.join("src","ohosTest"));for(let a of s)t.add(a)}return vM(r),t}function vM(n){if(n.size>0)throw new Error(uS.DUPLICATE_PERMISSION)}function fS(n,e,t,r,o){let i=bM(e.rootDir,n,o);if(i==null)return new Set;let s=[];for(let w of i){if(typeof w!="object"||w===null)continue;let v=SM(w,"name");v&&s.push(v)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=Oc.join(t.sdkPath,"default","sdk-pkg.json"),l=Rc(c),d=jn.getAclPermissionInfos(e),h=new Set(Array.from(d).filter(w=>{let v=Number(w.minSupportApiLevel);return Number.isFinite(v)&&v<=l}).map(w=>w.permissionName));for(let w of Array.from(a))h.has(w)||a.delete(w);return a}function SM(n,e){let t=n[e];return typeof t=="string"?t:""}function bM(n,e,t){let r=Oc.join(n,e.srcPath,t,"module.json5"),o=EM(r);if(o==null)return null;let i=PM(o,"module");return i==null?null:CM(i,"requestPermissions")}function EM(n){try{if(!mS.existsSync(n))return null;let e=mS.readFileSync(n,"utf-8");return wM.parse(e)}catch{return null}}function PM(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 CM(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var sp=class{verifyStorePassword(e,t){try{let r=$n.readFileSync(e),o=gS.asn1.fromDer(r.toString("binary"));return gS.pkcs12.pkcs12FromAsn1(o,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=$n.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(o=>this.formatFp(new Mc.X509Certificate(o).fingerprint256));try{return[this.formatFp(new Mc.X509Certificate($n.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let o=$n.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let i of o)try{let s=new Mc.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 AM(n){let e=$n.readFileSync(n,"utf-8"),t=DM(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let o=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:ip(o["bundle-name"]),expiryDate:TM(r?.validity?.["not-after"]),cerFingerprintInProfile:RM(ip(o["development-certificate"])),deviceUdidsInProfile:kM(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:xM(r?.acls?.["allowed-acls"]),teamIdInProfile:ip(o["developer-id"])}}function DM(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 TM(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function RM(n){if(!n)return null;try{let t=new Mc.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function kM(n){return Array.isArray(n)?Ui(n.filter(e=>typeof e=="string")):[]}function xM(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 ip(n){return typeof n=="string"?n:null}var Gi=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.#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=J.discover(process.cwd()),a=s.rootDir,c=Ui(e.manualUdids??[]),[l,d]=await Promise.all([NM(i,a),LM(t.hdcPath,c.length>0)]),h=null;if(yS(l).allExist)try{h=AM(l.profileFile)}catch{}return{force:r,teamId:o,productName:i,projectPath:a,materialPaths:l,bundleName:s.getBundleName(),deviceUdids:Ui([...d,...c]),manualUdids:c,storePassword:await OM(a,i,l.storeFile),localAclPermissions:[...Lc(s,t)].sort(),hapSignTool:new sp,profileInfo:h}}static#t(e){return e.force?(m("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:Ke({force:!0})}):null}static#n(e){let t=yS(e.materialPaths);return t.allExist?null:(m(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:Ke({allFilesExist:!1,missingFiles:t.missing})})}static#r(e){return(e.profileInfo?.rawContent??"").trim().length>0?null:(m("[reGenerateSign] profile content is empty"),{shouldRegenerate:!0,reason:"Profile file content is empty",checkDetails:Ke({allFilesExist:!0,profileContentNotEmpty:!1})})}static#o(e){let t=e.profileInfo?.expiryDate;return!t||t>=new Date?null:(m(`[reGenerateSign] profile expired at ${t.toISOString()}`),{shouldRegenerate:!0,reason:`Profile expired at ${t.toISOString()}`,checkDetails:Ke({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#i(e){let t=e.profileInfo?.bundleNameInProfile;return t&&t===e.bundleName?null:(m(`[reGenerateSign] bundleName mismatch \u2014 current=${e.bundleName}, profile=${t}`),{shouldRegenerate:!0,reason:`bundleName mismatch: current=${e.bundleName}, in profile=${t}`,checkDetails:Ke({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!1})})}static#s(e){let t=e.profileInfo?.teamIdInProfile;return t&&t===e.teamId?null:(m(`[reGenerateSign] teamId mismatch \u2014 current=${e.teamId}, profile=${t}`),{shouldRegenerate:!0,reason:`teamId mismatch: current=${e.teamId}, in profile=${t}`,checkDetails:Ke({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=FM(e.profileInfo?.deviceUdidsInProfile??[],e.deviceUdids);return t.allPresent?null:(m(`[reGenerateSign] missing device UDIDs: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Device UDID(s) not in profile: ${t.missing.map(o=>e.manualUdids.includes(o)?`${o} (manual)`:`${o} (detected)`).join(", ")}`,checkDetails:Ke({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return jM(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(m("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:Ke({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!1})})}static#l(e){let t=e.hapSignTool.getLocalCerFingerprints(e.materialPaths.cerFile),r=e.profileInfo?.cerFingerprintInProfile;return r&&t.includes(r)?null:(m("[reGenerateSign] certificate mismatch"),{shouldRegenerate:!0,reason:"Certificate mismatch between profile and local .cer file",checkDetails:Ke({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!1})})}static#d(e){let t=e.profileInfo?.cerFingerprintInProfile,r=e.hapSignTool.getLocalCerExpiry(e.materialPaths.cerFile,t);return!r||r>=new Date?null:(m(`[reGenerateSign] local certificate expired at ${r.toISOString()}`),{shouldRegenerate:!0,reason:`Local certificate expired at ${r.toISOString()}`,checkDetails:Ke({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!1})})}static async#u(e){return e.storePassword?e.hapSignTool.verifyStorePassword(e.materialPaths.storeFile,e.storePassword)?null:(m("[reGenerateSign] keystore password verification failed"),{shouldRegenerate:!0,reason:"Keystore password verification failed (storeFile may be corrupted or password changed)",checkDetails:Ke({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})}):(m("[reGenerateSign] no stored keystore password"),{shouldRegenerate:!0,reason:"No stored keystore password available for verification",checkDetails:Ke({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})})}static#p(){return m("[reGenerateSign] all checks passed \u2014 skip regeneration"),{shouldRegenerate:!1,reason:"",checkDetails:Ke({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function NM(n,e){let[t,r,o,i]=await Promise.all([Ae(n,e,"p12"),Ae(n,e,"csr"),Ae(n,e,"cer"),Ae(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:o,profileFile:i}}async function OM(n,e,t){let r=wS.join(n,"build-profile.json5");if(!$n.existsSync(r))return;let o;try{o=IM.parse($n.readFileSync(r,"utf-8"))}catch{return}let a=(o?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await Fn.decryptPassword(a,t)}catch{return}}async function LM(n,e){try{return await MM(n)}catch(t){if(!e)throw t;return m(`[reGenerateSign] device detection failed, continuing with --udid only: ${t.message}`),[]}}async function MM(n){m(`Executing: ${n} list targets`);let{stdout:e}=await hS(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let o of e.split(`
|
|
1424
|
+
`)){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{m(`Executing: ${n} -t ${o} shell bm get -u`);let{stdout:i}=await hS(n,["-t",o,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),s=_M(i);s&&r.push(s)}catch{m(`[reGenerateSign] Failed to get UDID for ${o}, skipping`)}return r}function _M(n){let e=n.trim();if(!e)return null;let t=e.split(`
|
|
1425
|
+
`);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 yS(n){let e=[n.storeFile,n.csrFile,n.cerFile,n.profileFile],t=[];for(let r of e)$n.existsSync(r)||t.push(r);return{allExist:t.length===0,missing:t}}function FM(n,e){let t=[];for(let r of e)n.includes(r)||t.push(r);return{allPresent:t.length===0,missing:t}}function jM(n,e){let t=[...n].sort(),r=[...e].sort();return t.length!==r.length?!1:t.every((o,i)=>o===r[i])}function Ke(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 ap}from"util";import{execa as cp}from"execa";async function SS(n,e,t=[]){let r=await _c(n),o=await UM(e,t.length>0),i=Wu(o,t);if(i.length===0)throw new Error(E.DEVICE_LIST_EMPTY);let s=new Set(r.map(l=>l.udid.toUpperCase()));for(let l of i)s.has(l.udid)||await $M(n,l);let c=(await _c(n)).map(l=>l.id);if(c.length===0)throw new Error(E.DEVICE_LIST_EMPTY);return{allDeviceIds:c,devices:i}}async function $M(n,e){try{await HM(n,e.udid,Ec[e.type])}catch(t){let r=e.source==="manual"?"from --udid":"detected locally";throw new Error(`${t.message} (device ${e.udid}, ${r})`,{cause:t})}}async function vS(n,e=1,t=100){let r=`${ie.BASE_URL}${ie.DEVICE_LIST_PATH}?encodeFlag=0&start=${e}&pageSize=${t}`,o=ES(n),i=await L.get(r,{headers:o});if(!i)throw ap("query devices failed: response is null"),new Error(E.ERROR_WHILE_ADD_DEVICE);if(i.statusCode!==200)throw bS(i.statusCode,i.statusText,i.data);let s=JSON.parse(i.data);if(!s||!s.list)throw ap("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 bS(n,e,t){return n===St.FORBIDDEN?e===Ee.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN):n===St.UNAUTHORIZED?new Error(E.ERR_UNAUTHORIZED):t.includes(Ee.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(E.DEVICE_LIMIT_REACHED):new Error(E.ERROR_WHILE_ADD_DEVICE)}async function _c(n){let t=await vS(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 vS(n,s,100);if(!a||!a.deviceList||a.deviceList.length===0)break;r.push(...a.deviceList)}return r}async function HM(n,e,t){let r=`${ie.BASE_URL}${ie.DEVICE_ADD_PATH}`,o=ES(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 ap("add device failed: response is null"),new Error(E.ERROR_WHILE_ADD_DEVICE);if(a.statusCode!==200)throw bS(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(Ee.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(E.DEVICE_LIMIT_REACHED):c.includes(Ee.DEVICE_NAME_REPEAT_CODE)?new Error(E.DEVICE_NAME_REPEAT):new Error(E.ERROR_WHILE_ADD_DEVICE)}function ES(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}async function UM(n,e){try{return await BM(n)}catch(t){if(!e)throw t;return m(`[registerDevice] local detection failed, continuing with --udid only: ${t.message}`),[]}}async function BM(n){m(`Executing: ${n} list targets`);let{stdout:e}=await cp(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let o of e.split(`
|
|
1426
|
+
`)){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 WM(o,n),s=await VM(o,n);i.length>0&&r.push({udid:i,type:s})}catch{m(`Failed to get device info for ${o}, skipping`)}return r}async function WM(n,e){m(`Executing: ${e} -t ${n} shell bm get -u`);let{stdout:t}=await cp(e,["-t",n,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),r=t.trim();if(!r)return"";let o=r.split(`
|
|
1427
|
+
`);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 VM(n,e){let t="hw_sc.build.os.deviceType";m(`Executing: ${e} -c -t ${n} shell getprop ${t}`);let{stdout:r}=await cp(e,["-c","-t",n,"shell","getprop",t],{stdio:["ignore","pipe","pipe"]});return GM(r)}function GM(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 fr from"fs";import{createHash as zM}from"crypto";import{Buffer as CS}from"buffer";import{createPublicKey as qM,X509Certificate as lp}from"crypto";import{readFileSync as YM}from"fs";import hr from"node-forge";async function IS(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=`${ie.BASE_URL}${ie.PROVISION_ADD_TEST_PATH}`,h=JM(t,r),w=await XM(n,d,a||[],r,s,h,i||[]);if(!w||!w.profileInfo||!w.profileInfo.provisionFileUrl)throw m("add provision failed, the provision file url is null"),new Error(E.ADD_PROFILE_FAIL);let v=w.profileInfo,ne=(await t_(n,v.provisionFileUrl)).urlList,Ve=w.profileInfo.id;if(ne&&ne.length>0){let ct=await rS(t,o),lt=ct.profilePath;if(!await n_(ne,lt))throw await PS(n,Ve),new Error(E.ERROR_WHILE_DOWNLOAD_PROFILE);if(await PS(n,Ve),fr.existsSync(ct.certPath)&&fr.existsSync(lt)&&fr.existsSync(ct.p12Path)){let Bc=fr.readFileSync(ct.certPath,"utf8"),Wc=fr.readFileSync(lt,"utf8");return r_(Wc,Bc,ct.p12Path,c,l)||e_(lt),lt}}throw new Error(E.ADD_PROFILE_FAIL)}function JM(n,e){let t=n?`${n}_`:"";return`${KM(`${t}${e}_${e}`)}`}function KM(n){return zM("sha256").update(n).digest("hex").substring(0,16)}async function XM(n,e,t,r,o,i,s){ZM(r);let a=up(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 m("add provision failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw dp(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw m(`add provision fail: ${l.data}`),QM(l.data,i),new Error(d.ret?.msg||E.ADD_PROFILE_FAIL);let h=d.provisionFileUrl;return{profileInfo:{id:d.id,name:i,provisionFileUrl:h}}}function dp(n,e,t){return n===St.FORBIDDEN?e===Ee.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN):n===St.UNAUTHORIZED?new Error(E.ERR_UNAUTHORIZED):t.includes(Ee.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(E.TEST_PROVISION_EXCEEDS_LIMIT):new Error(E.ADD_PROFILE_FAIL)}function ZM(n){if(!n||n.trim().length===0)throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!Be.BUNDLE_NAME_REGEX.test(n))throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function QM(n,e){if(n.includes(Ee.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(E.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(Ee.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(E.PROFILE_NAME_REPEAT)}async function PS(n,e){if(!e||e.trim().length===0)return;let t=`${ie.BASE_URL}${ie.PROVISION_DELETE_PATH}?id=${e}`,r=await L.deleteAllowFailure(t,{headers:up(n)});if(r.statusCode!==200)throw dp(r.statusCode,r.statusText,r.data);let o=JSON.parse(r.data);(!o||!o.ret||o.ret.code!==0)&&m(`delete provision failed: ${r.data}`)}function e_(...n){for(let e of n)try{fr.existsSync(e)&&fr.unlinkSync(e)}catch(t){m(`delete local sign file error: ${t.message}`)}}async function t_(n,e){let t=`${ie.BASE_URL}${ie.CERT_DOWNLOAD_URL_PATH}`,r=up(n),o={sourceUrls:e},i=await L.postAllowFailure(t,{headers:r,params:o});if(!i)throw m("get download list failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(i.statusCode!==200)throw dp(i.statusCode,i.statusText,i.data);let s=JSON.parse(i.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw m("download: The application does not exist"),new Error(s.ret?.msg||E.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function n_(n,e){if(!n||n.length===0)return!1;let t=n[0].newUrl;return await Bi(t,e),!0}function r_(n,e,t,r,o){return o_(n,e),r=r||Be.TARGET_FRIENDLY_NAME,o=o||"",i_(e,t,r,o),!0}function o_(n,e){if(e.lastIndexOf(Be.CERT_BEGIN_HEADER)<0)throw new Error(E.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(Be.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function i_(n,e,t,r){let o=n.matchAll(Be.CERTIFICATE_PATTERN_GLOBAL),i=[],s=new Date;for(let c of o)try{let l=c[0],d=s_(l),h=new Date(d.validFrom),w=new Date(d.validTo);if(s<h||s>w){let v=`Certificate is not valid, Valid from ${h} to ${w}`;throw console.warn(`checkCertificateInValidityPeriod: ${v}`),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(!c_(e,t,r,i))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function s_(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new lp(t);let r=CS.from(t,"base64");return new lp(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function a_(n){if(n.cert){let e=hr.pki.publicKeyToPem(n.cert.publicKey);return qM(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=hr.asn1.toDer(n.asn1).getBytes(),t=CS.from(e,"binary");return new lp(t).publicKey.export({type:"spki",format:"der"})}catch(e){return m(`Failed to parse cert from asn1: ${e}`),null}return null}function c_(n,e,t,r){try{let o=YM(n),i=hr.asn1.fromDer(hr.util.createBuffer(o)),c=hr.pkcs12.pkcs12FromAsn1(i,t).getBags({bagType:hr.pki.oids.certBag})[hr.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let h=a_(l);if(!h)continue;if(r.some(v=>{let T=v.publicKey.export({type:"spki",format:"der"});return h.equals(T)}))return!0}return!1}catch(o){let i=o instanceof Error?o.message:String(o);return m(`Failed to process P12 file: ${n}, error: ${i}`),!1}}function up(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var DS="https://developer.huawei.com",l_={"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"},d_="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function u_(n){let e=l_[n];return e?`${DS}${e}`:void 0}function p_(){return`${DS}${d_}`}var m_={"acl.can.apply.text":"Permission Application Scenarios","acl.permissions.warn":"Note: You are applying for restricted ACL permissions: {0} These permissions are subject to review together with your app release. For a faster review process, apply for the following permissions instead, if they are sufficient for your purposes: {1} {2}"};function AS(n,e){return(m_[n]??n).replace(/\{(\d+)\}/g,(r,o)=>String(e[Number(o)]??""))}function f_(n){return Array.from(n).join(", ")}function TS(n,e){if(n.size===0)return;let t=jn.getAclPermissionInfos(e),r=new Set;for(let h of t)n.has(h.permissionName)&&r.add(h);for(let h of r){let w=u_(h.permissionName);w!=null&&(h.permissionHelpUrlKey=w)}let o=new Set;for(let h of r)o.add(h.permissionDisplayName);let i=new Set;for(let h of r)if(h.permissionHelpUrlKey!=null){let w=h.permissionInsteadName??h.permissionDisplayName;i.add(`${w} (${h.permissionHelpUrlKey})`)}let s=p_(),a=AS("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=i.size>0?Array.from(i).join(", ")+".":"",d=AS("acl.permissions.warn",[f_(o),l,c]);console.log(d)}var Fc=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=J.discover(process.cwd()),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Project.discover() failed: ${t.message}`),e(te.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Product validation failed: ${r.message}`),t(`Product "${e}" not found.Check the product property in the build-profile.json5 file.`)}}checkBundleName(e,t){try{return this._project.getBundleName(),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] BundleName check failed: ${r.message}`),t(`bundleName was not found under product "${e}".Check the bundleName configuration.`)}}checkAtomicService(){return this._project.isAtomicService()?{passed:!1,message:te.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import h_ from"fs";import RS from"path";var jc=class{constructor(e){this.toolProvider=e}toolProvider;checkJava(e){try{return this.toolProvider.assertJava(),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Java check failed: ${t.message}`),e(te.JAVA_PLATFORM_UNSUPPORTED)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=b()?"hap-sign-tool":"hap-sign-tool.jar",o=RS.join(t,"default","openharmony","toolchains","lib",r);if(!h_.existsSync(o)){let i=RS.join("sdk","default","openharmony","toolchains","lib",r);return e(`${r} not found.Check whether ${i} exists.`)}return{passed:!0,message:""}}};var $c=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await Re.getUserInfo()}catch(e){return m(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await Re.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(te.LOGIN_REQUIRED)}catch(t){return m(`[EnvCheck] Login check failed: ${t.message}`),e(te.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(te.TEAM_INFO_FAILED);try{if((await pn()).teamList.length>0)return{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Team API error: ${r.message}`),e(te.TEAM_INFO_FAILED)}return m("[EnvCheck] No teams found for current user"),e(te.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(te.REALNAME_REQUIRED):t.isRealName!==!0?(m("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(te.REALNAME_REQUIRED)):{passed:!0,message:""}:e(te.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let o=await pn();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 m(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(o){return m(`[EnvCheck] Team ID check failed: ${o.message}`),{passed:!1,message:`team-id for ${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(te.REGION_CHINA_ONLY):{passed:!0,message:""}:(m("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(te.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function g_(n){try{let{teamList:e}=await pn();if(e.length>0)return e[0].id}catch(e){m(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function y_(n){let e=await Re.getUserInfo(),t=await Re.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await g_(e.userId);if(!r)throw new Error("No team found");let o={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await _c(o)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var Hc=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t,r=!1){if(r)return m("[EnvCheck] Scenario 4 Device check: --udid provided, skipping device detection"),{passed:!0,message:""};try{let o=await y_(t);if(o.length>0)return m(`[EnvCheck] Scenario 4 Device check: ${o.length} device(s) found in AGC cloud, skipping local device check`),{passed:!0,message:""};m("[EnvCheck] Scenario 4 Device check: no cloud devices found, falling back to local hdc");let s=await ae.from(this.toolProvider).listDevices();return s.length===0?(m("[EnvCheck] Scenario 4 Device check: no local devices found"),e(te.DEVICE_MISSING)):s.some(c=>qn(c.serial))?{passed:!0,message:""}:(m("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(te.DEVICE_MISSING))}catch(o){return m(`[EnvCheck] Scenario 4 Device check failed: ${o.message}`),e(te.DEVICE_DETECT_FAILED)}}};var Uc=class{projectChecker=new Fc;toolchainChecker=null;authChecker=new $c;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 D.new();return this.toolchainChecker=new jc(e),this.deviceChecker=new Hc(e),!0}catch(e){throw m(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(te.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,e.hasManualDevices??!1))}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 m(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};function b_(n){if(mp.existsSync(n)){let e=mp.readFileSync(n,"utf-8");return S_.parse(e)}return{app:{signingConfigs:[],products:[]}}}function E_(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function P_(n){if(n.keyPwd===n.storePassword){let r=await Fn.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await Fn.encryptedPassword(n.keyPwd,n.p12FilePath),t=await Fn.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function C_(n,e,t){let r=kS.join(n,"build-profile.json5"),o=b_(r);E_(o);let i=t??"default",{keyPassword:s,storePassword:a}=await P_(e),c={name:i,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:bt.signAlg,storeFile:e.p12FilePath,storePassword:a}},l=o.app?.signingConfigs?.findIndex(h=>h.name===i);l!==void 0&&l>=0?o.app.signingConfigs[l]=c:o.app.signingConfigs.push(c);let d=o.app?.products?.findIndex(h=>h.name===i);d!==void 0&&d>=0?o.app.products[d].signingConfig=i:o.app.products.push({name:i,signingConfig:i}),mp.writeFileSync(r,JSON.stringify(o,null,2),"utf-8")}async function I_(n){let e=await Re.getUserInfo(),t=await Re.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 A_(n){let e=n.product||"default",t=Uu(n.udid??[]);await new Uc().preflight({productName:e,teamId:n.teamId,hasManualDevices:t.length>0}),console.log("Executing signature generate command");let o=await I_(n),i=await D.new(),{shouldRegenerate:s}=await Gi.shouldRegenerate({force:n.force??!1,teamId:o.teamId,productName:n.product,manualUdids:t.map(a=>a.udid)},i);if(!s){console.log(pp("Signature generation completed successfully."));return}await T_(n,o,i,t),console.log(pp("Signature generation completed successfully."))}function D_(n){console.log(`Profile covers ${n.length} device(s):`);for(let e of n){let t=e.source==="manual"&&e.typeInferred?"manual, type inferred":e.source;console.log(` ${e.udid} ${e.type.padEnd(12)} (${t})`)}}async function T_(n,e,t,r){let o=await Qu(e,n.product),i=R_(n,e,o,t),{allDeviceIds:s,devices:a}=await SS(e,t.hdcPath,r);i.allDeviceIds=s,await IS(e,i),D_(a);let c=J.discover(process.cwd()).rootDir;await C_(c,o,n.product??"default"),console.log(pp(`Signing config written to ${kS.join(c,"build-profile.json5")}`))}function R_(n,e,t,r){let o=process.cwd(),i=J.discover(o),s=Lc(i,r);return TS(s,i),{productName:n.product||"default",bundleName:i.getBundleName(),projectPath:i.rootDir,teamId:e.teamId,force:n.force||!1,aclPermissionList:[...s],certIds:[t.certId],keyAlias:t.keyAlias,keyPwd:t.keyPwd}}var xS=new w_("signature").description("Generate application signature.");xS.command("generate").description("Automatically generate signing materials and write them to the project configuration.").option("--force","Force overwrite existing local signing materials.").option("--team-id <team-id>","Specify the team ID to use.").option("--product <product>","Specify the product. The default value is default.").option("--udid <udid...>",'Add device UDID(s) that are not connected. Repeatable or comma-separated; append ":<type>" to declare phone|wearable|liteWearable|tv (default: phone).').action(async n=>{let e={event:A.CommandExecuted,args:["signature","generate",...n.force?["--force"]:[],...n.teamId?["--team-id"]:[],...n.product?["--product"]:[],...n.udid?["--udid",String(Bu(n.udid))]:[]]},t=Date.now(),r=!0,o=null;try{await A_(n)}catch(i){r=!1,o=Y(i),console.error(v_(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await I.track(e,i)}});var NS=xS;if(!Ze())try{I.init(hp.join(Kt(),"TraceLogData")),I.startScheduler()}catch(n){g.error(`[telemetry] init failed: ${n instanceof Error?n.message:String(n)}`)}(async()=>{if(!Ze())try{let n=await D.new();I.setSourceType(n.sourceType);let e=n.readVersion();e&&(n.sourceType==="clt"?I.setCltVersion(e):I.setStudioVersion(e))}catch(n){g.error(`[telemetry] toolchain info failed: ${n instanceof Error?n.message:String(n)}`)}})();le.name("devecocli").description(`HarmonyOS application development command line tool
|
|
1431
1428
|
|
|
1432
|
-
Privacy: ${
|
|
1429
|
+
Privacy: ${bo.PRIVACY_URL}`).version("1.3.11-Test.1");le.addCommand(Cm);le.addCommand(ef);le.addCommand(of);le.addCommand(vf);le.addCommand(gh);le.addCommand(Bh);le.addCommand(zh);le.addCommand(rg);le.addCommand(pg);le.addCommand(Ng);le.addCommand(Ww);le.addCommand(NS);le.addCommand(qv);le.addCommand(fv);b()||le.addCommand(qf);var fp=process.argv.slice(2);fp.length>=2&&fp[fp.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var x_=new Set(["update","auth"]);le.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==le;)t=t.parent;x_.has(t.name())||await D.checkVersion()});le.parseAsync(process.argv).finally(()=>{I.stopScheduler();try{il(hp.join(Kt(),"TraceLogData"))}catch(n){g.error(`[telemetry] background upload spawn check failed: ${n instanceof Error?n.message:String(n)}`)}}).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(k_(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
|