@deveco-test/deveco-cli 1.3.0-Test.2 → 1.3.0-Test.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,44 +1,46 @@
1
1
  #!/usr/bin/env node
2
- import{bootstrap as rb}from"global-agent";import{program as Z}from"commander";import{red as ib}from"colorette";import{Command as ku}from"commander";import{green as Ds,red as Ci,yellow as As}from"colorette";import X from"fs";import*as Q from"path";import Ke from"json5";import*as bi from"fs";import*as B from"path";function y(n){process.env.DEVECO_CLI_DEBUG&&console.log(`[DEBUG] ${n}`)}var b=class n{static ASCII_CONTROL_MAX=31;static ASCII_DELETE=127;static parsePositiveInteger(e,t="value"){let r=e.trim();if(!/^\d+$/.test(r))throw new Error(`${t} must be a positive integer`);let i=Number.parseInt(r,10);if(!Number.isInteger(i)||i<=0)throw new Error(`${t} must be a positive integer`);return i}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
2
+ import{bootstrap as Ab}from"global-agent";import{program as X}from"commander";import{red as xb}from"colorette";import{Command as Yu}from"commander";import{green as Fs,red as _i,yellow as js}from"colorette";import q from"fs";import*as Q from"path";import et from"json5";import*as ki from"fs";import*as W from"path";function g(n){process.env.DEVECO_CLI_DEBUG&&console.log(`[DEBUG] ${n}`)}var b=class n{static ASCII_CONTROL_MAX=31;static ASCII_DELETE=127;static parsePositiveInteger(e,t="value"){let r=e.trim();if(!/^\d+$/.test(r))throw new Error(`${t} must be a positive integer`);let i=Number.parseInt(r,10);if(!Number.isInteger(i)||i<=0)throw new Error(`${t} must be a positive integer`);return i}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
3
3
  `)}static parseDurationToSeconds(e,t="value"){let i=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!i)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported).`);let o=i[1];if((i[2]??"s")==="s")return n.parsePositiveInteger(o,t);if(!/^\d+(?:\.\d)?$/.test(o))throw new Error(`${t} supports a maximum of 1 decimal place for minutes (e.g. 2.5m).`);let a=Number.parseFloat(o);if(!Number.isFinite(a)||a<=0)throw new Error(`${t} must be a positive duration.`);return Math.round(a*60)}static 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,i=new Date){if(!t&&!r)return e;let[o,s]=n.resolveTimeBounds(t,r,i),a=e.split(/\r?\n/),c=[],l=!1;for(let u of a){let f=n.extractTimestampFromLogLine(u,i);f&&(l=n.isWithinBounds(f,o,s)),l&&c.push(u)}return c.join(`
4
- `)}static resolveTimeBounds(e,t,r){let i=e?new Date(r.getTime()-e*1e3):null,o=t?new Date(r.getTime()-t*1e3):null;return i&&o?i<o?[i,o]:[o,i]:i?[i,r]:o?[null,o]:[null,null]}static isWithinBounds(e,t,r){let i=e.getTime(),o=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(o!==null&&i<o||s!==null&&i>s)}static extractTimestampFromLogLine(e,t){let r=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!r)return null;let i=t.getFullYear(),o=Number.parseInt(r[1],10)-1,s=Number.parseInt(r[2],10),a=Number.parseInt(r[3],10),c=Number.parseInt(r[4],10),l=Number.parseInt(r[5],10),u=r[6]??"0",f=Number.parseInt(u.padEnd(3,"0").slice(0,3),10),E=new Date(i,o,s,a,c,l,f);return E.getTime()>t.getTime()+1440*60*1e3&&E.setFullYear(i-1),E}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(r=>{let i=r.charCodeAt(0);return i<=n.ASCII_CONTROL_MAX||i===n.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let r=`'${e.replace(/'/g,"'\\''")}'`;return y(`quotePosixShellArg: ${e} -> ${r}`),r}static assertCrashFilename(e){if(!/^\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(B.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=B.resolve(B.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=B.normalize(e),i=B.relative(r,t);if(i.split(B.sep)[0]===".."||B.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||B.isAbsolute(e)}static isPathContained(e,t){let r=B.resolve(t,e),i=B.relative(t,r);return n.isPathEscaping(i)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){if(B.isAbsolute(e))return{contained:!1,reason:`Absolute path is not allowed: ${e}`};let r=n.isPathContained(e,t);if(!r.contained)return r;let i;try{i=bi.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=B.resolve(i,e),s;try{s=bi.realpathSync(o)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${o}`}}return n.isPathContained(s,i)}};var Ze=class n{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let r=n.tryLoadProjectProfile(t);if(r)return new n(t,r);let i=Q.dirname(t);if(i===t)break;t=i}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=Q.join(e,"build-profile.json5");if(!X.existsSync(t))return null;try{let r=X.readFileSync(t,"utf-8"),i=Ke.parse(r);return i.app?i:null}catch(r){return console.error(`Error parsing ${t}:`,r),null}}getModuleType(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=b.resolvePathWithinRoot(this.rootDir,t.srcPath),i=Q.join(r,"src","main","module.json5");if(!X.existsSync(i))return"entry";try{let o=X.readFileSync(i,"utf-8");return Ke.parse(o)?.module?.type||"entry"}catch(o){return console.warn(`Warning: Failed to parse ${i}:`,o),"entry"}}getModuleProfile(e){let t=this.profile.modules.find(a=>a.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=b.resolvePathWithinRoot(this.rootDir,t.srcPath),i=Q.join(r,"build-profile.json5");if(!X.existsSync(i))throw new Error(`Build profile for module '${e}' not found at ${i}.`);let o=X.readFileSync(i,"utf-8");return Ke.parse(o)}getBundleName(){let e=Q.join(this.rootDir,"AppScope","app.json5");if(X.existsSync(e))try{let t=X.readFileSync(e,"utf-8"),r=Ke.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.")}getMainAbility(e,t){if(t)return t;let r=this.profile.modules.find(s=>s.name===e);if(!r)return"EntryAbility";let i=b.resolvePathWithinRoot(this.rootDir,r.srcPath),o=Q.join(i,"src","main","module.json5");if(!X.existsSync(o))return"EntryAbility";try{let s=X.readFileSync(o,"utf-8"),c=Ke.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let l=c.find(u=>u.name==="EntryAbility");return l?l.name:c[0].name}catch(s){return console.warn(`Warning: Failed to parse ${o}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new Error(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`);if(!this.profile.app.products?.some(r=>r.name===e)){let r=this.profile.app.products?.map(i=>i.name).join(", ")||"none";throw new Error(`Product '${e}' not found in project configuration. Available products: ${r}`)}}getModuleDependencies(e){let t=this.profile.modules.find(s=>s.name===e);if(!t)return[];let r=b.resolvePathWithinRoot(this.rootDir,t.srcPath),i=Q.join(r,"oh-package.json5");if(!X.existsSync(i))return[];let o=[];try{let s=X.readFileSync(i,"utf-8"),c=Ke.parse(s)?.dependencies||{};for(let l of Object.values(c)){if(typeof l!="string")continue;let u=l;if(!(u.startsWith("file:")||u.startsWith(".")||u.startsWith("..")))continue;u.startsWith("file:")&&(u=u.substring(5));let E=Q.join(t.srcPath,u),M=b.resolvePathWithinRoot(this.rootDir,E),j=this.profile.modules.find(wi=>Q.resolve(this.rootDir,wi.srcPath)===M);j&&o.push(j.name)}}catch{}return o}collectNonHarDependentModuleList(e){let t=[],r=[],i=new Set;for(r.push(e),i.add(e);r.length>0;){let o=r.shift();this.getModuleType(o)!=="har"&&t.push(o);let a=this.getModuleDependencies(o);for(let c of a)i.has(c)||(r.push(c),i.add(c))}return t}findArtifactPath(e,t,r,i="default"){this.validateProduct(i);let o=this.profile.modules.find(M=>M.name===e);if(!o)throw new Error(`Module '${e}' not found`);let a=this.getModuleType(e)==="shared",c=a?"hspName":"hapName",l=this.buildOutputPath(o.srcPath,i,["intermediates",a?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!X.existsSync(l))throw new Error(`Build metadata not found for module '${e}' at ${l}. Build the project first.`);let{packageName:u,isSigned:f}=this.parseOutputMetadata(l,c);if(!r&&!f)throw new Error(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`);let E=this.buildOutputPath(o.srcPath,i,["outputs",t,u]);if(!X.existsSync(E))throw new Error(`Generated package file not found in ${E}.`);return E}buildOutputPath(e,t,r){let i=b.resolvePathWithinRoot(this.rootDir,e),o=Q.resolve(i,"build",t,...r);return b.ensurePathWithinRoot(this.rootDir,o)}parseOutputMetadata(e,t){let r=X.readFileSync(e,"utf-8"),i=Ke.parse(r),o,s=!1;if(Array.isArray(i)){let a=i[0];a&&(o=a[t],s=a.isSigned===!0)}else i&&typeof i=="object"&&(o=i[t],s=i.isSigned===!0);if(!o)throw new Error(`Could not find ${t} in output_metadata.json at ${e}`);return this.validatePackageName(o),{packageName:o,isSigned:s}}validatePackageName(e){let t=Q.basename(e);if(t!==e)throw new Error(`Invalid traversal name: '${e}'. It must contain path characters.`);if(!t.endsWith(".hap")&&!t.endsWith(".hsp"))throw new Error(`Invalid package name '${t}'.It must be a .hap or .hsp file.`)}};import{execFileSync as Si}from"child_process";import _,{existsSync as bs}from"fs";import*as D from"path";import*as ie from"os";import bu from"regedit";import{join as Ss}from"path";import{red as Su}from"colorette";var Es="https://developer.huawei.com/consumer/cn/download/",Ps="6.1.0",_n=n=>new Promise((e,t)=>{bu.list(n,(r,i)=>{r?t(r):e(i)})}),L=class n{_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;_emulatorLauncherPath;static _verifiedPaths=new Set;static _powerShellPath;static verifyAndCache(e){n._verifiedPaths.has(e)||(n.verifySignature(e),n._verifiedPaths.add(e))}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return n.verifyAndCache(this._nodePath),this._nodePath}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get javaPath(){return n.verifyAndCache(this._javaPath),this._javaPath}get sdkPath(){return this._sdkPath}get hdcPath(){return n.verifyAndCache(this._hdcPath),this._hdcPath}get emulatorPath(){return n.verifyAndCache(this._emulatorPath),this._emulatorPath}get emulatorLauncherPath(){return this._emulatorLauncherPath&&n.verifyAndCache(this._emulatorLauncherPath),this._emulatorLauncherPath}constructor(e,t,r,i,o,s,a,c,l){this._devecoStudioPath=e,this._nodePath=t,this._ohpmJsPath=r,this._hvigorJsPath=i,this._javaPath=o,this._sdkPath=s,this._hdcPath=a,this._emulatorPath=c,this._emulatorLauncherPath=l}static enforceStudioMinVersion(e){let t=n.parseProductInfoVersion(e);if(t===void 0)throw new Error(`Failed to determine DevEco Studio version at ${e}`);n.assertMinVersion(e,t)}static async checkVersion(){let e=await n.findDevEcoStudio();n.enforceStudioMinVersion(e)}static async new(){let e=await n.findDevEcoStudio(),{nodePath:t,ohpmJsPath:r,hvigorJsPath:i,javaPath:o,sdkPath:s,hdcPath:a,emulatorPath:c}=n.resolveTools(e),l=n.getEmulatorExe(e);return new n(e,t,r,i,o,s,a,c,l??void 0)}static _cachedInstallRoot;static async findDevEcoStudio(){if(n._cachedInstallRoot!==void 0)return y(`[ToolProvider] findDevEcoStudio: cache hit -> ${n._cachedInstallRoot}`),n._cachedInstallRoot;let e=ie.platform(),t=e==="win32"?await n.collectCandidatesWindows():e==="darwin"?n.collectCandidatesMac():(()=>{throw new Error("Linux is not fully supported yet for automatic DevEco Studio detection.")})();return n._cachedInstallRoot=n.pickLatestByProductInfo(t),n._cachedInstallRoot}static async collectCandidatesWindows(){let e=new Set,t=[],r=(i,o)=>{if(!n.isExistingDirectory(i))return;let s=D.normalize(i).toLowerCase();e.has(s)||(e.add(s),t.push(i),y(`[ToolProvider] Found via ${o}: ${i}`))};if(await n.addFromUninstallKey(r),await n.addFromHuaweiStudioKeys(r),n.addFromDefaultWindowsPath(r),t.length===0)throw new Error("DevEco Studio installation not found in registry or default locations.");return t}static UNINSTALL_REGISTRY_PARENTS=["HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall","HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"];static HUAWEI_STUDIO_REGISTRY_KEYS=["HKLM\\SOFTWARE\\Huawei\\DevEco Studio","HKLM\\SOFTWARE\\WOW6432Node\\Huawei\\DevEco Studio"];static isDevEcoStudioUninstallSubkey(e){return e.normalize("NFKC").trim().toLowerCase().startsWith("deveco studio")}static async addFromUninstallKey(e){for(let t of n.UNINSTALL_REGISTRY_PARENTS)try{let o=((await _n([t]))[t]?.keys??[]).filter(n.isDevEcoStudioUninstallSubkey);if(o.length===0)continue;let s=o.map(c=>`${t}\\${c}`),a=await _n(s);for(let c of s){let l=a[c]?.values?.InstallLocation?.value;e(l,`Uninstall registry key (${c})`)}}catch{}}static async addFromHuaweiStudioRegistryKey(e,t,r){try{let o=(await _n([t]))[t]?.keys??[];if(o.length===0)return;let s=o.map(c=>`${t}\\${c}`),a=await _n(s);for(let c of s){let l=a[c]?.values?.[""]?.value;e(l,`${r} subkey ${c}`)}}catch{}}static async addFromHuaweiStudioKeys(e){for(let t of n.HUAWEI_STUDIO_REGISTRY_KEYS){let r=t.includes("WOW6432Node")?"Huawei DevEco Studio (WOW6432Node)":"Huawei DevEco Studio";await n.addFromHuaweiStudioRegistryKey(e,t,r)}}static addFromDefaultWindowsPath(e){let t=D.join("C:","Program Files","Huawei","DevEco Studio");e(t,"default installation path")}static collectCandidatesMac(){let e=ie.homedir(),t=[D.join(e,"Applications"),"/Applications"],r=[],i=new Set;for(let o of t){if(!_.existsSync(o))continue;let s;try{s=_.readdirSync(o)}catch{continue}for(let a of s){if(!a.endsWith(".app")||!a.toLowerCase().includes("deveco"))continue;let l=D.join(o,a);n.isExistingDirectory(l)&&(i.has(l)||(i.add(l),r.push(l),y(`[ToolProvider] Found macOS candidate: ${l}`)))}}if(r.length===0)throw new Error("DevEco Studio not found in /Applications or ~/Applications.");return r}static productInfoPath(e){return ie.platform()==="darwin"?D.join(e,"Contents","product-info.json"):D.join(e,"product-info.json")}static macInfoPlistPath(e){return D.join(e,"Contents","Info.plist")}static readMacInfoPlistKey(e,t){if(!_.existsSync(e)){y(`[ToolProvider] Info.plist not found at: ${e}`);return}try{let r=Si("defaults",["read",e,t],{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:5e3}).trim();if(r.length>0&&r!=="(null)")return r}catch{y(`[ToolProvider] defaults read failed for ${e} key ${t}`)}}static extractCompactBuildCode(e){let t=e.split(".").at(-1);if(t!==void 0&&/^\d+$/.test(t))return t}static compactPrefixFromShortVersion(e){let t=e.split(".").slice(0,3);if(!(t.length<3||!t.every(r=>/^\d+$/.test(r))))return t.join("")}static extractFourthSegmentMatchingShortVersion(e,t){let r=n.compactPrefixFromShortVersion(e),i=n.extractCompactBuildCode(t);if(r===void 0||i===void 0)return;if(!i.startsWith(r)){y(`[ToolProvider] CFBundleVersion suffix ${i} does not match short-version prefix ${r} (${e})`);return}let o=i.slice(r.length);if(!(o.length===0||!/^\d+$/.test(o)))return o}static readMacFourthSegmentFromPlist(e,t){let r=n.readMacInfoPlistKey(e,"CFBundleVersion");if(r!==void 0){let s=n.extractFourthSegmentMatchingShortVersion(t,r);if(s!==void 0)return s}let i=n.readMacInfoPlistKey(e,"CFBundleGetInfoString");if(i===void 0)return;let o=i.match(/DS-[\d.]+/);if(o!==null)return n.extractFourthSegmentMatchingShortVersion(t,o[0])}static parseMacInfoPlistVersion(e){let t=n.macInfoPlistPath(e),r=n.readMacInfoPlistKey(t,"CFBundleShortVersionString");if(r!==void 0){let i=n.readMacFourthSegmentFromPlist(t,r);return i!==void 0?`${r}.${i}`:r}return n.readMacInfoPlistKey(t,"CFBundleVersion")}static parseProductInfoVersion(e){if(ie.platform()==="darwin"){let r=n.parseMacInfoPlistVersion(e);if(r!==void 0)return r}let t=n.productInfoPath(e);if(!_.existsSync(t)){y(`[ToolProvider] product-info.json not found at: ${t}`);return}try{let i=JSON.parse(_.readFileSync(t,"utf-8"))?.version;if(typeof i!="string"||i.trim()===""){y(`[ToolProvider] product-info.json at ${t} has no valid "version" field`);return}return i.trim()}catch{y(`[ToolProvider] Failed to parse product-info.json at: ${t}`);return}}static compareVersion(e,t){let r=e.split(".").map(s=>parseInt(s,10)||0),i=t.split(".").map(s=>parseInt(s,10)||0),o=Math.max(r.length,i.length);for(let s=0;s<o;s++){let a=(r[s]??0)-(i[s]??0);if(a!==0)return a}return 0}static pickLatestByProductInfo(e){let t=n.selectHighestVersion(e);return y(`[ToolProvider] Selected DevEco Studio ${t.version} at ${t.installRoot}`),t.installRoot}static selectHighestVersion(e){let t=[];for(let r of e){let i=n.parseProductInfoVersion(r);i!==void 0?(t.push({installRoot:r,version:i}),y(`[ToolProvider] ${r} => version ${i}`)):y(`[ToolProvider] Skipping ${r}: could not read version (Info.plist / product-info.json).`)}if(t.length===0){let r=e.join(`
5
- `),i=ie.platform()==="darwin"?"Contents/Info.plist (CFBundleShortVersionString / CFBundleVersion) and Contents/product-info.json":"product-info.json";throw new Error(`Failed to determine DevEco Studio version from ${i}.
4
+ `)}static resolveTimeBounds(e,t,r){let i=e?new Date(r.getTime()-e*1e3):null,o=t?new Date(r.getTime()-t*1e3):null;return i&&o?i<o?[i,o]:[o,i]:i?[i,r]:o?[null,o]:[null,null]}static isWithinBounds(e,t,r){let i=e.getTime(),o=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(o!==null&&i<o||s!==null&&i>s)}static extractTimestampFromLogLine(e,t){let r=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!r)return null;let i=t.getFullYear(),o=Number.parseInt(r[1],10)-1,s=Number.parseInt(r[2],10),a=Number.parseInt(r[3],10),c=Number.parseInt(r[4],10),l=Number.parseInt(r[5],10),u=r[6]??"0",f=Number.parseInt(u.padEnd(3,"0").slice(0,3),10),P=new Date(i,o,s,a,c,l,f);return P.getTime()>t.getTime()+1440*60*1e3&&P.setFullYear(i-1),P}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(r=>{let i=r.charCodeAt(0);return i<=n.ASCII_CONTROL_MAX||i===n.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let r=`'${e.replace(/'/g,"'\\''")}'`;return g(`quotePosixShellArg: ${e} -> ${r}`),r}static assertCrashFilename(e){if(!/^\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(W.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=W.resolve(W.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=W.normalize(e),i=W.relative(r,t);if(i.split(W.sep)[0]===".."||W.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||W.isAbsolute(e)}static isPathContained(e,t){let r=W.resolve(t,e),i=W.relative(t,r);return n.isPathEscaping(i)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){if(W.isAbsolute(e))return{contained:!1,reason:`Absolute path is not allowed: ${e}`};let r=n.isPathContained(e,t);if(!r.contained)return r;let i;try{i=ki.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=W.resolve(i,e),s;try{s=ki.realpathSync(o)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${o}`}}return n.isPathContained(s,i)}};var tt=class n{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let r=n.tryLoadProjectProfile(t);if(r)return new n(t,r);let i=Q.dirname(t);if(i===t)break;t=i}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=Q.join(e,"build-profile.json5");if(!q.existsSync(t))return null;try{let r=q.readFileSync(t,"utf-8"),i=et.parse(r);return i.app?i:null}catch(r){return console.error(`Error parsing ${t}:`,r),null}}getModuleType(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=b.resolvePathWithinRoot(this.rootDir,t.srcPath),i=Q.join(r,"src","main","module.json5");if(!q.existsSync(i))return"entry";try{let o=q.readFileSync(i,"utf-8");return et.parse(o)?.module?.type||"entry"}catch(o){return console.warn(`Warning: Failed to parse ${i}:`,o),"entry"}}getModuleProfile(e){let t=this.profile.modules.find(a=>a.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=b.resolvePathWithinRoot(this.rootDir,t.srcPath),i=Q.join(r,"build-profile.json5");if(!q.existsSync(i))throw new Error(`Build profile for module '${e}' not found at ${i}.`);let o=q.readFileSync(i,"utf-8");return et.parse(o)}getBundleName(){let e=Q.join(this.rootDir,"AppScope","app.json5");if(q.existsSync(e))try{let t=q.readFileSync(e,"utf-8"),r=et.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.")}getMainAbility(e,t){if(t)return t;let r=this.profile.modules.find(s=>s.name===e);if(!r)return"EntryAbility";let i=b.resolvePathWithinRoot(this.rootDir,r.srcPath),o=Q.join(i,"src","main","module.json5");if(!q.existsSync(o))return"EntryAbility";try{let s=q.readFileSync(o,"utf-8"),c=et.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let l=c.find(u=>u.name==="EntryAbility");return l?l.name:c[0].name}catch(s){return console.warn(`Warning: Failed to parse ${o}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new Error(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`);if(!this.profile.app.products?.some(r=>r.name===e)){let r=this.profile.app.products?.map(i=>i.name).join(", ")||"none";throw new Error(`Product '${e}' not found in project configuration. Available products: ${r}`)}}getModuleDependencies(e){let t=this.profile.modules.find(s=>s.name===e);if(!t)return[];let r=b.resolvePathWithinRoot(this.rootDir,t.srcPath),i=Q.join(r,"oh-package.json5");if(!q.existsSync(i))return[];let o=[];try{let s=q.readFileSync(i,"utf-8"),c=et.parse(s)?.dependencies||{};for(let l of Object.values(c)){if(typeof l!="string")continue;let u=l;if(!(u.startsWith("file:")||u.startsWith(".")||u.startsWith("..")))continue;u.startsWith("file:")&&(u=u.substring(5));let P=Q.join(t.srcPath,u),C=b.resolvePathWithinRoot(this.rootDir,P),L=this.profile.modules.find(ne=>Q.resolve(this.rootDir,ne.srcPath)===C);L&&o.push(L.name)}}catch{}return o}collectNonHarDependentModuleList(e){let t=[],r=[],i=new Set;for(r.push(e),i.add(e);r.length>0;){let o=r.shift();this.getModuleType(o)!=="har"&&t.push(o);let a=this.getModuleDependencies(o);for(let c of a)i.has(c)||(r.push(c),i.add(c))}return t}findArtifactPath(e,t,r,i="default"){this.validateProduct(i);let o=this.profile.modules.find(ne=>ne.name===e);if(!o)throw new Error(`Module '${e}' not found`);let a=this.getModuleType(e)==="shared",c=a?"hspName":"hapName",l=this.buildOutputPath(o.srcPath,i,["intermediates",a?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!q.existsSync(l))throw new Error(`Build metadata not found for module '${e}' at ${l}. Build the project first.`);let{packageName:u,isSigned:f}=this.parseOutputMetadata(l,c),P=u;if(!f){let ne=this.getSignedHapName(u,o.srcPath,i,t);ne&&(P=ne)}let C=a?"-signed.hsp":"-signed.hap";if(!r&&!P.endsWith(C))throw new Error(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`);let L=this.buildOutputPath(o.srcPath,i,["outputs",t,P]);if(!q.existsSync(L))throw new Error(`Generated package file not found in ${L}.`);return L}getSignedHapName(e,t,r,i){let o=null;if(e.endsWith("-unsigned.hap")?o=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(o=e.replace("-unsigned.hsp","-signed.hsp")),!o)return null;let s=this.buildOutputPath(t,r,["outputs",i,o]);return q.existsSync(s)?o:null}buildOutputPath(e,t,r){let i=b.resolvePathWithinRoot(this.rootDir,e),o=Q.resolve(i,"build",t,...r);return b.ensurePathWithinRoot(this.rootDir,o)}parseOutputMetadata(e,t){let r=q.readFileSync(e,"utf-8"),i=et.parse(r),o,s=!1;if(Array.isArray(i)){let a=i[0];a&&(o=a[t],s=a.isSigned===!0)}else i&&typeof i=="object"&&(o=i[t],s=i.isSigned===!0);if(!o)throw new Error(`Could not find ${t} in output_metadata.json at ${e}`);return this.validatePackageName(o),{packageName:o,isSigned:s}}validatePackageName(e){let t=Q.basename(e);if(t!==e)throw new Error(`Invalid traversal name: '${e}'. It must contain path characters.`);if(!t.endsWith(".hap")&&!t.endsWith(".hsp"))throw new Error(`Invalid package name '${t}'.It must be a .hap or .hsp file.`)}};import{execFileSync as Ri}from"child_process";import H,{existsSync as Ts}from"fs";import*as I from"path";import*as ce from"os";import Nu from"regedit";import{join as ks}from"path";import{red as _u}from"colorette";var Rs="https://developer.huawei.com/consumer/cn/download/",Ms="6.1.0",Un=n=>new Promise((e,t)=>{Nu.list(n,(r,i)=>{r?t(r):e(i)})}),N=class n{_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;_emulatorLauncherPath;static _verifiedPaths=new Set;static _powerShellPath;static verifyAndCache(e){n._verifiedPaths.has(e)||(n.verifySignature(e),n._verifiedPaths.add(e))}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return n.verifyAndCache(this._nodePath),this._nodePath}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get javaPath(){return n.verifyAndCache(this._javaPath),this._javaPath}get sdkPath(){return this._sdkPath}get hdcPath(){return n.verifyAndCache(this._hdcPath),this._hdcPath}get emulatorPath(){return n.verifyAndCache(this._emulatorPath),this._emulatorPath}get emulatorLauncherPath(){return this._emulatorLauncherPath&&n.verifyAndCache(this._emulatorLauncherPath),this._emulatorLauncherPath}constructor(e,t,r,i,o,s,a,c,l){this._devecoStudioPath=e,this._nodePath=t,this._ohpmJsPath=r,this._hvigorJsPath=i,this._javaPath=o,this._sdkPath=s,this._hdcPath=a,this._emulatorPath=c,this._emulatorLauncherPath=l}static enforceStudioMinVersion(e){let t=n.parseProductInfoVersion(e);if(t===void 0)throw new Error(`Failed to determine DevEco Studio version at ${e}`);n.assertMinVersion(e,t)}static async checkVersion(){let e=await n.findDevEcoStudio();n.enforceStudioMinVersion(e)}static async new(){let e=await n.findDevEcoStudio(),{nodePath:t,ohpmJsPath:r,hvigorJsPath:i,javaPath:o,sdkPath:s,hdcPath:a,emulatorPath:c}=n.resolveTools(e),l=n.getEmulatorExe(e);return new n(e,t,r,i,o,s,a,c,l??void 0)}static _cachedInstallRoot;static async findDevEcoStudio(){if(n._cachedInstallRoot!==void 0)return g(`[ToolProvider] findDevEcoStudio: cache hit -> ${n._cachedInstallRoot}`),n._cachedInstallRoot;let e=ce.platform(),t=e==="win32"?await n.collectCandidatesWindows():e==="darwin"?n.collectCandidatesMac():(()=>{throw new Error("Linux is not fully supported yet for automatic DevEco Studio detection.")})();return n._cachedInstallRoot=n.pickLatestByProductInfo(t),n._cachedInstallRoot}static async collectCandidatesWindows(){let e=new Set,t=[],r=(i,o)=>{if(!n.isExistingDirectory(i))return;let s=I.normalize(i).toLowerCase();e.has(s)||(e.add(s),t.push(i),g(`[ToolProvider] Found via ${o}: ${i}`))};if(await n.addFromUninstallKey(r),await n.addFromHuaweiStudioKeys(r),n.addFromDefaultWindowsPath(r),t.length===0)throw new Error("DevEco Studio installation not found in registry or default locations.");return t}static UNINSTALL_REGISTRY_PARENTS=["HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall","HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"];static HUAWEI_STUDIO_REGISTRY_KEYS=["HKLM\\SOFTWARE\\Huawei\\DevEco Studio","HKLM\\SOFTWARE\\WOW6432Node\\Huawei\\DevEco Studio"];static isDevEcoStudioUninstallSubkey(e){return e.normalize("NFKC").trim().toLowerCase().startsWith("deveco studio")}static async addFromUninstallKey(e){for(let t of n.UNINSTALL_REGISTRY_PARENTS)try{let o=((await Un([t]))[t]?.keys??[]).filter(n.isDevEcoStudioUninstallSubkey);if(o.length===0)continue;let s=o.map(c=>`${t}\\${c}`),a=await Un(s);for(let c of s){let l=a[c]?.values?.InstallLocation?.value;e(l,`Uninstall registry key (${c})`)}}catch{}}static async addFromHuaweiStudioRegistryKey(e,t,r){try{let o=(await Un([t]))[t]?.keys??[];if(o.length===0)return;let s=o.map(c=>`${t}\\${c}`),a=await Un(s);for(let c of s){let l=a[c]?.values?.[""]?.value;e(l,`${r} subkey ${c}`)}}catch{}}static async addFromHuaweiStudioKeys(e){for(let t of n.HUAWEI_STUDIO_REGISTRY_KEYS){let r=t.includes("WOW6432Node")?"Huawei DevEco Studio (WOW6432Node)":"Huawei DevEco Studio";await n.addFromHuaweiStudioRegistryKey(e,t,r)}}static addFromDefaultWindowsPath(e){let t=I.join("C:","Program Files","Huawei","DevEco Studio");e(t,"default installation path")}static collectCandidatesMac(){let e=ce.homedir(),t=[I.join(e,"Applications"),"/Applications"],r=[],i=new Set;for(let o of t){if(!H.existsSync(o))continue;let s;try{s=H.readdirSync(o)}catch{continue}for(let a of s){if(!a.endsWith(".app")||!a.toLowerCase().includes("deveco"))continue;let l=I.join(o,a);n.isExistingDirectory(l)&&(i.has(l)||(i.add(l),r.push(l),g(`[ToolProvider] Found macOS candidate: ${l}`)))}}if(r.length===0)throw new Error("DevEco Studio not found in /Applications or ~/Applications.");return r}static productInfoPath(e){return I.join(e,"product-info.json")}static macInfoPlistPath(e){return I.join(e,"Contents","Info.plist")}static readMacInfoPlistKey(e,t){if(!H.existsSync(e)){g(`[ToolProvider] Info.plist not found at: ${e}`);return}let r=[{command:"/usr/libexec/PlistBuddy",args:["-c",`Print :${t}`,e],label:`PlistBuddy Print :${t}`},{command:"plutil",args:["-extract",t,"raw","-o","-",e],label:`plutil -extract ${t}`}];for(let{command:i,args:o,label:s}of r)try{let a=Ri(i,o,{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:5e3}).trim();if(a.length>0&&!a.includes("Does Not Exist"))return a}catch(a){let c=a,l=c.stderr?String(c.stderr).trim():"",u=c.status??c.code??"?";g(`[ToolProvider] ${s} failed for ${e} (exit ${u})${l?`: ${l}`:""}`)}}static extractCompactBuildCode(e){let t=e.split(".").at(-1);if(t!==void 0&&/^\d+$/.test(t))return t}static compactPrefixFromShortVersion(e){let t=e.split(".").slice(0,3);if(!(t.length<3||!t.every(r=>/^\d+$/.test(r))))return t.join("")}static extractFourthSegmentMatchingShortVersion(e,t){let r=n.compactPrefixFromShortVersion(e),i=n.extractCompactBuildCode(t);if(r===void 0||i===void 0)return;if(!i.startsWith(r)){g(`[ToolProvider] CFBundleVersion suffix ${i} does not match short-version prefix ${r} (${e})`);return}let o=i.slice(r.length);if(!(o.length===0||!/^\d+$/.test(o)))return o}static readMacFourthSegmentFromPlist(e,t){let r=n.readMacInfoPlistKey(e,"CFBundleVersion");if(r!==void 0){let s=n.extractFourthSegmentMatchingShortVersion(t,r);if(s!==void 0)return s}let i=n.readMacInfoPlistKey(e,"CFBundleGetInfoString");if(i===void 0)return;let o=i.match(/DS-[\d.]+/);if(o!==null)return n.extractFourthSegmentMatchingShortVersion(t,o[0])}static parseMacInfoPlistVersion(e){let t=n.macInfoPlistPath(e),r=n.readMacInfoPlistKey(t,"CFBundleShortVersionString");if(r!==void 0){let i=n.readMacFourthSegmentFromPlist(t,r);return i!==void 0?`${r}.${i}`:r}return n.readMacInfoPlistKey(t,"CFBundleVersion")}static parseProductInfoVersion(e){if(ce.platform()==="darwin")return n.parseMacInfoPlistVersion(e);let t=n.productInfoPath(e);if(!H.existsSync(t)){g(`[ToolProvider] product-info.json not found at: ${t}`);return}try{let i=JSON.parse(H.readFileSync(t,"utf-8"))?.version;if(typeof i!="string"||i.trim()===""){g(`[ToolProvider] product-info.json at ${t} has no valid "version" field`);return}return i.trim()}catch(r){g(`[ToolProvider] Failed to parse product-info.json at ${t}: ${r instanceof Error?r.message:String(r)}`);return}}static compareVersion(e,t){let r=e.split(".").map(s=>parseInt(s,10)||0),i=t.split(".").map(s=>parseInt(s,10)||0),o=Math.max(r.length,i.length);for(let s=0;s<o;s++){let a=(r[s]??0)-(i[s]??0);if(a!==0)return a}return 0}static pickLatestByProductInfo(e){let t=n.selectHighestVersion(e);return g(`[ToolProvider] Selected DevEco Studio ${t.version} at ${t.installRoot}`),t.installRoot}static selectHighestVersion(e){let t=[];for(let r of e){let i=n.parseProductInfoVersion(r);i!==void 0?(t.push({installRoot:r,version:i}),g(`[ToolProvider] ${r} => version ${i}`)):g(`[ToolProvider] Skipping ${r}: could not read version from Info.plist.`)}if(t.length===0){let r=e.join(`
5
+ `),i=ce.platform()==="darwin"?"Contents/Info.plist (CFBundleShortVersionString / CFBundleVersion)":"product-info.json";throw new Error(`Failed to determine DevEco Studio version from ${i}.
6
6
  Searched locations:
7
7
  ${r}
8
8
  Please reinstall DevEco Studio or download the latest version from:
9
- `+Es)}return t.reduce((r,i)=>n.compareVersion(i.version,r.version)>0?i:r)}static assertMinVersion(e,t){n.compareVersion(t,Ps)>=0||(y(`[ToolProvider] Selected DevEco Studio ${t} at ${e} \u2014 below minimum`),console.error(Su(`Error: The detected DevEco Studio version is ${t}, which is below the minimum required version ${Ps}. Upgrade to the latest version before using deveco-cli:`)+`
10
- `+Es),process.exit(1))}static isExistingDirectory(e){return!!e&&_.existsSync(e)&&_.statSync(e).isDirectory()}static resolveWindowsTools(e){let t=D.join(e,"tools");return{nodePath:D.join(t,"node","node.exe"),ohpmJsPath:D.join(t,"ohpm","bin","pm-cli.js"),hvigorJsPath:D.join(t,"hvigor","bin","hvigorw.js"),javaPath:D.join(e,"jbr","bin","java.exe"),sdkPath:D.join(e,"sdk")}}static resolveMacTools(e){let t=D.join(e,"Contents","tools");return{nodePath:D.join(t,"node","bin","node"),ohpmJsPath:D.join(t,"ohpm","bin","pm-cli.js"),hvigorJsPath:D.join(t,"hvigor","bin","hvigorw.js"),javaPath:D.join(e,"Contents","jbr","Contents","Home","bin","java"),sdkPath:D.join(e,"Contents","sdk")}}static resolveTools(e){let t=ie.platform(),r=t==="win32"?n.resolveWindowsTools(e):t==="darwin"?n.resolveMacTools(e):(()=>{throw new Error("Linux is not fully supported yet.")})();n.verifyTools(r.nodePath,r.ohpmJsPath,r.hvigorJsPath,r.javaPath);let i=n.resolveHdcPath(r.sdkPath,t),o=n.resolveEmulatorPath(e,t);return{...r,hdcPath:i,emulatorPath:o}}static resolveHdcPath(e,t){let r=t==="win32"?".exe":"",i=[D.join(e,"default","openharmony","toolchains",`hdc${r}`),D.join(e,"toolchains",`hdc${r}`)];for(let o of i)if(_.existsSync(o))return o;throw new Error(`hdc executable not found. Searched in:
9
+ `+Rs)}return t.reduce((r,i)=>n.compareVersion(i.version,r.version)>0?i:r)}static assertMinVersion(e,t){n.compareVersion(t,Ms)>=0||(g(`[ToolProvider] Selected DevEco Studio ${t} at ${e} \u2014 below minimum`),console.error(_u(`Error: The detected DevEco Studio version is ${t}, which is below the minimum required version ${Ms}. Upgrade to the latest version before using deveco-cli:`)+`
10
+ `+Rs),process.exit(1))}static isExistingDirectory(e){return!!e&&H.existsSync(e)&&H.statSync(e).isDirectory()}static resolveWindowsTools(e){let t=I.join(e,"tools");return{nodePath:I.join(t,"node","node.exe"),ohpmJsPath:I.join(t,"ohpm","bin","pm-cli.js"),hvigorJsPath:I.join(t,"hvigor","bin","hvigorw.js"),javaPath:I.join(e,"jbr","bin","java.exe"),sdkPath:I.join(e,"sdk")}}static resolveMacTools(e){let t=I.join(e,"Contents","tools");return{nodePath:I.join(t,"node","bin","node"),ohpmJsPath:I.join(t,"ohpm","bin","pm-cli.js"),hvigorJsPath:I.join(t,"hvigor","bin","hvigorw.js"),javaPath:I.join(e,"Contents","jbr","Contents","Home","bin","java"),sdkPath:I.join(e,"Contents","sdk")}}static resolveTools(e){let t=ce.platform(),r=t==="win32"?n.resolveWindowsTools(e):t==="darwin"?n.resolveMacTools(e):(()=>{throw new Error("Linux is not fully supported yet.")})();n.verifyTools(r.nodePath,r.ohpmJsPath,r.hvigorJsPath,r.javaPath);let i=n.resolveHdcPath(r.sdkPath,t),o=n.resolveEmulatorPath(e,t);return{...r,hdcPath:i,emulatorPath:o}}static resolveHdcPath(e,t){let r=t==="win32"?".exe":"",i=[I.join(e,"default","openharmony","toolchains",`hdc${r}`),I.join(e,"toolchains",`hdc${r}`)];for(let o of i)if(H.existsSync(o))return o;throw new Error(`hdc executable not found. Searched in:
11
11
  ${i.join(`
12
- `)}`)}static resolveEmulatorPath(e,t){let r;if(t==="win32")r=D.join(e,"tools","emulator","Emulator.exe");else if(t==="darwin")r=D.join(e,"Contents","tools","emulator","Emulator");else throw new Error("Linux is not fully supported yet");if(!_.existsSync(r))throw new Error(`Emulator executable not found at: ${r}`);return r}static verifyTools(e,t,r,i){if(!_.existsSync(e))throw new Error(`Node executable not found at: ${e}`);if(!_.existsSync(t))throw new Error(`ohpm js file not found at: ${t}`);if(!_.existsSync(r))throw new Error(`hvigor js file not found at: ${r}`);if(!_.existsSync(i))throw new Error(`java executable not found at: ${i}`)}static getEmulatorExe(e){let t=ie.platform(),r;if(t==="win32")r=Ss(e,"tools","emulator","Emulator.exe");else if(t==="darwin")r=Ss(e,"Contents","tools","emulator","Emulator");else return;return bs(r)?r:void 0}static isValidApiLevel(e,t){let r=t??23;return Number.isInteger(e)&&e>=17&&e<=r}static parseApiLevelFromFile(e){if(_.existsSync(e))try{let t=_.readFileSync(e,"utf-8"),r=JSON.parse(t),i=r?.apiVersion??r?.data?.apiVersion;if(typeof i!="string"&&typeof i!="number")return;let o=Number(i);return Number.isInteger(o)&&o>=17?o:void 0}catch{return}}static detectFromSdkPkg(e){let t=D.join(e,"default","sdk-pkg.json");return n.parseApiLevelFromFile(t)}static detectFromOhUniPackage(e){let t=[D.join(e,"default","openharmony","toolchains","oh-uni-package.json"),D.join(e,"default","openharmony","native","oh-uni-package.json"),D.join(e,"default","openharmony","previewer","oh-uni-package.json")];for(let r of t){let i=n.parseApiLevelFromFile(r);if(i!==void 0)return i}}getMaxApiLevel(){let e=n.detectFromSdkPkg(this.sdkPath);if(e!==void 0)return e;let t=n.detectFromOhUniPackage(this.sdkPath);return t!==void 0?t:23}detectApiLevel(){return this.getMaxApiLevel()}static findPowerShellPath(){if(n._powerShellPath)return n._powerShellPath;if(ie.platform()!=="win32")return n._powerShellPath="",n._powerShellPath;let e=D.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return bs(e)?(y(`[ToolProvider] Found PowerShell at: ${e}`),n._powerShellPath=e,e):(n._powerShellPath="",n._powerShellPath)}static verifySignature(e){if(!_.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=ie.platform();if(n.isExecutableFile(e,t)){if(t==="win32"){if(!n.verifyWindowsSignature(e).signed)throw new Error(`The executable is not digitally signed: ${e}`)}else if(t==="darwin"&&!n.verifyMacSignature(e).signed)throw new Error(`The executable is not digitally signed: ${e}`)}}static isExecutableFile(e,t){if(t==="win32")return D.extname(e).toLowerCase()===".exe";if(t==="darwin")try{return _.accessSync(e,_.constants.X_OK),!0}catch{return!1}return!1}static createSignatureScript(){let e=_.mkdtempSync(D.join(ie.tmpdir(),"deveco-verify-")),t=D.join(e,"Verify-Signature.ps1");return _.writeFileSync(t,"$env:PSModulePath = ($env:PSModulePath -split ';' | Where-Object { $_ -notmatch 'windowsapps' }) -join ';'; Get-AuthenticodeSignature -FilePath $args[0] | ConvertTo-Json -Depth 3 -Compress","utf-8"),{tmpDir:e,scriptPath:t}}static verifyWindowsSignature(e){let t=n.findPowerShellPath();if(!t)throw new Error("PowerShell application not found");let{tmpDir:r,scriptPath:i}=n.createSignatureScript();try{let o=Si(t,["-NoProfile","-ExecutionPolicy","Bypass","-File",i,e],{encoding:"utf-8",timeout:5e3,stdio:["pipe","pipe","ignore"]}),s=JSON.parse(o);return{signed:s?.Status===0,signer:s?.SignerCertificate?.Subject??void 0}}catch(o){return y(`[ToolProvider] verify Windows Signature, error msg: ${o}`),{signed:!0}}finally{try{_.rmSync(r,{recursive:!0,force:!0})}catch{}}}static verifyMacSignature(e){try{return Si("codesign",["-v",e],{encoding:"utf-8",timeout:5e3}),{signed:!0}}catch{return{signed:!1}}}};import{execa as Eu}from"execa";import*as Hn from"path";var Xe=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let i=`${Hn.dirname(e.javaPath)}${Hn.delimiter}${process.env.PATH||""}`;this.env={...process.env,PATH:i,DEVECO_SDK_HOME:e.sdkPath}}async sync(e,t){let r=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(r)}async buildProduct(e,t){let r=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(r)}async buildModules(e,t,r,i){let o=[...Array.from(i),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(o)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];await this.runHvigor(e)}async stopDaemon(){await this.runHvigor(["--stop-daemon"])}async runHvigor(e){let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];y(`Executing: ${t} ${r.join(" ")}`),await Eu(t,r,{cwd:this.projectRoot,env:this.env,stdout:"inherit",stderr:"inherit"})}};import{execa as Pu}from"execa";var dt=class{toolProvider;projectRoot;constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=[this.toolProvider.ohpmJsPath,"install","--all"];y(`Executing: ${e} ${t.join(" ")}`),await Pu(e,t,{cwd:this.projectRoot,stdout:"inherit",stderr:"inherit"})}};import{mkdir as Cu}from"fs/promises";import{dirname as Iu,resolve as Du}from"path";import{execa as Au}from"execa";import{lock as Ei,check as _b}from"proper-lockfile";function Pi(n){return Du(n,".hvigor",".build-lock")}function Tu(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function Cs(n){let e=Iu(Pi(n));if(await Cu(e,{recursive:!0}),process.platform==="win32")try{await Au("attrib",["+h",e])}catch{}}async function xu(n,e){let t=new AbortController,r=Tu(e);await Cs(n);let i={lockfilePath:Pi(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await Ei(n,{...i,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return r(),{release:await Ei(n,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function qt(n,e,t){let{release:r,signal:i}=await xu(n,t);try{return await e(i)}finally{await r()}}async function Is(n,e){let t=new AbortController;await Cs(n);let r={lockfilePath:Pi(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await Ei(n,{...r,retries:0})}catch(o){if(o&&typeof o=="object"&&"code"in o&&o.code==="ELOCKED")return{acquired:!1};throw o}try{return{acquired:!0,result:await e(t.signal)}}finally{await i()}}function Ru(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 Mu(n,e){let t;if(e.modules&&e.modules.length>0)t=e.modules;else{let i=n.profile.modules,o=i.filter(s=>n.getModuleType(s.name)==="entry");if(i.length===1)t=[i[0].name];else if(o.length===1)t=[o[0].name];else throw o.length>1?new Error(`Multiple entry modules found (${o.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`):new Error(`No entry module found and multiple modules available (${i.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`)}let r=new Set;for(let i of t){let o=i.indexOf("@"),s=o!==-1?i.substring(0,o):i,a=o!==-1?i.substring(o+1):"default";r.add(`${s}@${a}`)}return Array.from(r)}function Ii(n,e){let t=new Set;for(let r of e){let i=r.indexOf("@"),o=i!==-1?r.substring(0,i):r,s=n.getModuleType(o);s==="shared"?t.add("assembleHsp"):s==="har"?t.add("assembleHar"):t.add("assembleHap")}return t}function Gt(n,e){let t=e,r=`${n} failed`;console.error(Ci(r));let i=t.stdout||t.message;throw i&&console.error(i),t.stderr&&console.error(t.stderr),new Error(r,{cause:e})}async function Di(n,e,t,r,i){console.log(`
13
- [1/3] Running ohpm install...`);try{await n.installAll()}catch(o){Gt("ohpm install",o)}console.log(`
14
- [2/3] Running hvigor sync...`);try{await e.sync(t,r)}catch(o){Gt("hvigor sync",o)}console.log(`
15
- [3/3] Running hvigor build...`);try{i.type==="product"?await e.buildProduct(t,r):await e.buildModules(t,r,i.modulesToBuild,i.moduleTasks)}catch(o){Gt("hvigor build",o)}}var Ts=new ku("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=>{try{let e=process.cwd(),t=Ze.discover(e);console.warn(As("Ensure the project source is trustworthy before proceeding."));let r=await L.new();Ru(t,n);let i=n.product||"default",o=n.buildMode||"debug",s;if(n.product&&!n.modules)s={type:"product"};else{let l=Mu(t,n),u=Ii(t,l);s={type:"modules",modulesToBuild:l,moduleTasks:u}}let a=new dt(r,t.rootDir),c=new Xe(r,t.rootDir);await qt(t.rootDir,async()=>Di(a,c,i,o,s),()=>{console.log("Another build is already running for this project. Waiting for completion...")}),console.log(`
16
- `+Ds("Build completed successfully"))}catch(e){console.error(Ci(e.message)),process.exit(1)}});Ts.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{try{let n=process.cwd(),e=Ze.discover(n);console.warn(As("Ensure the project source is trusted before proceeding."));let t=await L.new(),r=new Xe(t,e.rootDir);await qt(e.rootDir,async()=>{console.log(`
17
- [1/2] Running hvigor clean...`);try{await r.clean()}catch(i){Gt("hvigor clean",i)}console.log(`
18
- [2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(i){Gt("hvigor --stop-daemon",i)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
19
- `+Ds("Clean completed successfully."))}catch(n){console.error(Ci(n.message)),process.exit(1)}});var xs=Ts;import{Command as Yu}from"commander";import{green as _s,red as Vu,yellow as Ju}from"colorette";import{randomUUID as qu}from"crypto";import{execa as Gu}from"execa";import{execa as zu}from"execa";import{execFile as Ou,spawn as Lu}from"child_process";import{promisify as Nu}from"util";var _u=Nu(Ou);function ks(n,e,t){let i=n.replace(/\r\n/g,`
12
+ `)}`)}static resolveEmulatorPath(e,t){let r;if(t==="win32")r=I.join(e,"tools","emulator","Emulator.exe");else if(t==="darwin")r=I.join(e,"Contents","tools","emulator","Emulator");else throw new Error("Linux is not fully supported yet");if(!H.existsSync(r))throw new Error(`Emulator executable not found at: ${r}`);return r}static verifyTools(e,t,r,i){if(!H.existsSync(e))throw new Error(`Node executable not found at: ${e}`);if(!H.existsSync(t))throw new Error(`ohpm js file not found at: ${t}`);if(!H.existsSync(r))throw new Error(`hvigor js file not found at: ${r}`);if(!H.existsSync(i))throw new Error(`java executable not found at: ${i}`)}static getEmulatorExe(e){let t=ce.platform(),r;if(t==="win32")r=ks(e,"tools","emulator","Emulator.exe");else if(t==="darwin")r=ks(e,"Contents","tools","emulator","Emulator");else return;return Ts(r)?r:void 0}static isValidApiLevel(e,t){let r=t??23;return Number.isInteger(e)&&e>=17&&e<=r}static parseApiLevelFromFile(e){if(H.existsSync(e))try{let t=H.readFileSync(e,"utf-8"),r=JSON.parse(t),i=r?.apiVersion??r?.data?.apiVersion;if(typeof i!="string"&&typeof i!="number")return;let o=Number(i);return Number.isInteger(o)&&o>=17?o:void 0}catch{return}}static detectFromSdkPkg(e){let t=I.join(e,"default","sdk-pkg.json");return n.parseApiLevelFromFile(t)}static detectFromOhUniPackage(e){let t=[I.join(e,"default","openharmony","toolchains","oh-uni-package.json"),I.join(e,"default","openharmony","native","oh-uni-package.json"),I.join(e,"default","openharmony","previewer","oh-uni-package.json")];for(let r of t){let i=n.parseApiLevelFromFile(r);if(i!==void 0)return i}}getMaxApiLevel(){let e=n.detectFromSdkPkg(this.sdkPath);if(e!==void 0)return e;let t=n.detectFromOhUniPackage(this.sdkPath);return t!==void 0?t:23}detectApiLevel(){return this.getMaxApiLevel()}static findPowerShellPath(){if(n._powerShellPath)return n._powerShellPath;if(ce.platform()!=="win32")return n._powerShellPath="",n._powerShellPath;let e=I.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return Ts(e)?(g(`[ToolProvider] Found PowerShell at: ${e}`),n._powerShellPath=e,e):(n._powerShellPath="",n._powerShellPath)}static verifySignature(e){if(!H.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=ce.platform();if(n.isExecutableFile(e,t)){if(t==="win32"){if(!n.verifyWindowsSignature(e).signed)throw new Error(`The executable is not digitally signed: ${e}`)}else if(t==="darwin"&&!n.verifyMacSignature(e).signed)throw new Error(`The executable is not digitally signed: ${e}`)}}static isExecutableFile(e,t){if(t==="win32")return I.extname(e).toLowerCase()===".exe";if(t==="darwin")try{return H.accessSync(e,H.constants.X_OK),!0}catch{return!1}return!1}static createSignatureScript(){let e=H.mkdtempSync(I.join(ce.tmpdir(),"deveco-verify-")),t=I.join(e,"Verify-Signature.ps1");return H.writeFileSync(t,"$env:PSModulePath = ($env:PSModulePath -split ';' | Where-Object { $_ -notmatch 'windowsapps' }) -join ';'; Get-AuthenticodeSignature -FilePath $args[0] | ConvertTo-Json -Depth 3 -Compress","utf-8"),{tmpDir:e,scriptPath:t}}static verifyWindowsSignature(e){let t=n.findPowerShellPath();if(!t)throw new Error("PowerShell application not found");let{tmpDir:r,scriptPath:i}=n.createSignatureScript();try{let o=Ri(t,["-NoProfile","-ExecutionPolicy","Bypass","-File",i,e],{encoding:"utf-8",timeout:5e3,stdio:["pipe","pipe","ignore"]}),s=JSON.parse(o);return{signed:s?.Status===0,signer:s?.SignerCertificate?.Subject??void 0}}catch(o){return g(`[ToolProvider] verify Windows Signature, error msg: ${o}`),{signed:!0}}finally{try{H.rmSync(r,{recursive:!0,force:!0})}catch{}}}static verifyMacSignature(e){try{return Ri("codesign",["-v",e],{encoding:"utf-8",timeout:5e3}),{signed:!0}}catch{return{signed:!1}}}};import{execa as Hu}from"execa";import*as zn from"path";var nt=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let i=`${zn.dirname(e.javaPath)}${zn.delimiter}${process.env.PATH||""}`;this.env={...process.env,PATH:i,DEVECO_SDK_HOME:e.sdkPath}}async sync(e,t){let r=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(r)}async buildProduct(e,t){let r=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(r)}async buildModules(e,t,r,i){let o=[...Array.from(i),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(o)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];await this.runHvigor(e)}async stopDaemon(){await this.runHvigor(["--stop-daemon"])}async runHvigor(e){let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];g(`Executing: ${t} ${r.join(" ")}`),await Hu(t,r,{cwd:this.projectRoot,env:this.env,stdout:"inherit",stderr:"inherit"})}};import{execa as Fu}from"execa";var ft=class{toolProvider;projectRoot;constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=[this.toolProvider.ohpmJsPath,"install","--all"];g(`Executing: ${e} ${t.join(" ")}`),await Fu(e,t,{cwd:this.projectRoot,stdout:"inherit",stderr:"inherit"})}};import{mkdir as ju}from"fs/promises";import{dirname as $u,resolve as Bu}from"path";import{execa as Wu}from"execa";import{lock as Mi,check as sS}from"proper-lockfile";function Oi(n){return Bu(n,".hvigor",".build-lock")}function Uu(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function Os(n){let e=$u(Oi(n));if(await ju(e,{recursive:!0}),process.platform==="win32")try{await Wu("attrib",["+h",e])}catch{}}async function zu(n,e){let t=new AbortController,r=Uu(e);await Os(n);let i={lockfilePath:Oi(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await Mi(n,{...i,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return r(),{release:await Mi(n,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Kt(n,e,t){let{release:r,signal:i}=await zu(n,t);try{return await e(i)}finally{await r()}}async function Ls(n,e){let t=new AbortController;await Os(n);let r={lockfilePath:Oi(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await Mi(n,{...r,retries:0})}catch(o){if(o&&typeof o=="object"&&"code"in o&&o.code==="ELOCKED")return{acquired:!1};throw o}try{return{acquired:!0,result:await e(t.signal)}}finally{await i()}}import*as He from"fs";import*as rt from"path";import qu from"json5";var Li={HTTP_TIMEOUT_MS:2e4},qn={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 Ni="https://matrix.openharmony.cn",fe={TAGS_API_URL:`${Ni}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${Ni}/api/registry/skill/skills`,SKILL_API_BASE:`${Ni}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},ge={"trae-cn":{path:".trae-cn/skills",displayName:"trae-cn"},opencode:{path:".config/opencode/skills",displayName:"opencode"},cursor:{path:".cursor/skills",displayName:"cursor"},codebuddy:{path:".codebuddy/skills",displayName:"codebuddy"},qoder:{path:".qoder/skills",displayName:"qoder"},"claude-code":{path:".claude/skills",projectPath:".claude/skills",displayName:"claude-code"},codex:{path:".codex/skills",displayName:"codex"}};import{homedir as Ae}from"os";import oe from"path";var Ce="deveco-mcp";var _e={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:oe.join(Ae(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:oe.join(process.platform==="win32"?oe.join(process.env.APPDATA??oe.join(Ae(),"AppData","Roaming"),"Trae CN","User"):oe.join(Ae(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:oe.join(Ae(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:oe.join(Ae(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:oe.join(process.platform==="win32"?oe.join(process.env.APPDATA??oe.join(Ae(),"AppData","Roaming"),"Qoder","SharedClientCache"):oe.join(Ae(),"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:oe.join(Ae(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:oe.join(Ae(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function _s(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function Ns(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Hs(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function Gn(n,e){return n.format==="opencode"?_s(e):n.format==="claude-code"||n.format==="codex"?Ns(e):Hs(e)}var ye={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var Gu=1e3;function Yn(n){g(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=rt.join(n,ye.SYNC_OUTPUT_PATH);if(!He.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return g(`[ProjectCheck] ${l.reason}`),l}let t=He.statSync(e).mtimeMs;g(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Vu(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return g(`[ProjectCheck] ${l.reason}`),l}let i=rt.join(n,ye.OH_PACKAGE_JSON5),o=Vn(i,t,"root");if(o.required)return g(`[ProjectCheck] Root check: ${o.reason}`),o;let s=rt.join(n,ye.BUILD_PROFILE_JSON5),a=Vn(s,t,"build-profile");if(a.required)return g(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let u=rt.join(n,l.srcPath,ye.OH_PACKAGE_JSON5),f=Vn(u,t,l.name);if(f.required)return g(`[ProjectCheck] Module '${l.name}' check: ${f.reason}`),f;let P=rt.join(n,l.srcPath,ye.BUILD_PROFILE_JSON5),C=Vn(P,t,l.name);if(C.required)return g(`[ProjectCheck] Module '${l.name}' build-profile check: ${C.reason}`),C}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return g(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function Vn(n,e,t){if(!He.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=He.statSync(n).mtimeMs;return r-e>Gu?{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 Vu(n){let e=rt.join(n,ye.BUILD_PROFILE_JSON5);try{let t=He.readFileSync(e,"utf-8");if(!t.trim())return null;let r=qu.parse(t);if(typeof r!="object"||r===null)return null;let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}function Ju(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 Ku(n,e){let t;if(e.modules&&e.modules.length>0)t=e.modules;else{let i=n.profile.modules,o=i.filter(s=>n.getModuleType(s.name)==="entry");if(i.length===1)t=[i[0].name];else if(o.length===1)t=[o[0].name];else throw o.length>1?new Error(`Multiple entry modules found (${o.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`):new Error(`No entry module found and multiple modules available (${i.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`)}let r=new Set;for(let i of t){let o=i.indexOf("@"),s=o!==-1?i.substring(0,o):i,a=o!==-1?i.substring(o+1):"default";r.add(`${s}@${a}`)}return Array.from(r)}function Hi(n,e){let t=new Set;for(let r of e){let i=r.indexOf("@"),o=i!==-1?r.substring(0,i):r,s=n.getModuleType(o);s==="shared"?t.add("assembleHsp"):s==="har"?t.add("assembleHar"):t.add("assembleHap")}return t}function Zt(n,e){let t=e,r=`${n} failed`;console.error(_i(r));let i=t.stdout||t.message;throw i&&console.error(i),t.stderr&&console.error(t.stderr),new Error(r,{cause:e})}async function Fi(n,e,t,r,i,o){if(Yn(o).required){console.log(`
13
+ [1/3] Running ohpm install...`);try{await n.installAll()}catch(a){Zt("ohpm install",a)}console.log(`
14
+ [2/3] Running hvigor sync...`);try{await e.sync(t,r)}catch(a){Zt("hvigor sync",a)}console.log(`
15
+ [3/3] Running hvigor build...`)}else console.log(`
16
+ [skip] ohpm install & hvigor sync (configurations unchanged)`),console.log(`
17
+ [1/1] Running hvigor build...`);try{i.type==="product"?await e.buildProduct(t,r):await e.buildModules(t,r,i.modulesToBuild,i.moduleTasks)}catch(a){Zt("hvigor build",a)}}var $s=new Yu("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=>{try{let e=process.cwd(),t=tt.discover(e);console.warn(js("Ensure the project source is trustworthy before proceeding."));let r=await N.new();Ju(t,n);let i=n.product||"default",o=n.buildMode||"debug",s;if(n.product&&!n.modules)s={type:"product"};else{let l=Ku(t,n),u=Hi(t,l);s={type:"modules",modulesToBuild:l,moduleTasks:u}}let a=new ft(r,t.rootDir),c=new nt(r,t.rootDir);await Kt(t.rootDir,async()=>Fi(a,c,i,o,s,t.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")}),console.log(`
18
+ `+Fs("Build completed successfully"))}catch(e){console.error(_i(e.message)),process.exit(1)}});$s.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{try{let n=process.cwd(),e=tt.discover(n);console.warn(js("Ensure the project source is trusted before proceeding."));let t=await N.new(),r=new nt(t,e.rootDir);await Kt(e.rootDir,async()=>{console.log(`
19
+ [1/2] Running hvigor clean...`);try{await r.clean()}catch(i){Zt("hvigor clean",i)}console.log(`
20
+ [2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(i){Zt("hvigor --stop-daemon",i)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
21
+ `+Fs("Clean completed successfully."))}catch(n){console.error(_i(n.message)),process.exit(1)}});var Bs=$s;import{Command as up}from"commander";import{green as Ys,red as pp,yellow as mp}from"colorette";import{randomUUID as lp}from"crypto";import{execa as dp}from"execa";import{execa as cp}from"execa";import{execFile as Zu,spawn as Xu}from"child_process";import{promisify as Qu}from"util";var ep=Qu(Zu);function Ws(n,e,t){let i=n.replace(/\r\n/g,`
20
22
  `).split(`
21
- `),o=i.pop()??"",s=i.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),o}function Rs(n,e,t){let r=n.endsWith("\r")?n.slice(0,-1):n;r.length>0&&t.onData([r],e)}function Hu(n,e){return{stdout:n.stdoutChunks.join(""),stderr:n.stderrChunks.join(""),exitCode:e??0}}function Fu(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function ju(n,e,t,r,i){n.stdout?.on("data",o=>{let s=o.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=ks(e.stdoutLineBuffer+s,"stdout",t)}),n.stderr?.on("data",o=>{let s=o.toString();e.stderrChunks.push(s),e.stderrLineBuffer=ks(e.stderrLineBuffer+s,"stderr",t)}),n.on("error",o=>{e.settled||(e.settled=!0,t.onError(o),i(o))}),n.on("close",o=>{if(e.settled)return;e.settled=!0,Rs(e.stdoutLineBuffer,"stdout",t),Rs(e.stderrLineBuffer,"stderr",t),t.onClose(o);let s=Hu(e,o);s.exitCode!==0&&t.onError(new Error(`Command process exited with code ${s.exitCode}`)),r(s)})}async function Ms(n,e=[],t={}){try{let{stdout:r,stderr:i}=await _u(n,e,t);return{stdout:typeof r=="string"?r.trim():"",stderr:typeof i=="string"?i.trim():"",exitCode:0}}catch(r){let i=r;return{stdout:i.stdout?.trim()||"",stderr:i.stderr?.trim()||i.message,exitCode:typeof i.code=="number"?i.code:1}}}async function Os(n,e,t){return await new Promise((r,i)=>{let o=Lu(n,e,{stdio:["inherit","pipe","pipe"]}),s=Fu();ju(o,s,t,r,i)})}function Ls(n){let e=n.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var $u=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],Wu=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function ut(n){return n?$u.some(e=>e.test(n))?"transient":Wu.some(e=>e.test(n))?"fatal":"ok":"ok"}var Ai=[800,1500,2500];function Bu(n){return new Promise(e=>setTimeout(e,n))}async function Oe(n,e){let t=1+Ai.length,r={stdout:"",stderr:"",exitCode:-1};for(let i=0;i<t;i++){r=await Ms(n,e);let o=r.exitCode===0?r.stdout:r.stderr||r.stdout;if(ut(o)!=="transient"||i>=t-1)return r;y(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${Ai[i]}ms`),await Bu(Ai[i])}return r}async function Fn(n,e,t){let r=await Oe(n,["-t",e,"shell","param","get",t]);if(r.exitCode!==0)return;let i=r.stdout.trim();if(!(!i||ut(i)!=="ok"))return Ls(i)}var Ti="__DEVECO_PARAM_DELIM__";function Uu(n,e){let t=new Map,r=n.split(Ti);for(let i=0;i<e.length;i++){let o=(r[i]??"").trim();if(!o||ut(o)!=="ok")continue;let s=Ls(o);s&&t.set(e[i],s)}return t}async function pt(n,e,t){if(t.length===0)return new Map;if(t.length===1){let s=new Map,a=await Fn(n,e,t[0]);return a&&s.set(t[0],a),s}let r=t.map(s=>`param get ${s}`).join(`; echo ${Ti}; `)+`; echo ${Ti}`,i=await Oe(n,["-t",e,"shell",r]);if(i.exitCode===0){let s=Uu(i.stdout,t);if(s.size>0)return s}y(`Batched param fetch failed (exit=${i.exitCode}), falling back to individual calls for ${e}`);let o=new Map;for(let s of t){let a=await Fn(n,e,s);a&&o.set(s,a)}return o}function Yt(n){return n.startsWith("127.0.0.1:")}var Ns=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],q=class n{hdcPath;constructor(e){this.hdcPath=e}static from(e){return new n(e.hdcPath)}static withHdcPath(e){return new n(e)}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}stripBrandPrefix(e,t){let r=e.trim(),i=t?.trim();if(!r||!i)return r;let o=new RegExp(`^${this.escapeRegExp(i)}(\\s+|[-_]+)?`,"i");return r.replace(o,"").trim()||r}async executeHdc(e){return zu(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let r of e.split(`
22
- `)){let i=r.trim();if(!i||i.startsWith("[Empty]"))continue;let o=i.split(/\s+/),s=o[0];!s||s.startsWith("[Empty]")||t.push({serial:s,status:o.length>=2?o[1]:"device"})}return t}extractDisplayName(e){let t=e.get("ohos.qemu.hvd.name");if(t)return t;let r=e.get("const.product.name");if(r&&r!=="emulator")return r;let i=e.get("const.product.model");if(i&&i!=="emulator"){let s=e.get("const.product.brand");return this.stripBrandPrefix(i,s)}let o=e.get("const.build.product");if(o&&o!=="emulator")return o}async getDeviceName(e){let t=await pt(this.hdcPath,e,[...Ns]);return this.extractDisplayName(t)??e}async getDeviceInfo(e,t){if(e.length===0)return null;if(t){let r=e.find(s=>s.serial===t);if(r)return r;let i=t.toLowerCase(),o=[];for(let s of e){let a=await this.getDeviceName(s.serial);a.toLowerCase()===i&&o.push({device:s,name:a})}if(o.length===1)return o[0].device;throw o.length>1?new Error(`Multiple devices match "${t}". Use a serial instead:
23
+ `),o=i.pop()??"",s=i.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),o}function Us(n,e,t){let r=n.endsWith("\r")?n.slice(0,-1):n;r.length>0&&t.onData([r],e)}function tp(n,e){return{stdout:n.stdoutChunks.join(""),stderr:n.stderrChunks.join(""),exitCode:e??0}}function np(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function rp(n,e,t,r,i){n.stdout?.on("data",o=>{let s=o.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=Ws(e.stdoutLineBuffer+s,"stdout",t)}),n.stderr?.on("data",o=>{let s=o.toString();e.stderrChunks.push(s),e.stderrLineBuffer=Ws(e.stderrLineBuffer+s,"stderr",t)}),n.on("error",o=>{e.settled||(e.settled=!0,t.onError(o),i(o))}),n.on("close",o=>{if(e.settled)return;e.settled=!0,Us(e.stdoutLineBuffer,"stdout",t),Us(e.stderrLineBuffer,"stderr",t),t.onClose(o);let s=tp(e,o);s.exitCode!==0&&t.onError(new Error(`Command process exited with code ${s.exitCode}`)),r(s)})}async function zs(n,e=[],t={}){try{let{stdout:r,stderr:i}=await ep(n,e,t);return{stdout:typeof r=="string"?r.trim():"",stderr:typeof i=="string"?i.trim():"",exitCode:0}}catch(r){let i=r;return{stdout:i.stdout?.trim()||"",stderr:i.stderr?.trim()||i.message,exitCode:typeof i.code=="number"?i.code:1}}}async function qs(n,e,t){return await new Promise((r,i)=>{let o=Xu(n,e,{stdio:["inherit","pipe","pipe"]}),s=np();rp(o,s,t,r,i)})}function Gs(n){let e=n.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var ip=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],op=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function gt(n){return n?ip.some(e=>e.test(n))?"transient":op.some(e=>e.test(n))?"fatal":"ok":"ok"}var ji=[800,1500,2500];function sp(n){return new Promise(e=>setTimeout(e,n))}async function Fe(n,e){let t=1+ji.length,r={stdout:"",stderr:"",exitCode:-1};for(let i=0;i<t;i++){r=await zs(n,e);let o=r.exitCode===0?r.stdout:r.stderr||r.stdout;if(gt(o)!=="transient"||i>=t-1)return r;g(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${ji[i]}ms`),await sp(ji[i])}return r}async function Jn(n,e,t){let r=await Fe(n,["-t",e,"shell","param","get",t]);if(r.exitCode!==0)return;let i=r.stdout.trim();if(!(!i||gt(i)!=="ok"))return Gs(i)}var $i="__DEVECO_PARAM_DELIM__";function ap(n,e){let t=new Map,r=n.split($i);for(let i=0;i<e.length;i++){let o=(r[i]??"").trim();if(!o||gt(o)!=="ok")continue;let s=Gs(o);s&&t.set(e[i],s)}return t}async function yt(n,e,t){if(t.length===0)return new Map;if(t.length===1){let s=new Map,a=await Jn(n,e,t[0]);return a&&s.set(t[0],a),s}let r=t.map(s=>`param get ${s}`).join(`; echo ${$i}; `)+`; echo ${$i}`,i=await Fe(n,["-t",e,"shell",r]);if(i.exitCode===0){let s=ap(i.stdout,t);if(s.size>0)return s}g(`Batched param fetch failed (exit=${i.exitCode}), falling back to individual calls for ${e}`);let o=new Map;for(let s of t){let a=await Jn(n,e,s);a&&o.set(s,a)}return o}function Xt(n){return n.startsWith("127.0.0.1:")}var Vs=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],G=class n{hdcPath;constructor(e){this.hdcPath=e}static from(e){return new n(e.hdcPath)}static withHdcPath(e){return new n(e)}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}stripBrandPrefix(e,t){let r=e.trim(),i=t?.trim();if(!r||!i)return r;let o=new RegExp(`^${this.escapeRegExp(i)}(\\s+|[-_]+)?`,"i");return r.replace(o,"").trim()||r}async executeHdc(e){return cp(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let r of e.split(`
24
+ `)){let i=r.trim();if(!i||i.startsWith("[Empty]"))continue;let o=i.split(/\s+/),s=o[0];if(!s||s.startsWith("[Empty]"))continue;let a=o.length>=2?o[1]:"device";if(a.toLowerCase()==="unauthorized"){g(`[DeviceManager] Skipping unauthorized device: ${s}`);continue}t.push({serial:s,status:a})}return t}extractDisplayName(e){let t=e.get("ohos.qemu.hvd.name");if(t)return t;let r=e.get("const.product.name");if(r&&r!=="emulator")return r;let i=e.get("const.product.model");if(i&&i!=="emulator"){let s=e.get("const.product.brand");return this.stripBrandPrefix(i,s)}let o=e.get("const.build.product");if(o&&o!=="emulator")return o}async getDeviceName(e){let t=await yt(this.hdcPath,e,[...Vs]);return this.extractDisplayName(t)??e}async getDeviceInfo(e,t){if(e.length===0)return null;if(t){let r=e.find(s=>s.serial===t);if(r)return r;let i=t.toLowerCase(),o=[];for(let s of e){let a=await this.getDeviceName(s.serial);a.toLowerCase()===i&&o.push({device:s,name:a})}if(o.length===1)return o[0].device;throw o.length>1?new Error(`Multiple devices match "${t}". Use a serial instead:
23
25
  `+o.map(s=>` - ${s.name} (${s.device.serial})`).join(`
24
- `)):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 pt(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=r.get("const.product.devicetype");let i=r.get("const.ohos.apiversion"),o=r.get("const.ohos.releasetype");i&&(t.osVersion=o?`API ${i} (${o})`:`API ${i}`)}catch{}return t}async listDevicesWithName(){let e=await this.listDevices();return Promise.all(e.map(async t=>({serial:t.serial,name:await this.getDeviceName(t.serial)})))}async getConnectedEntries(){let e=await this.listDevices();return Promise.all(e.map(t=>this.buildConnectedEntry(t.serial)))}async buildConnectedEntry(e){let t=Yt(e),r,i;try{let o=await pt(this.hdcPath,e,[...Ns]);r=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:i}}};var jn=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=q.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;y(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await Gu(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){let r=await this.runHdc(["-t",e,"shell","bm","uninstall","-n",t],!1);if(r.includes("uninstall bundle successfully"))return!0;if(r.includes("uninstall missing installed bundle"))return!1;throw new Error(`Uninstall failed: ${r}`)}async installApp(e,t){if(t.length===0)return;let i=`/data/local/tmp/${qu()}`;try{await this.runHdc(["-t",e,"shell","mkdir",i]);for(let s of t){let a=await this.runHdc(["-t",e,"file","send",s,i+"/"]);if(!a.startsWith("FileTransfer finish"))throw new Error(a)}let o=await this.runHdc(["-t",e,"shell","bm","install","-p",i]);if(!o.includes("install bundle successfully."))throw new Error(o);console.log("App installed successfully")}finally{await this.runHdc(["-t",e,"shell","rm","-rf",i],!1)}}async launchApp(e,t,r){let i=["-t",e,"shell","aa","start","-a",r,"-b",t];return await this.runHdc(i)}};function Ku(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 Zu(n,e){let t=await n.listDevices();if(t.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");if(!e&&t.length>1){let i=await n.listDevicesWithName();throw new Error("Multiple devices found. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+i.map(o=>` - ${o.name} (${o.serial})`).join(`
25
- `))}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let i=await n.getDeviceName(r.serial);console.log(`Auto-selected device: ${i} (${r.serial})`)}return r.serial}function Xu(n,e){if(e)return e;let t=n.profile.modules.filter(r=>{let i=n.getModuleType(r.name);return i==="entry"||i==="feature"||i==="shared"});if(t.length===1){let r=t[0].name;return console.log(`Auto-selected module: ${r}`),r}throw new Error(`Specify a module using --module <name>.
26
+ `)):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 yt(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=r.get("const.product.devicetype");let i=r.get("const.ohos.apiversion"),o=r.get("const.ohos.releasetype");i&&(t.osVersion=o?`API ${i} (${o})`:`API ${i}`)}catch{}return t}async listDevicesWithName(){let e=await this.listDevices();return Promise.all(e.map(async t=>({serial:t.serial,name:await this.getDeviceName(t.serial)})))}async getConnectedEntries(){let e=await this.listDevices();return Promise.all(e.map(t=>this.buildConnectedEntry(t.serial)))}async buildConnectedEntry(e){let t=Xt(e),r,i;try{let o=await yt(this.hdcPath,e,[...Vs]);r=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:i}}};var Kn=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=G.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;g(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await dp(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){let r=await this.runHdc(["-t",e,"shell","bm","uninstall","-n",t],!1);if(r.includes("uninstall bundle successfully"))return!0;if(r.includes("uninstall missing installed bundle"))return!1;throw new Error(`Uninstall failed: ${r}`)}async installApp(e,t){if(t.length===0)return;let i=`/data/local/tmp/${lp()}`;try{await this.runHdc(["-t",e,"shell","mkdir",i]);for(let s of t){let a=await this.runHdc(["-t",e,"file","send",s,i+"/"]);if(!a.startsWith("FileTransfer finish"))throw new Error(a)}let o=await this.runHdc(["-t",e,"shell","bm","install","-p",i]);if(!o.includes("install bundle successfully."))throw new Error(o);console.log("App installed successfully")}finally{await this.runHdc(["-t",e,"shell","rm","-rf",i],!1)}}async launchApp(e,t,r){let i=["-t",e,"shell","aa","start","-a",r,"-b",t];return await this.runHdc(i)}};function hp(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 fp(n,e){let t=await n.listDevices();if(t.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");if(!e&&t.length>1){let i=await n.listDevicesWithName();throw new Error("Multiple devices found. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+i.map(o=>` - ${o.name} (${o.serial})`).join(`
27
+ `))}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let i=await n.getDeviceName(r.serial);console.log(`Auto-selected device: ${i} (${r.serial})`)}return r.serial}function gp(n,e){if(e&&e.length>0)return e;let t=n.profile.modules.filter(r=>{let i=n.getModuleType(r.name);return i==="entry"||i==="feature"||i==="shared"});if(t.length===1){let r=t[0].name;return console.log(`Auto-selected module: ${r}`),[r]}throw new Error(`Specify module(s) using --module <name> [<name>...].
26
28
  Available runnable modules:
27
29
  `+t.map(r=>` - ${r.name}`).join(`
28
- `))}function Qu(n,e,t,r,i){let o=[],s=n.collectNonHarDependentModuleList(e);for(let c of s){let l=n.findArtifactPath(c,t,r,i);o.push(l)}let a=n.findArtifactPath(e,t,r,i);return o.push(a),o}async function ep(n,e,t,r,i,o){o&&(console.log(`Uninstalling ${t}...`),await n.uninstallApp(e,t)||console.log(`App ${t} not installed; skipping uninstallation.`)),console.log(`
29
- Installing artifacts to device ${e}...`),await n.installApp(e,r),console.log(`Launching ${t}/${i}...`);let s=await n.launchApp(e,t,i);console.log(_s(`
30
- Application '${t}': ${s}`))}var tp=new Yu("run").description("Build and run the project on a connected device").option("--module <module>","Module 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").action(async n=>{try{await rp(n)}catch(e){console.error(Vu(e.message)),process.exit(1)}});async function np(n,e,t,r,i,o){let s=new dt(e,n.rootDir),a=new Xe(e,n.rootDir),l=n.collectNonHarDependentModuleList(t).map(E=>`${E}@${r}`),u=Ii(n,l),f={type:"modules",modulesToBuild:l,moduleTasks:u};await qt(n.rootDir,()=>Di(s,a,i,o,f),()=>console.log("Another build is already running for this project. Waiting for completion...")),console.log(`
31
- `+_s("Build completed successfully."))}async function rp(n){let e=Ze.discover(process.cwd());console.warn(Ju("Ensure the project source is trusted before proceeding."));let t=await L.new(),r=Xu(e,n.module),{moduleName:i,targetName:o}=Ku(r),s=e.getModuleType(i);if(s!=="entry"&&s!=="feature"&&s!=="shared")throw new Error(`Module '${i}' '${s}' is not runnable. Specify an entry or feature module.`);let a=new jn(t),c=q.from(t),l=await Zu(c,n.device),u=l.includes("127.0.0.1")||l.includes("localhost"),f=n.product||"default";e.validateProduct(f);let E=n.buildMode||"debug";n.skipBuild||await np(e,t,i,o,f,E);let M=Qu(e,i,o,u,f),j=e.getBundleName(),wi=e.getMainAbility(i,n.ability);await ep(a,l,j,M,wi,!!n.uninstall)}var Hs=tp;import{Command as ip}from"commander";import{green as Fs,red as js,cyan as xi}from"colorette";import{execa as $s}from"execa";function op(){return"@deveco-test/deveco-cli"}function sp(){return"1.3.0-Test.2"}var ap=new ip("update").description("Update deveco-cli to latest").action(async()=>{let n=op(),e=sp();console.log(xi("Checking for updates..."));try{let{stdout:t}=await $s("npm",["view",n,"version"]),r=t.trim();if(r===e){console.log(Fs(`
32
- ${n} is already up to date (version ${e}.)`));return}console.log(xi(`
33
- New version found: ${r} (current: ${e})`)),console.log(xi(`Updating ${n}...`)),await $s("npm",["install","-g",`${n}@latest`],{stdio:"inherit"}),console.log(`
34
- `+Fs(`${n} updated successfully to version ${r}.`))}catch(t){let r=t;console.error(js(`Failed to update ${n}`)),r.message&&console.error(js(r.message)),process.exit(1)}}),Ws=ap;import{Command as Op}from"commander";import{execa as Wn}from"execa";function G(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as cp}from"child_process";var lp=2500;function dp(n,e,t,r,i,o){n.once("exit",s=>{if(o())return;clearTimeout(e);let a=t();s===0||s===null?r():i(a||`Emulator process exited with code ${s}`)})}function up(n,e,t,r){let i=!1,o=()=>i,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{i||(i=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners(),n.stderr?.destroy(),n.unref(),t())},c=u=>{if(!i){i=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners();try{n.kill()}catch{}r(new Error(u))}},l=setTimeout(a,lp);n.once("error",u=>c(u.message)),dp(n,l,s,a,c,o)}function Bs(n,e,t){return y(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,i)=>{let o=[],s=cp(n,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>o.push(a)),up(s,o,r,i)})}import*as mt from"path";function pp(n){let e=new Set,t=[];for(let r of n){let i=JSON.stringify(r);e.has(i)||(e.add(i),t.push(r))}return t}function mp(n){let e=n.instancePath?.trim();if(e)return mt.dirname(mt.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?mt.dirname(mt.normalize(t)).replace(/\\/g,"/"):""}function hp(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function Us(n,e){return e?[...n,"-bootmode",e]:n}function fp(n,e,t){let r=[Us(["-start",n],t)],i=mp(e);if(i)for(let o of hp(e.imageRoot))r.push(Us(["-hvd",n,"-path",i,...o],t));return pp(r)}async function zs(n,e,t,r){let i=new Error("No start strategy ran"),o=fp(n,e,r);for(let s of o)try{return await t(s),{ok:!0}}catch(a){i=a}return{ok:!1,lastError:i}}async function ki(n){return(await q.withHdcPath(n).listDevices()).map(t=>t.serial).filter(Yt)}async function Ri(n){let e=await ki(n);return e.length===0?[]:(await Promise.all(e.map(r=>Fn(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function qs(n,e){return(await Ri(n)).includes(e)}import*as ft from"path";import{existsSync as gp,statSync as yp}from"fs";function ht(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function vp(n){let e=ht(n,["instancePath","instance_path","InstancePath","instancepath","instanceDir","instance_dir","InstanceDir","deployPath","deploy_path","deployedPath","deployed_path","workPath","work_path","dataPath","data_path"]);if(e)return e;for(let[t,r]of Object.entries(n)){if(typeof r!="string"||!r.trim())continue;let i=t.toLowerCase();if(i.includes("instance")&&(i.includes("path")||i.includes("dir"))||i==="deployedpath")return r.trim()}return""}function wp(n){return ht(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function bp(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=ft.dirname(ft.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let i=ft.join(t,r.name);gp(i)&&yp(i).isDirectory()&&(r.instancePath=i.replace(/\\/g,"/"))}}function Sp(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=wp(t),i=ht(t,["deviceType","DeviceType","devicetype"]),o=ht(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:vp(t),path:ht(t,["path","Path","hvdPath","hvd_path"]),imageRoot:ht(t,["imageRoot","image_root","ImageRoot"]),uuid:r||void 0,deviceType:i||void 0,osVersion:o||void 0}}).filter(t=>t.name):null}catch{return null}}function Ep(n){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,r=null,i;for(;(i=t.exec(n))!==null;){let[,o,s]=i;if(o.toLowerCase()==="name")r&&e.push(r),r={name:s.trim()};else if(r){let a=o.toLowerCase();a==="isrunning"?r.isRunning=s.trim().toLowerCase()==="true":a==="instancepath"?r.instancePath=s.trim():a==="path"?r.path=s.trim():a==="imageroot"?r.imageRoot=s.trim():a==="devicetype"?r.deviceType=s.trim():a==="os.osversion"&&(r.osVersion=s.trim())}}return r&&e.push(r),e}function Gs(n){let t=Sp(n)??Ep(n);return bp(t),t}function Mi(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function Pp(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function Cp(n){if(!Pp(n))return null;let e=Mi(n,["osVersion","OsVersion","OSVersion"]),t=Mi(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=Mi(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function $n(n){let e=n.trim();if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let r=[];for(let i of t){if(!i||typeof i!="object")continue;let o=Cp(i);o&&r.push(o)}return r}catch{return[]}}function Ys(n){let t=$n(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var Vs=/no images are available/i,Ip="7.0.0";function be(n){return n.normalize("NFKC").trim().toLowerCase()}function Dp(n){let e=n.message||"";return Vs.test(e)}function Ap(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function Tp(n,e){let t=n.split(".").map(o=>Number(o)),r=e.split(".").map(o=>Number(o)),i=Math.max(t.length,r.length);for(let o=0;o<i;o++){let s=(t[o]??0)-(r[o]??0);if(s!==0)return s}return 0}function Vt(n,e){return`${n} ${e.join(" ")}`.trim()}function xp(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 gt=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 y(`Executing: ${Vt(this.emulatorPath,e)}`),Wn(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return Bs(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return Gs(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let r of t)r.name&&r.deviceType&&e.set(G(r.name),r.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),r=G(e),i=t.find(a=>G(a.name)===r);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;if(await this.isAlreadyRunning(o,i))return"already-running";await this.assertSystemImageAvailable(i);let s=await zs(o,i,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return"started";if(await this.isAlreadyRunning(o))return"already-running";throw new Error(`Unable to start emulator "${e}". All methods failed.
35
- Last error: ${s.lastError.message||"unknown"}`)}async isAlreadyRunning(e,t){return t?.isRunning===!0||t===void 0&&(await this.listEmulators()).find(i=>i.name===e)?.isRunning===!0?!0:qs(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=G(e),i=t.find(a=>G(a.name)===r);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;return await this.isAlreadyRunning(o,i)?(await this.executeEmulator(["-stop",o]),"stopped"):"already-stopped"}async controlEmulator(e,t){await this.assertControlCommandSupported();let r=this.buildControlArgs(e,t);y(`[EmulatorManager] control ${xp(t)} -> ${Vt(this.emulatorPath,r)}`),await this.runEmulatorChecked(r,{printOutputOnSuccess:!1})}async assertControlCommandSupported(){let e=this.emulatorPath;if(n.supportedControlPaths.has(e))return;let t=["-version"];y(`Executing: ${Vt(this.emulatorPath,t)}`);let{stdout:r,stderr:i,exitCode:o}=await Wn(this.emulatorPath,t,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:1024*1024}),s=[r,i].filter(Boolean).join(`
36
- `).trim(),a=Ap(s);if(o!==0||!a)throw new Error("Emulator scene control commands require Emulator 7.0 or later. Unable to determine the current Emulator version.");if(Tp(a,Ip)<0)throw new Error(`Emulator scene control commands require Emulator 7.0 or later. Current Emulator version is ${a}. Please upgrade DevEco Studio or the Emulator SDK.`);n.supportedControlPaths.add(e)}buildControlArgs(e,t){let r=["-instance",e];switch(t.type){case"shake":return[...r,"-shake"];case"power":return[...r,"-power"];case"rotation":return[...r,"-rotation",t.direction];case"volume":return[...r,"-volume",t.direction];case"folded-state":return[...r,"-foldedState",t.state];case"battery":return[...r,"-battery",String(t.level)];case"battery-status":return[...r,"-batteryStatus",String(t.status)];case"gps":return[...r,"-gps",`-${t.key}`,t.value];case"outdoor-running":return[...r,"-outdoorRunning"];case"outdoor-cycling":return[...r,"-outdoorCycling"];case"driving-navigation":return[...r,"-drivingNavigation"];case"sensor":return[...r,"-sensor",`-${t.key}`,String(t.value)]}}async executeEmulatorInherit(e){y(`Executing: ${Vt(this.emulatorPath,e)}`);let{exitCode:t}=await Wn(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(o){if(!Dp(o))throw o;r=o}(r!==void 0||await this.hasMatchingDownloadedImage(e))&&await this.runSoftwareVersionFallback(e,t,r)}async listEmulatorImages(e){let t=["-imageList"];e.deviceType&&t.push("-deviceType",e.deviceType),e.downloaded!==void 0&&t.push("-downloaded",e.downloaded?"true":"false");let{stdout:r}=await this.executeEmulator(t);return r}async listDownloadedImageOsVersions(){let e=await this.listEmulatorImages({downloaded:!0});return Ys(e)}async hasMatchingDownloadedImage(e){return(await this.findMatchingDownloadedImages(e)).length>0}async runSoftwareVersionFallback(e,t,r){try{for(let i of t)await this.runUninstallImageChecked(e.deviceType,i)}catch(i){let o=r!==void 0?`Primary uninstall failed: ${r.message}
37
- `:"";throw new Error(`${o}Fallback uninstall failed: ${i.message}`,{cause:i})}if(await this.hasMatchingDownloadedImage(e))throw new Error(`Image for --device-type "${e.deviceType}" and --os-version "${e.osVersion}" remains listed as downloaded after uninstallation.`)}async resolveSoftwareVersionsForUninstall(e){let t=await this.findMatchingDownloadedImages(e);return[...new Set(t.map(r=>r.softwareVersion).filter(Boolean))]}async findMatchingDownloadedImages(e){let t=await this.listEmulatorImages({deviceType:e.deviceType,downloaded:!0}),r=$n(t),i=be(e.deviceType),o=be(e.osVersion);return r.filter(s=>be(s.deviceType)===i&&(be(s.osVersion)===o||be(s.softwareVersion)===o))}async hasDownloadedSystemImage(e,t){let r=await this.listEmulatorImages({downloaded:!0}),i=$n(r),o=be(t),s=e?.trim()?be(e):void 0;return i.some(a=>be(a.osVersion)===o||be(a.softwareVersion)===o?s===void 0?!0:be(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:[Vs]})}async runEmulatorChecked(e,t){y(`Executing: ${Vt(this.emulatorPath,e)}`);let{stdout:r,stderr:i,exitCode:o}=await Wn(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:20*1024*1024}),s=[r,i].filter(Boolean).join(`
38
- `).trim(),a=/Invalid command|无效命令|鏃犳晥鍛戒护/i.test(s)||/please attach the correct parameter/i.test(s),c=(t?.extraReject??[]).some(u=>u.test(s));if(o!==0||a||c)throw new Error(s||`emulator exited with code ${o===null?"null":o}`);if(t?.printOutputOnSuccess!==!1&&s){let u=(t?.transformOutput?t.transformOutput(s):s).trim();u&&console.log(u)}}async checkExistingVirtualDevice(e,t){let r=await this.listEmulators(),i=G(e),o=r.find(s=>G(s.name)===i);if(o)if(t)await this.deleteVirtualDevice(o.name);else throw new Error(`Emulator "${e}" already exists. Use \`--force\` to overwrite.`);return i}async createVirtualDevice(e){let t=await this.checkExistingVirtualDevice(e.name,e.force),r=["-create",e.name,"-deviceType",e.deviceType,"-osVersion",e.osVersion];if(await this.runEmulatorChecked(r,{extraReject:[/Device create fail/i,/already exists/i,/Invalid OS version/i,/cannot be empty/i],printOutputOnSuccess:!0,transformOutput:o=>o.split(/\r?\n/).map(s=>s.trim().startsWith("Device create success.")?"Device create success.":s).join(`
39
- `)}),!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 i=Date.now()+t;for(;Date.now()<i;){if((await this.listEmulators()).some(a=>G(a.name)===e))return!0;await new Promise(a=>setTimeout(a,r))}return!1}async deleteVirtualDevice(e){let t=await this.listEmulators(),r=G(e),i=t.find(s=>G(s.name)===r);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;if(i.isRunning===!0||await this.isAlreadyRunning(o,i))throw new Error(`Failed to delete device: ${o}
40
- The device may be running.`);return await this.runEmulatorChecked(["-delete",o,"-force"],{printOutputOnSuccess:!1}),o}};import{red as Oi,yellow as Ks,gray as Zs}from"colorette";import Lp from"ora";import{red as kp}from"colorette";function Bn(n,e){n?n.fail(e):console.error(kp(e)),process.exit(1)}import{green as Rp}from"colorette";function Js(n,e){return n+" ".repeat(Math.max(0,e-n.length))}function Mp(n,e){return n.map((t,r)=>{let i=t.length;for(let o of e){let s=o.cells[r]??"";i=Math.max(i,s.length)}return i})}function Jt(n,e){let t=Mp(n,e),r=[];r.push(n.map((i,o)=>Js(i,t[o])).join(" ")),r.push(t.map(i=>"-".repeat(i)).join(" "));for(let i of e){let o=i.cells.map((s,a)=>Js(s??"",t[a])).join(" ").trimEnd();r.push(i.highlight?Rp(o):o)}return r.join(`
41
- `)}function Np(n,e){if(e.size!==0)for(let t of n){if(!t.isEmulator||!t.name)continue;let r=e.get(G(t.name));r&&(t.deviceType=r)}}var _p=["Name","Serial","Kind","Device Type"];function Hp(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function Fp(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function jp(){console.log(Ks(" No active devices.")),console.log(Zs(" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function $p(n){let t=[...n].sort(Fp).map(Hp);console.log(Jt(_p,t))}async function Wp(n,e){if(!n.some(i=>i.isEmulator)||!e.emulatorPath)return;let r=await gt.from(e).getDeviceTypeByName();Np(n,r)}async function Bp(n,e,t){try{let r=await n.getConnectedEntries();await Wp(r,e),t?.stop(),r.length===0?jp():$p(r)}catch(r){Bn(t,`Failed to list devices: ${r.message}`)}}async function Up(n,e){let t=await n.listDevices();if(!(t.length<2)){console.error(Oi("Multiple devices connected. Specify a device with:"));for(let r of t){let i=await n.getDeviceName(r.serial);console.error(Zs(` ${e} -t ${r.serial} # ${i}`))}process.exit(1)}}async function zp(n,e){try{e||await Up(n,"devecocli device view");let t=await n.listDevices(),r=await n.getDeviceInfo(t,e);r||(console.log(Ks("No connected device found.")),process.exit(1));let i=await n.getDeviceDetail(r.serial),o=await n.getDeviceName(r.serial);console.log(` Serial: ${r.serial}`),console.log(` Device Name: ${o}`),i.deviceType&&console.log(` Device Type: ${i.deviceType}`),i.osVersion&&console.log(` OS Version: ${i.osVersion}`)}catch(t){console.error(Oi(`Failed to show device details: ${t.message}`)),process.exit(1)}}async function Xs(){try{let n=await L.new();return{manager:q.from(n),toolProvider:n}}catch(n){console.error(Oi(`Failed to initialize device manager: ${n.message}`)),process.exit(1);return}}var Li=new Op("device").description("Manage connected devices");Li.command("list").description("List all connected devices").action(async()=>{let{manager:n,toolProvider:e}=await Xs(),t=Lp({text:"Querying connected devices\u2026",color:"cyan"}).start();await Bp(n,e,t)});Li.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").action(async n=>{let{manager:e}=await Xs();await zp(e,n.target)});var Qs=Li;import{Argument as ji,Command as $i,Option as Qt}from"commander";import{green as en,cyan as vt,red as ee,yellow as Se,gray as Xt}from"colorette";import lm from"ora";import qp from"readline/promises";import{execa as ta}from"execa";import*as Le from"fs/promises";import*as _i from"os";import*as Qe from"path";var Ni=`1/4:\r
30
+ `))}async function yp(n,e,t,r,i,o){o&&(console.log(`Uninstalling ${t}...`),await n.uninstallApp(e,t)||console.log(`App ${t} not installed; skipping uninstallation.`)),console.log(`
31
+ Installing artifacts to device ${e}...`),await n.installApp(e,r),console.log(`Launching ${t}/${i}...`);let s=await n.launchApp(e,t,i);console.log(Ys(`
32
+ Application '${t}': ${s}`))}var vp=new up("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").action(async n=>{try{await bp(n)}catch(e){console.error(pp(e.message)),process.exit(1)}});async function wp(n,e,t,r,i){let o=new ft(e,n.rootDir),s=new nt(e,n.rootDir),a=new Set;for(let{moduleName:f,targetName:P}of t)for(let C of n.collectNonHarDependentModuleList(f))a.add(`${C}@${P}`);let c=[...a],l=Hi(n,c),u={type:"modules",modulesToBuild:c,moduleTasks:l};await Kt(n.rootDir,()=>Fi(o,s,r,i,u,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion...")),console.log(`
33
+ `+Ys("Build completed successfully."))}async function bp(n){let e=tt.discover(process.cwd());console.warn(mp("Ensure the project source is trusted before proceeding."));let t=await N.new(),i=gp(e,n.module).map(hp);for(let{moduleName:ne}of i){let he=e.getModuleType(ne);if(he!=="entry"&&he!=="feature"&&he!=="shared")throw new Error(`Module '${ne}' '${he}' is not runnable. Specify an entry or feature module.`)}let o=new Kn(t),s=G.from(t),a=await fp(s,n.device),c=a.includes("127.0.0.1")||a.includes("localhost"),l=n.product||"default";e.validateProduct(l);let u=n.buildMode||"debug";n.skipBuild||await wp(e,t,i,l,u);let f=new Set;for(let{moduleName:ne,targetName:he}of i){let Wn=e.collectNonHarDependentModuleList(ne);for(let Lu of Wn)f.add(e.findArtifactPath(Lu,he,c,l));f.add(e.findArtifactPath(ne,he,c,l))}let P=[...f],C=e.getBundleName(),L=e.getMainAbility(i[0].moduleName,n.ability);await yp(o,a,C,P,L,!!n.uninstall)}var Js=vp;import{Command as Sp}from"commander";import{green as Ks,red as Zs,cyan as Bi}from"colorette";import{execa as Xs}from"execa";function Ep(){return"@deveco-test/deveco-cli"}function Pp(){return"1.3.0-Test.3"}var Cp=new Sp("update").description("Update deveco-cli to latest").action(async()=>{let n=Ep(),e=Pp();console.log(Bi("Checking for updates..."));try{let{stdout:t}=await Xs("npm",["view",n,"version"]),r=t.trim();if(r===e){console.log(Ks(`
34
+ ${n} is already up to date (version ${e}.)`));return}console.log(Bi(`
35
+ New version found: ${r} (current: ${e})`)),console.log(Bi(`Updating ${n}...`)),await Xs("npm",["install","-g",`${n}@latest`],{stdio:"inherit"}),console.log(`
36
+ `+Ks(`${n} updated successfully to version ${r}.`))}catch(t){let r=t;console.error(Zs(`Failed to update ${n}`)),r.message&&console.error(Zs(r.message)),process.exit(1)}}),Qs=Cp;import{Command as Kp}from"commander";import{execa as Xn}from"execa";function V(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as Dp}from"child_process";var Ip=2500;function Ap(n,e,t,r,i,o){n.once("exit",s=>{if(o())return;clearTimeout(e);let a=t();s===0||s===null?r():i(a||`Emulator process exited with code ${s}`)})}function xp(n,e,t,r){let i=!1,o=()=>i,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{i||(i=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners(),n.stderr?.destroy(),n.unref(),t())},c=u=>{if(!i){i=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners();try{n.kill()}catch{}r(new Error(u))}},l=setTimeout(a,Ip);n.once("error",u=>c(u.message)),Ap(n,l,s,a,c,o)}function ea(n,e,t){return g(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,i)=>{let o=[],s=Dp(n,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>o.push(a)),xp(s,o,r,i)})}import*as vt from"path";function Tp(n){let e=new Set,t=[];for(let r of n){let i=JSON.stringify(r);e.has(i)||(e.add(i),t.push(r))}return t}function kp(n){let e=n.instancePath?.trim();if(e)return vt.dirname(vt.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?vt.dirname(vt.normalize(t)).replace(/\\/g,"/"):""}function Rp(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function ta(n,e){return e?[...n,"-bootmode",e]:n}function Mp(n,e,t){let r=[ta(["-start",n],t)],i=kp(e);if(i)for(let o of Rp(e.imageRoot))r.push(ta(["-hvd",n,"-path",i,...o],t));return Tp(r)}async function na(n,e,t,r){let i=new Error("No start strategy ran"),o=Mp(n,e,r);for(let s of o)try{return await t(s),{ok:!0}}catch(a){i=a}return{ok:!1,lastError:i}}async function Wi(n){return(await G.withHdcPath(n).listDevices()).map(t=>t.serial).filter(Xt)}async function Ui(n){let e=await Wi(n);return e.length===0?[]:(await Promise.all(e.map(r=>Jn(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function ra(n,e){return(await Ui(n)).includes(e)}import*as bt from"path";import{existsSync as Op,statSync as Lp}from"fs";function wt(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function Np(n){let e=wt(n,["instancePath","instance_path","InstancePath","instancepath","instanceDir","instance_dir","InstanceDir","deployPath","deploy_path","deployedPath","deployed_path","workPath","work_path","dataPath","data_path"]);if(e)return e;for(let[t,r]of Object.entries(n)){if(typeof r!="string"||!r.trim())continue;let i=t.toLowerCase();if(i.includes("instance")&&(i.includes("path")||i.includes("dir"))||i==="deployedpath")return r.trim()}return""}function _p(n){return wt(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function Hp(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=bt.dirname(bt.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let i=bt.join(t,r.name);Op(i)&&Lp(i).isDirectory()&&(r.instancePath=i.replace(/\\/g,"/"))}}function Fp(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=_p(t),i=wt(t,["deviceType","DeviceType","devicetype"]),o=wt(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:Np(t),path:wt(t,["path","Path","hvdPath","hvd_path"]),imageRoot:wt(t,["imageRoot","image_root","ImageRoot"]),uuid:r||void 0,deviceType:i||void 0,osVersion:o||void 0}}).filter(t=>t.name):null}catch{return null}}function jp(n){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,r=null,i;for(;(i=t.exec(n))!==null;){let[,o,s]=i;if(o.toLowerCase()==="name")r&&e.push(r),r={name:s.trim()};else if(r){let a=o.toLowerCase();a==="isrunning"?r.isRunning=s.trim().toLowerCase()==="true":a==="instancepath"?r.instancePath=s.trim():a==="path"?r.path=s.trim():a==="imageroot"?r.imageRoot=s.trim():a==="devicetype"?r.deviceType=s.trim():a==="os.osversion"&&(r.osVersion=s.trim())}}return r&&e.push(r),e}function ia(n){let t=Fp(n)??jp(n);return Hp(t),t}function zi(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function $p(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function Bp(n){if(!$p(n))return null;let e=zi(n,["osVersion","OsVersion","OSVersion"]),t=zi(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=zi(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function Zn(n){let e=n.trim();if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let r=[];for(let i of t){if(!i||typeof i!="object")continue;let o=Bp(i);o&&r.push(o)}return r}catch{return[]}}function oa(n){let t=Zn(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var sa=/no images are available/i,Wp="7.0.0";function De(n){return n.normalize("NFKC").trim().toLowerCase()}function Up(n){let e=n.message||"";return sa.test(e)}function zp(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function qp(n,e){let t=n.split(".").map(o=>Number(o)),r=e.split(".").map(o=>Number(o)),i=Math.max(t.length,r.length);for(let o=0;o<i;o++){let s=(t[o]??0)-(r[o]??0);if(s!==0)return s}return 0}function Qt(n,e){return`${n} ${e.join(" ")}`.trim()}function Gp(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 St=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 g(`Executing: ${Qt(this.emulatorPath,e)}`),Xn(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return ea(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return ia(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let r of t)r.name&&r.deviceType&&e.set(V(r.name),r.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),r=V(e),i=t.find(a=>V(a.name)===r);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;if(await this.isAlreadyRunning(o,i))return"already-running";await this.assertSystemImageAvailable(i);let s=await na(o,i,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return"started";if(await this.isAlreadyRunning(o))return"already-running";throw new Error(`Unable to start emulator "${e}". All methods failed.
37
+ Last error: ${s.lastError.message||"unknown"}`)}async isAlreadyRunning(e,t){return t?.isRunning===!0||t===void 0&&(await this.listEmulators()).find(i=>i.name===e)?.isRunning===!0?!0:ra(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=V(e),i=t.find(a=>V(a.name)===r);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;return await this.isAlreadyRunning(o,i)?(await this.executeEmulator(["-stop",o]),"stopped"):"already-stopped"}async controlEmulator(e,t){await this.assertControlCommandSupported();let r=this.buildControlArgs(e,t);g(`[EmulatorManager] control ${Gp(t)} -> ${Qt(this.emulatorPath,r)}`),await this.runEmulatorChecked(r,{printOutputOnSuccess:!1})}async assertControlCommandSupported(){let e=this.emulatorPath;if(n.supportedControlPaths.has(e))return;let t=["-version"];g(`Executing: ${Qt(this.emulatorPath,t)}`);let{stdout:r,stderr:i,exitCode:o}=await Xn(this.emulatorPath,t,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:1024*1024}),s=[r,i].filter(Boolean).join(`
38
+ `).trim(),a=zp(s);if(o!==0||!a)throw new Error("Emulator scene control commands require Emulator 7.0 or later. Unable to determine the current Emulator version.");if(qp(a,Wp)<0)throw new Error(`Emulator scene control commands require Emulator 7.0 or later. Current Emulator version is ${a}. Please upgrade DevEco Studio or the Emulator SDK.`);n.supportedControlPaths.add(e)}buildControlArgs(e,t){let r=["-instance",e];switch(t.type){case"shake":return[...r,"-shake"];case"power":return[...r,"-power"];case"rotation":return[...r,"-rotation",t.direction];case"volume":return[...r,"-volume",t.direction];case"folded-state":return[...r,"-foldedState",t.state];case"battery":return[...r,"-battery",String(t.level)];case"battery-status":return[...r,"-batteryStatus",String(t.status)];case"gps":return[...r,"-gps",`-${t.key}`,t.value];case"outdoor-running":return[...r,"-outdoorRunning"];case"outdoor-cycling":return[...r,"-outdoorCycling"];case"driving-navigation":return[...r,"-drivingNavigation"];case"sensor":return[...r,"-sensor",`-${t.key}`,String(t.value)]}}async executeEmulatorInherit(e){g(`Executing: ${Qt(this.emulatorPath,e)}`);let{exitCode:t}=await Xn(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(o){if(!Up(o))throw o;r=o}(r!==void 0||await this.hasMatchingDownloadedImage(e))&&await this.runSoftwareVersionFallback(e,t,r)}async listEmulatorImages(e){let t=["-imageList"];e.deviceType&&t.push("-deviceType",e.deviceType),e.downloaded!==void 0&&t.push("-downloaded",e.downloaded?"true":"false");let{stdout:r}=await this.executeEmulator(t);return r}async listDownloadedImageOsVersions(){let e=await this.listEmulatorImages({downloaded:!0});return oa(e)}async hasMatchingDownloadedImage(e){return(await this.findMatchingDownloadedImages(e)).length>0}async runSoftwareVersionFallback(e,t,r){try{for(let i of t)await this.runUninstallImageChecked(e.deviceType,i)}catch(i){let o=r!==void 0?`Primary uninstall failed: ${r.message}
39
+ `:"";throw new Error(`${o}Fallback uninstall failed: ${i.message}`,{cause:i})}if(await this.hasMatchingDownloadedImage(e))throw new Error(`Image for --device-type "${e.deviceType}" and --os-version "${e.osVersion}" remains listed as downloaded after uninstallation.`)}async resolveSoftwareVersionsForUninstall(e){let t=await this.findMatchingDownloadedImages(e);return[...new Set(t.map(r=>r.softwareVersion).filter(Boolean))]}async findMatchingDownloadedImages(e){let t=await this.listEmulatorImages({deviceType:e.deviceType,downloaded:!0}),r=Zn(t),i=De(e.deviceType),o=De(e.osVersion);return r.filter(s=>De(s.deviceType)===i&&(De(s.osVersion)===o||De(s.softwareVersion)===o))}async hasDownloadedSystemImage(e,t){let r=await this.listEmulatorImages({downloaded:!0}),i=Zn(r),o=De(t),s=e?.trim()?De(e):void 0;return i.some(a=>De(a.osVersion)===o||De(a.softwareVersion)===o?s===void 0?!0:De(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:[sa]})}async runEmulatorChecked(e,t){g(`Executing: ${Qt(this.emulatorPath,e)}`);let{stdout:r,stderr:i,exitCode:o}=await Xn(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:20*1024*1024}),s=[r,i].filter(Boolean).join(`
40
+ `).trim(),a=/Invalid command|无效命令|鏃犳晥鍛戒护/i.test(s)||/please attach the correct parameter/i.test(s),c=(t?.extraReject??[]).some(u=>u.test(s));if(o!==0||a||c)throw new Error(s||`emulator exited with code ${o===null?"null":o}`);if(t?.printOutputOnSuccess!==!1&&s){let u=(t?.transformOutput?t.transformOutput(s):s).trim();u&&console.log(u)}}async checkExistingVirtualDevice(e,t){let r=await this.listEmulators(),i=V(e),o=r.find(s=>V(s.name)===i);if(o)if(t)await this.deleteVirtualDevice(o.name);else throw new Error(`Emulator "${e}" already exists. Use \`--force\` to overwrite.`);return i}async createVirtualDevice(e){let t=await this.checkExistingVirtualDevice(e.name,e.force),r=["-create",e.name,"-deviceType",e.deviceType,"-osVersion",e.osVersion];if(await this.runEmulatorChecked(r,{extraReject:[/Device create fail/i,/already exists/i,/Invalid OS version/i,/cannot be empty/i],printOutputOnSuccess:!0,transformOutput:o=>o.split(/\r?\n/).map(s=>s.trim().startsWith("Device create success.")?"Device create success.":s).join(`
41
+ `)}),!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 i=Date.now()+t;for(;Date.now()<i;){if((await this.listEmulators()).some(a=>V(a.name)===e))return!0;await new Promise(a=>setTimeout(a,r))}return!1}async deleteVirtualDevice(e){let t=await this.listEmulators(),r=V(e),i=t.find(s=>V(s.name)===r);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;if(i.isRunning===!0||await this.isAlreadyRunning(o,i))throw new Error(`Failed to delete device: ${o}
42
+ The device may be running.`);return await this.runEmulatorChecked(["-delete",o,"-force"],{printOutputOnSuccess:!1}),o}};import{red as qi,yellow as ca,gray as la}from"colorette";import Zp from"ora";import{red as Vp}from"colorette";function Qn(n,e){n?n.fail(e):console.error(Vp(e)),process.exit(1)}import{green as Yp}from"colorette";function aa(n,e){return n+" ".repeat(Math.max(0,e-n.length))}function Jp(n,e){return n.map((t,r)=>{let i=t.length;for(let o of e){let s=o.cells[r]??"";i=Math.max(i,s.length)}return i})}function en(n,e){let t=Jp(n,e),r=[];r.push(n.map((i,o)=>aa(i,t[o])).join(" ")),r.push(t.map(i=>"-".repeat(i)).join(" "));for(let i of e){let o=i.cells.map((s,a)=>aa(s??"",t[a])).join(" ").trimEnd();r.push(i.highlight?Yp(o):o)}return r.join(`
43
+ `)}function Xp(n,e){if(e.size!==0)for(let t of n){if(!t.isEmulator||!t.name)continue;let r=e.get(V(t.name));r&&(t.deviceType=r)}}var Qp=["Name","Serial","Kind","Device Type"];function em(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function tm(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function nm(){console.log(ca(" No active devices.")),console.log(la(" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function rm(n){let t=[...n].sort(tm).map(em);console.log(en(Qp,t))}async function im(n,e){if(!n.some(i=>i.isEmulator)||!e.emulatorPath)return;let r=await St.from(e).getDeviceTypeByName();Xp(n,r)}async function om(n,e,t){try{let r=await n.getConnectedEntries();await im(r,e),t?.stop(),r.length===0?nm():rm(r)}catch(r){Qn(t,`Failed to list devices: ${r.message}`)}}async function sm(n,e){let t=await n.listDevices();if(!(t.length<2)){console.error(qi("Multiple devices connected. Specify a device with:"));for(let r of t){let i=await n.getDeviceName(r.serial);console.error(la(` ${e} -t ${r.serial} # ${i}`))}process.exit(1)}}async function am(n,e){try{e||await sm(n,"devecocli device view");let t=await n.listDevices(),r=await n.getDeviceInfo(t,e);r||(console.log(ca("No connected device found.")),process.exit(1));let i=await n.getDeviceDetail(r.serial),o=await n.getDeviceName(r.serial);console.log(` Serial: ${r.serial}`),console.log(` Device Name: ${o}`),i.deviceType&&console.log(` Device Type: ${i.deviceType}`),i.osVersion&&console.log(` OS Version: ${i.osVersion}`)}catch(t){console.error(qi(`Failed to show device details: ${t.message}`)),process.exit(1)}}async function da(){try{let n=await N.new();return{manager:G.from(n),toolProvider:n}}catch(n){console.error(qi(`Failed to initialize device manager: ${n.message}`)),process.exit(1);return}}var Gi=new Kp("device").description("Manage connected devices");Gi.command("list").description("List all connected devices").action(async()=>{let{manager:n,toolProvider:e}=await da(),t=Zp({text:"Querying connected devices\u2026",color:"cyan"}).start();await om(n,e,t)});Gi.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").action(async n=>{let{manager:e}=await da();await am(e,n.target)});var ua=Gi;import{Argument as Zi,Command as Xi,Option as on}from"commander";import{green as sn,cyan as Pt,red as ee,yellow as Ie,gray as rn}from"colorette";import Im from"ora";import cm from"readline/promises";import{execa as ma}from"execa";import*as je from"fs/promises";import*as Yi from"os";import*as it from"path";var Vi=`1/4:\r
42
44
  ---------------------------------------\r
43
45
  Statement About HarmonyOS and Privacy\r
44
46
  \r
@@ -1208,13 +1210,13 @@ Part I: Chinese mainland.\r
1208
1210
  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
1209
1211
  \r
1210
1212
  Part III: Other countries and regions.\r
1211
- ---------------------------------------\r`;var Gp=new Set,Un=new Map,Hi="HarmonyOS_Software_Service_Agreement",na=["Emulator license agreements are not accepted yet.","","Accept the agreements in an interactive terminal:"," devecocli emulator license accept","","To review the agreement text (read-only):"," devecocli emulator license view"].join(`
1212
- `),ra=na,Fi="HarmonyOS_SDK_Agreement";function ia(n,e){return`${n}\0${e}`}function Yp(){Gp.clear(),Un.clear()}var Vp=na,me=class extends Error{constructor(e=Vp){super(e),this.name="EmulatorLicenseBlockedError"}};function oa(n,e){return[n??"",e??""].join(`
1213
- `)}function sa(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 Jp(n){return`Emulator${n.trim()}`}function aa(n){let e=Jp(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 Qe.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return Qe.join(_i.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||Qe.join(_i.homedir(),".cache");return Qe.join(t,"Huawei",e,".emu_config")}async function Kp(n,e,t){let r=ia(n,e),i=Un.get(r);if(i!==void 0)return i;let o=await ta(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=oa(o.stdout,o.stderr).trim();if(o.exitCode!==0||!s)throw new me(t);return Un.set(r,s),s}function Zp(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function Xp(n){try{let e=JSON.parse(n);if(e&&typeof e=="object"&&!Array.isArray(e)){let t={};for(let[r,i]of Object.entries(e))t[r]={value:typeof i=="string"?i:String(i),delimiter:"json"};return t}}catch{return}}function Qp(n){let e=n.trim();if(!(!e||e.startsWith("#")))for(let t of["=",":"]){let r=e.indexOf(t);if(r<=0)continue;let i=e.slice(0,r).trim();if(!i||t===":"&&i.includes("//"))continue;let o=Zp(e.slice(r+1).trim());return{key:i,entry:{value:o,delimiter:t}}}}function em(n){let e={};for(let t of n.split(/\r?\n/)){let r=Qp(t);r&&(e[r.key]=r.entry)}return e}function tm(n){let e=n.trim();if(!e)return{};let t=Xp(e);return t||em(n)}function nm(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function ca(n,e,t,r){let i=await Kp(n,e,r),o=sa(i);if(!o)throw new me(r);let s=aa(o),a;try{a=await Le.readFile(s,"utf8")}catch(u){throw u.code==="ENOENT"?new me(r):u}let l=tm(a)[t];if(!l)throw new me(r);if(l.delimiter==="=")throw new me(r);if(!nm(l.value))throw new me(r)}async function la(n,e){await ca(n,e,Hi,ra)}async function da(n,e){await ca(n,e,Fi,ra)}async function rm(n,e){let t=await ta(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),r=oa(t.stdout,t.stderr).trim();if(t.exitCode!==0||!r)throw new Error(`Emulator -version failed (exit ${String(t.exitCode)}); cannot resolve .emu_config path.`);let i=ia(n,e);return Un.set(i,r),r}async function im(n,e){let t=await rm(n,e),r=sa(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
1214
- ${t}.`);return aa(r)}function ea(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function om(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[Hi]="agree",r[Fi]="agree",await Le.writeFile(n,`${JSON.stringify(r,null,2)}
1215
- `,"utf8"),!0}catch{}return!1}async function sm(n,e){let t=Hi,r=Fi,i=[{k:t,re:new RegExp(`^\\s*${ea(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${ea(r)}\\s*[:=]`)}],o=e.length===0?[]:e.split(/\r?\n/),s=[],a=new Set;for(let c of o){let l=!1;for(let{k:u,re:f}of i)if(f.test(c)){s.push(`${u}:agree`),a.add(u),l=!0;break}l||s.push(c)}a.has(t)||s.push(`${t}:agree`),a.has(r)||s.push(`${r}:agree`),await Le.writeFile(n,s.join(`
1213
+ ---------------------------------------\r`;var lm=new Set,er=new Map,Ji="HarmonyOS_Software_Service_Agreement",ha=["Emulator license agreements are not accepted yet.","","Accept the agreements in an interactive terminal:"," devecocli emulator license accept","","To review the agreement text (read-only):"," devecocli emulator license view"].join(`
1214
+ `),fa=ha,Ki="HarmonyOS_SDK_Agreement";function ga(n,e){return`${n}\0${e}`}function dm(){lm.clear(),er.clear()}var um=ha,ve=class extends Error{constructor(e=um){super(e),this.name="EmulatorLicenseBlockedError"}};function ya(n,e){return[n??"",e??""].join(`
1215
+ `)}function va(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 pm(n){return`Emulator${n.trim()}`}function wa(n){let e=pm(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 it.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return it.join(Yi.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||it.join(Yi.homedir(),".cache");return it.join(t,"Huawei",e,".emu_config")}async function mm(n,e,t){let r=ga(n,e),i=er.get(r);if(i!==void 0)return i;let o=await ma(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=ya(o.stdout,o.stderr).trim();if(o.exitCode!==0||!s)throw new ve(t);return er.set(r,s),s}function hm(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function fm(n){try{let e=JSON.parse(n);if(e&&typeof e=="object"&&!Array.isArray(e)){let t={};for(let[r,i]of Object.entries(e))t[r]={value:typeof i=="string"?i:String(i),delimiter:"json"};return t}}catch{return}}function gm(n){let e=n.trim();if(!(!e||e.startsWith("#")))for(let t of["=",":"]){let r=e.indexOf(t);if(r<=0)continue;let i=e.slice(0,r).trim();if(!i||t===":"&&i.includes("//"))continue;let o=hm(e.slice(r+1).trim());return{key:i,entry:{value:o,delimiter:t}}}}function ym(n){let e={};for(let t of n.split(/\r?\n/)){let r=gm(t);r&&(e[r.key]=r.entry)}return e}function vm(n){let e=n.trim();if(!e)return{};let t=fm(e);return t||ym(n)}function wm(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function ba(n,e,t,r){let i=await mm(n,e,r),o=va(i);if(!o)throw new ve(r);let s=wa(o),a;try{a=await je.readFile(s,"utf8")}catch(u){throw u.code==="ENOENT"?new ve(r):u}let l=vm(a)[t];if(!l)throw new ve(r);if(l.delimiter==="=")throw new ve(r);if(!wm(l.value))throw new ve(r)}async function Sa(n,e){await ba(n,e,Ji,fa)}async function Ea(n,e){await ba(n,e,Ki,fa)}async function bm(n,e){let t=await ma(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),r=ya(t.stdout,t.stderr).trim();if(t.exitCode!==0||!r)throw new Error(`Emulator -version failed (exit ${String(t.exitCode)}); cannot resolve .emu_config path.`);let i=ga(n,e);return er.set(i,r),r}async function Sm(n,e){let t=await bm(n,e),r=va(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
1216
+ ${t}.`);return wa(r)}function pa(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function Em(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[Ji]="agree",r[Ki]="agree",await je.writeFile(n,`${JSON.stringify(r,null,2)}
1217
+ `,"utf8"),!0}catch{}return!1}async function Pm(n,e){let t=Ji,r=Ki,i=[{k:t,re:new RegExp(`^\\s*${pa(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${pa(r)}\\s*[:=]`)}],o=e.length===0?[]:e.split(/\r?\n/),s=[],a=new Set;for(let c of o){let l=!1;for(let{k:u,re:f}of i)if(f.test(c)){s.push(`${u}:agree`),a.add(u),l=!0;break}l||s.push(c)}a.has(t)||s.push(`${t}:agree`),a.has(r)||s.push(`${r}:agree`),await je.writeFile(n,s.join(`
1216
1218
  `)+(s.length>0?`
1217
- `:""),"utf8")}async function am(n){await Le.mkdir(Qe.dirname(n),{recursive:!0});let e="";try{e=await Le.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await om(n,e,t)||await sm(n,e)}async function ua(n,e){return console.log(Ni),0}var cm="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function pa(n,e){if(console.log(Ni),!process.stdin.isTTY||!process.stdout.isTTY)return console.error("`devecocli emulator license accept` requires an interactive terminal."),1;let r=qp.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await r.question(cm)}finally{r.close()}let o=i.trim().toLowerCase();if(o!=="y"&&o!=="yes")return 1;try{let s=await im(n,e);await am(s),Yp()}catch(s){return console.error(s.message),1}return 0}var dm=["ohos.qemu.hvd.name","const.product.name","const.product.model"],ma=["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"],um=`
1219
+ `:""),"utf8")}async function Cm(n){await je.mkdir(it.dirname(n),{recursive:!0});let e="";try{e=await je.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await Em(n,e,t)||await Pm(n,e)}async function Pa(n,e){return console.log(Vi),0}var Dm="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function Ca(n,e){if(console.log(Vi),!process.stdin.isTTY||!process.stdout.isTTY)return console.error("`devecocli emulator license accept` requires an interactive terminal."),1;let r=cm.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await r.question(Dm)}finally{r.close()}let o=i.trim().toLowerCase();if(o!=="y"&&o!=="yes")return 1;try{let s=await Sm(n,e);await Cm(s),dm()}catch(s){return console.error(s.message),1}return 0}var Am=["ohos.qemu.hvd.name","const.product.name","const.product.model"],Da=["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"],xm=`
1218
1220
  Folded state scene mappings:
1219
1221
  foldableFold (3):
1220
1222
  open Fully expanded state
@@ -1237,79 +1239,79 @@ Folded state scene mappings:
1237
1239
  left-half-folded-right-folded
1238
1240
  left-expanded-right-half-folded
1239
1241
  left-half-folded-right-half-folded
1240
- `;function pm(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function mm(n){let e=n.trim();if(!ma.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${ma.join(", ")}`);return e}function fa(n,e,t,r){let i=e.trim();if(!/^-?\d+$/.test(i))throw new Error(`${n} must be an integer in [${t}, ${r}].`);let o=Number(i);if(o<t||o>r)throw new Error(`${n} must be in [${t}, ${r}].`);return o}function ga(n,e,t,r,i){let o=e.trim(),s=Number(o);if(!o||Number.isNaN(s))throw new Error(`${n} must be a number in [${t}, ${r}].`);if(i!==void 0&&!hm(o,i))throw new Error(`${n} supports at most ${i} decimal place(s).`);if(s<t||s>r)throw new Error(`${n} must be in [${t}, ${r}].`);return o}function hm(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function fm(n,e,t,r,i){return Number(ga(n,e,t,r,i))}function gm(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 ym(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 vm(n,e){let t=i=>i.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(Se("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(Se("Run `devecocli emulator image download ...` followed by `devecocli emulator image list` and then copy an `osVersion` string exactly.")),new Error("No downloaded osVersion values parsed; cannot validate --os-version.");if(!e.some(i=>t(i)===r)){console.error(ee("--os-version does not match any downloaded image (exact string required).")),console.log(Se("Use one of these --os-version values:"));for(let i of e)console.log(` ${i}`);throw new Error(`No downloaded image matches --os-version "${n}".`)}}var wm=["Name","Status","Serial","Device Type","OS Version"];function bm(n,e,t){return{cells:[n.name,t?"running":"stopped",e??"-",n.deviceType??"-",n.osVersion??"-"],highlight:t}}async function Sm(n,e){let t=await Promise.all(e.map(async r=>{let i=await pt(n,r,dm);return[r,i]}));return new Map(t)}async function Em(n){let e=await ki(n),t=await Sm(n,e);return{serials:e,params:t}}function Pm(n,e,t,r,i){if(e)for(let o of["const.product.name","const.product.model"]){let s=e.get(o);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),i.set(s,n);let c=r.indexOf(n);c!==-1&&r.splice(c,1);return}}function Cm(n,e,t){let r=new Map,i=new Map,o=[...n],s=[...t];for(let a of n){let c=e.get(a),l=c?.get("ohos.qemu.hvd.name");l&&i.set(l,a),t.length>0&&Pm(a,c,s,o,r)}for(let a=0;a<s.length&&a<o.length;a++)r.set(s[a],o[a]);return{productSerialMap:r,hvdSerialMap:i}}function Im(n,e,t){let r=n.map(i=>({emu:i,serial:e.get(i.name)??t.get(i.name),effectiveRunning:i.isRunning===!0||t.has(i.name)}));return r.sort((i,o)=>i.effectiveRunning!==o.effectiveRunning?i.effectiveRunning?-1:1:i.emu.name.localeCompare(o.emu.name)),r.map(i=>bm(i.emu,i.serial,i.effectiveRunning))}async function Dm(n,e,t){try{let[r,i]=await Promise.all([n.listEmulators(),Em(e)]);if(r.length===0){t?.stop(),console.log(Se(" No emulator instances found."));return}let o=r.filter(l=>l.isRunning).map(l=>l.name),{productSerialMap:s,hvdSerialMap:a}=Cm(i.serials,i.params,o);t?.stop();let c=Im(r,s,a);console.log(Jt(wm,c))}catch(r){Bn(t,`Failed to list emulators: ${r.message}`)}}function ya(n,e,t){let r=!1;for(let i=0;i<n.length;i++){let o=n[i];if(o.status!=="rejected")continue;r=!0;let s=o.reason;console.error(ee(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(Xt(s.stdout)),s.stderr&&console.error(Xt(s.stderr))}return r}var Am=2e3,Tm=6e4;async function xm(n,e){let t=G(e);return(await Ri(n)).some(i=>G(i)===t)}async function va(n,e,t,r=Tm,i=Am){let o=Date.now()+r;for(;Date.now()<o;){if(await xm(n,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}async function km(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(Se(`Emulator "${t}" is already running.`));return}console.log(vt(`Starting emulator "${t}"...`));let i=await va(e,t,!0);console.log(i?en(`Emulator "${t}" started successfully.`):Se(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function Rm(n,e,t){let r=await Promise.allSettled(t.map(o=>km(n,e,o)));ya(r,t,"start")&&process.exit(1)}async function wa(n,e){let t=e.trim();if(!Yt(t))return t;let r=await q.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 Mm(n,e,t){let r=await wa(e,t);if(console.log(vt(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(Se(`Emulator "${r}" is already stopped.`));return}let o=await va(e,r,!1);console.log(o?en(`Emulator "${r}" stopped successfully.`):Se(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function Om(n,e,t){let r=await Promise.allSettled(t.map(o=>Mm(n,e,o)));ya(r,t,"stop")&&process.exit(1)}async function he(){try{let n=await L.new();return{manager:gt.from(n),toolProvider:n}}catch(n){console.error(ee(`Failed to initialize emulator: ${n.message}`)),process.exit(1);return}}async function Pe(n,e){try{let t=pm(n.target),r=e(),{manager:i,toolProvider:o}=await he(),s=await wa(o.hdcPath,t);await i.controlEmulator(s,r),console.log(en(`Emulator "${t}" operation completed.`))}catch(t){let r=n.target?.trim()||"<unknown>";console.error(ee(`Failed to operate emulator "${r}": ${t.message}`)),process.exit(1)}}function Lm(n){let e=[];return zn(e,"longitude",n.longitude,-180,180,8),zn(e,"latitude",n.latitude,-90,90,8),zn(e,"altitude",n.altitude,-1e4,1e4,2),zn(e,"bearing",n.direction,0,360,2),Wi(e,"Specify one geolocation option.")}function Nm(n){let e=[];return Kt(e,"light",n.lightIntensity,0,1e5,!1),Kt(e,"humidity",n.humidity,0,100,!1),Kt(e,"temperature",n.temperature,-273,100,!1),Kt(e,"steps",n.steps,0,1e4,!0),Kt(e,"heartrate",n.heartrate,0,255,!0),Wi(e,"Specify one sensor option.")}function Wi(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 zn(n,e,t,r,i,o){t!==void 0&&n.push({type:"gps",key:e,value:ga(`--${e}`,t,r,i,o)})}function Kt(n,e,t,r,i,o){if(t===void 0)return;let s=o?fa(`--${e}`,t,r,i):fm(`--${e}`,t,r,i,1);n.push({type:"sensor",key:e,value:s})}function _m(n){let e=[];return n.level!==void 0&&e.push({type:"battery",level:fa("--level",n.level,0,100)}),n.status!==void 0&&e.push({type:"battery-status",status:n.status==="charging"?1:0}),Wi(e,"Specify --level or --status.")}var U=new $i("emulator").description("Manage emulator instances"),Hm=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function qn(n){let e=new Qt("--device-type <type>","Emulator device type").choices([...Hm]);return n?e.makeOptionMandatory():e}function yt(n,e){for(let t of e)if(t in n)return n[t]}function Zt(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function ha(n){let e=Zt(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var Fm=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],jm="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function ba(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function Sa(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let i=r,o=Zt(yt(i,["osVersion","OsVersion","OSVersion","os_version"])),s=Zt(yt(i,["deviceType","DeviceType","device_type"])),a=ha(yt(i,["downloaded","Downloaded","isDownloaded"])),c=Zt(yt(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=Zt(yt(i,["releaseType","ReleaseType","release_type"])),u=ha(yt(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,l,u,a],highlight:e&&a==="true"})}return t}function $m(n){let e=n.trim();if(!e)return!0;let t=ba(e);return t===null?!1:t.length===0?!0:Sa(t,!0).length===0}function Wm(n,e){let t=n.trim();if(!t)return"";let r=ba(t);if(!r)return n.trimEnd();let i=Sa(r,e);return Jt(Fm,i)}var Gn=new $i("image").description("HarmonyOS emulator system images (download, list, remove)");Gn.command("download").description("Download system image").addOption(qn(!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 he();try{await da(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof me&&(console.error(ee(r.message)),process.exit(1)),r}n.deviceType?.trim()||(console.error(ee("Error: missing required option '--device-type <type>'")),process.exit(1)),n.osVersion?.trim()||(console.error(ee("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(ee(`Failed to download system image: ${r.message}`)),process.exit(1)}});Gn.command("remove").description("Remove a downloaded system image").addOption(qn(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let{manager:e}=await he();try{await e.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})}catch(t){console.error(ee(`Failed to remove system image: ${t.message}`)),process.exit(1)}});Gn.command("list").description("List system images").addOption(qn(!1)).option("--all","List all images (local and remote)").addOption(new Qt("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await he();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if($m(r)){console.log(Se(jm));return}if(n.format==="json"){console.log(r.trimEnd());return}let i=Wm(r,n.all===!0);console.log(i)}catch(t){console.error(ee(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});U.addCommand(Gn);var Bi=new $i("license").description("local emulator license");Bi.command("view").description("Review agreement text(read-only)").action(async()=>{let{toolProvider:n}=await he(),e=await ua(n.emulatorPath,n.sdkPath);process.exit(e)});Bi.command("accept").description("review and accept agreements").action(async()=>{let{toolProvider:n}=await he(),e=await pa(n.emulatorPath,n.sdkPath);process.exit(e)});U.addCommand(Bi);U.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Pe(n,()=>({type:"shake"})));U.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Pe(n,()=>({type:"power"})));U.command("rotate").description("Rotate emulator").addOption(new Qt("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new ji("<direction>").choices(["left","right"])).action((n,e)=>Pe(e,()=>({type:"rotation",direction:n})));U.command("volume").description("Change volume").addOption(new Qt("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new ji("<direction>").choices(["up","down"])).action((n,e)=>Pe(e,()=>({type:"volume",direction:n})));U.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",um).action((n,e)=>Pe(e,()=>({type:"folded-state",state:mm(n)})));U.command("battery").description("Set battery level or charging status").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--level <0-100>","Battery level, SOC (integer 0-100)").addOption(new Qt("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>Pe(n,()=>_m(n)));U.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 to 360)").action(n=>Pe(n,()=>Lm(n)));U.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new ji("<type>").choices(["outdoorRunning","outdoorCycling","drivingNavigation"])).action((n,e)=>{let t={outdoorRunning:{type:"outdoor-running"},outdoorCycling:{type:"outdoor-cycling"},drivingNavigation:{type:"driving-navigation"}};return Pe(e,()=>t[n])});U.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.0 to 100)").option("--steps <value>","Steps sensor (integer 0 to 10000)").option("--heartrate <value>","Heart rate sensor (integer 0 to 255)").action(n=>Pe(n,()=>Nm(n)));U.command("list").description("List all emulator instances").action(async()=>{let{manager:n,toolProvider:e}=await he(),t=lm({text:"Listing emulators\u2026",color:"cyan"}).start();await Dm(n,e.hdcPath,t)});U.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await he();try{await la(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof me&&(console.error(ee(r.message)),process.exit(1)),r}n?.length||(console.error(ee("Error: missing required argument 'names'")),process.exit(1)),await Rm(e,t.hdcPath,n)});U.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 he();n?.length||(console.error(ee("Error: missing required argument 'names'")),process.exit(1)),await Om(e,t.hdcPath,n)});var Ea=U.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(qn(!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");Ea.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
1241
- ${Se("Tip: ")}${Xt("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
1242
- ${vt('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
1243
- ${vt('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
1244
- `)}});Ea.action(async(n,e)=>{try{gm(n),ym(e.osVersion);let{manager:t}=await he(),r=await t.listDownloadedImageOsVersions();vm(e.osVersion,r),console.log(vt(`Creating emulator "${n}"...`)),await t.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(en(`Emulator "${n}" created successfully.`))}catch(t){console.error(ee(`${t.message}`)),process.exit(1)}});U.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let{manager:e}=await he();console.log(vt(`Deleting emulator "${n}"...`));try{let t=await e.deleteVirtualDevice(n);console.log(en(`Emulator "${t}" deleted successfully.`))}catch(t){let r=t;console.error(ee(r.message)),r.stdout&&console.error(Xt(r.stdout)),r.stderr&&console.error(Xt(r.stderr)),process.exit(1)}});var Pa=U;import oe from"fs";import ce from"path";import{randomUUID as Bm}from"crypto";import{Command as Um}from"commander";import{execa as Ca}from"execa";import{green as zm,red as qm}from"colorette";function Ui(){return new Date().toISOString().replace(/[:.]/g,"-")}function Gm(n){if(!n?.trim())return ce.resolve(`screenshot-${Ui()}.png`);let e=ce.resolve(n.trim());if(oe.existsSync(e)&&oe.statSync(e).isDirectory())return ce.join(e,`screenshot-${Ui()}.png`);if(ce.extname(e).toLowerCase()!==".png"){if(!oe.existsSync(e))throw new Error(`Screenshot directory does not exist: ${e}`);if(!oe.statSync(e).isDirectory())throw new Error(`Screenshot path is not a directory: ${e}`);return ce.join(e,`screenshot-${Ui()}.png`)}let t=ce.dirname(e);if(!oe.existsSync(t))throw new Error(`Screenshot directory does not exist: ${t}`);if(!oe.statSync(t).isDirectory())throw new Error(`Screenshot parent path is not a directory: ${t}`);return e}function Ia(n){if(!oe.existsSync(n))throw new Error(`Screenshot file was not created: ${n}`);let e=oe.statSync(n);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${n}`);let t=oe.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}`)}async function qi(n,e,t){y(`Executing: ${n} ${e.join(" ")}`);let{stdout:r}=await Ca(n,e,{env:{...process.env},cwd:t});return r}async function Ym(n,e,t){y(`Executing: ${n} ${e.join(" ")}`);let{stdout:r,stderr:i}=await Ca(n,e,{env:{...process.env},cwd:t});return{stdout:r,stderr:i}}async function Vm(n,e,t){try{return await qi(n,e,t)}catch(r){return r.stdout??""}}async function Jm(n,e){let t=q.from(n),r=await t.listDevices();if(r.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");if(e===void 0){if(r.length===1)return r[0].serial;let s=await Km(t,r);throw new Error(`Multiple devices found. Specify a target device using \`--device <name|serial>\`.
1242
+ `;function Tm(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function km(n){let e=n.trim();if(!Da.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${Da.join(", ")}`);return e}function Aa(n,e,t,r){let i=e.trim();if(!/^-?\d+$/.test(i))throw new Error(`${n} must be an integer in [${t}, ${r}].`);let o=Number(i);if(o<t||o>r)throw new Error(`${n} must be in [${t}, ${r}].`);return o}function xa(n,e,t,r,i){let o=e.trim(),s=Number(o);if(!o||Number.isNaN(s))throw new Error(`${n} must be a number in [${t}, ${r}].`);if(i!==void 0&&!Rm(o,i))throw new Error(`${n} supports at most ${i} decimal place(s).`);if(s<t||s>r)throw new Error(`${n} must be in [${t}, ${r}].`);return o}function Rm(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function Mm(n,e,t,r,i){return Number(xa(n,e,t,r,i))}function Om(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 Lm(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 Nm(n,e){let t=i=>i.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(Ie("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(Ie("Run `devecocli emulator image download ...` followed by `devecocli emulator image list` and then copy an `osVersion` string exactly.")),new Error("No downloaded osVersion values parsed; cannot validate --os-version.");if(!e.some(i=>t(i)===r)){console.error(ee("--os-version does not match any downloaded image (exact string required).")),console.log(Ie("Use one of these --os-version values:"));for(let i of e)console.log(` ${i}`);throw new Error(`No downloaded image matches --os-version "${n}".`)}}var _m=["Name","Status","Serial","Device Type","OS Version"];function Hm(n,e,t){return{cells:[n.name,t?"running":"stopped",e??"-",n.deviceType??"-",n.osVersion??"-"],highlight:t}}async function Fm(n,e){let t=await Promise.all(e.map(async r=>{let i=await yt(n,r,Am);return[r,i]}));return new Map(t)}async function jm(n){let e=await Wi(n),t=await Fm(n,e);return{serials:e,params:t}}function $m(n,e,t,r,i){if(e)for(let o of["const.product.name","const.product.model"]){let s=e.get(o);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),i.set(s,n);let c=r.indexOf(n);c!==-1&&r.splice(c,1);return}}function Bm(n,e,t){let r=new Map,i=new Map,o=[...n],s=[...t];for(let a of n){let c=e.get(a),l=c?.get("ohos.qemu.hvd.name");l&&i.set(l,a),t.length>0&&$m(a,c,s,o,r)}for(let a=0;a<s.length&&a<o.length;a++)r.set(s[a],o[a]);return{productSerialMap:r,hvdSerialMap:i}}function Wm(n,e,t){let r=n.map(i=>({emu:i,serial:e.get(i.name)??t.get(i.name),effectiveRunning:i.isRunning===!0||t.has(i.name)}));return r.sort((i,o)=>i.effectiveRunning!==o.effectiveRunning?i.effectiveRunning?-1:1:i.emu.name.localeCompare(o.emu.name)),r.map(i=>Hm(i.emu,i.serial,i.effectiveRunning))}async function Um(n,e,t){try{let[r,i]=await Promise.all([n.listEmulators(),jm(e)]);if(r.length===0){t?.stop(),console.log(Ie(" No emulator instances found."));return}let o=r.filter(l=>l.isRunning).map(l=>l.name),{productSerialMap:s,hvdSerialMap:a}=Bm(i.serials,i.params,o);t?.stop();let c=Wm(r,s,a);console.log(en(_m,c))}catch(r){Qn(t,`Failed to list emulators: ${r.message}`)}}function Ta(n,e,t){let r=!1;for(let i=0;i<n.length;i++){let o=n[i];if(o.status!=="rejected")continue;r=!0;let s=o.reason;console.error(ee(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(rn(s.stdout)),s.stderr&&console.error(rn(s.stderr))}return r}var zm=2e3,qm=6e4;async function Gm(n,e){let t=V(e);return(await Ui(n)).some(i=>V(i)===t)}async function ka(n,e,t,r=qm,i=zm){let o=Date.now()+r;for(;Date.now()<o;){if(await Gm(n,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}async function Vm(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(Ie(`Emulator "${t}" is already running.`));return}console.log(Pt(`Starting emulator "${t}"...`));let i=await ka(e,t,!0);console.log(i?sn(`Emulator "${t}" started successfully.`):Ie(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function Ym(n,e,t){let r=await Promise.allSettled(t.map(o=>Vm(n,e,o)));Ta(r,t,"start")&&process.exit(1)}async function Ra(n,e){let t=e.trim();if(!Xt(t))return t;let r=await G.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 Jm(n,e,t){let r=await Ra(e,t);if(console.log(Pt(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(Ie(`Emulator "${r}" is already stopped.`));return}let o=await ka(e,r,!1);console.log(o?sn(`Emulator "${r}" stopped successfully.`):Ie(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function Km(n,e,t){let r=await Promise.allSettled(t.map(o=>Jm(n,e,o)));Ta(r,t,"stop")&&process.exit(1)}async function we(){try{let n=await N.new();return{manager:St.from(n),toolProvider:n}}catch(n){console.error(ee(`Failed to initialize emulator: ${n.message}`)),process.exit(1);return}}async function xe(n,e){try{let t=Tm(n.target),r=e(),{manager:i,toolProvider:o}=await we(),s=await Ra(o.hdcPath,t);await i.controlEmulator(s,r),console.log(sn(`Emulator "${t}" operation completed.`))}catch(t){let r=n.target?.trim()||"<unknown>";console.error(ee(`Failed to operate emulator "${r}": ${t.message}`)),process.exit(1)}}function Zm(n){let e=[];return tr(e,"longitude",n.longitude,-180,180,8),tr(e,"latitude",n.latitude,-90,90,8),tr(e,"altitude",n.altitude,-1e4,1e4,2),tr(e,"bearing",n.direction,0,360,2),Qi(e,"Specify one geolocation option.")}function Xm(n){let e=[];return tn(e,"light",n.lightIntensity,0,1e5,!1),tn(e,"humidity",n.humidity,0,100,!1),tn(e,"temperature",n.temperature,-273,100,!1),tn(e,"steps",n.steps,0,1e4,!0),tn(e,"heartrate",n.heartrate,0,255,!0),Qi(e,"Specify one sensor option.")}function Qi(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 tr(n,e,t,r,i,o){t!==void 0&&n.push({type:"gps",key:e,value:xa(`--${e}`,t,r,i,o)})}function tn(n,e,t,r,i,o){if(t===void 0)return;let s=o?Aa(`--${e}`,t,r,i):Mm(`--${e}`,t,r,i,1);n.push({type:"sensor",key:e,value:s})}function Qm(n){let e=[];return n.level!==void 0&&e.push({type:"battery",level:Aa("--level",n.level,0,100)}),n.status!==void 0&&e.push({type:"battery-status",status:n.status==="charging"?1:0}),Qi(e,"Specify --level or --status.")}var U=new Xi("emulator").description("Manage emulator instances"),eh=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function nr(n){let e=new on("--device-type <type>","Emulator device type").choices([...eh]);return n?e.makeOptionMandatory():e}function Et(n,e){for(let t of e)if(t in n)return n[t]}function nn(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function Ia(n){let e=nn(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var th=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],nh="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function Ma(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function Oa(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let i=r,o=nn(Et(i,["osVersion","OsVersion","OSVersion","os_version"])),s=nn(Et(i,["deviceType","DeviceType","device_type"])),a=Ia(Et(i,["downloaded","Downloaded","isDownloaded"])),c=nn(Et(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=nn(Et(i,["releaseType","ReleaseType","release_type"])),u=Ia(Et(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,l,u,a],highlight:e&&a==="true"})}return t}function rh(n){let e=n.trim();if(!e)return!0;let t=Ma(e);return t===null?!1:t.length===0?!0:Oa(t,!0).length===0}function ih(n,e){let t=n.trim();if(!t)return"";let r=Ma(t);if(!r)return n.trimEnd();let i=Oa(r,e);return en(th,i)}var rr=new Xi("image").description("HarmonyOS emulator system images (download, list, remove)");rr.command("download").description("Download system image").addOption(nr(!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 we();try{await Ea(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof ve&&(console.error(ee(r.message)),process.exit(1)),r}n.deviceType?.trim()||(console.error(ee("Error: missing required option '--device-type <type>'")),process.exit(1)),n.osVersion?.trim()||(console.error(ee("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(ee(`Failed to download system image: ${r.message}`)),process.exit(1)}});rr.command("remove").description("Remove a downloaded system image").addOption(nr(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let{manager:e}=await we();try{await e.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})}catch(t){console.error(ee(`Failed to remove system image: ${t.message}`)),process.exit(1)}});rr.command("list").description("List system images").addOption(nr(!1)).option("--all","List all images (local and remote)").addOption(new on("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await we();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if(rh(r)){console.log(Ie(nh));return}if(n.format==="json"){console.log(r.trimEnd());return}let i=ih(r,n.all===!0);console.log(i)}catch(t){console.error(ee(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});U.addCommand(rr);var eo=new Xi("license").description("local emulator license");eo.command("view").description("Review agreement text(read-only)").action(async()=>{let{toolProvider:n}=await we(),e=await Pa(n.emulatorPath,n.sdkPath);process.exit(e)});eo.command("accept").description("review and accept agreements").action(async()=>{let{toolProvider:n}=await we(),e=await Ca(n.emulatorPath,n.sdkPath);process.exit(e)});U.addCommand(eo);U.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>xe(n,()=>({type:"shake"})));U.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>xe(n,()=>({type:"power"})));U.command("rotate").description("Rotate emulator").addOption(new on("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Zi("<direction>").choices(["left","right"])).action((n,e)=>xe(e,()=>({type:"rotation",direction:n})));U.command("volume").description("Change volume").addOption(new on("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Zi("<direction>").choices(["up","down"])).action((n,e)=>xe(e,()=>({type:"volume",direction:n})));U.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",xm).action((n,e)=>xe(e,()=>({type:"folded-state",state:km(n)})));U.command("battery").description("Set battery level or charging status").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--level <0-100>","Battery level, SOC (integer 0-100)").addOption(new on("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>xe(n,()=>Qm(n)));U.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 to 360)").action(n=>xe(n,()=>Zm(n)));U.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new Zi("<type>").choices(["outdoorRunning","outdoorCycling","drivingNavigation"])).action((n,e)=>{let t={outdoorRunning:{type:"outdoor-running"},outdoorCycling:{type:"outdoor-cycling"},drivingNavigation:{type:"driving-navigation"}};return xe(e,()=>t[n])});U.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.0 to 100)").option("--steps <value>","Steps sensor (integer 0 to 10000)").option("--heartrate <value>","Heart rate sensor (integer 0 to 255)").action(n=>xe(n,()=>Xm(n)));U.command("list").description("List all emulator instances").action(async()=>{let{manager:n,toolProvider:e}=await we(),t=Im({text:"Listing emulators\u2026",color:"cyan"}).start();await Um(n,e.hdcPath,t)});U.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await we();try{await Sa(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof ve&&(console.error(ee(r.message)),process.exit(1)),r}n?.length||(console.error(ee("Error: missing required argument 'names'")),process.exit(1)),await Ym(e,t.hdcPath,n)});U.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 we();n?.length||(console.error(ee("Error: missing required argument 'names'")),process.exit(1)),await Km(e,t.hdcPath,n)});var La=U.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(nr(!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");La.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
1243
+ ${Ie("Tip: ")}${rn("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
1244
+ ${Pt('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
1245
+ ${Pt('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
1246
+ `)}});La.action(async(n,e)=>{try{Om(n),Lm(e.osVersion);let{manager:t}=await we(),r=await t.listDownloadedImageOsVersions();Nm(e.osVersion,r),console.log(Pt(`Creating emulator "${n}"...`)),await t.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(sn(`Emulator "${n}" created successfully.`))}catch(t){console.error(ee(`${t.message}`)),process.exit(1)}});U.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let{manager:e}=await we();console.log(Pt(`Deleting emulator "${n}"...`));try{let t=await e.deleteVirtualDevice(n);console.log(sn(`Emulator "${t}" deleted successfully.`))}catch(t){let r=t;console.error(ee(r.message)),r.stdout&&console.error(rn(r.stdout)),r.stderr&&console.error(rn(r.stderr)),process.exit(1)}});var Na=U;import se from"fs";import le from"path";import{randomUUID as oh}from"crypto";import{Command as sh}from"commander";import{execa as _a}from"execa";import{green as ah,red as ch}from"colorette";function to(){return new Date().toISOString().replace(/[:.]/g,"-")}function lh(n){if(!n?.trim())return le.resolve(`screenshot-${to()}.png`);let e=le.resolve(n.trim());if(se.existsSync(e)&&se.statSync(e).isDirectory())return le.join(e,`screenshot-${to()}.png`);if(le.extname(e).toLowerCase()!==".png"){if(!se.existsSync(e))throw new Error(`Screenshot directory does not exist: ${e}`);if(!se.statSync(e).isDirectory())throw new Error(`Screenshot path is not a directory: ${e}`);return le.join(e,`screenshot-${to()}.png`)}let t=le.dirname(e);if(!se.existsSync(t))throw new Error(`Screenshot directory does not exist: ${t}`);if(!se.statSync(t).isDirectory())throw new Error(`Screenshot parent path is not a directory: ${t}`);return e}function Ha(n){if(!se.existsSync(n))throw new Error(`Screenshot file was not created: ${n}`);let e=se.statSync(n);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${n}`);let t=se.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}`)}async function ro(n,e,t){g(`Executing: ${n} ${e.join(" ")}`);let{stdout:r}=await _a(n,e,{env:{...process.env},cwd:t});return r}async function dh(n,e,t){g(`Executing: ${n} ${e.join(" ")}`);let{stdout:r,stderr:i}=await _a(n,e,{env:{...process.env},cwd:t});return{stdout:r,stderr:i}}async function uh(n,e,t){try{return await ro(n,e,t)}catch(r){return r.stdout??""}}async function ph(n,e){let t=G.from(n),r=await t.listDevices();if(r.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");if(e===void 0){if(r.length===1)return r[0].serial;let s=await mh(t,r);throw new Error(`Multiple devices found. Specify a target device using \`--device <name|serial>\`.
1245
1247
  Available devices:
1246
- ${s}`)}let i=e.trim();if(!i)throw new Error("--device must not be empty.");let o=await t.getDeviceInfo(r,i);if(!o)throw new Error(`Device "${i}" not found.`);return o.serial}async function Km(n,e){return(await Promise.all(e.map(async r=>` - ${await n.getDeviceName(r.serial)} (${r.serial})`))).join(`
1247
- `)}function Zm(n,e){let t=["-t",n.serial,"shell","snapshot_display"];return n.display?.trim()&&t.push("-i",Xm(n.display)),t.push("-f",n.remotePath),e&&t.push("-t",e),t}function Xm(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}function Qm(n,e){oe.copyFileSync(n,e),Ia(e)}function eh(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 th(n){let e=await Vm(n.hdcPath,["-t",n.serial,"shell","ls","-l",n.remotePath]);return eh(e)}function nh(n){return[n.stdout,n.stderr].filter(Boolean).join(`
1248
- `).trim()}async function rh(n,e){let t;try{t=await Ym(n.hdcPath,Zm(n,e))}catch(i){t={stdout:i.stdout??"",stderr:i.stderr??i.message}}let r=await th(n);return{created:r!==void 0&&r>0,output:nh(t)}}async function ih(n){let e=[];for(let t of[void 0,"png"]){let r=await rh(n,t);if(r.created)return;r.output&&e.push(r.output)}throw new Error(e.length>0?`Screenshot was not created on device: ${n.remotePath}. snapshot_display output: ${e.join(`
1249
- `)}`:`Screenshot was not created on device: ${n.remotePath}.`)}function Da(n){try{return Ia(n),!0}catch{return!1}}function Aa(n){let e=[];for(let t of oe.readdirSync(n,{withFileTypes:!0})){let r=ce.join(n,t.name);if(t.isDirectory()){e.push(...Aa(r));continue}t.isFile()&&Da(r)&&e.push(r)}return e}function oh(n,e){let t=ce.join(n,ce.basename(e));if(Da(t))return t;let r=Aa(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}async function zi(n,e,t,r){try{await qi(n.hdcPath,["-t",n.serial,"file","recv",n.remotePath,t],r)}catch(i){y(`hdc file recv failed: ${i.message}`)}return oh(e,n.remotePath)}async function sh(n){let e=oe.mkdtempSync(ce.join(ce.dirname(n.localPath),".devecocli-screenshot-"));try{let t=await zi(n,e,".",e)??await zi(n,e,e)??await zi(n,e,ce.join(e,"screenshot.png"));if(!t)throw new Error(`Screenshot file was not created in ${e}.`);Qm(t,n.localPath)}finally{oe.rmSync(e,{recursive:!0,force:!0})}}async function ah(n){await qi(n.hdcPath,["-t",n.serial,"shell","rm","-f",n.remotePath]).catch(()=>{})}async function ch(n){try{await ih(n),await sh(n)}finally{await ah(n)}}async function lh(n){try{let e=await L.new(),t=await Jm(e,n.device),r=Gm(n.path),i=`/data/local/tmp/devecocli-${Bm()}.png`;await ch({hdcPath:e.hdcPath,serial:t,localPath:r,remotePath:i,display:n.display}),console.log(zm(`Screenshot saved to ${r}`))}catch(e){console.error(qm(`Failed to capture screenshot: ${e.message}`)),process.exit(1)}}var Ta=new Um("ui").description("Inspect and interact with UI on a connected device");Ta.command("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").option("--path <path>","Existing directory or PNG file path whose parent exists").action(lh);var xa=Ta;import{Command as Ih}from"commander";import{green as Dh,red as sn,cyan as tc,yellow as nc,dim as rc}from"colorette";import Ah from"p-limit";import dh from"ora";var et=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=dh(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 Oa from"fs";import*as La from"path";import{homedir as ph}from"os";import uh from"axios";var Gi={HTTP_TIMEOUT_MS:2e4},Yn={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 Yi="https://matrix.openharmony.cn",fe={TAGS_API_URL:`${Yi}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${Yi}/api/registry/skill/skills`,SKILL_API_BASE:`${Yi}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},ge={"trae-cn":{path:".trae-cn/skills",displayName:"trae-cn"},opencode:{path:".config/opencode/skills",displayName:"opencode"},cursor:{path:".cursor/skills",displayName:"cursor"},codebuddy:{path:".codebuddy/skills",displayName:"codebuddy"},qoder:{path:".qoder/skills",displayName:"qoder"},"claude-code":{path:".claude/skills",projectPath:".claude/skills",displayName:"claude-code"},codex:{path:".codex/skills",displayName:"codex"}};import{homedir as Ce}from"os";import se from"path";var Ee="deveco-mcp";var Ne={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:se.join(Ce(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:se.join(process.platform==="win32"?se.join(process.env.APPDATA??se.join(Ce(),"AppData","Roaming"),"Trae CN","User"):se.join(Ce(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:se.join(Ce(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:se.join(Ce(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:se.join(process.platform==="win32"?se.join(process.env.APPDATA??se.join(Ce(),"AppData","Roaming"),"Qoder","SharedClientCache"):se.join(Ce(),"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:se.join(Ce(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:se.join(Ce(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function Ra(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function ka(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Ma(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function Vn(n,e){return n.format==="opencode"?Ra(e):n.format==="claude-code"||n.format==="codex"?ka(e):Ma(e)}var Vi=class{client;constructor(){let e={timeout:Gi.HTTP_TIMEOUT_MS,headers:{"User-Agent":Yn.USER_AGENT,"accept-language":Yn.ACCEPT_LANGUAGE},transformResponse:[t=>t],proxy:!1};this.client=uh.create(e),this.client.interceptors.response.use(t=>t,t=>{let r=`Network connection failed (${t.code}). Please check your proxy configuration or network settings`;throw new Error(`${t.message}
1250
- ${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,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)}},_e=new Vi;var Na=["DevEco"];async function Jn(){let n=await _e.get(fe.TAGS_API_URL),t=Kn(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 mh(n){let e=[],t=fe.DEFAULT_PAGE_SIZE,r=1;for(;;){let i=await _e.post(fe.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:r,pageSize:t,tagIds:[n]}}),o=Kn(i,"Skills API");if(e.push(...o.data.list),o.data.list.length<t)break;r++}return e}async function Ji(n){let e=new Map,t=n.map(i=>mh(i)),r=await Promise.all(t);for(let i of r)for(let o of i)e.has(o.id)||e.set(o.id,o);return Array.from(e.values()).filter(i=>i.tags?.every(o=>!Na.includes(o.name)))}async function hh(n,e){let t=await _e.post(fe.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:fe.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return Kn(t,"Skills API").data.list}async function Ki(n,e){let t=new Map,r=e.map(o=>hh(n,o)),i=await Promise.all(r);for(let o of i)for(let s of o)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(o=>o.tags?.every(s=>!Na.includes(s.name)))}function _a(n){let e=[];for(let[,t]of Object.entries(ge)){let r=La.join(ph(),t.path,n);Oa.existsSync(r)&&e.push(t.displayName)}return e.sort()}function Kn(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=_e.parseJson(n);if(t.code!==fe.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Ha(n){let e=`${fe.SKILL_API_BASE}/${n}/checksum`,t=await _e.get(e);return Kn(t,"Checksum API").data}import fh from"adm-zip";import gh from"crypto";import ja from"fs";import H from"path";import{fileURLToPath as yh}from"url";import{homedir as $a}from"os";import{red as vh}from"colorette";var Ie=ja.promises;function Zi(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function Fa(n,e){let t=H.resolve(e),r=H.resolve(n),i=H.relative(r,t);if(i.startsWith("..")||H.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function Xi(n){return H.isAbsolute(n)?n:H.resolve(process.cwd(),n)}function wh(n){return gh.createHash("sha256").update(n).digest("hex")}async function bh(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=wh(n),i=e.sha256.toLowerCase();if(r!==i)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function Wa(n){let e=`${fe.SKILL_API_BASE}/${n}/install?format=zip`,t=await _e.getBinary(e),r=await Ha(n);return await bh(t,r),t}async function Sh(n,e,t){Zi(t);let r=new fh(n),i=r.getEntries();try{await Ie.stat(e)}catch{await Ie.mkdir(e,{recursive:!0})}let o=H.join(e,t);Fa(e,o);for(let s of i){let a=H.join(o,s.entryName);Fa(o,a)}r.extractAllTo(o,!0)}async function Qi(n){let e=ge[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(ge).join(", ")}`);let t=H.join($a(),e.path.replace("/skills",""));try{return await Ie.access(t),!0}catch{return!1}}function eo(n){let e=ge[n];return H.join($a(),e.path)}function Eh(n){let e=ge[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(ge).join(", ")}`);return e}function to(n,e){let t=Eh(e),r="projectPath"in t?t.projectPath:H.join("."+e,"skills");return H.join(n,r)}async function Ph(n,e,t){Zi(e);let r=H.join(n,e);try{if(await Ie.access(r),t)await Ie.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 no(n,e,t){await Sh(n,e,t),console.log(`Skill ${t} installed to ${H.join(e,t)}.`)}async function ro(n,e,t){let r=H.join(e,t);await Ie.mkdir(r,{recursive:!0});let i=H.join(r,H.basename(n));await Ie.copyFile(n,i),console.log(`Skill ${t} installed to ${r}.`)}function Ba(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(vh(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function wt(n,e,t,r){try{let i=await e(),{shouldSkip:o}=await Ph(i,n,r);return o?{success:!0,skipped:!0}:(await t(i),{success:!0})}catch(i){return Ba(n,i,"Installation failed")}}async function io(n,e){try{Zi(n);let t=await e(),r=H.join(t,n);try{await Ie.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await Ie.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return Ba(n,t,"Removal failed")}}async function Ua(n,e,t,r=!1){return wt(n,()=>eo(e),i=>no(t,i,n),r)}async function za(n,e,t,r=!1){return wt(n,()=>t,i=>no(e,i,n),r)}async function qa(n,e,t,r,i=!1){return wt(n,()=>to(t,r),o=>no(e,o,n),i)}async function Ga(n,e,t,r=!1){return wt(n,()=>eo(t),i=>ro(e,i,n),r)}async function Ya(n,e,t,r,i=!1){return wt(n,()=>to(t,r),o=>ro(e,o,n),i)}async function Va(n,e,t,r=!1){return wt(n,()=>t,i=>ro(e,i,n),r)}async function Ja(n,e){return io(n,()=>eo(e))}async function Ka(n,e){return io(n,()=>e)}async function Za(n,e,t){return io(n,()=>to(e,t))}function Xa(){let e=H.dirname(yh(import.meta.url));for(;;){let t=H.join(e,"SKILL.md");if(ja.existsSync(t))return t;let r=H.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import Qa from"fs";import{cyan as Ch}from"colorette";async function tn(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await Qi(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function nn(){let n=[];for(let e of Object.keys(ge))await Qi(e)&&n.push(e);return n}function rn(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(Ch("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function He(n,e,t){if(!Qa.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!Qa.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function on(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?Xi(n):void 0,resolvedProject:e?Xi(e):void 0}}async function Zn(n,e,t){let r=[],i=[],o;if(e?o=e:t&&n.agent?i=(await tn(n.agent)).map(a=>({project:t,agent:a})):t?i=(await nn()).map(a=>({project:t,agent:a})):n.agent?r=await tn(n.agent):r=await nn(),!o&&r.length===0&&i.length===0)throw new Error("No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location.");return{agents:r,projectAgents:i,customPath:o}}async function Th(n){let e=await Jn();if(n.all)return(await Ji(e)).map(r=>r.enName);{let r=(await Ki(n.skill,e)).find(i=>i.enName===n.skill);if(!r)throw new Error(`Skill "${n.skill}" not found`);return[r.enName]}}async function xh(n,e,t,r){let i=[];if(t.customPath){let o=await za(n,e,t.customPath,r);return i.push(o),i}for(let o of t.agents){let s=await Ua(n,o,e,r);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await qa(n,e,o,s,r);i.push(a)}return i}function kh(n){if(n.all&&n.skill)throw new Error("`--all` and `--skill` cannot be specified together.");if(!n.all&&!n.skill)throw new Error("Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=on(n.path,n.project,n.agent);return t&&He(t,"Project directory",n.force),e&&He(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}async function Rh(n,e,t){let r=await Zn(n,e,t);return{skillNames:await Th(n),targets:r}}async function Mh(n,e,t,r){let i=[],o=n.length,s=Ah(5),a=n.map(async c=>s(async()=>{try{let l=await Wa(c);return{name:c,buffer:l,success:!0}}catch(l){let u=l instanceof Error?l.message:"unknown error";return{name:c,error:u,success:!1}}}));for(let c=0;c<n.length;c++){let l=n[c],u=o>1?` (${c+1}/${o})`:"";r.start(`Installing ${l}${u}...`);let f=await a[c];if(!f.success){r.fail(),console.log(sn(`${l}: Download failed - ${f.error}`)),i.push({success:!1});continue}r.stop();let E=await xh(l,f.buffer,e,t);i.push(...E)}return i}async function Oh(n){let e=new et;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=kh(n),{skillNames:i,targets:o}=await Rh(n,t,r),s=await Mh(i,o,n.force||!1,e);e.stop(),rn(s)}catch(t){throw e.stop(),t}}function Lh(n){let{resolvedPath:e,resolvedProject:t}=on(n.path,n.project,n.agent);return t&&He(t,"Project directory"),e&&He(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function Nh(n,e){let t=new et;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:i}=Lh(e);t.stop();let o=await _h(e,n,r,i);t.stop(),rn(o)}catch(r){throw t.stop(),r}}function ec(n,e=""){if(n.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function Xn(n,e){let t=[];for(let r of e){let i=r.type==="agent"?await Ja(n,r.agent):await Za(n,r.project,r.agent);t.push(i)}return t}async function _h(n,e,t,r){if(t)return[await Ka(e,t)];if(r&&n.agent){let a=(await tn(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return Xn(e,a)}if(r){let s=await nn();ec(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return Xn(e,a)}if(n.agent){let a=(await tn(n.agent)).map(c=>({type:"agent",agent:c}));return Xn(e,a)}let i=await nn();ec(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return Xn(e,o)}var an=new Ih("skills").description("Manage HarmonyOS skills");an.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async n=>{let e=new et;try{e.start("Fetching skills...");let t=await Jn(),r=await Ji(t);if(r.length===0){e.stop(),console.log(nc("No skills available."));return}e.succeed(`Fetched ${r.length} skills`);for(let i of r)if(n.long){console.log(tc(i.enName)),console.log(rc(i.description));let o=_a(i.enName);o.length>0&&console.log(Dh(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName)}catch(t){e.stop(),console.error(sn(t.message)),process.exit(1)}});an.command("find <keyword>").description("Search skills by keyword").action(async n=>{let e=new et;try{e.start("Searching skills...");let t=await Jn(),r=await Ki(n,t);if(r.length===0){console.log(nc(`No skills found matching '${n}'.`)),e.stop();return}e.succeed(`Found ${r.length} skills.`);for(let i of r)console.log(tc(i.enName)),console.log(rc(i.description)),console.log()}catch(t){e.stop(),console.error(sn(t.message)),process.exit(1)}});an.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 Oh(n)}catch(e){console.error(sn(e.message)),process.exit(1)}});an.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 Nh(n.skill,n)}catch(e){console.error(sn(e.message)),process.exit(1)}});var ic=an;import{Command as Fh,InvalidArgumentError as sc}from"commander";import{cyan as Qn}from"colorette";function tt(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=ut(t);return r==="transient"?new Error(`${e}: Device communication channel unavailabel. Retry in a few seconds.`):r==="fatal"?new Error(`${e}: ${t.trim()}`):null}var oo=[800,1500,2500];function Hh(n){return new Promise(e=>setTimeout(e,n))}var er=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=q.from(e)}createFollowLineHandler(e){return(t,r)=>{let i=e.keyword?t.filter(o=>o.includes(e.keyword)):t;if(r!=="stderr")for(let o of i)console.log(o)}}findDeviceByArg(e,t){return e.find(r=>r.serial===t||r.name===t)}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
1251
- `)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let i=t[0];return y(Qn(`Using device serial: ${i}`)),i}if(e&&t.includes(e))return y(Qn(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let i=this.findDeviceByArg(r,e);if(i)return y(Qn(`Using device: ${i.name} (${i.serial})`)),i.serial;let o=this.formatConnectedDeviceList(r);throw new Error(`Device '${e}' not found.
1248
+ ${s}`)}let i=e.trim();if(!i)throw new Error("--device must not be empty.");let o=await t.getDeviceInfo(r,i);if(!o)throw new Error(`Device "${i}" not found.`);return o.serial}async function mh(n,e){return(await Promise.all(e.map(async r=>` - ${await n.getDeviceName(r.serial)} (${r.serial})`))).join(`
1249
+ `)}function hh(n,e){let t=["-t",n.serial,"shell","snapshot_display"];return n.display?.trim()&&t.push("-i",fh(n.display)),t.push("-f",n.remotePath),e&&t.push("-t",e),t}function fh(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}function gh(n,e){se.copyFileSync(n,e),Ha(e)}function yh(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 vh(n){let e=await uh(n.hdcPath,["-t",n.serial,"shell","ls","-l",n.remotePath]);return yh(e)}function wh(n){return[n.stdout,n.stderr].filter(Boolean).join(`
1250
+ `).trim()}async function bh(n,e){let t;try{t=await dh(n.hdcPath,hh(n,e))}catch(i){t={stdout:i.stdout??"",stderr:i.stderr??i.message}}let r=await vh(n);return{created:r!==void 0&&r>0,output:wh(t)}}async function Sh(n){let e=[];for(let t of[void 0,"png"]){let r=await bh(n,t);if(r.created)return;r.output&&e.push(r.output)}throw new Error(e.length>0?`Screenshot was not created on device: ${n.remotePath}. snapshot_display output: ${e.join(`
1251
+ `)}`:`Screenshot was not created on device: ${n.remotePath}.`)}function Fa(n){try{return Ha(n),!0}catch{return!1}}function ja(n){let e=[];for(let t of se.readdirSync(n,{withFileTypes:!0})){let r=le.join(n,t.name);if(t.isDirectory()){e.push(...ja(r));continue}t.isFile()&&Fa(r)&&e.push(r)}return e}function Eh(n,e){let t=le.join(n,le.basename(e));if(Fa(t))return t;let r=ja(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}async function no(n,e,t,r){try{await ro(n.hdcPath,["-t",n.serial,"file","recv",n.remotePath,t],r)}catch(i){g(`hdc file recv failed: ${i.message}`)}return Eh(e,n.remotePath)}async function Ph(n){let e=se.mkdtempSync(le.join(le.dirname(n.localPath),".devecocli-screenshot-"));try{let t=await no(n,e,".",e)??await no(n,e,e)??await no(n,e,le.join(e,"screenshot.png"));if(!t)throw new Error(`Screenshot file was not created in ${e}.`);gh(t,n.localPath)}finally{se.rmSync(e,{recursive:!0,force:!0})}}async function Ch(n){await ro(n.hdcPath,["-t",n.serial,"shell","rm","-f",n.remotePath]).catch(()=>{})}async function Dh(n){try{await Sh(n),await Ph(n)}finally{await Ch(n)}}async function Ih(n){try{let e=await N.new(),t=await ph(e,n.device),r=lh(n.path),i=`/data/local/tmp/devecocli-${oh()}.png`;await Dh({hdcPath:e.hdcPath,serial:t,localPath:r,remotePath:i,display:n.display}),console.log(ah(`Screenshot saved to ${r}`))}catch(e){console.error(ch(`Failed to capture screenshot: ${e.message}`)),process.exit(1)}}var $a=new sh("ui").description("Inspect and interact with UI on a connected device");$a.command("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").option("--path <path>","Existing directory or PNG file path whose parent exists").action(Ih);var Ba=$a;import{Command as Wh}from"commander";import{green as Uh,red as un,cyan as dc,yellow as uc,dim as pc}from"colorette";import zh from"p-limit";import Ah from"ora";var ot=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=Ah(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 Wa from"fs";import*as Ua from"path";import{homedir as Th}from"os";import xh from"axios";var io=class{client;constructor(){let e={timeout:Li.HTTP_TIMEOUT_MS,headers:{"User-Agent":qn.USER_AGENT,"accept-language":qn.ACCEPT_LANGUAGE},transformResponse:[t=>t],proxy:!1};this.client=xh.create(e),this.client.interceptors.response.use(t=>t,t=>{let r=`Network connection failed (${t.code}). Please check your proxy configuration or network settings`;throw new Error(`${t.message}
1252
+ ${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,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)}},$e=new io;var za=["DevEco"];async function ir(){let n=await $e.get(fe.TAGS_API_URL),t=or(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 kh(n){let e=[],t=fe.DEFAULT_PAGE_SIZE,r=1;for(;;){let i=await $e.post(fe.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:r,pageSize:t,tagIds:[n]}}),o=or(i,"Skills API");if(e.push(...o.data.list),o.data.list.length<t)break;r++}return e}async function oo(n){let e=new Map,t=n.map(i=>kh(i)),r=await Promise.all(t);for(let i of r)for(let o of i)e.has(o.id)||e.set(o.id,o);return Array.from(e.values()).filter(i=>i.tags?.every(o=>!za.includes(o.name)))}async function Rh(n,e){let t=await $e.post(fe.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:fe.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return or(t,"Skills API").data.list}async function so(n,e){let t=new Map,r=e.map(o=>Rh(n,o)),i=await Promise.all(r);for(let o of i)for(let s of o)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(o=>o.tags?.every(s=>!za.includes(s.name)))}function qa(n){let e=[];for(let[,t]of Object.entries(ge)){let r=Ua.join(Th(),t.path,n);Wa.existsSync(r)&&e.push(t.displayName)}return e.sort()}function or(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=$e.parseJson(n);if(t.code!==fe.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Ga(n){let e=`${fe.SKILL_API_BASE}/${n}/checksum`,t=await $e.get(e);return or(t,"Checksum API").data}import Mh from"adm-zip";import Oh from"crypto";import Ya from"fs";import F from"path";import{fileURLToPath as Lh}from"url";import{homedir as Ja}from"os";import{red as Nh}from"colorette";var Te=Ya.promises;function ao(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function Va(n,e){let t=F.resolve(e),r=F.resolve(n),i=F.relative(r,t);if(i.startsWith("..")||F.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function co(n){return F.isAbsolute(n)?n:F.resolve(process.cwd(),n)}function _h(n){return Oh.createHash("sha256").update(n).digest("hex")}async function Hh(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=_h(n),i=e.sha256.toLowerCase();if(r!==i)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function Ka(n){let e=`${fe.SKILL_API_BASE}/${n}/install?format=zip`,t=await $e.getBinary(e),r=await Ga(n);return await Hh(t,r),t}async function Fh(n,e,t){ao(t);let r=new Mh(n),i=r.getEntries();try{await Te.stat(e)}catch{await Te.mkdir(e,{recursive:!0})}let o=F.join(e,t);Va(e,o);for(let s of i){let a=F.join(o,s.entryName);Va(o,a)}r.extractAllTo(o,!0)}async function lo(n){let e=ge[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(ge).join(", ")}`);let t=F.join(Ja(),e.path.replace("/skills",""));try{return await Te.access(t),!0}catch{return!1}}function uo(n){let e=ge[n];return F.join(Ja(),e.path)}function jh(n){let e=ge[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(ge).join(", ")}`);return e}function po(n,e){let t=jh(e),r="projectPath"in t?t.projectPath:F.join("."+e,"skills");return F.join(n,r)}async function $h(n,e,t){ao(e);let r=F.join(n,e);try{if(await Te.access(r),t)await Te.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 mo(n,e,t){await Fh(n,e,t),console.log(`Skill ${t} installed to ${F.join(e,t)}.`)}async function ho(n,e,t){let r=F.join(e,t);await Te.mkdir(r,{recursive:!0});let i=F.join(r,F.basename(n));await Te.copyFile(n,i),console.log(`Skill ${t} installed to ${r}.`)}function Za(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(Nh(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function Ct(n,e,t,r){try{let i=await e(),{shouldSkip:o}=await $h(i,n,r);return o?{success:!0,skipped:!0}:(await t(i),{success:!0})}catch(i){return Za(n,i,"Installation failed")}}async function fo(n,e){try{ao(n);let t=await e(),r=F.join(t,n);try{await Te.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await Te.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return Za(n,t,"Removal failed")}}async function Xa(n,e,t,r=!1){return Ct(n,()=>uo(e),i=>mo(t,i,n),r)}async function Qa(n,e,t,r=!1){return Ct(n,()=>t,i=>mo(e,i,n),r)}async function ec(n,e,t,r,i=!1){return Ct(n,()=>po(t,r),o=>mo(e,o,n),i)}async function tc(n,e,t,r=!1){return Ct(n,()=>uo(t),i=>ho(e,i,n),r)}async function nc(n,e,t,r,i=!1){return Ct(n,()=>po(t,r),o=>ho(e,o,n),i)}async function rc(n,e,t,r=!1){return Ct(n,()=>t,i=>ho(e,i,n),r)}async function ic(n,e){return fo(n,()=>uo(e))}async function oc(n,e){return fo(n,()=>e)}async function sc(n,e,t){return fo(n,()=>po(e,t))}function ac(){let e=F.dirname(Lh(import.meta.url));for(;;){let t=F.join(e,"SKILL.md");if(Ya.existsSync(t))return t;let r=F.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import cc from"fs";import{cyan as Bh}from"colorette";async function an(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await lo(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function cn(){let n=[];for(let e of Object.keys(ge))await lo(e)&&n.push(e);return n}function ln(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(Bh("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function Be(n,e,t){if(!cc.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!cc.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function dn(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?co(n):void 0,resolvedProject:e?co(e):void 0}}async function sr(n,e,t){let r=[],i=[],o;if(e?o=e:t&&n.agent?i=(await an(n.agent)).map(a=>({project:t,agent:a})):t?i=(await cn()).map(a=>({project:t,agent:a})):n.agent?r=await an(n.agent):r=await cn(),!o&&r.length===0&&i.length===0)throw new Error("No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location.");return{agents:r,projectAgents:i,customPath:o}}async function qh(n){let e=await ir();if(n.all)return(await oo(e)).map(r=>r.enName);{let r=(await so(n.skill,e)).find(i=>i.enName===n.skill);if(!r)throw new Error(`Skill "${n.skill}" not found`);return[r.enName]}}async function Gh(n,e,t,r){let i=[];if(t.customPath){let o=await Qa(n,e,t.customPath,r);return i.push(o),i}for(let o of t.agents){let s=await Xa(n,o,e,r);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await ec(n,e,o,s,r);i.push(a)}return i}function Vh(n){if(n.all&&n.skill)throw new Error("`--all` and `--skill` cannot be specified together.");if(!n.all&&!n.skill)throw new Error("Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=dn(n.path,n.project,n.agent);return t&&Be(t,"Project directory",n.force),e&&Be(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}async function Yh(n,e,t){let r=await sr(n,e,t);return{skillNames:await qh(n),targets:r}}async function Jh(n,e,t,r){let i=[],o=n.length,s=zh(5),a=n.map(async c=>s(async()=>{try{let l=await Ka(c);return{name:c,buffer:l,success:!0}}catch(l){let u=l instanceof Error?l.message:"unknown error";return{name:c,error:u,success:!1}}}));for(let c=0;c<n.length;c++){let l=n[c],u=o>1?` (${c+1}/${o})`:"";r.start(`Installing ${l}${u}...`);let f=await a[c];if(!f.success){r.fail(),console.log(un(`${l}: Download failed - ${f.error}`)),i.push({success:!1});continue}r.stop();let P=await Gh(l,f.buffer,e,t);i.push(...P)}return i}async function Kh(n){let e=new ot;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=Vh(n),{skillNames:i,targets:o}=await Yh(n,t,r),s=await Jh(i,o,n.force||!1,e);e.stop(),ln(s)}catch(t){throw e.stop(),t}}function Zh(n){let{resolvedPath:e,resolvedProject:t}=dn(n.path,n.project,n.agent);return t&&Be(t,"Project directory"),e&&Be(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function Xh(n,e){let t=new ot;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:i}=Zh(e);t.stop();let o=await Qh(e,n,r,i);t.stop(),ln(o)}catch(r){throw t.stop(),r}}function lc(n,e=""){if(n.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function ar(n,e){let t=[];for(let r of e){let i=r.type==="agent"?await ic(n,r.agent):await sc(n,r.project,r.agent);t.push(i)}return t}async function Qh(n,e,t,r){if(t)return[await oc(e,t)];if(r&&n.agent){let a=(await an(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return ar(e,a)}if(r){let s=await cn();lc(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return ar(e,a)}if(n.agent){let a=(await an(n.agent)).map(c=>({type:"agent",agent:c}));return ar(e,a)}let i=await cn();lc(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return ar(e,o)}var pn=new Wh("skills").description("Manage HarmonyOS skills");pn.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async n=>{let e=new ot;try{e.start("Fetching skills...");let t=await ir(),r=await oo(t);if(r.length===0){e.stop(),console.log(uc("No skills available."));return}e.succeed(`Fetched ${r.length} skills`);for(let i of r)if(n.long){console.log(dc(i.enName)),console.log(pc(i.description));let o=qa(i.enName);o.length>0&&console.log(Uh(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName)}catch(t){e.stop(),console.error(un(t.message)),process.exit(1)}});pn.command("find <keyword>").description("Search skills by keyword").action(async n=>{let e=new ot;try{e.start("Searching skills...");let t=await ir(),r=await so(n,t);if(r.length===0){console.log(uc(`No skills found matching '${n}'.`)),e.stop();return}e.succeed(`Found ${r.length} skills.`);for(let i of r)console.log(dc(i.enName)),console.log(pc(i.description)),console.log()}catch(t){e.stop(),console.error(un(t.message)),process.exit(1)}});pn.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 Kh(n)}catch(e){console.error(un(e.message)),process.exit(1)}});pn.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 Xh(n.skill,n)}catch(e){console.error(un(e.message)),process.exit(1)}});var mc=pn;import{Command as tf,InvalidArgumentError as fc}from"commander";import{cyan as cr}from"colorette";function st(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=gt(t);return r==="transient"?new Error(`${e}: Device communication channel unavailabel. Retry in a few seconds.`):r==="fatal"?new Error(`${e}: ${t.trim()}`):null}var go=[800,1500,2500];function ef(n){return new Promise(e=>setTimeout(e,n))}var lr=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=G.from(e)}createFollowLineHandler(e){return(t,r)=>{let i=e.keyword?t.filter(o=>o.includes(e.keyword)):t;if(r!=="stderr")for(let o of i)console.log(o)}}findDeviceByArg(e,t){return e.find(r=>r.serial===t||r.name===t)}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
1253
+ `)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let i=t[0];return g(cr(`Using device serial: ${i}`)),i}if(e&&t.includes(e))return g(cr(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let i=this.findDeviceByArg(r,e);if(i)return g(cr(`Using device: ${i.name} (${i.serial})`)),i.serial;let o=this.formatConnectedDeviceList(r);throw new Error(`Device '${e}' not found.
1252
1254
  Available devices:
1253
- ${o}`)}if(r.length===1){let i=r[0];return y(Qn(`Using device: ${i.name} (${i.serial})`)),i.serial}throw new Error("Multiple devices found. Specify a target device using `--device <name>` or `--device <serial>`.\nAvailable devices:\n"+this.formatConnectedDeviceList(r))}async getConnectedDeviceSerials(){let e=await this.deviceManager.listDevices();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e}async getPidForBundle(e,t,r){y(`Retrieving PID for bundle ${r}`),b.assertBundleName(r);let i=await Oe(e,["-t",t,"shell","pidof",r]),o=tt(i,"Failed to look up PID");if(o)throw o;if(i.exitCode===0&&i.stdout.trim()){let s=i.stdout.trim(),a=s.split(/\s+/)[0]||s;return y(`Found PID for ${r}: ${a}`),a}return y(`No PID found for bundle: ${r}`),null}async resizeHilogBuffer(e,t,r){y(`Setting hilog buffer size to: ${r}`);let i=await Oe(e,["-t",t,"shell","hilog","-G",r]),o=tt(i,"Failed to resize hilog buffer");if(o)throw o;i.exitCode!==0&&console.error(`Failed to resize hilog buffer: ${i.stderr||i.stdout}`)}buildHilogCommand(e,t,r,i){let o=this.buildHilogShellCommand(r,i);return[e,["-t",t,"shell",o]]}buildHilogShellCommand(e,t){let r=["hilog"];return e.isFollow||r.push("-x"),e.tag&&(b.assertHilogToken(e.tag,"tag"),r.push("-T",e.tag)),e.level&&(b.assertHilogLevel(e.level),r.push("-L",e.level)),e.domain&&(b.assertHilogToken(e.domain,"domain"),r.push("-D",e.domain)),t&&r.push("-P",t),e.keyword&&(b.assertHilogKeyword(e.keyword),r.push("-e",b.quotePosixShellArg(e.keyword))),r.join(" ")}async followHilog(e,t,r,i,o){let a=await Os(e,t,{onData:r,onError:i,onClose:o});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}async runHilogWithSpawnRetry(e,t,r,i,o){let s=1+oo.length,a={stdout:"",stderr:"",exitCode:-1};for(let c=0;c<s;c++){a=await this.followHilog(e,t,r,i,o);let l=a.exitCode===0?a.stdout:a.stderr||a.stdout;if(ut(l)!=="transient"||c>=s-1)return a;y(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${oo[c]}ms`),await Hh(oo[c])}return a}async printTailSnapshotIfNeeded(e,t,r,i){if(!r.tail&&!r.fromSeconds&&!r.toSeconds)return;let o={...r,isFollow:!1},[,s]=this.buildHilogCommand(e,t,o,i),a=await Oe(e,s),c=tt(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=b.filterLogsByRelativeWindow(a.stdout||a.stderr,r.fromSeconds,r.toSeconds);l=b.getLastLines(l,r.tail),l.trim()&&console.log(l)}async getHilogOnce(e,t,r,i){let[o,s]=this.buildHilogCommand(e,t,r,i);y(`Ready to run hilog command: ${o} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(o,s,()=>{},f=>{y(`Callback triggered when an error occurs during a single hilog streaming read: ${f.message}`)},()=>{}),c=tt(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,u=b.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return u=b.getLastLines(u,r.tail),u}async runHilogFollow(e,t,r,i){await this.printTailSnapshotIfNeeded(e,t,r,i);let[o,s]=this.buildHilogCommand(e,t,r,i);y(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${o} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(o,s,this.createFollowLineHandler(r),l=>{console.error(l.message)},()=>{}),c=tt(a,"Failed to follow hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to follow hilog: ${a.stderr}`);return""}async getHilog(e,t){let r=this.toolProvider.hdcPath,i=t.bundleName?await this.getPidForBundle(r,e,t.bundleName):void 0;if(t.bundleName&&!i)throw new Error(`No running process found for bundle '${t.bundleName}'. Ensure the app is launched on the device before fetching logs.`);return t.logSize&&await this.resizeHilogBuffer(r,e,t.logSize),t.isFollow?await this.runHilogFollow(r,e,t,i||""):await this.getHilogOnce(r,e,t,i||"")}async getCrashLog(e,t){y(`Fetching crash logs from device: ${e}`);let r=this.toolProvider.hdcPath,i=await this.listCrashLogs(r,e,t);if(i.length===0)return t?`No crash logs found for bundle '${t}'.`:"No crash logs found.";let s=[...i].sort((c,l)=>{let u=c.split("-").pop()||"";return(l.split("-").pop()||"").localeCompare(u)})[0],a=await this.fetchCrashLogContent(r,e,s);return`--- Latest Crash Log File: ${s} ---${a}`}async listCrashLogs(e,t,r){let i=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];y(`Running command: ${e} ${i.join(" ")}`);let o=await Oe(e,i),s=tt(o,"Failed to list crash logs");if(s)throw s;if(o.exitCode!==0)throw new Error(`Failed to list crash logs: ${o.stderr||o.stdout}`);return y(`Crash logs list output:
1255
+ ${o}`)}if(r.length===1){let i=r[0];return g(cr(`Using device: ${i.name} (${i.serial})`)),i.serial}throw new Error("Multiple devices found. Specify a target device using `--device <name>` or `--device <serial>`.\nAvailable devices:\n"+this.formatConnectedDeviceList(r))}async getConnectedDeviceSerials(){let e=await this.deviceManager.listDevices();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e}async getPidForBundle(e,t,r){g(`Retrieving PID for bundle ${r}`),b.assertBundleName(r);let i=await Fe(e,["-t",t,"shell","pidof",r]),o=st(i,"Failed to look up PID");if(o)throw o;if(i.exitCode===0&&i.stdout.trim()){let s=i.stdout.trim(),a=s.split(/\s+/)[0]||s;return g(`Found PID for ${r}: ${a}`),a}return g(`No PID found for bundle: ${r}`),null}async resizeHilogBuffer(e,t,r){g(`Setting hilog buffer size to: ${r}`);let i=await Fe(e,["-t",t,"shell","hilog","-G",r]),o=st(i,"Failed to resize hilog buffer");if(o)throw o;i.exitCode!==0&&console.error(`Failed to resize hilog buffer: ${i.stderr||i.stdout}`)}buildHilogCommand(e,t,r,i){let o=this.buildHilogShellCommand(r,i);return[e,["-t",t,"shell",o]]}buildHilogShellCommand(e,t){let r=["hilog"];return e.isFollow||r.push("-x"),e.tag&&(b.assertHilogToken(e.tag,"tag"),r.push("-T",e.tag)),e.level&&(b.assertHilogLevel(e.level),r.push("-L",e.level)),e.domain&&(b.assertHilogToken(e.domain,"domain"),r.push("-D",e.domain)),t&&r.push("-P",t),e.keyword&&(b.assertHilogKeyword(e.keyword),r.push("-e",b.quotePosixShellArg(e.keyword))),r.join(" ")}async followHilog(e,t,r,i,o){let a=await qs(e,t,{onData:r,onError:i,onClose:o});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}async runHilogWithSpawnRetry(e,t,r,i,o){let s=1+go.length,a={stdout:"",stderr:"",exitCode:-1};for(let c=0;c<s;c++){a=await this.followHilog(e,t,r,i,o);let l=a.exitCode===0?a.stdout:a.stderr||a.stdout;if(gt(l)!=="transient"||c>=s-1)return a;g(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${go[c]}ms`),await ef(go[c])}return a}async printTailSnapshotIfNeeded(e,t,r,i){if(!r.tail&&!r.fromSeconds&&!r.toSeconds)return;let o={...r,isFollow:!1},[,s]=this.buildHilogCommand(e,t,o,i),a=await Fe(e,s),c=st(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=b.filterLogsByRelativeWindow(a.stdout||a.stderr,r.fromSeconds,r.toSeconds);l=b.getLastLines(l,r.tail),l.trim()&&console.log(l)}async getHilogOnce(e,t,r,i){let[o,s]=this.buildHilogCommand(e,t,r,i);g(`Ready to run hilog command: ${o} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(o,s,()=>{},f=>{g(`Callback triggered when an error occurs during a single hilog streaming read: ${f.message}`)},()=>{}),c=st(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,u=b.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return u=b.getLastLines(u,r.tail),u}async runHilogFollow(e,t,r,i){await this.printTailSnapshotIfNeeded(e,t,r,i);let[o,s]=this.buildHilogCommand(e,t,r,i);g(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${o} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(o,s,this.createFollowLineHandler(r),l=>{console.error(l.message)},()=>{}),c=st(a,"Failed to follow hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to follow hilog: ${a.stderr}`);return""}async getHilog(e,t){let r=this.toolProvider.hdcPath,i=t.bundleName?await this.getPidForBundle(r,e,t.bundleName):void 0;if(t.bundleName&&!i)throw new Error(`No running process found for bundle '${t.bundleName}'. Ensure the app is launched on the device before fetching logs.`);return t.logSize&&await this.resizeHilogBuffer(r,e,t.logSize),t.isFollow?await this.runHilogFollow(r,e,t,i||""):await this.getHilogOnce(r,e,t,i||"")}async getCrashLog(e,t){g(`Fetching crash logs from device: ${e}`);let r=this.toolProvider.hdcPath,i=await this.listCrashLogs(r,e,t);if(i.length===0)return t?`No crash logs found for bundle '${t}'.`:"No crash logs found.";let s=[...i].sort((c,l)=>{let u=c.split("-").pop()||"";return(l.split("-").pop()||"").localeCompare(u)})[0],a=await this.fetchCrashLogContent(r,e,s);return`--- Latest Crash Log File: ${s} ---${a}`}async listCrashLogs(e,t,r){let i=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];g(`Running command: ${e} ${i.join(" ")}`);let o=await Fe(e,i),s=st(o,"Failed to list crash logs");if(s)throw s;if(o.exitCode!==0)throw new Error(`Failed to list crash logs: ${o.stderr||o.stdout}`);return g(`Crash logs list output:
1254
1256
  ${o.stdout}`),o.stdout.split(`
1255
- `).map(c=>c.trim()).filter(c=>c.length>0).filter(c=>{try{return b.assertCrashFilename(c),!0}catch{return!1}}).filter(c=>r?c.toLowerCase().includes(r.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){y(`Fetching latest crash log file: ${r}`);let i=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];y(`Executing command: ${e} ${i.join(" ")}`);let o=await Oe(e,i),s=tt(o,"Failed to fetch crash log content");if(s)throw s;return o.exitCode!==0&&o.stderr&&console.error(`Warning: Failed to fetch crash logs: ${o.stderr}`),o.stdout+o.stderr}};import{cyan as so,red as ac}from"colorette";import jh from"ora";function $h(n){try{return b.parsePositiveInteger(n,"tail")}catch{throw new sc("`tail` must be a positive integer.")}}function oc(n,e){try{return b.parseDurationToSeconds(n,e)}catch{throw new sc(`${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 Wh(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.");b.assertRelativeTimeRange(n.from,n.to)}async function Bh(n,e,t,r,i){return t.crash?await n.getCrashLog(e,t.bundleName):await n.getHilog(e,{level:t.level,bundleName:t.bundleName,keyword:t.keyword,isFollow:!!t.follow,tail:t.tail,fromSeconds:r,toSeconds:i})}function Uh(n,e,t,r){let i=b.filterLogsByRelativeWindow(n,t,r);return e.tail?b.getLastLines(i,e.tail):i}var zh=new Fh("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(ac(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").option("--bundle-name <bundle-name>","Filter by application bundle name").option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",$h).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>oc(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>oc(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await qh(n)});async function qh(n){let e=jh({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),Wh(n);let r=n.from,i=n.to,o=await L.new(),s=new er(o),a=await s.selectDevice(n.device);a||(t(),process.exit(1)),y(so(`deviceId: ${a}`)),y(so(`type: ${n.crash?"Crash logs":"Common logs"}`)),y(so("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await Bh(s,a,n,r,i);t(),n.crash&&c&&(c=Uh(c,n,r,i)),c&&console.log(c)}catch(r){t(),console.error(ac(r.message)),process.exit(1)}}var cc=zh;import ln from"path";import De from"fs";import co from"process";import gc from"os";import{Command as of}from"commander";import{green as pc,red as ao,cyan as sf,yellow as mc}from"colorette";import $ from"fs-extra";import x from"path";import*as lc from"os";import{fileURLToPath as Gh}from"url";var Yh={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"}},Vh=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function Jh(){let n=import.meta.url,e=Gh(n);if(e.includes("dist")){let o=x.dirname(e),s=x.dirname(o);return x.join(s,"templates","application")}let t=x.dirname(e),r=x.dirname(t),i=x.dirname(r);return x.join(i,"templates","application")}function dc(n,e){$.mkdirSync(e,{recursive:!0});for(let t of $.readdirSync(n,{withFileTypes:!0})){let r=x.join(n,t.name),i=x.join(e,t.name);if(t.isDirectory()){dc(r,i);continue}$.existsSync(i)||($.mkdirSync(x.dirname(i),{recursive:!0}),$.copyFileSync(r,i))}}function cn(n,e){let t=$.readFileSync(n,"utf-8"),r=t;for(let[i,o]of e)r=r.replaceAll(i,o);r!==t&&$.writeFileSync(n,r,"utf-8")}function Kh(n,e){if(e===22)return;let t=Yh[e];t&&(cn(x.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),cn(x.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),cn(x.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function Zh(n){return Vh.filter(t=>!$.existsSync(x.join(n,t))).length===0}function Xh(){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 Qh(n){return lc.platform()==="darwin"?x.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):x.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function ef(n,e){let t=Qh(e);if(!$.existsSync(t))return!1;let r=[["AppScope/resources/base/media/background.png","AppScope/resources/base/media/background.png"],["AppScope/resources/base/media/foreground.png","AppScope/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/background.png"],["entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/startIcon.png","entry/src/main/resources/base/media/startIcon.png"]];for(let[i,o]of r){let s=x.join(t,i),a=x.join(n,o);$.existsSync(s)&&($.mkdirSync(x.dirname(a),{recursive:!0}),$.copyFileSync(s,a))}return!0}function tf(n){let e=Xh(),t=["AppScope/resources/base/media/background.png","AppScope/resources/base/media/foreground.png","entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/startIcon.png"];for(let r of t){let i=x.join(n,r);$.mkdirSync(x.dirname(i),{recursive:!0}),$.writeFileSync(i,e)}}function nf(n,e){e&&ef(n,e)||tf(n)}function rf(n){let e=[x.join(n,"gitignore.txt"),x.join(n,"entry","gitignore.txt")];for(let t of e)if($.existsSync(t)){let r=x.dirname(t);$.renameSync(t,x.join(r,".gitignore"))}}function uc(n,e,t,r,i){let o=Jh();if(!$.existsSync(o))throw new Error(`Template directory not found: ${o}`);$.mkdirSync(n,{recursive:!0}),dc(o,n),rf(n),nf(n,i),cn(x.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),cn(x.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),Kh(n,r);let s=Zh(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function af(n){if(n.length<1||n.length>200)throw new Error(`App name length must be 1-200 characters. Current: ${n.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(n))throw new Error("Application name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function cf(n){if(n.length<7||n.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${n.length}`);if(n.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let e=n.split(".");if(e.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let t=/^[a-zA-Z0-9_]+$/;for(let r=0;r<e.length;r++){let i=e[r];if(!t.test(i))throw new Error(`Segment "${i}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(r===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.`)}}function yc(n){if(gc.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function hc(n){if(n.length===0)throw new Error("Project path cannot be empty.");if(n.length>120)throw new Error(`Project path cannot exceed 120 characters (current: ${n.length}).`);let e=gc.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(n)){let o=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new Error(`Project path can only contain ${o}.`)}let r=yc(n);if(/[\u4e00-\u9fff]/.test(r))throw new Error("Project path cannot contain Chinese characters.");if(r.endsWith("."))throw new Error("Project path cannot end with a dot (.)")}function lf(n){let e=n,t=ln.parse(n).root;for(;e!==t;){if(De.existsSync(e))return e;e=ln.dirname(e)}return De.existsSync(t)?t:null}function fc(n){let e=lf(n);if(!e)throw new Error(`No existing parent directory found for '${n}'. Cannot create project directory.`);try{De.accessSync(e,De.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=ln.join(e,`.deveco_write_test_${Date.now()}`);try{De.writeFileSync(t,"test"),De.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function df(n){return`com.example.${n.toLowerCase()}`}function uf(n,e){if(e){let i=yc(e),o=ln.resolve(i);if(De.existsSync(o)){if(De.readdirSync(o).length>0)throw new Error(`Directory '${o}' is not empty. Cannot create project here.`)}else fc(o);return o}let t=co.cwd(),r=ln.join(t,n);if(De.existsSync(r))throw new Error(`Directory '${r}' already exists. Cannot create project here.`);return fc(r),r}function pf(n,e){let t=e?.getMaxApiLevel(),r=23;if(n.apiLevel){let i=Number(n.apiLevel);if(!Number.isInteger(i)||i<17)throw new Error(`Invalid API version ${n.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(i>t)throw new Error(`Invalid API version ${n.apiLevel}. Your SDK supports API version 17-${t}`)}else if(i>r)throw new Error(`Invalid API version ${n.apiLevel}. Without DevEco Studio, supported range is API version 17-${r}`);return i}return t!==void 0?t:23}async function mf(){try{return await L.new()}catch(n){console.error(mc(`DevEco Studio not found: ${n.message}`)),console.log(mc("Use placeholder API level instead."));return}}var hf=new of("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=>{try{n.appName||(console.error(ao("Error: --app-name is required")),co.exit(1));let e=n.appName;af(e);let t=n.bundleName||df(e);cf(t),n.projectPath&&hc(n.projectPath);let r=uf(e,n.projectPath);hc(r),console.log(sf("Initializing project...")),console.log(`Project path: ${r}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let i=await mf(),o=pf(n,i);console.log(`API level: ${o}`);let s=i?.devecoStudioPath,a=uc(r,e,t,o,s);console.log(`
1256
- `+pc("Project created successfully.")),console.log(`Project root: ${a.projectRoot}`),console.log(`App name: ${a.appName}`),console.log(`Bundle name: ${a.bundleName}`),console.log(`API level: ${a.apiLevel}`),console.log(pc("Template integrity check passed."))}catch(e){let t=e;console.error(ao(`
1257
- Failed to create project.`)),console.error(ao(t.message)),co.exit(1)}}),vc=hf;import{Command as Sf}from"commander";import{red as Ef,cyan as Ic}from"colorette";import ff from"fs";import tr from"path";import{cyan as gf}from"colorette";import*as nr from"smol-toml";var bt=ff.promises;async function yf(n){try{let e=await bt.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 vf(n){try{let e=await bt.readFile(n,"utf8");return e.trim()===""?{}:nr.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 wf(n,e){let t=tr.dirname(n);await bt.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await bt.writeFile(n,r,"utf8")}async function bf(n,e){let t=tr.dirname(n);await bt.mkdir(t,{recursive:!0});let r=nr.stringify(e);await bt.writeFile(n,r,"utf8")}function wc(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function bc(n,e,t,r,i){(!n[e]||typeof n[e]!="object")&&(n[e]={});let o=n[e];return t in o&&!i?!1:(o[t]=r,!0)}async function Sc(n,e){return n.format==="codex"?vf(e):yf(e)}async function Ec(n,e,t){return n.format==="codex"?bf(e,t):wf(e,t)}async function Pc(n,e,t=!1){let r=Ne[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Ne).join(", ")}`};if(!r.supportsGlobal)return{success:!1,error:`${r.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let i=await Sc(r,r.globalConfigPath);if(wc(i,r.mcpServersKey,Ee)&&!t)return console.log(`MCP server ${Ee} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let o=Vn(r,void 0);return bc(i,r.mcpServersKey,Ee,o,t),await Ec(r,r.globalConfigPath,i),console.log(`MCP server ${Ee} configured in ${r.globalConfigPath}.`),{success:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${i.message}`}}}async function lo(n,e,t=!1){let r=Ne[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Ne).join(", ")}`};let i=tr.isAbsolute(r.projectConfigPath)?r.projectConfigPath:tr.join(e,r.projectConfigPath);try{let o=await Sc(r,i);if(wc(o,r.mcpServersKey,Ee)&&!t)return console.log(`MCP server ${Ee} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:n,installType:"project"};let s=Vn(r,e);return bc(o,r.mcpServersKey,Ee,s,t),await Ec(r,i,o),console.log(`MCP server ${Ee} configured in ${i}.`),{success:!0,configPath:i,agentName:n,installType:"project"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${o.message}`}}}function Cc(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(gf("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`);for(let i of n)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);r>0&&(process.exitCode=1)}var uo="deveco-cli";async function Pf(n,e,t){if(n.customPath)return[await Va(uo,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>Ya(uo,e,s,a,t.force)),...n.agents.map(s=>()=>Ga(uo,e,s,t.force))],i=5,o=[];for(let s=0;s<r.length;s+=i){let a=r.slice(s,s+i);o.push(...await Promise.all(a.map(c=>c())))}return o}async function Cf(n,e,t){let r=[];for(let{project:i,agent:o}of n.projectAgents){let s=await lo(o,i,t);r.push(s)}for(let i of n.agents){let o=await lo(i,e,t);r.push(o)}return r}async function If(n,e){let t=[];for(let r of n){if(!Ne[r])continue;let o=await Pc(r,process.cwd(),e);t.push(o)}return t}async function Df(n,e,t){if(t.agent&&t.agent.split(",").map(l=>l.trim()).includes("qoder"))throw new Error("Qoder does not support MCP configuration via DevEco CLI. Use other supported agents instead.");let r=t.force??!1,i=n.projectAgents.filter(c=>c.agent!=="qoder"),o=n.agents.filter(c=>c!=="qoder"),s={...n,projectAgents:i,agents:o},a=e?await Cf(s,e,r):await If(s.agents,r);a.length>0&&(console.log(Ic("MCP Configuration:")),Cc(a))}async function Af(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}=on(n.path,n.project,n.agent);t&&He(t,"Project directory",n.force),e&&He(e,"Directory",n.force);let r=await Zn(n,e,t);if(n.mcp){await Df(r,t,n);return}let i=Xa(),o=await Pf(r,i,n);console.log(),o.length>0&&(console.log(Ic("Skill Installation:")),rn(o))}var Tf=new Sf("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 Af(n)}catch(e){console.error(Ef(e.message)),process.exit(1)}}),Dc=Tf;import{Command as iy}from"commander";import{McpServer as Yg}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Vg}from"@modelcontextprotocol/sdk/server/stdio.js";import*as Ft from"path";import{z as V}from"zod";var rr=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 i=>r(i)))}};function po(){return new rr}import*as ne from"fs";import*as Y from"path";import{z as Co}from"zod";import T from"fs";import*as ir from"os";import*as P from"path";import xf from"json5";var mo="Huawei";var kf=3,kc=3,Ac="DevEco Studio",Rc={DevEcoStudio:"deveco_studio"};function ho(n){if(!T.existsSync(n)||!T.statSync(n).isDirectory())return!1;let e=T.existsSync(P.join(n,"build-profile.json5")),t=T.existsSync(P.join(n,"hvigorfile.js"))||T.existsSync(P.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=T.readFileSync(P.join(n,"build-profile.json5"),"utf-8");return xf.parse(r).app!==void 0}catch{return!1}}function Mc(n,e,t){if(e>=t)return null;let r=Rf(n),i=Mf(r);if(i)return i;for(let o of r){let s=Mc(o,e+1,t);if(s)return s}return null}function Rf(n){try{let e=T.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(P.join(n,r.name));return t}catch{return[]}}function Mf(n){for(let e of n)if(ho(e))return e;return null}function Ae(n){if(!n||n.trim()==="")return null;let e=P.resolve(n),t;try{t=T.realpathSync(e)}catch{t=e}if(!T.existsSync(t))return null;if(ho(t))return t;let r=t;for(let i=1;i<=3;i++){let o=P.dirname(r);if(o===r)break;if(ho(o))return o;r=o}if(T.statSync(t).isDirectory()){let i=Mc(t,0,kf);if(i)return i}return null}function or(n){if(process.platform==="linux")return null;let e=n??Te();if(!e)return null;let t;if(process.platform==="win32")t=P.join(e,"plugins","openharmony");else if(process.platform==="darwin")t=P.join(e,"contents","plugins","openharmony");else return null;let r=P.join(t,"ace-server","out","index.js");return T.existsSync(r)?t:null}var Of=["sdk","default","openharmony","native","llvm","bin","clangd"],fo=[".idea",".deveco","cxx","compile_commands.json"];function Lf(n){return process.platform==="darwin"&&n.endsWith(".app")?P.join(n,"Contents"):n}function Tc(n){let e=new Set,t=[n,Lf(n)];for(let r of t){let i=P.join(r,...Of);e.add(process.platform==="win32"?i+".exe":i)}return[...e]}function Oc(n){let e=[],t=process.env.DEVECO_HOME??process.env.DEVECO_PATH;if(t&&t.trim()){for(let i of Tc(t.trim()))if(e.push(i),T.existsSync(i))return i}let r=n??Te();if(r){for(let i of Tc(r))if(e.push(i),T.existsSync(i))return i}return null}function sr(n){return P.join(n,...fo)}function Te(){if(process.platform==="win32"){let n=[P.join("C:\\Program Files",mo,Ac),P.join("C:\\Program Files (x86)",mo,Ac)];return xc(n)}if(process.platform==="darwin"){let n=["/Applications/DevEco Studio.app",P.join(process.env.HOME??"","Applications","DevEco Studio.app")];return xc(n)}return null}function xc(n){for(let e of n)if(T.existsSync(e))return e;return null}function le(n){return process.platform==="darwin"?P.join(n,"Contents"):n}function Nf(n){if(!n||!T.existsSync(n)||!Lc(n))return!1;let e=le(n);return[P.join(e,"plugins","openharmony"),P.join(e,"sdk"),P.join(e,"tools")].some(r=>T.existsSync(r))}function Lc(n){try{return T.statSync(n).isDirectory()}catch{return!1}}function go(n,e){return!n||!T.existsSync(n)?!1:e===Rc.DevEcoStudio?Nf(n):!1}function ar(n,e=Rc.DevEcoStudio){if(!n)return"";if(go(n,e))return n;let t=_f(n,e);if(t)return t;let r=Hf(n,e);return r||n}function _f(n,e){let t=n;for(let r=0;r<kc;r++){let i=P.dirname(t);if(!i||i===t)break;if(go(i,e))return i;t=i}return null}function Hf(n,e){if(!T.existsSync(n)||!Lc(n))return null;let t=[{p:n,depth:0}];for(;t.length>0;){let{p:r,depth:i}=t.shift();if(i>=kc)continue;let o=Ff(r,i,e,t);if(o)return o}return null}function Ff(n,e,t,r){let i;try{i=T.readdirSync(n,{withFileTypes:!0})}catch{return null}for(let o of i){if(!o.isDirectory())continue;let s=P.join(n,o.name);if(go(s,t))return s;r.push({p:s,depth:e+1})}return null}function Nc(n){return new Promise(e=>setTimeout(e,n))}var jf=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function cr(n){let e=P.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&jf.has(e)}function _c(n){return P.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function de(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function $f(n){return de(n)}function nt(n){let e=$f(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function St(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??P.join(ir.homedir(),"AppData","Local");return P.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?P.join(ir.homedir(),"Library","Logs","devecocli-mcp-server"):P.join(ir.homedir(),".local","share","devecocli-mcp-server","logs")}function Hc(n,e){let t=Wf(e),r=Bf(t,n);if(r!==null)return r;let i=Date.now(),s=`${n.replace(/:/g,"\\:")}=${i}`,a=Uf(t,n,s);return zf(e,a),i}function Wf(n){let e;try{e=T.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function Bf(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let o=parseInt(t.slice(r+1),10);return Number.isFinite(o)&&o>0?o:null}return null}function Uf(n,e,t){let r=!1,i=n.map(o=>{if(r)return o;let s=o.indexOf("=");return s<=0?o:o.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):o});return r||i.push(t),i}function zf(n,e){try{T.mkdirSync(P.dirname(n),{recursive:!0})}catch{}try{T.writeFileSync(n,e.join(`
1257
+ `).map(c=>c.trim()).filter(c=>c.length>0).filter(c=>{try{return b.assertCrashFilename(c),!0}catch{return!1}}).filter(c=>r?c.toLowerCase().includes(r.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){g(`Fetching latest crash log file: ${r}`);let i=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];g(`Executing command: ${e} ${i.join(" ")}`);let o=await Fe(e,i),s=st(o,"Failed to fetch crash log content");if(s)throw s;return o.exitCode!==0&&o.stderr&&console.error(`Warning: Failed to fetch crash logs: ${o.stderr}`),o.stdout+o.stderr}};import{cyan as yo,red as gc}from"colorette";import nf from"ora";function rf(n){try{return b.parsePositiveInteger(n,"tail")}catch{throw new fc("`tail` must be a positive integer.")}}function hc(n,e){try{return b.parseDurationToSeconds(n,e)}catch{throw new fc(`${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 of(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.");b.assertRelativeTimeRange(n.from,n.to)}async function sf(n,e,t,r,i){return t.crash?await n.getCrashLog(e,t.bundleName):await n.getHilog(e,{level:t.level,bundleName:t.bundleName,keyword:t.keyword,isFollow:!!t.follow,tail:t.tail,fromSeconds:r,toSeconds:i})}function af(n,e,t,r){let i=b.filterLogsByRelativeWindow(n,t,r);return e.tail?b.getLastLines(i,e.tail):i}var cf=new tf("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(gc(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").option("--bundle-name <bundle-name>","Filter by application bundle name").option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",rf).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>hc(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>hc(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await lf(n)});async function lf(n){let e=nf({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),of(n);let r=n.from,i=n.to,o=await N.new(),s=new lr(o),a=await s.selectDevice(n.device);a||(t(),process.exit(1)),g(yo(`deviceId: ${a}`)),g(yo(`type: ${n.crash?"Crash logs":"Common logs"}`)),g(yo("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await sf(s,a,n,r,i);t(),n.crash&&c&&(c=af(c,n,r,i)),c&&console.log(c)}catch(r){t(),console.error(gc(r.message)),process.exit(1)}}var yc=cf;import hn from"path";import ke from"fs";import wo from"process";import Dc from"os";import{Command as Ef}from"commander";import{green as Sc,red as vo,cyan as Pf,yellow as Ec}from"colorette";import $ from"fs-extra";import k from"path";import*as vc from"os";import{fileURLToPath as df}from"url";var uf={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"}},pf=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function mf(){let n=import.meta.url,e=df(n);if(e.includes("dist")){let o=k.dirname(e),s=k.dirname(o);return k.join(s,"templates","application")}let t=k.dirname(e),r=k.dirname(t),i=k.dirname(r);return k.join(i,"templates","application")}function wc(n,e){$.mkdirSync(e,{recursive:!0});for(let t of $.readdirSync(n,{withFileTypes:!0})){let r=k.join(n,t.name),i=k.join(e,t.name);if(t.isDirectory()){wc(r,i);continue}$.existsSync(i)||($.mkdirSync(k.dirname(i),{recursive:!0}),$.copyFileSync(r,i))}}function mn(n,e){let t=$.readFileSync(n,"utf-8"),r=t;for(let[i,o]of e)r=r.replaceAll(i,o);r!==t&&$.writeFileSync(n,r,"utf-8")}function hf(n,e){if(e===22)return;let t=uf[e];t&&(mn(k.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),mn(k.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),mn(k.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function ff(n){return pf.filter(t=>!$.existsSync(k.join(n,t))).length===0}function gf(){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 yf(n){return vc.platform()==="darwin"?k.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):k.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function vf(n,e){let t=yf(e);if(!$.existsSync(t))return!1;let r=[["AppScope/resources/base/media/background.png","AppScope/resources/base/media/background.png"],["AppScope/resources/base/media/foreground.png","AppScope/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/background.png"],["entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/startIcon.png","entry/src/main/resources/base/media/startIcon.png"]];for(let[i,o]of r){let s=k.join(t,i),a=k.join(n,o);$.existsSync(s)&&($.mkdirSync(k.dirname(a),{recursive:!0}),$.copyFileSync(s,a))}return!0}function wf(n){let e=gf(),t=["AppScope/resources/base/media/background.png","AppScope/resources/base/media/foreground.png","entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/startIcon.png"];for(let r of t){let i=k.join(n,r);$.mkdirSync(k.dirname(i),{recursive:!0}),$.writeFileSync(i,e)}}function bf(n,e){e&&vf(n,e)||wf(n)}function Sf(n){let e=[k.join(n,"gitignore.txt"),k.join(n,"entry","gitignore.txt")];for(let t of e)if($.existsSync(t)){let r=k.dirname(t);$.renameSync(t,k.join(r,".gitignore"))}}function bc(n,e,t,r,i){let o=mf();if(!$.existsSync(o))throw new Error(`Template directory not found: ${o}`);$.mkdirSync(n,{recursive:!0}),wc(o,n),Sf(n),bf(n,i),mn(k.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),mn(k.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),hf(n,r);let s=ff(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function Cf(n){if(n.length<1||n.length>200)throw new Error(`App name length must be 1-200 characters. Current: ${n.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(n))throw new Error("Application name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function Df(n){if(n.length<7||n.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${n.length}`);if(n.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let e=n.split(".");if(e.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let t=/^[a-zA-Z0-9_]+$/;for(let r=0;r<e.length;r++){let i=e[r];if(!t.test(i))throw new Error(`Segment "${i}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(r===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.`)}}function Ic(n){if(Dc.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function Pc(n){if(n.length===0)throw new Error("Project path cannot be empty.");if(n.length>120)throw new Error(`Project path cannot exceed 120 characters (current: ${n.length}).`);let e=Dc.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(n)){let o=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new Error(`Project path can only contain ${o}.`)}let r=Ic(n);if(/[\u4e00-\u9fff]/.test(r))throw new Error("Project path cannot contain Chinese characters.");if(r.endsWith("."))throw new Error("Project path cannot end with a dot (.)")}function If(n){let e=n,t=hn.parse(n).root;for(;e!==t;){if(ke.existsSync(e))return e;e=hn.dirname(e)}return ke.existsSync(t)?t:null}function Cc(n){let e=If(n);if(!e)throw new Error(`No existing parent directory found for '${n}'. Cannot create project directory.`);try{ke.accessSync(e,ke.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=hn.join(e,`.deveco_write_test_${Date.now()}`);try{ke.writeFileSync(t,"test"),ke.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function Af(n){return`com.example.${n.toLowerCase()}`}function xf(n,e){if(e){let i=Ic(e),o=hn.resolve(i);if(ke.existsSync(o)){if(ke.readdirSync(o).length>0)throw new Error(`Directory '${o}' is not empty. Cannot create project here.`)}else Cc(o);return o}let t=wo.cwd(),r=hn.join(t,n);if(ke.existsSync(r))throw new Error(`Directory '${r}' already exists. Cannot create project here.`);return Cc(r),r}function Tf(n,e){let t=e?.getMaxApiLevel(),r=23;if(n.apiLevel){let i=Number(n.apiLevel);if(!Number.isInteger(i)||i<17)throw new Error(`Invalid API version ${n.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(i>t)throw new Error(`Invalid API version ${n.apiLevel}. Your SDK supports API version 17-${t}`)}else if(i>r)throw new Error(`Invalid API version ${n.apiLevel}. Without DevEco Studio, supported range is API version 17-${r}`);return i}return t!==void 0?t:23}async function kf(){try{return await N.new()}catch(n){console.error(Ec(`DevEco Studio not found: ${n.message}`)),console.log(Ec("Use placeholder API level instead."));return}}var Rf=new Ef("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=>{try{n.appName||(console.error(vo("Error: --app-name is required")),wo.exit(1));let e=n.appName;Cf(e);let t=n.bundleName||Af(e);Df(t),n.projectPath&&Pc(n.projectPath);let r=xf(e,n.projectPath);Pc(r),console.log(Pf("Initializing project...")),console.log(`Project path: ${r}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let i=await kf(),o=Tf(n,i);console.log(`API level: ${o}`);let s=i?.devecoStudioPath,a=bc(r,e,t,o,s);console.log(`
1258
+ `+Sc("Project created successfully.")),console.log(`Project root: ${a.projectRoot}`),console.log(`App name: ${a.appName}`),console.log(`Bundle name: ${a.bundleName}`),console.log(`API level: ${a.apiLevel}`),console.log(Sc("Template integrity check passed."))}catch(e){let t=e;console.error(vo(`
1259
+ Failed to create project.`)),console.error(vo(t.message)),wo.exit(1)}}),Ac=Rf;import{Command as Ff}from"commander";import{red as jf,cyan as Lc}from"colorette";import Mf from"fs";import dr from"path";import{cyan as Of}from"colorette";import*as ur from"smol-toml";var Dt=Mf.promises;async function Lf(n){try{let e=await Dt.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 Nf(n){try{let e=await Dt.readFile(n,"utf8");return e.trim()===""?{}:ur.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 _f(n,e){let t=dr.dirname(n);await Dt.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await Dt.writeFile(n,r,"utf8")}async function Hf(n,e){let t=dr.dirname(n);await Dt.mkdir(t,{recursive:!0});let r=ur.stringify(e);await Dt.writeFile(n,r,"utf8")}function xc(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function Tc(n,e,t,r,i){(!n[e]||typeof n[e]!="object")&&(n[e]={});let o=n[e];return t in o&&!i?!1:(o[t]=r,!0)}async function kc(n,e){return n.format==="codex"?Nf(e):Lf(e)}async function Rc(n,e,t){return n.format==="codex"?Hf(e,t):_f(e,t)}async function Mc(n,e,t=!1){let r=_e[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(_e).join(", ")}`};if(!r.supportsGlobal)return{success:!1,error:`${r.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let i=await kc(r,r.globalConfigPath);if(xc(i,r.mcpServersKey,Ce)&&!t)return console.log(`MCP server ${Ce} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let o=Gn(r,void 0);return Tc(i,r.mcpServersKey,Ce,o,t),await Rc(r,r.globalConfigPath,i),console.log(`MCP server ${Ce} configured in ${r.globalConfigPath}.`),{success:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${i.message}`}}}async function bo(n,e,t=!1){let r=_e[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(_e).join(", ")}`};let i=dr.isAbsolute(r.projectConfigPath)?r.projectConfigPath:dr.join(e,r.projectConfigPath);try{let o=await kc(r,i);if(xc(o,r.mcpServersKey,Ce)&&!t)return console.log(`MCP server ${Ce} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:n,installType:"project"};let s=Gn(r,e);return Tc(o,r.mcpServersKey,Ce,s,t),await Rc(r,i,o),console.log(`MCP server ${Ce} configured in ${i}.`),{success:!0,configPath:i,agentName:n,installType:"project"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${o.message}`}}}function Oc(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(Of("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`);for(let i of n)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);r>0&&(process.exitCode=1)}var So="deveco-cli";async function $f(n,e,t){if(n.customPath)return[await rc(So,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>nc(So,e,s,a,t.force)),...n.agents.map(s=>()=>tc(So,e,s,t.force))],i=5,o=[];for(let s=0;s<r.length;s+=i){let a=r.slice(s,s+i);o.push(...await Promise.all(a.map(c=>c())))}return o}async function Bf(n,e,t){let r=[];for(let{project:i,agent:o}of n.projectAgents){let s=await bo(o,i,t);r.push(s)}for(let i of n.agents){let o=await bo(i,e,t);r.push(o)}return r}async function Wf(n,e){let t=[];for(let r of n){if(!_e[r])continue;let o=await Mc(r,process.cwd(),e);t.push(o)}return t}async function Uf(n,e,t){if(t.agent&&t.agent.split(",").map(l=>l.trim()).includes("qoder"))throw new Error("Qoder does not support MCP configuration via DevEco CLI. Use other supported agents instead.");let r=t.force??!1,i=n.projectAgents.filter(c=>c.agent!=="qoder"),o=n.agents.filter(c=>c!=="qoder"),s={...n,projectAgents:i,agents:o},a=e?await Bf(s,e,r):await Wf(s.agents,r);a.length>0&&(console.log(Lc("MCP Configuration:")),Oc(a))}async function zf(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}=dn(n.path,n.project,n.agent);t&&Be(t,"Project directory",n.force),e&&Be(e,"Directory",n.force);let r=await sr(n,e,t);if(n.mcp){await Uf(r,t,n);return}let i=ac(),o=await $f(r,i,n);console.log(),o.length>0&&(console.log(Lc("Skill Installation:")),ln(o))}var qf=new Ff("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 zf(n)}catch(e){console.error(jf(e.message)),process.exit(1)}}),Nc=qf;import{Command as wy}from"commander";import{McpServer as cy}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as ly}from"@modelcontextprotocol/sdk/server/stdio.js";import*as ut from"path";import*as Cl from"fs";import{z as J}from"zod";var pr=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 i=>r(i)))}};function Eo(){return new pr}import*as re from"fs";import*as Y from"path";import{z as Lo}from"zod";import x from"fs";import*as mr from"os";import*as E from"path";import Gf from"json5";var Po="Huawei";var Vf=3,jc=3,_c="DevEco Studio",$c={DevEcoStudio:"deveco_studio"};function Co(n){if(!x.existsSync(n)||!x.statSync(n).isDirectory())return!1;let e=x.existsSync(E.join(n,"build-profile.json5")),t=x.existsSync(E.join(n,"hvigorfile.js"))||x.existsSync(E.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=x.readFileSync(E.join(n,"build-profile.json5"),"utf-8");return Gf.parse(r).app!==void 0}catch{return!1}}function Bc(n,e,t){if(e>=t)return null;let r=Yf(n),i=Jf(r);if(i)return i;for(let o of r){let s=Bc(o,e+1,t);if(s)return s}return null}function Yf(n){try{let e=x.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(E.join(n,r.name));return t}catch{return[]}}function Jf(n){for(let e of n)if(Co(e))return e;return null}function Re(n){if(!n||n.trim()==="")return null;let e=E.resolve(n),t;try{t=x.realpathSync(e)}catch{t=e}if(!x.existsSync(t))return null;if(Co(t))return t;let r=t;for(let i=1;i<=3;i++){let o=E.dirname(r);if(o===r)break;if(Co(o))return o;r=o}if(x.statSync(t).isDirectory()){let i=Bc(t,0,Vf);if(i)return i}return null}function It(n){if(process.platform==="linux")return null;let e=n??be();if(!e)return null;let t;if(process.platform==="win32")t=E.join(e,"plugins","openharmony");else if(process.platform==="darwin")t=E.join(e,"contents","plugins","openharmony");else return null;let r=E.join(t,"ace-server","out","index.js");return x.existsSync(r)?t:null}var Kf=["sdk","default","openharmony","native","llvm","bin","clangd"],Do=[".idea",".deveco","cxx","compile_commands.json"];function Zf(n){return process.platform==="darwin"&&n.endsWith(".app")?E.join(n,"Contents"):n}function Hc(n){let e=new Set,t=[n,Zf(n)];for(let r of t){let i=E.join(r,...Kf);e.add(process.platform==="win32"?i+".exe":i)}return[...e]}function Wc(n){let e=[],t=process.env.DEVECO_HOME??process.env.DEVECO_PATH;if(t&&t.trim()){for(let i of Hc(t.trim()))if(e.push(i),x.existsSync(i))return i}let r=n??be();if(r){for(let i of Hc(r))if(e.push(i),x.existsSync(i))return i}return null}function hr(n){return E.join(n,...Do)}function be(){if(process.platform==="win32"){let n=[E.join("C:\\Program Files",Po,_c),E.join("C:\\Program Files (x86)",Po,_c)];return Fc(n)}if(process.platform==="darwin"){let n=["/Applications/DevEco Studio.app",E.join(process.env.HOME??"","Applications","DevEco Studio.app")];return Fc(n)}return null}function Fc(n){for(let e of n)if(x.existsSync(e))return e;return null}function de(n){return process.platform==="darwin"?E.join(n,"Contents"):n}function Xf(n){if(!n||!x.existsSync(n)||!Uc(n))return!1;let e=de(n);return[E.join(e,"plugins","openharmony"),E.join(e,"sdk"),E.join(e,"tools")].some(r=>x.existsSync(r))}function Uc(n){try{return x.statSync(n).isDirectory()}catch{return!1}}function Io(n,e){return!n||!x.existsSync(n)?!1:e===$c.DevEcoStudio?Xf(n):!1}function fr(n,e=$c.DevEcoStudio){if(!n)return"";if(Io(n,e))return n;let t=Qf(n,e);if(t)return t;let r=eg(n,e);return r||n}function Qf(n,e){let t=n;for(let r=0;r<jc;r++){let i=E.dirname(t);if(!i||i===t)break;if(Io(i,e))return i;t=i}return null}function eg(n,e){if(!x.existsSync(n)||!Uc(n))return null;let t=[{p:n,depth:0}];for(;t.length>0;){let{p:r,depth:i}=t.shift();if(i>=jc)continue;let o=tg(r,i,e,t);if(o)return o}return null}function tg(n,e,t,r){let i;try{i=x.readdirSync(n,{withFileTypes:!0})}catch{return null}for(let o of i){if(!o.isDirectory())continue;let s=E.join(n,o.name);if(Io(s,t))return s;r.push({p:s,depth:e+1})}return null}function zc(n){return new Promise(e=>setTimeout(e,n))}var ng=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function gr(n){let e=E.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&ng.has(e)}function qc(n){return E.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function ue(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function rg(n){return ue(n)}function at(n){let e=rg(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function At(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??E.join(mr.homedir(),"AppData","Local");return E.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?E.join(mr.homedir(),"Library","Logs","devecocli-mcp-server"):E.join(mr.homedir(),".local","share","devecocli-mcp-server","logs")}function Gc(n,e){let t=ig(e),r=og(t,n);if(r!==null)return r;let i=Date.now(),s=`${n.replace(/:/g,"\\:")}=${i}`,a=sg(t,n,s);return ag(e,a),i}function ig(n){let e;try{e=x.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function og(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let o=parseInt(t.slice(r+1),10);return Number.isFinite(o)&&o>0?o:null}return null}function sg(n,e,t){let r=!1,i=n.map(o=>{if(r)return o;let s=o.indexOf("=");return s<=0?o:o.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):o});return r||i.push(t),i}function ag(n,e){try{x.mkdirSync(E.dirname(n),{recursive:!0})}catch{}try{x.writeFileSync(n,e.join(`
1258
1260
  `)+`
1259
- `,"utf8")}catch{}}function yo(n,e,t="[Cleanup]"){try{let r=P.dirname(n);if(!T.existsSync(r))return;let i=Date.now();for(let o of T.readdirSync(r,{withFileTypes:!0}))o.isDirectory()&&qf(P.join(r,o.name),i,e,t)}catch{}}function qf(n,e,t,r){try{let{mtimeMs:i}=T.statSync(n);if(e-i<=t)return;T.rmSync(n,{recursive:!0,force:!0});let o=Math.floor((e-i)/1e3);console.error(`${r} Removed expired dir (age ${Math.floor(o/86400)}d ${Math.floor(o%86400/3600)}h): ${n}`)}catch(i){console.error(`${r} Failed to remove expired dir ${n}: ${i}`)}}function lr(n){let e=n.replace(/sdk\/?$/i,"tools"),t=process.platform==="win32"?"node.exe":"node",r=P.join(e,"node",t);return T.existsSync(r)||process.platform!=="win32"&&(r=P.join(e,"node","bin","node"),T.existsSync(r))?r:process.execPath??"node"}import*as k from"fs";import*as ur from"path";var Fc="mcp-server.log",Gf="mcp-server",Yf={maxSize:10*1024*1024,maxFiles:4},vo=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={...Yf,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=St(),this.currentLogFile=ur.join(this.logDir,Fc),k.existsSync(this.logDir)||k.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${i}`}getRotatedFileName(e,t){return ur.join(this.logDir,`${Gf}-${e}.log.${t}`)}fileExists(e){try{return k.accessSync(e,k.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=k.readdirSync(this.logDir),t=[];for(let i of e)if(i===Fc||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=ur.join(this.logDir,i),s=k.statSync(o);t.push({name:i,mtime:s.mtime,path:o})}t.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let i=r;i<t.length;i++)try{k.unlinkSync(t[i].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&k.unlinkSync(t);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(e,i),s=this.getRotatedFileName(e,i+1);this.fileExists(o)&&k.renameSync(o,s)}let r=this.getRotatedFileName(e,1);k.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=k.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=k.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{k.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...r){if(this.mode==="silent"||n.LEVEL_ORDER[e]<n.LEVEL_ORDER[this.minLevel])return;let i=r.map(c=>typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),o=i?`${t} ${i}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] ${o}
1260
- `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);k.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{k.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},ue=null;function dn(n=!1){ue&&ue.dispose(),ue=new vo(n)}function jc(){ue&&(ue.dispose(),ue=null)}function $c(){ue&&ue.flush()}function Wc(){return ue?.getLogFilePath()??null}function Bc(){return ue?.getLogDirectory()??null}function dr(){return ue||dn(!1),ue}var h={debug:(n,...e)=>dr().debug(n,...e),info:(n,...e)=>dr().info(n,...e),warn:(n,...e)=>dr().warn(n,...e),error:(n,...e)=>dr().error(n,...e)};function Uc(n){return"method"in n&&!("id"in n)}import{spawn as Jf}from"child_process";import{EventEmitter as Kf}from"events";import*as Pt from"fs";import*as Zc from"path";import*as zc from"util";var wo="";function qc(n){if(!n||n==="auto"||n==="stdout"||n==="none"){wo="";return}wo=n}function Gc(){return wo||(Bc()??"")}function pr(n,...e){if(e.length===0)return n;try{return zc.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var d={info(n,...e){h.info(`[lsp] ${pr(n,...e)}`)},warn(n,...e){h.warn(`[lsp] ${pr(n,...e)}`)},error(n,...e){h.error(`[lsp] ${pr(n,...e)}`)},debug(n,...e){h.debug(`[lsp] ${pr(n,...e)}`)}};import*as un from"fs";import*as pn from"os";import*as Et from"path";import Vf from"json5";var g={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",BROADCAST:"lsp/broadcast"},A="2.0";var Yc=8192,bo=100,Vc=.03,Jc=.7,Fe=900*1e3;function te(n){if(!un.existsSync(n))return null;try{let e=un.readFileSync(n,"utf-8");return e.trim()?Vf.parse(e):null}catch{return null}}function mr(n,e){let t=Math.floor(pn.totalmem()/1048576),r=Math.floor(t*Jc),i,o;e!==void 0&&Number.isFinite(e)&&e>0?(i=e,o=`override(${e})`):(i=Yc,n>bo&&(i+=(n-bo)*Vc*1024),o=`formula(moduleCount=${n})`);let s=r>0&&i>r;s&&(i=r);let a=Math.round(i);return d.info(`[computeLspServerMaxSize] source=${o}, physicalTotal=${t}MB, physicalCap(70%)=${r}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function je(n){if(n.startsWith("file:"))return n;try{let e=Et.resolve(n),t=new URL(`file://${e}`).toString();if(pn.platform()==="win32"){let r=t.match(/^file:\/\/\/([A-Za-z]):/);if(r){let i=r[1].toUpperCase(),o=t.substring(`file:///${r[1]}:`.length);t=`file:///${i}%3A${o}`}}return t}catch{return n}}function hr(n){return n&&n.replace(/\\/g,"/")}function F(n){let e=Et.normalize(n).replace(/\\/g,"/");if(pn.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function Kc(n){return Et.join(n,"build-profile.json5")}var Ct=class extends Kf{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;ensureDirectories(){let t=Zc.join(this.config.logPath,"lspLog");return Pt.existsSync(t)||Pt.mkdirSync(t,{recursive:!0}),Pt.existsSync(this.config.indexingDataLocation)||Pt.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let r=this.ensureDirectories();d.info(`[LspClient] serverMaxSize=${t}MB`);let i=F(r),o=["--expose-gc",`--max-old-space-size=${t}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${i}`,this.config.serverPath,"--stdio",`--logger-path=${i}`,"--logger-level=TRACE"];d.info(`[LspClient] Starting process: node ${o.join(" ")}`);let s=process.execPath??"node";d.info(`[LspClient] nodePath: ${s}`),this.process=Jf(s,o,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0}),this.process.stdout?.on("data",a=>{this.handleData(a)}),this.process.stderr?.on("data",a=>{let c=a.toString("utf8").trim();d.error(`[LspClient] stderr: ${c}`),this.isClosing||this.emit("error",new Error(`[LspClient] stderr: ${c}`))}),this.process.on("exit",a=>{d.info(`[LSP EXIT] code=${a}`),this.isClosing||this.emit("error",new Error(`LSP process exited with code ${a}`))}),await new Promise(a=>setTimeout(a,500)),d.info("[LspClient] start lsp process success")}sendRaw(t,r){if(!this.process?.stdin?.writable){d.warn("[LspClient] Cannot send message, stdin not writable");return}d.info(`[LspClient] send message: ${r}`);let i=this.buildLspMessage(t);this.process.stdin.write(i,"utf8")}send(t,r,i){let o={jsonrpc:"2.0",method:t,params:r};i!==void 0&&(o.id=i),this.sendRaw(JSON.stringify(o),t)}sendNotification(t,r){this.sendRaw(JSON.stringify({jsonrpc:"2.0",method:t,params:r}),t)}sendRequest(t,r,i){this.sendRaw(JSON.stringify({jsonrpc:"2.0",id:i,method:t,params:r}),t)}buildLspMessage(t){return`Content-Length: ${Buffer.from(t,"utf8").length}\r
1261
+ `,"utf8")}catch{}}function Ao(n,e,t="[Cleanup]"){try{let r=E.dirname(n);if(!x.existsSync(r))return;let i=Date.now();for(let o of x.readdirSync(r,{withFileTypes:!0}))o.isDirectory()&&cg(E.join(r,o.name),i,e,t)}catch{}}function cg(n,e,t,r){try{let{mtimeMs:i}=x.statSync(n);if(e-i<=t)return;x.rmSync(n,{recursive:!0,force:!0});let o=Math.floor((e-i)/1e3);console.error(`${r} Removed expired dir (age ${Math.floor(o/86400)}d ${Math.floor(o%86400/3600)}h): ${n}`)}catch(i){console.error(`${r} Failed to remove expired dir ${n}: ${i}`)}}function yr(n){let e=n.replace(/sdk\/?$/i,"tools"),t=process.platform==="win32"?"node.exe":"node",r=E.join(e,"node",t);return x.existsSync(r)||process.platform!=="win32"&&(r=E.join(e,"node","bin","node"),x.existsSync(r))?r:process.execPath??"node"}import*as R from"fs";import*as wr from"path";var Vc="mcp-server.log",lg="mcp-server",dg={maxSize:10*1024*1024,maxFiles:4},xo=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={...dg,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=At(),this.currentLogFile=wr.join(this.logDir,Vc),R.existsSync(this.logDir)||R.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${i}`}getRotatedFileName(e,t){return wr.join(this.logDir,`${lg}-${e}.log.${t}`)}fileExists(e){try{return R.accessSync(e,R.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=R.readdirSync(this.logDir),t=[];for(let i of e)if(i===Vc||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=wr.join(this.logDir,i),s=R.statSync(o);t.push({name:i,mtime:s.mtime,path:o})}t.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let i=r;i<t.length;i++)try{R.unlinkSync(t[i].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&R.unlinkSync(t);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(e,i),s=this.getRotatedFileName(e,i+1);this.fileExists(o)&&R.renameSync(o,s)}let r=this.getRotatedFileName(e,1);R.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=R.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=R.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{R.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...r){if(this.mode==="silent"||n.LEVEL_ORDER[e]<n.LEVEL_ORDER[this.minLevel])return;let i=r.map(c=>typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),o=i?`${t} ${i}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] ${o}
1262
+ `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);R.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{R.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},pe=null;function fn(n=!1){pe&&pe.dispose(),pe=new xo(n)}function Yc(){pe&&(pe.dispose(),pe=null)}function Jc(){pe&&pe.flush()}function Kc(){return pe?.getLogFilePath()??null}function Zc(){return pe?.getLogDirectory()??null}function vr(){return pe||fn(!1),pe}var h={debug:(n,...e)=>vr().debug(n,...e),info:(n,...e)=>vr().info(n,...e),warn:(n,...e)=>vr().warn(n,...e),error:(n,...e)=>vr().error(n,...e)};function Xc(n){return"method"in n&&!("id"in n)}import{spawn as pg}from"child_process";import{EventEmitter as mg}from"events";import*as Tt from"fs";import*as sl from"path";import*as Qc from"util";var To="";function el(n){if(!n||n==="auto"||n==="stdout"||n==="none"){To="";return}To=n}function tl(){return To||(Zc()??"")}function br(n,...e){if(e.length===0)return n;try{return Qc.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var d={info(n,...e){h.info(`[lsp] ${br(n,...e)}`)},warn(n,...e){h.warn(`[lsp] ${br(n,...e)}`)},error(n,...e){h.error(`[lsp] ${br(n,...e)}`)},debug(n,...e){h.debug(`[lsp] ${br(n,...e)}`)}};import*as gn from"fs";import*as yn from"os";import*as xt from"path";import ug 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",BROADCAST:"lsp/broadcast"},A="2.0";var nl=8192,ko=100,rl=.03,il=.7,We=900*1e3;function ae(n){if(!gn.existsSync(n))return null;try{let e=gn.readFileSync(n,"utf-8");return e.trim()?ug.parse(e):null}catch{return null}}function Sr(n,e){let t=Math.floor(yn.totalmem()/1048576),r=Math.floor(t*il),i,o;e!==void 0&&Number.isFinite(e)&&e>0?(i=e,o=`override(${e})`):(i=nl,n>ko&&(i+=(n-ko)*rl*1024),o=`formula(moduleCount=${n})`);let s=r>0&&i>r;s&&(i=r);let a=Math.round(i);return d.info(`[computeLspServerMaxSize] source=${o}, physicalTotal=${t}MB, physicalCap(70%)=${r}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function Ue(n){if(n.startsWith("file:"))return n;try{let e=xt.resolve(n),t=new URL(`file://${e}`).toString();if(yn.platform()==="win32"){let r=t.match(/^file:\/\/\/([A-Za-z]):/);if(r){let i=r[1].toUpperCase(),o=t.substring(`file:///${r[1]}:`.length);t=`file:///${i}%3A${o}`}}return t}catch{return n}}function Er(n){return n&&n.replace(/\\/g,"/")}function j(n){let e=xt.normalize(n).replace(/\\/g,"/");if(yn.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function ol(n){return xt.join(n,"build-profile.json5")}var kt=class extends mg{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;ensureDirectories(){let t=sl.join(this.config.logPath,"lspLog");return Tt.existsSync(t)||Tt.mkdirSync(t,{recursive:!0}),Tt.existsSync(this.config.indexingDataLocation)||Tt.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let r=this.ensureDirectories();d.info(`[LspClient] serverMaxSize=${t}MB`);let i=j(r),o=["--expose-gc",`--max-old-space-size=${t}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${i}`,this.config.serverPath,"--stdio",`--logger-path=${i}`,"--logger-level=TRACE"];d.info(`[LspClient] Starting process: node ${o.join(" ")}`);let s=process.execPath??"node";d.info(`[LspClient] nodePath: ${s}`),this.process=pg(s,o,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0}),this.process.stdout?.on("data",a=>{this.handleData(a)}),this.process.stderr?.on("data",a=>{let c=a.toString("utf8").trim();d.error(`[LspClient] stderr: ${c}`),this.isClosing||this.emit("error",new Error(`[LspClient] stderr: ${c}`))}),this.process.on("exit",a=>{d.info(`[LSP EXIT] code=${a}`),this.isClosing||this.emit("error",new Error(`LSP process exited with code ${a}`))}),await new Promise(a=>setTimeout(a,500)),d.info("[LspClient] start lsp process success")}sendRaw(t,r){if(!this.process?.stdin?.writable){d.warn("[LspClient] Cannot send message, stdin not writable");return}d.info(`[LspClient] send message: ${r}`);let i=this.buildLspMessage(t);this.process.stdin.write(i,"utf8")}send(t,r,i){let o={jsonrpc:"2.0",method:t,params:r};i!==void 0&&(o.id=i),this.sendRaw(JSON.stringify(o),t)}sendNotification(t,r){this.sendRaw(JSON.stringify({jsonrpc:"2.0",method:t,params:r}),t)}sendRequest(t,r,i){this.sendRaw(JSON.stringify({jsonrpc:"2.0",id:i,method:t,params:r}),t)}buildLspMessage(t){return`Content-Length: ${Buffer.from(t,"utf8").length}\r
1261
1263
  \r
1262
1264
  ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this.buffer.indexOf(`\r
1263
1265
  \r
1264
- `);if(r===-1)break;let o=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!o){d.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(o[1],10),a=r+4,c=a+s;if(this.buffer.length<c)break;let l=this.buffer.slice(a,c).toString("utf8"),u=this.recoverFramedJson(l);if(u&&u.rest.length>0){d.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${l.length}, restLen=${u.rest.length}`),this.emit("message",u.json),this.buffer=Buffer.concat([Buffer.from(u.rest,"utf8"),this.buffer.slice(c)]);continue}this.emit("message",l),this.buffer=this.buffer.slice(c)}}waitForExitOrTimeout(t){let r=this.process;return!r||r.exitCode!==null||r.signalCode!==null?Promise.resolve():new Promise(i=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(c),r.off("exit",a),i())},a=()=>s();r.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let r=t.search(/\S/);if(r<0||t[r]!=="{"&&t[r]!=="[")return null;let i=0,o=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(o=!1);continue}if(c==='"'){o=!0;continue}if(c==="{"||c==="["){i++;continue}if((c==="}"||c==="]")&&(i--,i===0)){let l=t.slice(r,a+1),u=t.slice(a+1);return{json:l,rest:u}}}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 It=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,r){return new Promise((i,o)=>{let s;r>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),o(new Error(`LSP request '${t}' (id=${e}) timeout after ${r}ms`))},r),this.timeouts.set(e,s)),this.pending.set(e,{resolve:i,reject:o,method:t,timer:s})})}resolvePending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.resolve(t),this.pending.delete(e),!0):!1}rejectPending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.reject(t),this.pending.delete(e),!0):!1}register(e,t){this.callbacks.set(e,t)}emit(e,t,r){d.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let i=this.callbacks.get(e);if(i)i(t,r),this.callbacks.delete(e);else{let o=[...this.callbacks.keys()].map(s=>String(s));d.info(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${o.join(",")}]`)}}registerTimeout(e,t,r,i){let o=this.timeouts.get(e);o&&clearTimeout(o);let s=setTimeout(()=>{d.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`),i(),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 fr=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var Dt=class{map=new Map;register(e,t){let r=this.map.get(e);r||(r=new Set,this.map.set(e,r)),r.add(t)}unregister(e,t){let r=this.map.get(e);r&&(t!==void 0?r.delete(t):r.clear(),r.size===0&&this.map.delete(e))}invoke(e,...t){let r=this.map.get(e);if(r)for(let i of r)try{i(...t)}catch(o){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,o)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function S(n){return typeof n=="object"&&n!==null}var Xc=20*1e3,Zf=30*1e3,gr=class{client;nextRequestId=1;stopOnce=null;callbacks=new Dt;requestCallbacks=new It;diagnosticMap=new Map;initProgressReset=null;constructor(e){this.client=new Ct(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()=>{d.info("[ClientMessageHandle] Sending shutdown request"),this.client.sendRequest(g.SHUTDOWN,null,this.nextRequestId++),d.info("[ClientMessageHandle] Sending exit notification"),this.client.sendNotification(g.EXIT,null),d.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),d.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(g.BROADCAST),this.callbacks.register(g.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(g.BROADCAST,e)}async sendInitialize(e){let t=this.nextRequestId++,r=this.requestCallbacks.registerPending(t,g.INITIALIZE,Fe);return this.client.sendRequest(g.INITIALIZE,e,t),r}sendInitializeResettable(e,t){let r=this.nextRequestId++,i=this.requestCallbacks.registerPending(r,g.INITIALIZE,0);return this.client.sendRequest(g.INITIALIZE,e,r),new Promise((o,s)=>{let a,c=()=>{a=setTimeout(()=>{this.initProgressReset=null,s(new Error(`LSP initialization timeout after ${t}ms`))},t)},l=()=>{clearTimeout(a),c()};this.initProgressReset=l,c(),i.then(()=>{clearTimeout(a),this.initProgressReset=null,o()},u=>{clearTimeout(a),this.initProgressReset=null,s(u)})})}sendInitialized(){this.client.sendNotification(g.INITIALIZED,{})}sendDidOpen(e){let t=e.textDocument.uri;this.diagnosticMap.has(t)||(this.diagnosticMap.set(t,new fr(t)),this.registerDiagnosticTimeout(t)),this.client.sendNotification(g.DID_OPEN,e)}sendDidChange(e){let t=e.textDocument.uri,r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t)),this.client.sendNotification(g.DID_CHANGE,e)}closeFile(e){this.cleanupDiagnosticState(e.textDocument.uri),this.client.sendNotification(g.DID_CLOSE,e)}sendLspRequest(e,t,r=Zf){let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}onDidChangeWatchedFiles(e){e.length!==0&&this.client.sendNotification(g.WORKSPACE_DID_CHANGE_WATCHED_FILES,{changes:e})}sendDidChangeConfiguration(e){this.client.sendNotification(g.WORKSPACE_DID_CHANGE_CONFIGURATION,{settings:e})}sendNotification(e,t){this.client.sendNotification(e,t)}getDiagnosticMessages(e){let t=this.diagnosticMap.get(e);return t?t.get():[]}clearDiagnostic(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let i=r instanceof Error?r.message:String(r);d.error(`[LSP] JSON parse error: ${i}, raw: ${e}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotificationOrRequest(t):d.warn(`[LSP] Unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t===void 0)return;let r=t;if(e.error){let i=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(r,i)}else this.requestCallbacks.resolvePending(r,e.result)}handleNotificationOrRequest(e){let t=e.method;if(t)switch(this.initProgressReset?.(),t){case g.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case g.PROGRESS:this.handleProgress(e.params);break;case g.WINDOW_SHOW_MESSAGE:d.info(`[LSP] window/showMessage: ${JSON.stringify(e.params)}`);break;case g.WINDOW_LOG_MESSAGE:d.info(`[LSP] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.broadcastToClients(e)}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=e.uri,r=this.diagnosticMap.get(t);if(!r)return;let i=e.diagnostics||[];this.normalizeDiagnostics(i),r.set(i),this.finalizeDiagnostic(t,i)}normalizeDiagnostics(e){for(let t of e)if(t.severity!==void 0){let r={1:"Error",2:"Warning",3:"Information",4:"Hint"};t.severityStr=r[t.severity]||"Unknown"}}handleProgress(e){S(e)&&this.broadcastToClients({jsonrpc:A,method:g.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,g.PUBLISH_DIAGNOSTICS,Xc,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${Xc}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,r){let i={uri:e,diagnostics:t,...r?{errorMessage:r}:{}};this.requestCallbacks.emit(e,g.PUBLISH_DIAGNOSTICS,i),this.diagnosticMap.get(e)?.clear()}handleError(e){let t=Array.from(this.diagnosticMap.keys()).filter(r=>this.requestCallbacks.hasCallback(r));if(t.length>0){let r={range:{start:{line:0,character:0},end:{line:0,character:0}},severity:1,message:e.message};for(let i of t)this.finalizeDiagnostic(i,[r]);return}this.broadcastToClients({jsonrpc:A,method:g.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var yr=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)){d.info(`[LegacyDiagnostic] addMessage: duplicate message=${r}`);return}this.uniqueMessages.add(r),this.messages.push(new So(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)}},So=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var Xf={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"},Qf={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"},I={...Xf,...Qf},$e={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"},Qc=new Set([1e3,2e3,3e3,3001]);function eg(n){if(!S(n))return!1;let e=n.textDocument;return S(e)&&typeof e.uri=="string"}function tg(n){return S(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function ng(n){return S(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 vr=class n{client;isInitialized=!1;stopOnce=null;callbacks=new Dt;requestCallbacks=new It;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;constructor(e){this.client=new Ct(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()=>{d.info("[LegacyClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:A,method:I.EXIT,params:{}}),$e.EXIT),d.info("[LegacyClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),d.info("[LegacyClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(I.BROADCAST),this.callbacks.register(I.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(I.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(I.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(I.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:A,method:I.INITIALIZED,params:{editors:e}}),$e.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:A,id:0,result:{}}),$e.EMPTY)}sendAsyncRequest(e,t,r,i){if(!S(t)){d.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!eg(t)){d.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof r!="number"){d.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(r)}`);return}let o=t.textDocument.uri,s=je(o);t.textDocument.uri=s,delete t.requestId;let a=i??e;d.info(`[LSP] sendAsyncRequest ${a}, filePath: ${o}`),this.client.sendRaw(JSON.stringify({jsonrpc:A,method:e,params:{params:t,requestId:r}}),a)}onDidChangeWatchedFiles(e){if(d.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let r of e){if(!tg(r)){d.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:A,method:I.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),I.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!S(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){d.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;d.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:A,method:I.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),$e.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let i=je(t);e.textDocument.uri=i,d.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new yr(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,I.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:A,method:I.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),$e.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=je(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,I.PUBLISH_DIAGNOSTICS)),d.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:A,method:I.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),$e.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=je(e);d.info(`[LSP] didClose, uri: ${r}`);let i=this.diagnosticMap.get(r);if(!t&&(!i||i.isFromEditor)){d.info(`[LSP] closeFile skip, !diagnostic: ${!i}, isFromEditor: ${i?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:A,method:I.DID_CLOSE,params:{textDocument:{uri:r}}}),$e.DID_CLOSE)}getDiagnosticMessage(e){let t=je(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);d.error(`[LSP] JSON parse error: ${r}, raw: ${e}`)}}handleError(e){let t=this.getPendingDiagnosticUris();if(t.length>0){let r=JSON.stringify({message:e.message,severity:"Error",severityStr:"Error"});for(let i of t)this.finalizeDiagnostic(i,I.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:A,method:I.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 I.MODULE_INIT_FINISH:return d.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(I.MODULE_INIT_FINISH),this.callbacks.unregister(I.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case I.INDEXING_PROGRESS_UPDATE:return d.info(`[LSP] onIndexingProgressUpdate: ${ng(t.params)}`),this.callbacks.invoke(I.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case I.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case I.ON_PACKAGE_CHANGE_FINISH:d.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case I.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case I.ON_ASYNC_HOVER:this.handleAsyncResponse(t,I.HOVER);return;case I.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,I.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case I.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,I.REFERENCES);return;default:d.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){d.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;S(t)&&S(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){d.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,r={jsonrpc:A,method:I.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){d.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(r);return}if(!(t.length>0&&t[0]===!0)){d.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(r);return}d.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){d.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let r=e.params;if(!S(r)){d.warn("[LSP] aceProject/onAsyncHover message invalid");return}let i=r.requestId;if(typeof i!="number"){d.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(i,t,r)}handleForceOpenFile(e){if(!e){d.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,I.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){d.info("[LSP] publishDiagnostics uri is null");return}let r=e.version??-1;if(r===-1)return;let i=this.diagnosticMap.get(t);if(!i){d.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let o=e.diagnostics||[];o.length!==0?o.forEach(s=>{this.normalizeDiagnostic(s),i.addMessage(r,JSON.stringify(s))}):i.setReceivedType(r),i.hasReceivedAllTypes(Qc)&&this.finalizeDiagnostic(t,I.PUBLISH_DIAGNOSTICS,i.getMessages())}normalizeDiagnostic(e){let t=e;if(delete t.source,t.severity!==void 0){let r=typeof t.severity=="number"?t.severity:parseInt(t.severity),o={1:"Error",2:"Warning",3:"Information",4:"Hint"}[r]||"Unknown";t.severityStr=o,t.severity=o}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let r=e[t];r&&typeof r.line=="number"&&(r.line=r.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,n.DIAGNOSTIC_TIMEOUT_MS,()=>{let r=this.diagnosticMap.get(e),i=r?r.getMessages():[];this.finalizeDiagnostic(e,t,i,i.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,i){let o={uri:e,diagnostics:r,...i?{errorMessage:i}:{}};this.requestCallbacks.emit(e,t,o),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import vn from"path";import*as Ir from"path";var wr=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var br=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var Sr=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var Er=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Pr=class{typeSetting=new Sr;parameterNames=new Er};var Cr=class{constructor(e,t,r,i){this.rootUri=e;this.lspServerWorkspacePath=F(Ir.dirname(t)),this.indexingDataLocation=F(i),this.loggerPath=F(Ir.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new wr;gutterIconsSetting=new br;inlayHintsSetting=new Pr;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as el from"path";var mn=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(F(el.join(e,"src","main","resources")))}};var rg="OS",At=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${rg}`;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 mn(e)):this.buildProfileParam=new mn}toString(){return JSON.stringify(this)}};var Tt=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as pe from"path";import*as Rt from"fs";var Dr=class{modulePath;dependencies={};dynamicDependencies={}};var rt=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 xt=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 xe from"path";import*as Ar from"fs";var kt=class{name="";version="";storePath="";dependencyPath="";path=""};var C={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:"oh-package.json5",SYNC_OUTPUT_FILE:"output.json",ENV_FORCE_SYNC:"DEVECO_MCP_FORCE_SYNC"},hn=`${C.HVIGOR_CACHE}/${C.DEPENDENCY}`,it=`${C.DEPENDENCY}${C.JSON5}`,tl=`${C.HVIGOR_CACHE}/outputs/sync/${C.SYNC_OUTPUT_FILE}`;var fn=class n{dependencyPath;modulePath;projectPath;static FILE_DEPENDENCY_PREFIX="file:";static PARAMETER_PREFIX="@param:";fileSpecPattern;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;static PACKAGE_JSON_PARSER_MAP=new Map;dependencies=[];devDependencies=[];dynamicDependencies=[];static getInstance(e,t,r){let i=this.PACKAGE_JSON_PARSER_MAP.get(e);return i||(i=new n(e,t,r),this.PACKAGE_JSON_PARSER_MAP.set(e,i)),i}constructor(e,t,r){this.dependencyPath=e,this.modulePath=t,this.projectPath=r,this.fileSpecPattern=n.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=xe.join(this.dependencyPath,C.OH_PACKAGE_JSON5),r=te(t);r&&(this.dependencies=this.getDependencyList(r,C.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(r,C.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(r,C.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let r=[];if(!S(e))return r;let i=e[t];if(!S(i))return r;for(let[o,s]of Object.entries(i)){if(typeof s!="string"){d.error(`${o} package dependency value is not String ${t}`);continue}let a=new kt;a.name=o;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(n.PARAMETER_PREFIX)||this.parseDependencyPath(o,c,a,!1),r.push(a)}return r}parseDependencyPath(e,t,r,i){if(!(!e||!t))try{let o=xe.normalize(xe.join(this.modulePath,C.OH_MODULES_PATH,e));if(!(t.startsWith(n.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){r.dependencyPath=o;return}if(r.path=t,this.fileNameForOhpm.test(t)){r.dependencyPath=o;return}let s=t;if(t.startsWith(n.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(n.FILE_DEPENDENCY_PREFIX.length)),xe.isAbsolute(s)){r.dependencyPath=o;return}if(!i){let a=xe.resolve(this.modulePath,s);o=b.ensurePathWithinRoot(this.projectPath,a)}Ar.existsSync(o)&&Ar.statSync(o).isDirectory()&&(r.dependencyPath=o)}catch(o){d.error("parser dependency path is invalid",o)}}};import*as gn from"fs";import*as yn from"path";import ig from"json5";var Tr=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,C.OH_MODULES_PATH,C.OHPM_PATH,C.LOCK_JSON5_FILE)}readLockFile(e){if(!gn.existsSync(e))return d.error("lock file does not exist"),this.clearDependencies(),null;try{let t=gn.readFileSync(e,"utf8"),r=ig.parse(t);return r||(d.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return d.error("Error parsing lock.json5:",t),this.clearDependencies(),null}}validateLockFile(e){if(!S(e))return d.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return d.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let r=e.packages;return r?{valid:!0,modules:t,packages:r}:(d.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,r){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,C.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,C.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,C.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!S(e))return t;for(let[r,i]of Object.entries(e)){if(!S(i)){d.error(`${r} value is not json object`);continue}typeof i.storePath=="string"&&t.set(r,i.storePath)}return t}getDependencyList(e,t,r){if(!S(e))return[];for(let[i,o]of Object.entries(e))if(S(o)){let s=typeof o.name=="string"?o.name:"";if(r==="."&&s===""||s===r)return this.getFinalDependencyList(e,t,i)}return[]}getFinalDependencyList(e,t,r){let i=e[r];if(!S(i))return d.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!S(s))return[];for(let[a,c]of Object.entries(s)){if(!S(c))continue;let l=typeof c.specifier=="string"?c.specifier:"",u=typeof c.version=="string"?c.version:"",f=new kt;f.name=a,f.version=u.startsWith(n.FILE_DEPENDENCY_PREFIX)?u.substring(n.FILE_DEPENDENCY_PREFIX.length):u,this.parseDependencyPath(f,r,a,l,u);let E=`${a}@${u}`;this.storePathMap.has(E)&&(f.storePath=this.storePathMap.get(E)||""),o.push(f)}return o}parseDependencyPath(e,t,r,i,o){let s=b.resolvePathWithinRoot(this.projectPath,yn.join(t,C.OH_MODULES_PATH,r));try{let a=o.startsWith(n.FILE_DEPENDENCY_PREFIX)?o.substring(n.FILE_DEPENDENCY_PREFIX.length):o,c=yn.isAbsolute(a)?b.ensurePathWithinRoot(this.projectPath,a):b.resolvePathWithinRoot(this.projectPath,a);gn.existsSync(c)?(e.path=i,e.dependencyPath=this.fileNameForOhpm.test(o)?s:c):e.dependencyPath=s}catch(a){d.error("Invalid dependency path in lock.json5",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};var ke=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=Kc(this.projectRoot);try{let t=te(e);if(typeof t!="object"||t===null)return[];let r=t.modules;return Array.isArray(r)?r.filter(i=>{if(typeof i!="object"||i===null)return!1;let o=i;return typeof o.name=="string"&&typeof o.srcPath=="string"}):[]}catch(t){return d.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};function nl(n){return S(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var ot=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new ke(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=pe.join(t,hn),i=pe.join(r,it);if(!Rt.existsSync(r)||!Rt.existsSync(i)){let c="Dependency map or JSON not found";return d.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let o=new xt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(r,o),this.parseLockJson(o);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return d.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];nl(l)&&(this.parseSingleModule(l,r,o,e),(c+1)%100===0&&d.info(`[Parser] getAllDependencyMap progress: ${c+1}/${s.length} (${Date.now()-a}ms)`))}return d.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-a}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],r=this.projectPath,i=pe.join(r,hn),o=pe.join(i,it);if(!Rt.existsSync(i)||!Rt.existsSync(o))return d.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 xt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return d.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let l of c){if(!nl(l))continue;let u=l.name;if(s&&!s.has(u))continue;let f=b.resolvePathWithinRoot(this.projectPath,l.srcPath),E=pe.join(i,u),M=F(f),j=this.buildModuleDependencies(u,M,E,a);j.moduleName=u,t.push(j)}return t}parseSingleModule(e,t,r,i){let o=e.name,s=b.resolvePathWithinRoot(this.projectPath,e.srcPath),a=pe.join(t,o),c=F(s),l=new At(c),u=this.buildModuleDependencies(o,c,a,r);this.parseModuleJson5(c,l);let f=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=o,l.moduleType=o,l.packageName=o,l.moduleDependencies=u,l.moduleJsonParam=new Tt(f),i.push(l)}buildModuleDependencies(e,t,r,i){let o=new xt(this.projectPath,e,t);fn.getInstance(r,t,this.projectPath).parseDependency(o),this.parseLockJson(o),o.finalDependencies.push(...i.finalDependencies),o.finalDevDependencies.push(...i.finalDevDependencies),o.finalDynamicDependencies.push(...i.finalDynamicDependencies),o.finalDependencies.push(...o.finalDevDependencies);let a=new Dr;return a.modulePath=t,this.toModuleDependencies(o,a),a}toModuleDependencies(e,t){let r={},i={};for(let o of e.finalDependencies)r[o.name]=new rt(o);for(let o of e.finalDynamicDependencies)i[o.name]=new rt(o);t.dependencies=r,t.dynamicDependencies=i}parseProjectDependencies(e,t){let r=pe.join(e,C.OH_PACKAGE_JSON5);if(!Rt.existsSync(r))return;fn.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 Tr(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=pe.join(e,"src","main","module.json5"),i=te(r);if(!S(i)||!S(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(S(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)S(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=pe.join(e,"src","main","resources","base","profile","main_pages.json"),r=te(t);return!S(r)||!Array.isArray(r.src)?[]:r.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!S(t)||!S(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=pe.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=te(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!S(t)||!S(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!S(r)||typeof r.compatibleSdkVersion!="string")return;let[i,o]=this.parseBySplit(r.compatibleSdkVersion);e.compatibleSdkVersion=i,e.compatibleSdkLevel=o}getBuildProfile(){if(this.buildProfileCache===void 0){let e=pe.join(this.projectPath,"build-profile.json5");this.buildProfileCache=te(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,e];let r=e.substring(0,t),i=e.substring(t+1,e.length-1);return[r,i]}parseDeviceTypes(e){return!S(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 xr=class{constructor(e=[]){this.valueSet=e}valueSet};var Mt=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var rl=(v=>(v[v.File=1]="File",v[v.Module=2]="Module",v[v.Namespace=3]="Namespace",v[v.Package=4]="Package",v[v.Class=5]="Class",v[v.Method=6]="Method",v[v.Property=7]="Property",v[v.Field=8]="Field",v[v.Constructor=9]="Constructor",v[v.Enum=10]="Enum",v[v.Interface=11]="Interface",v[v.Function=12]="Function",v[v.Variable=13]="Variable",v[v.Constant=14]="Constant",v[v.String=15]="String",v[v.Number=16]="Number",v[v.Boolean=17]="Boolean",v[v.Array=18]="Array",v[v.Object=19]="Object",v[v.Key=20]="Key",v[v.Null=21]="Null",v[v.EnumMember=22]="EnumMember",v[v.Struct=23]="Struct",v[v.Event=24]="Event",v[v.Operator=25]="Operator",v[v.TypeParameter=26]="TypeParameter",v))(rl||{}),il=()=>Object.values(rl).filter(n=>typeof n=="number");var kr=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Rr=class{applyEdit=!0;workspaceEdit=new kr;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new xr(il());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Mt;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Mr=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Or=class{constructor(e=[]){this.valueSet=e}valueSet};var Lr=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var ol=(w=>(w[w.Text=1]="Text",w[w.Method=2]="Method",w[w.Function=3]="Function",w[w.Constructor=4]="Constructor",w[w.Field=5]="Field",w[w.Variable=6]="Variable",w[w.Class=7]="Class",w[w.Interface=8]="Interface",w[w.Module=9]="Module",w[w.Property=10]="Property",w[w.Unit=11]="Unit",w[w.Value=12]="Value",w[w.Enum=13]="Enum",w[w.Keyword=14]="Keyword",w[w.Snippet=15]="Snippet",w[w.Color=16]="Color",w[w.File=17]="File",w[w.Reference=18]="Reference",w[w.Folder=19]="Folder",w[w.EnumMember=20]="EnumMember",w[w.Constant=21]="Constant",w[w.Struct=22]="Struct",w[w.Event=23]="Event",w[w.Operator=24]="Operator",w[w.TypeParameter=25]="TypeParameter",w))(ol||{}),sl=()=>Object.values(ol).filter(n=>typeof n=="number");var Nr=class{completionItemKind=new Or(sl());completionItem=new Lr;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var _r=class{synchronization=new Mr;completion=new Nr;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 Mt;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var Hr=class{workspace=new Rr;textDocument=new _r;notebookDocument=null;window=null;general=null;experimental=null};var Fr=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var jr=class{constructor(e,t,r,i,o,s=!0){this.sdkPath=e;this.rootUri=r;this.nodeMaxOldSpaceSize=o;this.useStandardProtocol=s;this.serverPath=this.useStandardProtocol?vn.resolve(t,"ace-server","out","standardIndex","index.js"):vn.resolve(t,"ace-server","out","index.js"),this.logPath=Gc(),this.indexLogPath=i||this.logPath;let a={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath};this.messageHandle=this.useStandardProtocol?new gr(a):new vr(a),this.messageHandle.setBroadcastToClients(c=>this.onLspMessage(c))}sdkPath;rootUri;nodeMaxOldSpaceSize;useStandardProtocol;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=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}async start(e,t){let r=!1;try{d.info(`serverPath: ${this.serverPath}`),d.info(`rootUri: ${this.rootUri}`),d.info(`sdkPath: ${this.sdkPath}`),d.info(`logPath: ${this.logPath}`);let i=je(this.rootUri),o=new Cr(i,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new ot(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),o.modules=s;let l=mr(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new Fr(i,o,new Hr),this.useStandardProtocol){let u=this.messageHandle;await u.sendInitializeResettable(this.currentParams,Fe),d.info("[LSP] initialize response received"),u.broadcastToClients({jsonrpc:A,method:g.ARKTS_INDEXING_PROGRESS,params:{}}),u.sendInitialized()}else await this.startLegacy(this.currentParams,e);r=!0}catch(i){this.lastStartErrorMessage=i instanceof Error?i.message:String(i),d.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:A,method:g.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((i,o)=>{r.onIndexingProgressUpdate(o),r.onInitializationCompleted(i)},"LSP initialization",Fe),r.sendInitialized(t)}withResettableTimeout(e,t,r){return new Promise((i,o)=>{let s,a=()=>{s=setTimeout(()=>{o(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),i()},c)})}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){d.info(`[LSP] registerDiagnosticCallback uri='${e}', useStandardProtocol=${this.useStandardProtocol}`),this.messageHandle.registerRequestCallback(e,(t,r)=>{let i=S(r)?r:{};d.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let o={jsonrpc:A,method:t,params:{uri:typeof i.uri=="string"?i.uri:e,diagnostics:Array.isArray(i.diagnostics)?i.diagnostics:[],...typeof i.errorMessage=="string"?{errorMessage:i.errorMessage}:{}}};this.onLspMessage(o)})}async hover(e){let t=e.textDocument.uri;return this.registerDiagnosticCallback(t),this.stdHandle.sendLspRequest(g.HOVER,e)}async definition(e){return this.stdHandle.sendLspRequest(g.DEFINITION,e)}async references(e){return this.stdHandle.sendLspRequest(g.REFERENCES,e)}async completion(e){return this.stdHandle.sendLspRequest(g.COMPLETION,e)}async documentSymbol(e){return this.stdHandle.sendLspRequest(g.DOCUMENT_SYMBOL,e)}async diagnostic(e){return this.stdHandle.sendLspRequest(g.DIAGNOSTIC,e,120*1e3)}async sendFeatureRequest(e,t){return this.stdHandle.sendLspRequest(e,t)}reloadDependenciesOnly(e){let t=e?.fullReload??!1,r=new ot(this.rootUri,this.sdkPath),i=this.getModuleModelsByName();if(t){d.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let l=r.getDependenciesOnly();this.markDependencyTypesIncremental(l);let u=this.mergeDepsOnlyIntoModuleList(l,i);return this.applyModuleModelsUpdate(u),this.sendDidChangeConfiguration({moduleSet:u}),d.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${u.length}`),this.lastDepsOnlyForDiff=l,l}let o=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(o.length===0&&s.size===0)return d.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];d.info(`[LspServerProxy] Module-level deps changed, parsing: [${o.join(", ")}]`);let a=r.getDependenciesOnly(o);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),this.sendDidChangeConfiguration({moduleSet:c}),d.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}sendDidChangeConfiguration(e){this.stdHandle.sendDidChangeConfiguration(e)}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),r=new Map(this.lastDepsOnlyForDiff.map(i=>[i.moduleName??"",i]));for(let i of e){let o=i.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(o,t,r),c=i.dependencies??{},l=i.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(u,f)=>{(i.dependencies??={})[u]=this.makeDeleteEntry(u,f)}),this.markAddAndDeleteInDeps(a,l,(u,f)=>{(i.dynamicDependencies??={})[u]=this.makeDeleteEntry(u,f)})}}getOldDepsForModule(e,t,r){let i=t.get(e),o=i?.moduleDependencies?.dependencies??{},s=i?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(o).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(o=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:o,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let i of Object.keys(t))i in e||(t[i].type="add");for(let i of Object.keys(e))i in t||r(i,e[i])}makeDeleteEntry(e,t){return new rt({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new At(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new Tt([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let i of e){let o=i.moduleName??"",s=t.get(o);s?(s.modulePath=i.modulePath,s.moduleDependencies=i):s=this.createMinimalModelFromDepsItem(i),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let i=new Map(r.map(s=>[s.moduleName??"",s])),o=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=i.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,i.delete(a)),o.push(s)}for(let[,s]of i)o.push(this.createMinimalModelFromDepsItem(s));return o}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=hr(vn.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=hr(vn.join(t,"default/openharmony/ets/api")),o=hr(vn.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=i,s.hosSdkPath=o}sendRequest(e){switch(e.method){case g.HOVER:this.stdHandle.sendLspRequest(g.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:A,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:A,id:e.id,error:{code:-32603,message:t.message}}));break;case g.DEFINITION:this.stdHandle.sendLspRequest(g.DEFINITION,e.params).then(t=>this.onLspMessage({jsonrpc:A,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:A,id:e.id,error:{code:-32603,message:t.message}}));break;case g.REFERENCES:this.stdHandle.sendLspRequest(g.REFERENCES,e.params).then(t=>this.onLspMessage({jsonrpc:A,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:A,id:e.id,error:{code:-32603,message:t.message}}));break;default:d.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!Uc(e)){d.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case g.DID_OPEN:this.handleDidOpenNotification(e);break;case g.DID_CHANGE:this.handleDidChangeNotification(e);break;case g.DID_CLOSE:this.handleDidCloseNotification(e);break;case g.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;case g.DID_CREATE_FILES:this.handleDidCreateFiles(e);break;case g.DID_DELETE_FILES:this.handleDidDeleteFiles(e);break;default:d.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){d.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"){d.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"){d.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(g.DID_CREATE_FILES,t)}handleDidDeleteFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(g.DID_DELETE_FILES,t)}async dispose(){await this.messageHandle.stop()}};import*as Re from"fs";import*as We from"path";import{createHash as sg}from"crypto";import{EventEmitter as ag}from"events";var $r=class extends ag{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r}projectRoot;watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),r=new Set(this.watchers.keys());for(let i of t)r.has(i)||this.watchFile(i);for(let i of r)t.has(i)||(this.unwatchFile(i),d.info(`[ConfigFileWatcher] Stopped watching: ${i}`));d.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!Re.existsSync(t)){d.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Re.watch(t,r=>{r==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",r=>{d.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${r.message}`)}),d.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(r){d.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${r instanceof Error?r.message:String(r)}`)}}emitModuleAddedEvents(t,r){for(let i of t){let o=b.resolvePathWithinRoot(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:o,relativePath:i.srcPath,timestamp:r,moduleName:i.name})}}emitModuleRemovedEvents(t,r){for(let i of t){let o=b.resolvePathWithinRoot(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:o,relativePath:i.srcPath,timestamp:r,removedModuleName:i.name})}}emitModuleRenamedEvents(t,r){for(let i of t){let o=b.resolvePathWithinRoot(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name,removedModuleName:i.before.name})}}emitModuleMovedEvents(t,r){for(let i of t){let o=b.resolvePathWithinRoot(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let r=Date.now();this.emitModuleAddedEvents(t.added,r),this.emitModuleRemovedEvents(t.removed,r),this.emitModuleRenamedEvents(t.renamed,r),this.emitModuleMovedEvents(t.moved,r)}onBuildProfileChanged(){let t="__build_profile__",r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(o);if(s===this.lastModulesSnapshot){d.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,o);this.lastModules=o,this.lastModulesSnapshot=s,d.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,i)}computeModulesSnapshot(t){return t.map(i=>`${i.name}::${i.srcPath}`).sort().join("|")}diffModules(t,r){let i=this.buildModuleMatchState(r),o={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,i),this.matchRenamedModules(t,i,o),this.matchMovedModules(t,i,o),this.collectRemovedModules(t,i,o),this.collectAddedModules(r,i,o),o}buildModuleMatchState(t){let r=new Map,i=new Map;for(let o of t)r.set(o.srcPath,o),i.set(o.name,o);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:i}}matchExactModules(t,r){for(let i of t){let o=r.newBySrc.get(i.srcPath);o&&o.name===i.name&&(r.matchedOld.add(i),r.matchedNew.add(o))}}matchRenamedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newBySrc.get(o.srcPath);s&&!r.matchedNew.has(s)&&s.name!==o.name&&(i.renamed.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}matchMovedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newByName.get(o.name);s&&!r.matchedNew.has(s)&&s.srcPath!==o.srcPath&&(i.moved.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}collectRemovedModules(t,r,i){for(let o of t)r.matchedOld.has(o)||i.removed.push(o)}collectAddedModules(t,r,i){for(let o of t)r.matchedNew.has(o)||i.added.push(o)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=te(t);if(typeof r!="object"||r===null)return[];let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return d.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=We.join(this.projectRoot,C.OH_PACKAGE_JSON5);Re.existsSync(r)&&t.push(r);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=b.resolvePathWithinRoot(this.projectRoot,o.srcPath),a=We.join(s,C.OH_PACKAGE_JSON5);Re.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return We.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Re.readFileSync(t,"utf-8");return sg("sha256").update(r).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let r=this.computeFileHash(t);r&&this.contentHashes.set(t,r);let i=Re.watch(t,o=>{o==="change"&&this.onFileChanged(t)});i.on("error",o=>{d.error(`[ConfigFileWatcher] Watch error for ${t}: ${o.message}`)}),this.watchers.set(t,i)}catch(r){d.error(`[ConfigFileWatcher] Failed to watch ${t}: ${r instanceof Error?r.message:String(r)}`)}}unwatchFile(t){let r=this.watchers.get(t);r&&(r.close(),this.watchers.delete(t)),this.contentHashes.delete(t);let i=this.debounceTimers.get(t);i&&(clearTimeout(i),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.computeFileHash(t);if(!o){d.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===o){d.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,o),d.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:We.basename(t),relativePath:We.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,i)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),d.info("[ConfigFileWatcher] All watchers stopped")}};import*as Be from"fs";import*as ye from"path";import{createHash as cg}from"crypto";import{EventEmitter as lg}from"events";var Wr=class extends lg{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=ye.join(t,hn)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!Be.existsSync(this.depMapDir)){d.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=Be.watch(this.depMapDir,{recursive:!0},(t,r)=>this.onDirEvent(t,r)),this.dirWatcher.on("error",t=>{d.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){d.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),d.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return F(ye.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let i=r.replace(/\\/g,"/"),o;if(i===C.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===it)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=ye.join(this.depMapDir,r);Be.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,d.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=ye.join(this.depMapDir,C.OH_PACKAGE_JSON5),r=ye.join(this.depMapDir,it),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...i.map(s=>({path:ye.join(this.depMapDir,s.name,C.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!Be.existsSync(s))continue;let c=this.canonicalPath(s),l=this.computeFileHash(s);if(!l)continue;let u=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,l);continue}u!==l&&(this.contentHashes.set(c,l),d.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=ye.join(this.depMapDir,it);try{let r=te(t);if(typeof r!="object"||r===null)return[];let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return d.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${r instanceof Error?r.message:String(r)}`),[]}}scheduleCoalescedReload(t){this.pendingTags.push(t),t==="dep-map-json"&&this.applyDepMapJsonDiff(),this.coalesceTimer&&clearTimeout(this.coalesceTimer),this.coalesceTimer=setTimeout(()=>{this.coalesceTimer=null,this.flushPendingReload()},this.coalesceMs)}collectPendingState(){let t=this.pendingTags,r=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:r}}processTagsIntoSets(t,r,i,o){for(let s of t)s.startsWith("module:")?(i.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(i.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(o.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,i,o,s){for(let a of t)s.push(a.info),i.add(a.info.newName),o.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let i=new Set;for(let o of t)o.startsWith("dep-added:")&&i.add(o.substring(10));for(let o of r)i.add(o.info.newName);return i}emitIncrementalReload(t,r,i,o,s){d.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...i].join(",")}], added=[${[...o].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...i],addedModuleNames:[...o],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:r}=this.collectPendingState();if(t.length===0&&r.length===0)return;if(d.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${r.length}`),t.includes("root-oh-package")){d.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let i=new Set,o=new Set,s=new Set,a=[];this.processTagsIntoSets(t,i,o,s),this.processRenameEntries(r,i,o,s,a);for(let l of o)s.delete(l);if(o.size===0&&s.size===0&&a.length===0){d.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(i,o,s,c,a)}normalizeSrcPath(t){return F(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(o=>[o.name,o])),i=new Map(t.map(o=>[this.normalizeSrcPath(o.srcPath),o]));return{byName:r,bySrcPath:i}}detectModuleRenames(t,r,i,o){for(let[s,a]of t){let c=r.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),i.add(a.name),o.add(c.name);let l=ye.join(this.depMapDir,a.name,C.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(l)),d.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,r,i,o){for(let[s,a]of t){if(i.has(s))continue;let c=r.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),i.add(s),o.add(s),d.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,i){for(let[o]of t)i.has(o)||r.has(o)||(this.pendingTags.push(`dep-added:${o}`),i.add(o))}detectRemovedModules(t,r,i){for(let[o]of t)if(!i.has(o)&&!r.has(o)){this.pendingTags.push(`dep-removed:${o}`),i.add(o);let s=ye.join(this.depMapDir,o,C.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(i=>i.startsWith("dep-")),r=this.pendingRenames.map(i=>`${i.kind}(${i.info.oldName}\u2192${i.info.newName})`);d.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:i}=this.buildModuleLookupMaps(this.lastModules),{byName:o,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(i,s,a,c),this.detectModuleMoves(r,o,a,c),this.detectAddedModules(o,r,c),this.detectRemovedModules(r,o,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=Be.readFileSync(t,"utf-8");return cg("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as dg}from"child_process";import*as zr from"path";import*as Ur from"fs";var ug=600*1e3;function pg(n,e,t){let r=t.split(/\s+/).filter(i=>i.length>0);return[n,[e,...r]]}function mg(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 Br(n){return n.join("")}function hg(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
1266
+ `);if(r===-1)break;let o=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!o){d.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(o[1],10),a=r+4,c=a+s;if(this.buffer.length<c)break;let l=this.buffer.slice(a,c).toString("utf8"),u=this.recoverFramedJson(l);if(u&&u.rest.length>0){d.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${l.length}, restLen=${u.rest.length}`),this.emit("message",u.json),this.buffer=Buffer.concat([Buffer.from(u.rest,"utf8"),this.buffer.slice(c)]);continue}this.emit("message",l),this.buffer=this.buffer.slice(c)}}waitForExitOrTimeout(t){let r=this.process;return!r||r.exitCode!==null||r.signalCode!==null?Promise.resolve():new Promise(i=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(c),r.off("exit",a),i())},a=()=>s();r.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let r=t.search(/\S/);if(r<0||t[r]!=="{"&&t[r]!=="[")return null;let i=0,o=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(o=!1);continue}if(c==='"'){o=!0;continue}if(c==="{"||c==="["){i++;continue}if((c==="}"||c==="]")&&(i--,i===0)){let l=t.slice(r,a+1),u=t.slice(a+1);return{json:l,rest:u}}}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 Rt=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,r){return new Promise((i,o)=>{let s;r>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),o(new Error(`LSP request '${t}' (id=${e}) timeout after ${r}ms`))},r),this.timeouts.set(e,s)),this.pending.set(e,{resolve:i,reject:o,method:t,timer:s})})}resolvePending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.resolve(t),this.pending.delete(e),!0):!1}rejectPending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.reject(t),this.pending.delete(e),!0):!1}register(e,t){this.callbacks.set(e,t)}emit(e,t,r){d.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let i=this.callbacks.get(e);if(i)i(t,r),this.callbacks.delete(e);else{let o=[...this.callbacks.keys()].map(s=>String(s));d.info(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${o.join(",")}]`)}}registerTimeout(e,t,r,i){let o=this.timeouts.get(e);o&&clearTimeout(o);let s=setTimeout(()=>{d.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`),i(),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 Pr=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var Mt=class{map=new Map;register(e,t){let r=this.map.get(e);r||(r=new Set,this.map.set(e,r)),r.add(t)}unregister(e,t){let r=this.map.get(e);r&&(t!==void 0?r.delete(t):r.clear(),r.size===0&&this.map.delete(e))}invoke(e,...t){let r=this.map.get(e);if(r)for(let i of r)try{i(...t)}catch(o){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,o)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function S(n){return typeof n=="object"&&n!==null}var al=20*1e3,hg=30*1e3,Cr=class{client;nextRequestId=1;stopOnce=null;callbacks=new Mt;requestCallbacks=new Rt;diagnosticMap=new Map;initProgressReset=null;constructor(e){this.client=new kt(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()=>{d.info("[ClientMessageHandle] Sending shutdown request"),this.client.sendRequest(y.SHUTDOWN,null,this.nextRequestId++),d.info("[ClientMessageHandle] Sending exit notification"),this.client.sendNotification(y.EXIT,null),d.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),d.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,We);return this.client.sendRequest(y.INITIALIZE,e,t),r}sendInitializeResettable(e,t){let r=this.nextRequestId++,i=this.requestCallbacks.registerPending(r,y.INITIALIZE,0);return this.client.sendRequest(y.INITIALIZE,e,r),new Promise((o,s)=>{let a,c=()=>{a=setTimeout(()=>{this.initProgressReset=null,s(new Error(`LSP initialization timeout after ${t}ms`))},t)},l=()=>{clearTimeout(a),c()};this.initProgressReset=l,c(),i.then(()=>{clearTimeout(a),this.initProgressReset=null,o()},u=>{clearTimeout(a),this.initProgressReset=null,s(u)})})}sendInitialized(){this.client.sendNotification(y.INITIALIZED,{})}sendDidOpen(e){let t=e.textDocument.uri;this.diagnosticMap.has(t)||(this.diagnosticMap.set(t,new Pr(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=hg){let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}onDidChangeWatchedFiles(e){e.length!==0&&this.client.sendNotification(y.WORKSPACE_DID_CHANGE_WATCHED_FILES,{changes:e})}sendDidChangeConfiguration(e){this.client.sendNotification(y.WORKSPACE_DID_CHANGE_CONFIGURATION,{settings:e})}sendNotification(e,t){this.client.sendNotification(e,t)}getDiagnosticMessages(e){let t=this.diagnosticMap.get(e);return t?t.get():[]}clearDiagnostic(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let i=r instanceof Error?r.message:String(r);d.error(`[LSP] JSON parse error: ${i}, raw: ${e}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotificationOrRequest(t):d.warn(`[LSP] Unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t===void 0)return;let r=t;if(e.error){let i=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(r,i)}else this.requestCallbacks.resolvePending(r,e.result)}handleNotificationOrRequest(e){let t=e.method;if(t)switch(this.initProgressReset?.(),t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.handleProgress(e.params);break;case y.WINDOW_SHOW_MESSAGE:d.info(`[LSP] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:d.info(`[LSP] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.broadcastToClients(e)}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=e.uri,r=this.diagnosticMap.get(t);if(!r)return;let i=e.diagnostics||[];this.normalizeDiagnostics(i),r.set(i),this.finalizeDiagnostic(t,i)}normalizeDiagnostics(e){for(let t of e)if(t.severity!==void 0){let r={1:"Error",2:"Warning",3:"Information",4:"Hint"};t.severityStr=r[t.severity]||"Unknown"}}handleProgress(e){S(e)&&this.broadcastToClients({jsonrpc:A,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,al,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${al}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,r){let i={uri:e,diagnostics:t,...r?{errorMessage:r}:{}};this.requestCallbacks.emit(e,y.PUBLISH_DIAGNOSTICS,i),this.diagnosticMap.get(e)?.clear()}handleError(e){let t=Array.from(this.diagnosticMap.keys()).filter(r=>this.requestCallbacks.hasCallback(r));if(t.length>0){let r={range:{start:{line:0,character:0},end:{line:0,character:0}},severity:1,message:e.message};for(let i of t)this.finalizeDiagnostic(i,[r]);return}this.broadcastToClients({jsonrpc:A,method:y.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var Dr=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)){d.info(`[LegacyDiagnostic] addMessage: duplicate message=${r}`);return}this.uniqueMessages.add(r),this.messages.push(new Ro(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)}},Ro=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var fg={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"},gg={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"},D={...fg,...gg},ze={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"},cl=new Set([1e3,2e3,3e3,3001]);function yg(n){if(!S(n))return!1;let e=n.textDocument;return S(e)&&typeof e.uri=="string"}function vg(n){return S(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function wg(n){return S(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 Ir=class n{client;isInitialized=!1;stopOnce=null;callbacks=new Mt;requestCallbacks=new Rt;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;constructor(e){this.client=new kt(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()=>{d.info("[LegacyClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:A,method:D.EXIT,params:{}}),ze.EXIT),d.info("[LegacyClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),d.info("[LegacyClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(D.BROADCAST),this.callbacks.register(D.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(D.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(D.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(D.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:A,method:D.INITIALIZED,params:{editors:e}}),ze.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:A,id:0,result:{}}),ze.EMPTY)}sendAsyncRequest(e,t,r,i){if(!S(t)){d.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!yg(t)){d.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof r!="number"){d.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(r)}`);return}let o=t.textDocument.uri,s=Ue(o);t.textDocument.uri=s,delete t.requestId;let a=i??e;d.info(`[LSP] sendAsyncRequest ${a}, filePath: ${o}`),this.client.sendRaw(JSON.stringify({jsonrpc:A,method:e,params:{params:t,requestId:r}}),a)}onDidChangeWatchedFiles(e){if(d.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let r of e){if(!vg(r)){d.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:A,method:D.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),D.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!S(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){d.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;d.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:A,method:D.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),ze.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let i=Ue(t);e.textDocument.uri=i,d.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new Dr(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,D.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:A,method:D.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),ze.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=Ue(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,D.PUBLISH_DIAGNOSTICS)),d.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:A,method:D.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),ze.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=Ue(e);d.info(`[LSP] didClose, uri: ${r}`);let i=this.diagnosticMap.get(r);if(!t&&(!i||i.isFromEditor)){d.info(`[LSP] closeFile skip, !diagnostic: ${!i}, isFromEditor: ${i?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:A,method:D.DID_CLOSE,params:{textDocument:{uri:r}}}),ze.DID_CLOSE)}getDiagnosticMessage(e){let t=Ue(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);d.error(`[LSP] JSON parse error: ${r}, raw: ${e}`)}}handleError(e){let t=this.getPendingDiagnosticUris();if(t.length>0){let r=JSON.stringify({message:e.message,severity:"Error",severityStr:"Error"});for(let i of t)this.finalizeDiagnostic(i,D.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:A,method:D.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 D.MODULE_INIT_FINISH:return d.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(D.MODULE_INIT_FINISH),this.callbacks.unregister(D.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case D.INDEXING_PROGRESS_UPDATE:return d.info(`[LSP] onIndexingProgressUpdate: ${wg(t.params)}`),this.callbacks.invoke(D.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case D.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case D.ON_PACKAGE_CHANGE_FINISH:d.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case D.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case D.ON_ASYNC_HOVER:this.handleAsyncResponse(t,D.HOVER);return;case D.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,D.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case D.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,D.REFERENCES);return;default:d.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){d.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;S(t)&&S(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){d.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,r={jsonrpc:A,method:D.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){d.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(r);return}if(!(t.length>0&&t[0]===!0)){d.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(r);return}d.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){d.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let r=e.params;if(!S(r)){d.warn("[LSP] aceProject/onAsyncHover message invalid");return}let i=r.requestId;if(typeof i!="number"){d.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(i,t,r)}handleForceOpenFile(e){if(!e){d.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,D.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){d.info("[LSP] publishDiagnostics uri is null");return}let r=e.version??-1;if(r===-1)return;let i=this.diagnosticMap.get(t);if(!i){d.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let o=e.diagnostics||[];o.length!==0?o.forEach(s=>{this.normalizeDiagnostic(s),i.addMessage(r,JSON.stringify(s))}):i.setReceivedType(r),i.hasReceivedAllTypes(cl)&&this.finalizeDiagnostic(t,D.PUBLISH_DIAGNOSTICS,i.getMessages())}normalizeDiagnostic(e){let t=e;if(delete t.source,t.severity!==void 0){let r=typeof t.severity=="number"?t.severity:parseInt(t.severity),o={1:"Error",2:"Warning",3:"Information",4:"Hint"}[r]||"Unknown";t.severityStr=o,t.severity=o}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let r=e[t];r&&typeof r.line=="number"&&(r.line=r.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,n.DIAGNOSTIC_TIMEOUT_MS,()=>{let r=this.diagnosticMap.get(e),i=r?r.getMessages():[];this.finalizeDiagnostic(e,t,i,i.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,i){let o={uri:e,diagnostics:r,...i?{errorMessage:i}:{}};this.requestCallbacks.emit(e,t,o),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import Pn from"path";import*as Or from"path";var Ar=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var xr=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var Tr=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var kr=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Rr=class{typeSetting=new Tr;parameterNames=new kr};var Mr=class{constructor(e,t,r,i){this.rootUri=e;this.lspServerWorkspacePath=j(Or.dirname(t)),this.indexingDataLocation=j(i),this.loggerPath=j(Or.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new Ar;gutterIconsSetting=new xr;inlayHintsSetting=new Rr;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as ll from"path";var vn=class{productName="default";buildModeName="debug";targetName="default";arkTSVersion="1.1";resourceDirectories=[];targetESVersion="ES2021";maxFlowDepth=2e3;caseSensitiveCheck=!0;tsImportSendable=!1;compatibleSdkVersionStage="";useNormalizedOHMUrl=!0;reExportCheckMode="noCheck";skipOhModulesLint=!1;byteCodeHar=!0;obfuscationRuleOptionsEnable=!1;enableStrictCheckOHModules=!1;sourceRoots=[];constructor(e){e&&this.resourceDirectories.push(j(ll.join(e,"src","main","resources")))}};var bg="OS",Ot=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${bg}`;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 vn(e)):this.buildProfileParam=new vn}toString(){return JSON.stringify(this)}};var Lt=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as me from"path";import*as Ht from"fs";var Lr=class{modulePath;dependencies={};dynamicDependencies={}};var ct=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 Nt=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 Me from"path";import*as Nr from"fs";var _t=class{name="";version="";storePath="";dependencyPath="";path=""};var T={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:ye.OH_PACKAGE_JSON5},wn=`${T.HVIGOR_CACHE}/${T.DEPENDENCY}`,lt=`${T.DEPENDENCY}${T.JSON5}`,PA=ye.SYNC_OUTPUT_PATH;var bn=class n{dependencyPath;modulePath;projectPath;static FILE_DEPENDENCY_PREFIX="file:";static PARAMETER_PREFIX="@param:";fileSpecPattern;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;static PACKAGE_JSON_PARSER_MAP=new Map;dependencies=[];devDependencies=[];dynamicDependencies=[];static getInstance(e,t,r){let i=this.PACKAGE_JSON_PARSER_MAP.get(e);return i||(i=new n(e,t,r),this.PACKAGE_JSON_PARSER_MAP.set(e,i)),i}constructor(e,t,r){this.dependencyPath=e,this.modulePath=t,this.projectPath=r,this.fileSpecPattern=n.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=Me.join(this.dependencyPath,T.OH_PACKAGE_JSON5),r=ae(t);r&&(this.dependencies=this.getDependencyList(r,T.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(r,T.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(r,T.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let r=[];if(!S(e))return r;let i=e[t];if(!S(i))return r;for(let[o,s]of Object.entries(i)){if(typeof s!="string"){d.error(`${o} package dependency value is not String ${t}`);continue}let a=new _t;a.name=o;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(n.PARAMETER_PREFIX)||this.parseDependencyPath(o,c,a,!1),r.push(a)}return r}parseDependencyPath(e,t,r,i){if(!(!e||!t))try{let o=Me.normalize(Me.join(this.modulePath,T.OH_MODULES_PATH,e));if(!(t.startsWith(n.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){r.dependencyPath=o;return}if(r.path=t,this.fileNameForOhpm.test(t)){r.dependencyPath=o;return}let s=t;if(t.startsWith(n.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(n.FILE_DEPENDENCY_PREFIX.length)),Me.isAbsolute(s)){r.dependencyPath=o;return}if(!i){let a=Me.resolve(this.modulePath,s);o=b.ensurePathWithinRoot(this.projectPath,a)}Nr.existsSync(o)&&Nr.statSync(o).isDirectory()&&(r.dependencyPath=o)}catch(o){d.error("parser dependency path is invalid",o)}}};import*as Sn from"fs";import*as En from"path";import Sg from"json5";var _r=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 En.join(this.projectPath,T.OH_MODULES_PATH,T.OHPM_PATH,T.LOCK_JSON5_FILE)}readLockFile(e){if(!Sn.existsSync(e))return d.error("lock file does not exist"),this.clearDependencies(),null;try{let t=Sn.readFileSync(e,"utf8"),r=Sg.parse(t);return r||(d.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return d.error("Error parsing lock.json5:",t),this.clearDependencies(),null}}validateLockFile(e){if(!S(e))return d.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return d.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let r=e.packages;return r?{valid:!0,modules:t,packages:r}:(d.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,r){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,T.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,T.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,T.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!S(e))return t;for(let[r,i]of Object.entries(e)){if(!S(i)){d.error(`${r} value is not json object`);continue}typeof i.storePath=="string"&&t.set(r,i.storePath)}return t}getDependencyList(e,t,r){if(!S(e))return[];for(let[i,o]of Object.entries(e))if(S(o)){let s=typeof o.name=="string"?o.name:"";if(r==="."&&s===""||s===r)return this.getFinalDependencyList(e,t,i)}return[]}getFinalDependencyList(e,t,r){let i=e[r];if(!S(i))return d.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!S(s))return[];for(let[a,c]of Object.entries(s)){if(!S(c))continue;let l=typeof c.specifier=="string"?c.specifier:"",u=typeof c.version=="string"?c.version:"",f=new _t;f.name=a,f.version=u.startsWith(n.FILE_DEPENDENCY_PREFIX)?u.substring(n.FILE_DEPENDENCY_PREFIX.length):u,this.parseDependencyPath(f,r,a,l,u);let P=`${a}@${u}`;this.storePathMap.has(P)&&(f.storePath=this.storePathMap.get(P)||""),o.push(f)}return o}parseDependencyPath(e,t,r,i,o){let s=b.resolvePathWithinRoot(this.projectPath,En.join(t,T.OH_MODULES_PATH,r));try{let a=o.startsWith(n.FILE_DEPENDENCY_PREFIX)?o.substring(n.FILE_DEPENDENCY_PREFIX.length):o,c=En.isAbsolute(a)?b.ensurePathWithinRoot(this.projectPath,a):b.resolvePathWithinRoot(this.projectPath,a);Sn.existsSync(c)?(e.path=i,e.dependencyPath=this.fileNameForOhpm.test(o)?s:c):e.dependencyPath=s}catch(a){d.error("Invalid dependency path in lock.json5",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};var Oe=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=ol(this.projectRoot);try{let t=ae(e);if(typeof t!="object"||t===null)return[];let r=t.modules;return Array.isArray(r)?r.filter(i=>{if(typeof i!="object"||i===null)return!1;let o=i;return typeof o.name=="string"&&typeof o.srcPath=="string"}):[]}catch(t){return d.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};function dl(n){return S(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var dt=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new Oe(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=me.join(t,wn),i=me.join(r,lt);if(!Ht.existsSync(r)||!Ht.existsSync(i)){let c="Dependency map or JSON not found";return d.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let o=new Nt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(r,o),this.parseLockJson(o);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return d.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];dl(l)&&(this.parseSingleModule(l,r,o,e),(c+1)%100===0&&d.info(`[Parser] getAllDependencyMap progress: ${c+1}/${s.length} (${Date.now()-a}ms)`))}return d.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-a}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],r=this.projectPath,i=me.join(r,wn),o=me.join(i,lt);if(!Ht.existsSync(i)||!Ht.existsSync(o))return d.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 Nt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return d.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let l of c){if(!dl(l))continue;let u=l.name;if(s&&!s.has(u))continue;let f=b.resolvePathWithinRoot(this.projectPath,l.srcPath),P=me.join(i,u),C=j(f),L=this.buildModuleDependencies(u,C,P,a);L.moduleName=u,t.push(L)}return t}parseSingleModule(e,t,r,i){let o=e.name,s=b.resolvePathWithinRoot(this.projectPath,e.srcPath),a=me.join(t,o),c=j(s),l=new Ot(c),u=this.buildModuleDependencies(o,c,a,r);this.parseModuleJson5(c,l);let f=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=o,l.moduleType=o,l.packageName=o,l.moduleDependencies=u,l.moduleJsonParam=new Lt(f),i.push(l)}buildModuleDependencies(e,t,r,i){let o=new Nt(this.projectPath,e,t);bn.getInstance(r,t,this.projectPath).parseDependency(o),this.parseLockJson(o),o.finalDependencies.push(...i.finalDependencies),o.finalDevDependencies.push(...i.finalDevDependencies),o.finalDynamicDependencies.push(...i.finalDynamicDependencies),o.finalDependencies.push(...o.finalDevDependencies);let a=new Lr;return a.modulePath=t,this.toModuleDependencies(o,a),a}toModuleDependencies(e,t){let r={},i={};for(let o of e.finalDependencies)r[o.name]=new ct(o);for(let o of e.finalDynamicDependencies)i[o.name]=new ct(o);t.dependencies=r,t.dynamicDependencies=i}parseProjectDependencies(e,t){let r=me.join(e,T.OH_PACKAGE_JSON5);if(!Ht.existsSync(r))return;bn.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 _r(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=me.join(e,"src","main","module.json5"),i=ae(r);if(!S(i)||!S(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(S(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)S(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=me.join(e,"src","main","resources","base","profile","main_pages.json"),r=ae(t);return!S(r)||!Array.isArray(r.src)?[]:r.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!S(t)||!S(t.data))){if(typeof t.data.apiVersion=="string"){let r=parseInt(t.data.apiVersion,10);!Number.isNaN(r)&&r>=26&&typeof t.data.platformVersion=="string"?e.compileSdkLevel=t.data.platformVersion:e.compileSdkLevel=t.data.apiVersion}typeof t.data.releaseType=="string"&&(e.compileSdkType=t.data.releaseType),typeof t.data.version=="string"&&(e.compileSdkVersion=t.data.version)}}getSdkPkg(){if(this.sdkPkgCache===void 0){let e=me.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=ae(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!S(t)||!S(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!S(r)||typeof r.compatibleSdkVersion!="string")return;let[i,o]=this.parseBySplit(r.compatibleSdkVersion);e.compatibleSdkVersion=i,e.compatibleSdkLevel=o}getBuildProfile(){if(this.buildProfileCache===void 0){let e=me.join(this.projectPath,"build-profile.json5");this.buildProfileCache=ae(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,e];let r=e.substring(0,t),i=e.substring(t+1,e.length-1);return[r,i]}parseDeviceTypes(e){return!S(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 Hr=class{constructor(e=[]){this.valueSet=e}valueSet};var Ft=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var ul=(v=>(v[v.File=1]="File",v[v.Module=2]="Module",v[v.Namespace=3]="Namespace",v[v.Package=4]="Package",v[v.Class=5]="Class",v[v.Method=6]="Method",v[v.Property=7]="Property",v[v.Field=8]="Field",v[v.Constructor=9]="Constructor",v[v.Enum=10]="Enum",v[v.Interface=11]="Interface",v[v.Function=12]="Function",v[v.Variable=13]="Variable",v[v.Constant=14]="Constant",v[v.String=15]="String",v[v.Number=16]="Number",v[v.Boolean=17]="Boolean",v[v.Array=18]="Array",v[v.Object=19]="Object",v[v.Key=20]="Key",v[v.Null=21]="Null",v[v.EnumMember=22]="EnumMember",v[v.Struct=23]="Struct",v[v.Event=24]="Event",v[v.Operator=25]="Operator",v[v.TypeParameter=26]="TypeParameter",v))(ul||{}),pl=()=>Object.values(ul).filter(n=>typeof n=="number");var Fr=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var jr=class{applyEdit=!0;workspaceEdit=new Fr;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Hr(pl());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Ft;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var $r=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Br=class{constructor(e=[]){this.valueSet=e}valueSet};var Wr=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var ml=(w=>(w[w.Text=1]="Text",w[w.Method=2]="Method",w[w.Function=3]="Function",w[w.Constructor=4]="Constructor",w[w.Field=5]="Field",w[w.Variable=6]="Variable",w[w.Class=7]="Class",w[w.Interface=8]="Interface",w[w.Module=9]="Module",w[w.Property=10]="Property",w[w.Unit=11]="Unit",w[w.Value=12]="Value",w[w.Enum=13]="Enum",w[w.Keyword=14]="Keyword",w[w.Snippet=15]="Snippet",w[w.Color=16]="Color",w[w.File=17]="File",w[w.Reference=18]="Reference",w[w.Folder=19]="Folder",w[w.EnumMember=20]="EnumMember",w[w.Constant=21]="Constant",w[w.Struct=22]="Struct",w[w.Event=23]="Event",w[w.Operator=24]="Operator",w[w.TypeParameter=25]="TypeParameter",w))(ml||{}),hl=()=>Object.values(ml).filter(n=>typeof n=="number");var Ur=class{completionItemKind=new Br(hl());completionItem=new Wr;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var zr=class{synchronization=new $r;completion=new Ur;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 Ft;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var qr=class{workspace=new jr;textDocument=new zr;notebookDocument=null;window=null;general=null;experimental=null};var Gr=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var Vr=class{constructor(e,t,r,i,o,s=!0){this.sdkPath=e;this.rootUri=r;this.nodeMaxOldSpaceSize=o;this.useStandardProtocol=s;this.serverPath=this.useStandardProtocol?Pn.resolve(t,"ace-server","out","standardIndex","index.js"):Pn.resolve(t,"ace-server","out","index.js"),this.logPath=tl(),this.indexLogPath=i||this.logPath;let a={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath};this.messageHandle=this.useStandardProtocol?new Cr(a):new Ir(a),this.messageHandle.setBroadcastToClients(c=>this.onLspMessage(c))}sdkPath;rootUri;nodeMaxOldSpaceSize;useStandardProtocol;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=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}async start(e,t){let r=!1;try{d.info(`serverPath: ${this.serverPath}`),d.info(`rootUri: ${this.rootUri}`),d.info(`sdkPath: ${this.sdkPath}`),d.info(`logPath: ${this.logPath}`);let i=Ue(this.rootUri),o=new Mr(i,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new dt(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),o.modules=s;let l=Sr(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new Gr(i,o,new qr),this.useStandardProtocol){let u=this.messageHandle;await u.sendInitializeResettable(this.currentParams,We),d.info("[LSP] initialize response received"),u.broadcastToClients({jsonrpc:A,method:y.ARKTS_INDEXING_PROGRESS,params:{}}),u.sendInitialized()}else await this.startLegacy(this.currentParams,e);r=!0}catch(i){this.lastStartErrorMessage=i instanceof Error?i.message:String(i),d.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:A,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((i,o)=>{r.onIndexingProgressUpdate(o),r.onInitializationCompleted(i)},"LSP initialization",We),r.sendInitialized(t)}withResettableTimeout(e,t,r){return new Promise((i,o)=>{let s,a=()=>{s=setTimeout(()=>{o(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),i()},c)})}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){d.info(`[LSP] registerDiagnosticCallback uri='${e}', useStandardProtocol=${this.useStandardProtocol}`),this.messageHandle.registerRequestCallback(e,(t,r)=>{let i=S(r)?r:{};d.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let o={jsonrpc:A,method:t,params:{uri:typeof i.uri=="string"?i.uri:e,diagnostics:Array.isArray(i.diagnostics)?i.diagnostics:[],...typeof i.errorMessage=="string"?{errorMessage:i.errorMessage}:{}}};this.onLspMessage(o)})}async hover(e){let t=e.textDocument.uri;return this.registerDiagnosticCallback(t),this.stdHandle.sendLspRequest(y.HOVER,e)}async definition(e){return this.stdHandle.sendLspRequest(y.DEFINITION,e)}async references(e){return this.stdHandle.sendLspRequest(y.REFERENCES,e)}async completion(e){return this.stdHandle.sendLspRequest(y.COMPLETION,e)}async documentSymbol(e){return this.stdHandle.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async diagnostic(e){return this.stdHandle.sendLspRequest(y.DIAGNOSTIC,e,120*1e3)}async sendFeatureRequest(e,t){return this.stdHandle.sendLspRequest(e,t)}reloadDependenciesOnly(e){let t=e?.fullReload??!1,r=new dt(this.rootUri,this.sdkPath),i=this.getModuleModelsByName();if(t){d.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let l=r.getDependenciesOnly();this.markDependencyTypesIncremental(l);let u=this.mergeDepsOnlyIntoModuleList(l,i);return this.applyModuleModelsUpdate(u),this.sendDidChangeConfiguration({moduleSet:u}),d.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${u.length}`),this.lastDepsOnlyForDiff=l,l}let o=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(o.length===0&&s.size===0)return d.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];d.info(`[LspServerProxy] Module-level deps changed, parsing: [${o.join(", ")}]`);let a=r.getDependenciesOnly(o);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),this.sendDidChangeConfiguration({moduleSet:c}),d.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}sendDidChangeConfiguration(e){this.stdHandle.sendDidChangeConfiguration(e)}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),r=new Map(this.lastDepsOnlyForDiff.map(i=>[i.moduleName??"",i]));for(let i of e){let o=i.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(o,t,r),c=i.dependencies??{},l=i.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(u,f)=>{(i.dependencies??={})[u]=this.makeDeleteEntry(u,f)}),this.markAddAndDeleteInDeps(a,l,(u,f)=>{(i.dynamicDependencies??={})[u]=this.makeDeleteEntry(u,f)})}}getOldDepsForModule(e,t,r){let i=t.get(e),o=i?.moduleDependencies?.dependencies??{},s=i?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(o).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(o=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:o,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let i of Object.keys(t))i in e||(t[i].type="add");for(let i of Object.keys(e))i in t||r(i,e[i])}makeDeleteEntry(e,t){return new ct({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Ot(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new Lt([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let i of e){let o=i.moduleName??"",s=t.get(o);s?(s.modulePath=i.modulePath,s.moduleDependencies=i):s=this.createMinimalModelFromDepsItem(i),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let i=new Map(r.map(s=>[s.moduleName??"",s])),o=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=i.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,i.delete(a)),o.push(s)}for(let[,s]of i)o.push(this.createMinimalModelFromDepsItem(s));return o}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=Er(Pn.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=Er(Pn.join(t,"default/openharmony/ets/api")),o=Er(Pn.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=i,s.hosSdkPath=o}sendRequest(e){switch(e.method){case y.HOVER:this.stdHandle.sendLspRequest(y.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:A,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:A,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:A,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:A,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:A,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:A,id:e.id,error:{code:-32603,message:t.message}}));break;default:d.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!Xc(e)){d.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:d.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){d.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"){d.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"){d.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 Le from"fs";import*as qe from"path";import{createHash as Pg}from"crypto";import{EventEmitter as Cg}from"events";var Yr=class extends Cg{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r}projectRoot;watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),r=new Set(this.watchers.keys());for(let i of t)r.has(i)||this.watchFile(i);for(let i of r)t.has(i)||(this.unwatchFile(i),d.info(`[ConfigFileWatcher] Stopped watching: ${i}`));d.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!Le.existsSync(t)){d.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Le.watch(t,r=>{r==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",r=>{d.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${r.message}`)}),d.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(r){d.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${r instanceof Error?r.message:String(r)}`)}}emitModuleAddedEvents(t,r){for(let i of t){let o=b.resolvePathWithinRoot(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:o,relativePath:i.srcPath,timestamp:r,moduleName:i.name})}}emitModuleRemovedEvents(t,r){for(let i of t){let o=b.resolvePathWithinRoot(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:o,relativePath:i.srcPath,timestamp:r,removedModuleName:i.name})}}emitModuleRenamedEvents(t,r){for(let i of t){let o=b.resolvePathWithinRoot(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name,removedModuleName:i.before.name})}}emitModuleMovedEvents(t,r){for(let i of t){let o=b.resolvePathWithinRoot(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let r=Date.now();this.emitModuleAddedEvents(t.added,r),this.emitModuleRemovedEvents(t.removed,r),this.emitModuleRenamedEvents(t.renamed,r),this.emitModuleMovedEvents(t.moved,r)}onBuildProfileChanged(){let t="__build_profile__",r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(o);if(s===this.lastModulesSnapshot){d.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,o);this.lastModules=o,this.lastModulesSnapshot=s,d.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,i)}computeModulesSnapshot(t){return t.map(i=>`${i.name}::${i.srcPath}`).sort().join("|")}diffModules(t,r){let i=this.buildModuleMatchState(r),o={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,i),this.matchRenamedModules(t,i,o),this.matchMovedModules(t,i,o),this.collectRemovedModules(t,i,o),this.collectAddedModules(r,i,o),o}buildModuleMatchState(t){let r=new Map,i=new Map;for(let o of t)r.set(o.srcPath,o),i.set(o.name,o);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:i}}matchExactModules(t,r){for(let i of t){let o=r.newBySrc.get(i.srcPath);o&&o.name===i.name&&(r.matchedOld.add(i),r.matchedNew.add(o))}}matchRenamedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newBySrc.get(o.srcPath);s&&!r.matchedNew.has(s)&&s.name!==o.name&&(i.renamed.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}matchMovedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newByName.get(o.name);s&&!r.matchedNew.has(s)&&s.srcPath!==o.srcPath&&(i.moved.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}collectRemovedModules(t,r,i){for(let o of t)r.matchedOld.has(o)||i.removed.push(o)}collectAddedModules(t,r,i){for(let o of t)r.matchedNew.has(o)||i.added.push(o)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=ae(t);if(typeof r!="object"||r===null)return[];let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return d.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=qe.join(this.projectRoot,T.OH_PACKAGE_JSON5);Le.existsSync(r)&&t.push(r);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=b.resolvePathWithinRoot(this.projectRoot,o.srcPath),a=qe.join(s,T.OH_PACKAGE_JSON5);Le.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return qe.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Le.readFileSync(t,"utf-8");return Pg("sha256").update(r).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let r=this.computeFileHash(t);r&&this.contentHashes.set(t,r);let i=Le.watch(t,o=>{o==="change"&&this.onFileChanged(t)});i.on("error",o=>{d.error(`[ConfigFileWatcher] Watch error for ${t}: ${o.message}`)}),this.watchers.set(t,i)}catch(r){d.error(`[ConfigFileWatcher] Failed to watch ${t}: ${r instanceof Error?r.message:String(r)}`)}}unwatchFile(t){let r=this.watchers.get(t);r&&(r.close(),this.watchers.delete(t)),this.contentHashes.delete(t);let i=this.debounceTimers.get(t);i&&(clearTimeout(i),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.computeFileHash(t);if(!o){d.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===o){d.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,o),d.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:qe.basename(t),relativePath:qe.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,i)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),d.info("[ConfigFileWatcher] All watchers stopped")}};import*as Ge from"fs";import*as Se from"path";import{createHash as Dg}from"crypto";import{EventEmitter as Ig}from"events";var Jr=class extends Ig{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=Se.join(t,wn)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!Ge.existsSync(this.depMapDir)){d.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=Ge.watch(this.depMapDir,{recursive:!0},(t,r)=>this.onDirEvent(t,r)),this.dirWatcher.on("error",t=>{d.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){d.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),d.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return j(Se.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let i=r.replace(/\\/g,"/"),o;if(i===T.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===lt)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=Se.join(this.depMapDir,r);Ge.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,d.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=Se.join(this.depMapDir,T.OH_PACKAGE_JSON5),r=Se.join(this.depMapDir,lt),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...i.map(s=>({path:Se.join(this.depMapDir,s.name,T.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!Ge.existsSync(s))continue;let c=this.canonicalPath(s),l=this.computeFileHash(s);if(!l)continue;let u=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,l);continue}u!==l&&(this.contentHashes.set(c,l),d.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=Se.join(this.depMapDir,lt);try{let r=ae(t);if(typeof r!="object"||r===null)return[];let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return d.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${r instanceof Error?r.message:String(r)}`),[]}}scheduleCoalescedReload(t){this.pendingTags.push(t),t==="dep-map-json"&&this.applyDepMapJsonDiff(),this.coalesceTimer&&clearTimeout(this.coalesceTimer),this.coalesceTimer=setTimeout(()=>{this.coalesceTimer=null,this.flushPendingReload()},this.coalesceMs)}collectPendingState(){let t=this.pendingTags,r=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:r}}processTagsIntoSets(t,r,i,o){for(let s of t)s.startsWith("module:")?(i.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(i.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(o.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,i,o,s){for(let a of t)s.push(a.info),i.add(a.info.newName),o.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let i=new Set;for(let o of t)o.startsWith("dep-added:")&&i.add(o.substring(10));for(let o of r)i.add(o.info.newName);return i}emitIncrementalReload(t,r,i,o,s){d.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...i].join(",")}], added=[${[...o].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...i],addedModuleNames:[...o],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:r}=this.collectPendingState();if(t.length===0&&r.length===0)return;if(d.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${r.length}`),t.includes("root-oh-package")){d.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let i=new Set,o=new Set,s=new Set,a=[];this.processTagsIntoSets(t,i,o,s),this.processRenameEntries(r,i,o,s,a);for(let l of o)s.delete(l);if(o.size===0&&s.size===0&&a.length===0){d.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(i,o,s,c,a)}normalizeSrcPath(t){return j(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(o=>[o.name,o])),i=new Map(t.map(o=>[this.normalizeSrcPath(o.srcPath),o]));return{byName:r,bySrcPath:i}}detectModuleRenames(t,r,i,o){for(let[s,a]of t){let c=r.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),i.add(a.name),o.add(c.name);let l=Se.join(this.depMapDir,a.name,T.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(l)),d.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,r,i,o){for(let[s,a]of t){if(i.has(s))continue;let c=r.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),i.add(s),o.add(s),d.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,i){for(let[o]of t)i.has(o)||r.has(o)||(this.pendingTags.push(`dep-added:${o}`),i.add(o))}detectRemovedModules(t,r,i){for(let[o]of t)if(!i.has(o)&&!r.has(o)){this.pendingTags.push(`dep-removed:${o}`),i.add(o);let s=Se.join(this.depMapDir,o,T.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(i=>i.startsWith("dep-")),r=this.pendingRenames.map(i=>`${i.kind}(${i.info.oldName}\u2192${i.info.newName})`);d.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:i}=this.buildModuleLookupMaps(this.lastModules),{byName:o,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(i,s,a,c),this.detectModuleMoves(r,o,a,c),this.detectAddedModules(o,r,c),this.detectRemovedModules(r,o,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=Ge.readFileSync(t,"utf-8");return Dg("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as Ag}from"child_process";import*as Xr from"path";import*as Zr from"fs";var xg=600*1e3;function Tg(n,e,t){let r=t.split(/\s+/).filter(i=>i.length>0);return[n,[e,...r]]}function kg(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 Kr(n){return n.join("")}function Rg(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
1265
1267
  Output so far:
1266
- `+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function fg(n,e,t){return new Promise(r=>{let i=dg(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:o,stderr:s}=mg(i),a=setTimeout(()=>{i.kill();let c=[Br(o),Br(s)].filter(Boolean).join(`
1268
+ `+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function Mg(n,e,t){return new Promise(r=>{let i=Ag(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:o,stderr:s}=kg(i),a=setTimeout(()=>{i.kill();let c=[Kr(o),Kr(s)].filter(Boolean).join(`
1267
1269
  `).trim();r({success:!1,output:`Build process timeout after 10 minutes.
1268
1270
  Output so far:
1269
- `+c,exitCode:-1})},ug);i.on("close",(c,l)=>{clearTimeout(a);let u=[Br(o),Br(s)].filter(Boolean).join(`
1270
- `).trim()||"";r(hg(c,l,u))}),i.on("error",c=>{clearTimeout(a),r({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function Eo(n,e,t,r,i){let o={...process.env,DEVECO_SDK_HOME:r},s=pg(e,t,i);return await fg(s,n,o)}function gg(n){let e=zr.join(zr.dirname(n),"tools","hvigor","bin","hvigorw.js");return{node_path:lr(n),hvigor_path:e,sdk_path:n}}function yg(n){return!n.node_path||!Ur.existsSync(n.node_path)?`Node path not found or invalid: ${n.node_path}`:!n.hvigor_path||!Ur.existsSync(n.hvigor_path)?`Hvigor path not found or invalid: ${n.hvigor_path}`:!n.sdk_path||!Ur.existsSync(n.sdk_path)?`SDK path not found or invalid: ${n.sdk_path}`:null}var vg="--sync -p product=default --analyze=normal --parallel --incremental --no-daemon";async function al(n,e){try{let t=gg(e),r=yg(t);return r!=null?(d.info(`Config validation failed: ${r}`),!1):(await Eo(n,t.node_path,t.hvigor_path,e,vg)).success}catch(t){return d.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}import{spawn as wg}from"child_process";import*as Po from"fs";import*as wn from"path";var bg=["install","--all"];function Sg(n){let e=n.replace(/sdk\/?$/i,"tools"),t=wn.join(e,"ohpm","bin","pm-cli.js");if(Po.existsSync(t))return t;let r=n.toLowerCase().endsWith("sdk")?wn.dirname(n):n;return t=wn.join(r,"ohpm","bin","pm-cli.js"),Po.existsSync(t)?t:null}async function Eg(n,e,t,r){return new Promise(i=>{let o=wg(n,[e,...bg],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";o.stdout?.on("data",c=>{s+=c.toString()}),o.stderr?.on("data",c=>{a+=c.toString()}),o.on("close",c=>{let l=[s,a].filter(Boolean).join(`
1271
+ `+c,exitCode:-1})},xg);i.on("close",(c,l)=>{clearTimeout(a);let u=[Kr(o),Kr(s)].filter(Boolean).join(`
1272
+ `).trim()||"";r(Rg(c,l,u))}),i.on("error",c=>{clearTimeout(a),r({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function Mo(n,e,t,r,i){let o={...process.env,DEVECO_SDK_HOME:r},s=Tg(e,t,i);return await Mg(s,n,o)}function Og(n){let e=Xr.join(Xr.dirname(n),"tools","hvigor","bin","hvigorw.js");return{node_path:yr(n),hvigor_path:e,sdk_path:n}}function Lg(n){return!n.node_path||!Zr.existsSync(n.node_path)?`Node path not found or invalid: ${n.node_path}`:!n.hvigor_path||!Zr.existsSync(n.hvigor_path)?`Hvigor path not found or invalid: ${n.hvigor_path}`:!n.sdk_path||!Zr.existsSync(n.sdk_path)?`SDK path not found or invalid: ${n.sdk_path}`:null}var Ng="--sync -p product=default --analyze=normal --parallel --incremental --no-daemon";async function fl(n,e){try{let t=Og(e),r=Lg(t);return r!=null?(d.info(`Config validation failed: ${r}`),!1):(await Mo(n,t.node_path,t.hvigor_path,e,Ng)).success}catch(t){return d.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}import{spawn as _g}from"child_process";import*as Oo from"fs";import*as Cn from"path";var Hg=["install","--all"];function Fg(n){let e=n.replace(/sdk\/?$/i,"tools"),t=Cn.join(e,"ohpm","bin","pm-cli.js");if(Oo.existsSync(t))return t;let r=n.toLowerCase().endsWith("sdk")?Cn.dirname(n):n;return t=Cn.join(r,"ohpm","bin","pm-cli.js"),Oo.existsSync(t)?t:null}async function jg(n,e,t,r){return new Promise(i=>{let o=_g(n,[e,...Hg],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";o.stdout?.on("data",c=>{s+=c.toString()}),o.stderr?.on("data",c=>{a+=c.toString()}),o.on("close",c=>{let l=[s,a].filter(Boolean).join(`
1271
1273
  `);i({exitCode:c??-1,output:l})}),o.on("error",c=>{let l=[s,a].filter(Boolean).join(`
1272
1274
  `);i({exitCode:-1,output:l+`
1273
- `+c.message})})})}function Pg(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>d.info("[ohpm] %s",e))}async function cl(n,e){try{let t=lr(e);if(!t)return d.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;let r=Sg(e);if(!r)return d.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:i,output:o}=await Eg(t,r,n,e);return Pg(o),i===0?(d.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(d.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",i),d.error("ohpm \u8F93\u51FA: %s",o),!1)}catch(t){return d.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var ll={UNINITIALIZED:-32099,UNKNOWN:-32e3},bn=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,ll.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,ll.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var Ot=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,this.startConfigWatcher(),this.startLspProxy(e)}sendNotification(e){if(!this.lspProxy){d.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){d.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){if(d.info("[ArktsLspManager] Received arkts/syncProject"),!e||!t)return d.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let r=await Is(e,async()=>await cl(e,t)?await al(e,t)?(d.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(d.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(d.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return r.acquired?r.result:(d.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){d.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){d.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){d.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new jr(this.config.sdkPath,this.config.arktsLangServerPath,this.config.workspaceRoot,this.config.indexLogPath,this.config.nodeMaxOldSpaceSize,this.config.useStandardProtocol);t.setOnMessage(r=>this.handleLspMessage(r)),t.start(e,r=>this.handleLspInitialized(r)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)d.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:A,method:g.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();d.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?bn.uninitialized(t):bn.unknown();this.onMessage({jsonrpc:A,method:g.ARKTS_INITIALIZATION_FAILED,params:r.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(d.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:A,method:g.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new $r(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Wr(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){d.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let r=this.lspProxy.reloadDependenciesOnly(e).map(i=>({modulePath:i.modulePath??"",dependencies:i.dependencies??{},dynamicDependencies:i.dynamicDependencies??{}}));this.onMessage({jsonrpc:A,method:g.ARKTS_SYNC_COMPLETED,params:{success:!0,moduleSet:r}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){d.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var Cg=10080*60*1e3,Ig=7200*60*1e3,Dg=120*1e3,Lt=class n{manager=null;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;devecoPath;nodeMaxOldSpaceSize;onConfigChangedCallback=null;useStandardProtocol=!0;diagnosticWaiters=new Map;static FEATURE_METHOD_MAP={hover:g.HOVER,definition:g.DEFINITION,declaration:g.DECLARATION,references:g.REFERENCES,implementation:g.IMPLEMENTATION,completion:g.COMPLETION,signatureHelp:g.SIGNATURE_HELP,documentHighlight:g.DOCUMENT_HIGHLIGHT};constructor(e,t,r){this.projectPath=e,this.devecoPath=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:Co.object({files:Co.array(Co.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:i}=this.resolveProjectAndDeveco();this.useStandardProtocol=i;let o=de(e),{logPath:s,indexPath:a}=this.getLogAndIndexPath(o);setImmediate(()=>{yo(a,Cg,"[ArkTS-Check]"),yo(s,Ig,"[ArkTS-Check]")}),qc(s);let c=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,l=Number.isNaN(c)?void 0:c;h.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${l??"undefined \u2192 dynamic formula applies"}`);let u=Y.join(le(t),"sdk");h.info(`ArktsCheck devecoPath: ${t}, contentRoot: ${le(t)}, sdkPath: ${u}`),this.manager=new Ot({sdkPath:u,arktsLangServerPath:r,workspaceRoot:F(o),indexLogPath:a,nodeMaxOldSpaceSize:l,useStandardProtocol:i}),this.manager.setOnMessage(f=>this.handleLspMessage(f)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((f,E)=>{this.initResolve=f,this.initReject=E,this.armInitTimer(Fe),this.manager.start([]).catch(M=>{let j=M instanceof Error?M:new Error(String(M));this.failInit(j)})})}resolveProjectAndDeveco(){let e=Ae(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.devecoPath??Te();if(h.debug(`DevEco Studio installation path: ${t}, this.devecoPath: ${this.devecoPath}`),!t)throw new Error("DevEco Studio installation path not found");this.devecoPath=t;let r=or(t);if(!r)throw new Error("arkts-lang-server path not found");let i=Y.resolve(r,"ace-server","out","standardIndex","index.js"),o=ne.existsSync(i);return h.info(`ArktsCheck protocol: ${o?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${o})`),{harmonyRoot:e,devecoPath:t,arktsLangServerPath:r,useStandardProtocol:o}}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=nt(e),i=await ne.promises.readFile(e,"utf8"),s=`deveco.apptool.${Y.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,r,i,s):this.checkFileLegacy(t,e,r,i,s)}async checkFileStandard(e,t,r,i){h.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:i,version:1}});try{h.debug(`textDocument/diagnostic uri=${t}`);let o=await e.diagnostic({textDocument:{uri:t}});return Ag(o)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:t}})}}async checkFileLegacy(e,t,r,i,o){let s=r;e.registerDiagnosticCallback(r);let a=new Promise((c,l)=>{let u=setTimeout(()=>{this.diagnosticWaiters.delete(s)&&l(new Error("Wait for diagnostics timeout"))},Dg);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:u})});h.debug(`textDocument/didOpen(legacy) uri=${r} content_len=${i.length}`),e.onAsyncOpenFile({textDocument:{uri:r,text:i,languageId:o,version:i.length},editorFiles:[r],isFromEditor:!1});try{return await a}finally{e.closeFileLegacy(r,!1)}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],r=[],i=this.collectValidFiles(e.files,t);return i.length===0?{content:[{type:"text",text:t.length>0?t.join(`
1274
- `):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],isError:!0}:(await this.runDiagnosticsForFiles(i,t,r),this.formatCallResult(t,r))}async handleLspFeature(e,t){if(!this.initialized)return this.buildNotReadyResponse();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){let s=o instanceof Error?o.message:String(o);return h.error(`handleLspFeature ${e} failed: ${s}`),{content:[{type:"text",text:`${e} failed: ${s}`}],isError:!0}}}async handleWorkspaceSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();h.info(`handleWorkspaceSymbol: query="${e}"`);try{let t=await this.manager.sendFeatureRequest(g.WORKSPACE_SYMBOL,{query:e});return{content:[{type:"text",text:t==null?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(t,null,2)}`}]}}catch(t){let r=t instanceof Error?t.message:String(t);return h.error(`handleWorkspaceSymbol failed: ${r}`),{content:[{type:"text",text:`workspaceSymbol failed: ${r}`}],isError:!0}}}async handleDocumentSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};h.info(`handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(g.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return h.error(`handleDocumentSymbol failed: ${i}`),{content:[{type:"text",text:`documentSymbol failed: ${i}`}],isError:!0}}}async handleCallHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,async o=>{let s=await this.manager.sendFeatureRequest(g.PREPARE_CALL_HIERARCHY,{textDocument:{uri:o},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],calls:[]};let c=e.direction==="incoming"?g.INCOMING_CALLS:g.OUTGOING_CALLS,l=[];for(let u of a){let f=await this.manager.sendFeatureRequest(c,{item:u});Array.isArray(f)?l.push(...f):f&&l.push(f)}return{items:a,calls:l}});return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return h.error(`handleCallHierarchy failed: ${i}`),{content:[{type:"text",text:`callHierarchy failed: ${i}`}],isError:!0}}}async handleCodeAction(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleCodeAction: file=${t} line=${e.line} char=${e.character}`);try{let r=await this.withOpenFile(t,async o=>{let s={line:e.line,character:e.character};return this.manager.sendFeatureRequest(g.CODE_ACTION,{textDocument:{uri:o},range:{start:s,end:s},context:{diagnostics:[]}})});return{content:[{type:"text",text:r==null?"codeAction: no result":`codeAction: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("codeAction",r)}}async handleRename(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleRename: file=${t} line=${e.line} char=${e.character} newName=${e.newName}`);try{let r=await this.withOpenFile(t,async o=>{let s={line:e.line,character:e.character};if(await this.manager.sendFeatureRequest(g.PREPARE_RENAME,{textDocument:{uri:o},position:s})==null)throw new Error("Symbol at this position cannot be renamed");return this.manager.sendFeatureRequest(g.RENAME,{textDocument:{uri:o},position:s,newName:e.newName})});return{content:[{type:"text",text:r==null?"rename: no result":`rename: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("rename",r)}}async handleTypeHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleTypeHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,async o=>{let s=await this.manager.sendFeatureRequest(g.PREPARE_TYPE_HIERARCHY,{textDocument:{uri:o},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"?g.SUPERTYPES:g.SUBTYPES,l=[];for(let u of a){let f=await this.manager.sendFeatureRequest(c,{item:u});Array.isArray(f)?l.push(...f):f&&l.push(f)}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();h.info("handleCompletionItemResolve");try{let t=await this.manager.sendFeatureRequest(g.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 i=(await ne.promises.readFile(t,"utf8")).split(`
1275
- `).length,o=await this.withOpenFile(t,async a=>this.manager.sendFeatureRequest(g.INLAY_HINT,{textDocument:{uri:a},range:{start:{line:0,character:0},end:{line:i,character:0}}}));return{content:[{type:"text",text:o==null?"inlayHint: no result":`inlayHint: ${JSON.stringify(o,null,2)}`}]}}catch(r){return this.buildErrorResponse("inlayHint",r)}}async handleDocumentLink(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(g.DOCUMENT_LINK,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentLink: no result":`documentLink: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("documentLink",r)}}buildErrorResponse(e,t){let r=t instanceof Error?t.message:String(t);return h.error(`${e} failed: ${r}`),{content:[{type:"text",text:`${e} failed: ${r}`}],isError:!0}}async withOpenFile(e,t){let r=nt(e),i=await ne.promises.readFile(e,"utf8"),s=`deveco.apptool.${Y.extname(e).replace(/^\./,"")||"plaintext"}`;h.debug(`withOpenFile didOpen uri=${r} len=${i.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,text:i,languageId:s,version:i.length}});try{return await t(r)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:r},isManual:!1})}}resolveSingleFile(e){let t=Y.isAbsolute(e)?e:Y.join(this.projectPath,e);return!ne.existsSync(t)||!ne.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,i=[];for(let o of e){let s=Y.isAbsolute(o)?o:Y.join(r,o);if(!ne.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!ne.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${o}`);continue}if(!s.endsWith(".ets")){t.push(`\u4E0D\u662F .ets \u6587\u4EF6: ${o}`);continue}i.push(s)}return i}async runDiagnosticsForFiles(e,t,r){for(let i of e){await Nc(500);try{let o=await this.checkFile(i);r.push(Tg(i,o))}catch(o){t.push(`${i} => wait for diagnostics failed: ${o.message}`)}}}formatCallResult(e,t){let r=[];e.length>0&&r.push(e.join(`
1275
+ `+c.message})})})}function $g(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>d.info("[ohpm] %s",e))}async function gl(n,e){try{let t=yr(e);if(!t)return d.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;let r=Fg(e);if(!r)return d.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:i,output:o}=await jg(t,r,n,e);return $g(o),i===0?(d.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(d.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",i),d.error("ohpm \u8F93\u51FA: %s",o),!1)}catch(t){return d.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var yl={UNINITIALIZED:-32099,UNKNOWN:-32e3},Dn=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,yl.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,yl.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var jt=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,this.startConfigWatcher(),this.startLspProxy(e)}sendNotification(e){if(!this.lspProxy){d.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){d.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){if(d.info("[ArktsLspManager] Received arkts/syncProject"),!e||!t)return d.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let r=await Ls(e,async()=>await gl(e,t)?await fl(e,t)?(d.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(d.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(d.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return r.acquired?r.result:(d.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){d.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){d.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){d.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new Vr(this.config.sdkPath,this.config.arktsLangServerPath,this.config.workspaceRoot,this.config.indexLogPath,this.config.nodeMaxOldSpaceSize,this.config.useStandardProtocol);t.setOnMessage(r=>this.handleLspMessage(r)),t.start(e,r=>this.handleLspInitialized(r)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)d.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:A,method:y.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();d.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?Dn.uninitialized(t):Dn.unknown();this.onMessage({jsonrpc:A,method:y.ARKTS_INITIALIZATION_FAILED,params:r.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(d.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:A,method:y.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Yr(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Jr(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){d.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let r=this.lspProxy.reloadDependenciesOnly(e).map(i=>({modulePath:i.modulePath??"",dependencies:i.dependencies??{},dynamicDependencies:i.dynamicDependencies??{}}));this.onMessage({jsonrpc:A,method:y.ARKTS_SYNC_COMPLETED,params:{success:!0,moduleSet:r}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){d.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var Bg=10080*60*1e3,Wg=7200*60*1e3,Ug=120*1e3,$t=class n{manager=null;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;devecoPath;nodeMaxOldSpaceSize;onConfigChangedCallback=null;useStandardProtocol=!0;diagnosticWaiters=new Map;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.devecoPath=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:Lo.object({files:Lo.array(Lo.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:i}=this.resolveProjectAndDeveco();this.useStandardProtocol=i;let o=ue(e),{logPath:s,indexPath:a}=this.getLogAndIndexPath(o);setImmediate(()=>{Ao(a,Bg,"[ArkTS-Check]"),Ao(s,Wg,"[ArkTS-Check]")}),el(s);let c=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,l=Number.isNaN(c)?void 0:c;h.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${l??"undefined \u2192 dynamic formula applies"}`);let u=Y.join(de(t),"sdk");h.info(`ArktsCheck devecoPath: ${t}, contentRoot: ${de(t)}, sdkPath: ${u}`),this.manager=new jt({sdkPath:u,arktsLangServerPath:r,workspaceRoot:j(o),indexLogPath:a,nodeMaxOldSpaceSize:l,useStandardProtocol:i}),this.manager.setOnMessage(f=>this.handleLspMessage(f)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((f,P)=>{this.initResolve=f,this.initReject=P,this.armInitTimer(We),this.manager.start([]).catch(C=>{let L=C instanceof Error?C:new Error(String(C));this.failInit(L)})})}resolveProjectAndDeveco(){let e=Re(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.devecoPath??be();if(h.debug(`DevEco Studio installation path: ${t}, this.devecoPath: ${this.devecoPath}`),!t)throw new Error("DevEco Studio installation path not found");this.devecoPath=t;let r=It(t);if(!r)throw new Error("arkts-lang-server path not found");let i=Y.resolve(r,"ace-server","out","standardIndex","index.js"),o=re.existsSync(i);return h.info(`ArktsCheck protocol: ${o?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${o})`),{harmonyRoot:e,devecoPath:t,arktsLangServerPath:r,useStandardProtocol:o}}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=at(e),i=await re.promises.readFile(e,"utf8"),s=`deveco.apptool.${Y.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,r,i,s):this.checkFileLegacy(t,e,r,i,s)}async checkFileStandard(e,t,r,i){h.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:i,version:1}});try{h.debug(`textDocument/diagnostic uri=${t}`);let o=await e.diagnostic({textDocument:{uri:t}});return zg(o)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:t}})}}async checkFileLegacy(e,t,r,i,o){let s=r;e.registerDiagnosticCallback(r);let a=new Promise((c,l)=>{let u=setTimeout(()=>{this.diagnosticWaiters.delete(s)&&l(new Error("Wait for diagnostics timeout"))},Ug);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:u})});h.debug(`textDocument/didOpen(legacy) uri=${r} content_len=${i.length}`),e.onAsyncOpenFile({textDocument:{uri:r,text:i,languageId:o,version:i.length},editorFiles:[r],isFromEditor:!1});try{return await a}finally{e.closeFileLegacy(r,!1)}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],r=[],i=this.collectValidFiles(e.files,t);return i.length===0?{content:[{type:"text",text:t.length>0?t.join(`
1276
+ `):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],isError:!0}:(await this.runDiagnosticsForFiles(i,t,r),this.formatCallResult(t,r))}async handleLspFeature(e,t){if(!this.initialized)return this.buildNotReadyResponse();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){let s=o instanceof Error?o.message:String(o);return h.error(`handleLspFeature ${e} failed: ${s}`),{content:[{type:"text",text:`${e} failed: ${s}`}],isError:!0}}}async handleWorkspaceSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();h.info(`handleWorkspaceSymbol: query="${e}"`);try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return{content:[{type:"text",text:t==null?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(t,null,2)}`}]}}catch(t){let r=t instanceof Error?t.message:String(t);return h.error(`handleWorkspaceSymbol failed: ${r}`),{content:[{type:"text",text:`workspaceSymbol failed: ${r}`}],isError:!0}}}async handleDocumentSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};h.info(`handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return h.error(`handleDocumentSymbol failed: ${i}`),{content:[{type:"text",text:`documentSymbol failed: ${i}`}],isError:!0}}}async handleCallHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,async o=>{let s=await this.manager.sendFeatureRequest(y.PREPARE_CALL_HIERARCHY,{textDocument:{uri:o},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],calls:[]};let c=e.direction==="incoming"?y.INCOMING_CALLS:y.OUTGOING_CALLS,l=[];for(let u of a){let f=await this.manager.sendFeatureRequest(c,{item:u});Array.isArray(f)?l.push(...f):f&&l.push(f)}return{items:a,calls:l}});return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return h.error(`handleCallHierarchy failed: ${i}`),{content:[{type:"text",text:`callHierarchy failed: ${i}`}],isError:!0}}}async handleCodeAction(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleCodeAction: file=${t} line=${e.line} char=${e.character}`);try{let r=await this.withOpenFile(t,async o=>{let s={line:e.line,character:e.character};return this.manager.sendFeatureRequest(y.CODE_ACTION,{textDocument:{uri:o},range:{start:s,end:s},context:{diagnostics:[]}})});return{content:[{type:"text",text:r==null?"codeAction: no result":`codeAction: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("codeAction",r)}}async handleRename(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleRename: file=${t} line=${e.line} char=${e.character} newName=${e.newName}`);try{let r=await this.withOpenFile(t,async o=>{let s={line:e.line,character:e.character};if(await this.manager.sendFeatureRequest(y.PREPARE_RENAME,{textDocument:{uri:o},position:s})==null)throw new Error("Symbol at this position cannot be renamed");return this.manager.sendFeatureRequest(y.RENAME,{textDocument:{uri:o},position:s,newName:e.newName})});return{content:[{type:"text",text:r==null?"rename: no result":`rename: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("rename",r)}}async handleTypeHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleTypeHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,async o=>{let s=await this.manager.sendFeatureRequest(y.PREPARE_TYPE_HIERARCHY,{textDocument:{uri:o},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 u of a){let f=await this.manager.sendFeatureRequest(c,{item:u});Array.isArray(f)?l.push(...f):f&&l.push(f)}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();h.info("handleCompletionItemResolve");try{let t=await this.manager.sendFeatureRequest(y.COMPLETION_ITEM_RESOLVE,{item:e});return{content:[{type:"text",text:t==null?"completionItemResolve: no result":`completionItemResolve: ${JSON.stringify(t,null,2)}`}]}}catch(t){return this.buildErrorResponse("completionItemResolve",t)}}async handleInlayHint(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};try{let i=(await re.promises.readFile(t,"utf8")).split(`
1277
+ `).length,o=await this.withOpenFile(t,async a=>this.manager.sendFeatureRequest(y.INLAY_HINT,{textDocument:{uri:a},range:{start:{line:0,character:0},end:{line:i,character:0}}}));return{content:[{type:"text",text:o==null?"inlayHint: no result":`inlayHint: ${JSON.stringify(o,null,2)}`}]}}catch(r){return this.buildErrorResponse("inlayHint",r)}}async handleDocumentLink(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_LINK,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentLink: no result":`documentLink: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("documentLink",r)}}buildErrorResponse(e,t){let r=t instanceof Error?t.message:String(t);return h.error(`${e} failed: ${r}`),{content:[{type:"text",text:`${e} failed: ${r}`}],isError:!0}}async withOpenFile(e,t){let r=at(e),i=await re.promises.readFile(e,"utf8"),s=`deveco.apptool.${Y.extname(e).replace(/^\./,"")||"plaintext"}`;h.debug(`withOpenFile didOpen uri=${r} len=${i.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,text:i,languageId:s,version:i.length}});try{return await t(r)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:r},isManual:!1})}}resolveSingleFile(e){let t=Y.isAbsolute(e)?e:Y.join(this.projectPath,e);return!re.existsSync(t)||!re.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,i=[];for(let o of e){let s=Y.isAbsolute(o)?o:Y.join(r,o);if(!re.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!re.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${o}`);continue}if(!s.endsWith(".ets")){t.push(`\u4E0D\u662F .ets \u6587\u4EF6: ${o}`);continue}i.push(s)}return i}async runDiagnosticsForFiles(e,t,r){for(let i of e){await zc(500);try{let o=await this.checkFile(i);r.push(qg(i,o))}catch(o){t.push(`${i} => wait for diagnostics failed: ${o.message}`)}}}formatCallResult(e,t){let r=[];e.length>0&&r.push(e.join(`
1276
1278
  `)),t.length>0&&r.push(t.join(`
1277
1279
  `));let i=r.join(`
1278
- `).trim(),o=e.length>0;return!o&&t.length===0&&(i="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:i}],isError:o}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){h.warn(`Failed to dispose ArktsLspManager: ${t}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":{this.handleDiagnosticsNotification(t.params);break}case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(Fe),h.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{h.info("Received arkts/initialized");let i=this.initResolve;this.clearInitHandlers(),i?.();break}case"arkts/initializationFailed":{let o=t.params?.message??"unknown";h.error(`LSP initialization failed: ${o}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${o}`));break}case"workspace/didChangeConfiguration":h.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let r=this.popDiagnosticWaiter(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.popDiagnosticWaiter(s)}if(!r)return;if(typeof e.errorMessage=="string"){h.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let i=e.diagnostics,o=Array.isArray(i)?i.length:0;h.debug(`diagnostics received uri=${t} count=${o}`),r.resolve(Array.isArray(i)?i:[])}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}getLogAndIndexPath(e){try{let t=Y.join(St(),"ArkTSCheck"),r=Y.join(t,"mapping-config.properties"),i=Hc(e,r),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=Y.join(t,"lsp-log",String(i),o),a=Y.join(t,"lsp-index",String(i));return ne.mkdirSync(s,{recursive:!0}),ne.mkdirSync(a,{recursive:!0}),{logPath:de(s),indexPath:de(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function Ag(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 Tg(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{spawn as xg}from"child_process";import*as R from"fs";import*as W from"path";import{z as Io}from"zod";var dl=60*1e3,kg=30*1e3,Rg=new Set(["textDocument/didOpen","textDocument/didChange","textDocument/didClose","textDocument/didSave"]),Mg=1e3,Do=class{nextRequestId=1;pendingRequests=new Map;diagnosticWaiters=new Map;fileCheckLock=Promise.resolve();closed=!1;wrapperState="preInitialize";queuedDocumentNotifications=[];backendReady=!1;projectPath=null;clangdStdin=null;clangdStdout=null;clangdBuffer=Buffer.alloc(0);constructor(){}isClosed(){return this.closed}async initialize(e){this.projectPath=e,this.wrapperState="waitingForDatabase"}async connectClangdProcess(e,t){if(this.closed)throw new Error("Client is already closed");this.clangdStdin=e,this.clangdStdout=t,this.wrapperState="startingBackend",this.clangdStdout.on("data",a=>this.handleClangdData(a)),this.clangdStdout.on("error",a=>{h.warn(`[CppCheck] clangd stdout error: ${a}`),this.failAll(new Error(`clangd stdout error: ${a}`))}),this.clangdStdout.on("end",()=>{this.failAll(new Error("C++ language server connection closed"))});let r=de(this.projectPath),i=nt(r),o=W.basename(r)||"workspace",s={processId:null,clientInfo:{name:"devecocli-mcp-server",version:"1.3.0-Test.2"},rootPath:r,rootUri:i,workspaceFolders:[{uri:i,name:o}],capabilities:{}};await this.sendRequestToClangd("initialize",s,dl),await this.sendNotificationToClangd("initialized",{}),this.backendReady=!0,this.wrapperState="proxying";for(let a of this.queuedDocumentNotifications)await this.writeToClangd(a);this.queuedDocumentNotifications.length=0,h.info("[CppCheck] clangd backend ready, switched to proxying mode")}async waitForBackendReady(){if(this.backendReady)return;let e=dl,t=Date.now();for(;!this.backendReady&&!this.closed&&Date.now()-t<e;)await new Promise(r=>setTimeout(r,500));if(!this.backendReady)throw new Error("Timed out waiting for clangd backend to be ready")}async checkFile(e){await this.waitForBackendReady();let t=await this.acquireFileCheckLock();try{return await this.doCheckFile(e)}finally{t()}}async doCheckFile(e){let t;try{t=R.realpathSync(e)}catch{t=e}let r=nt(t),i=_c(t),o=await R.promises.readFile(t,"utf8"),s=new Promise((a,c)=>{let l=setTimeout(()=>{this.diagnosticWaiters.delete(r)&&c(new Error(`Timed out waiting for diagnostics: ${e}`))},kg);this.diagnosticWaiters.set(r,{resolve:a,reject:c,timer:l})});try{await this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,languageId:i,version:1,text:o}})}catch(a){let c=this.diagnosticWaiters.get(r);throw c&&(clearTimeout(c.timer),this.diagnosticWaiters.delete(r)),a}try{return await s}finally{await this.closeFile(r).catch(a=>{h.warn(`[CppCheck] didClose failed for ${r}: ${a}`)})}}async close(){if(!this.closed&&(this.closed=!0,this.wrapperState="shuttingDown",this.backendReady&&this.clangdStdin)){try{await this.sendRequestToClangd("shutdown",null,3e3)}catch(e){h.warn(`[CppCheck] shutdown request failed: ${e}`)}try{await this.sendNotificationToClangd("exit",null)}catch(e){h.warn(`[CppCheck] exit notification failed: ${e}`)}try{this.clangdStdin.end()}catch(e){h.warn(`[CppCheck] stdin.end() failed: ${e}`)}}}async sendNotification(e,t){let r={jsonrpc:"2.0",method:e,params:t??void 0};if(this.backendReady&&this.clangdStdin){await this.writeToClangd(r);return}Rg.has(e)&&this.queuedDocumentNotifications.push(r)}async closeFile(e){await this.sendNotification("textDocument/didClose",{textDocument:{uri:e}})}async sendRequestToClangd(e,t,r){let i=this.nextRequestId++;return new Promise((o,s)=>{let a=setTimeout(()=>{this.pendingRequests.delete(i)&&s(new Error(`Timed out waiting for ${e} response`))},r);this.pendingRequests.set(i,{resolve:o,reject:s,timer:a}),this.writeToClangd({jsonrpc:"2.0",id:i,method:e,params:t??void 0}).catch(c=>{this.pendingRequests.delete(i)&&(clearTimeout(a),s(c))})})}async sendNotificationToClangd(e,t){await this.writeToClangd({jsonrpc:"2.0",method:e,params:t??void 0})}async writeToClangd(e){if(!this.clangdStdin)throw new Error("clangd stdin not available");return new Promise((t,r)=>{let i;try{i=JSON.stringify(e)}catch(u){r(new Error(`Failed to encode LSP message: ${u}`));return}let o=Buffer.from(i,"utf8"),s=Buffer.from(`Content-Length: ${o.length}\r
1280
+ `).trim(),o=e.length>0;return!o&&t.length===0&&(i="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:i}],isError:o}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){h.warn(`Failed to dispose ArktsLspManager: ${t}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":{this.handleDiagnosticsNotification(t.params);break}case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(We),h.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{h.info("Received arkts/initialized");let i=this.initResolve;this.clearInitHandlers(),i?.();break}case"arkts/initializationFailed":{let o=t.params?.message??"unknown";h.error(`LSP initialization failed: ${o}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${o}`));break}case"workspace/didChangeConfiguration":h.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let r=this.popDiagnosticWaiter(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.popDiagnosticWaiter(s)}if(!r)return;if(typeof e.errorMessage=="string"){h.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let i=e.diagnostics,o=Array.isArray(i)?i.length:0;h.debug(`diagnostics received uri=${t} count=${o}`),r.resolve(Array.isArray(i)?i:[])}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}getLogAndIndexPath(e){try{let t=Y.join(At(),"ArkTSCheck"),r=Y.join(t,"mapping-config.properties"),i=Gc(e,r),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=Y.join(t,"lsp-log",String(i),o),a=Y.join(t,"lsp-index",String(i));return re.mkdirSync(s,{recursive:!0}),re.mkdirSync(a,{recursive:!0}),{logPath:ue(s),indexPath:ue(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function zg(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 qg(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{spawn as Gg}from"child_process";import*as M from"fs";import*as B from"path";import{z as No}from"zod";var vl=60*1e3,Vg=30*1e3,Yg=new Set(["textDocument/didOpen","textDocument/didChange","textDocument/didClose","textDocument/didSave"]),Jg=1e3,_o=class{nextRequestId=1;pendingRequests=new Map;diagnosticWaiters=new Map;fileCheckLock=Promise.resolve();closed=!1;wrapperState="preInitialize";queuedDocumentNotifications=[];backendReady=!1;projectPath=null;clangdStdin=null;clangdStdout=null;clangdBuffer=Buffer.alloc(0);constructor(){}isClosed(){return this.closed}async initialize(e){this.projectPath=e,this.wrapperState="waitingForDatabase"}async connectClangdProcess(e,t){if(this.closed)throw new Error("Client is already closed");this.clangdStdin=e,this.clangdStdout=t,this.wrapperState="startingBackend",this.clangdStdout.on("data",a=>this.handleClangdData(a)),this.clangdStdout.on("error",a=>{h.warn(`[CppCheck] clangd stdout error: ${a}`),this.failAll(new Error(`clangd stdout error: ${a}`))}),this.clangdStdout.on("end",()=>{this.failAll(new Error("C++ language server connection closed"))});let r=ue(this.projectPath),i=at(r),o=B.basename(r)||"workspace",s={processId:null,clientInfo:{name:"devecocli-mcp-server",version:"1.3.0-Test.3"},rootPath:r,rootUri:i,workspaceFolders:[{uri:i,name:o}],capabilities:{}};await this.sendRequestToClangd("initialize",s,vl),await this.sendNotificationToClangd("initialized",{}),this.backendReady=!0,this.wrapperState="proxying";for(let a of this.queuedDocumentNotifications)await this.writeToClangd(a);this.queuedDocumentNotifications.length=0,h.info("[CppCheck] clangd backend ready, switched to proxying mode")}async waitForBackendReady(){if(this.backendReady)return;let e=vl,t=Date.now();for(;!this.backendReady&&!this.closed&&Date.now()-t<e;)await new Promise(r=>setTimeout(r,500));if(!this.backendReady)throw new Error("Timed out waiting for clangd backend to be ready")}async checkFile(e){await this.waitForBackendReady();let t=await this.acquireFileCheckLock();try{return await this.doCheckFile(e)}finally{t()}}async doCheckFile(e){let t;try{t=M.realpathSync(e)}catch{t=e}let r=at(t),i=qc(t),o=await M.promises.readFile(t,"utf8"),s=new Promise((a,c)=>{let l=setTimeout(()=>{this.diagnosticWaiters.delete(r)&&c(new Error(`Timed out waiting for diagnostics: ${e}`))},Vg);this.diagnosticWaiters.set(r,{resolve:a,reject:c,timer:l})});try{await this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,languageId:i,version:1,text:o}})}catch(a){let c=this.diagnosticWaiters.get(r);throw c&&(clearTimeout(c.timer),this.diagnosticWaiters.delete(r)),a}try{return await s}finally{await this.closeFile(r).catch(a=>{h.warn(`[CppCheck] didClose failed for ${r}: ${a}`)})}}async close(){if(!this.closed&&(this.closed=!0,this.wrapperState="shuttingDown",this.backendReady&&this.clangdStdin)){try{await this.sendRequestToClangd("shutdown",null,3e3)}catch(e){h.warn(`[CppCheck] shutdown request failed: ${e}`)}try{await this.sendNotificationToClangd("exit",null)}catch(e){h.warn(`[CppCheck] exit notification failed: ${e}`)}try{this.clangdStdin.end()}catch(e){h.warn(`[CppCheck] stdin.end() failed: ${e}`)}}}async sendNotification(e,t){let r={jsonrpc:"2.0",method:e,params:t??void 0};if(this.backendReady&&this.clangdStdin){await this.writeToClangd(r);return}Yg.has(e)&&this.queuedDocumentNotifications.push(r)}async closeFile(e){await this.sendNotification("textDocument/didClose",{textDocument:{uri:e}})}async sendRequestToClangd(e,t,r){let i=this.nextRequestId++;return new Promise((o,s)=>{let a=setTimeout(()=>{this.pendingRequests.delete(i)&&s(new Error(`Timed out waiting for ${e} response`))},r);this.pendingRequests.set(i,{resolve:o,reject:s,timer:a}),this.writeToClangd({jsonrpc:"2.0",id:i,method:e,params:t??void 0}).catch(c=>{this.pendingRequests.delete(i)&&(clearTimeout(a),s(c))})})}async sendNotificationToClangd(e,t){await this.writeToClangd({jsonrpc:"2.0",method:e,params:t??void 0})}async writeToClangd(e){if(!this.clangdStdin)throw new Error("clangd stdin not available");return new Promise((t,r)=>{let i;try{i=JSON.stringify(e)}catch(u){r(new Error(`Failed to encode LSP message: ${u}`));return}let o=Buffer.from(i,"utf8"),s=Buffer.from(`Content-Length: ${o.length}\r
1279
1281
  \r
1280
1282
  `,"ascii"),a=!1,c=u=>{a||(a=!0,u?r(u):t())};if(this.clangdStdin.write(Buffer.concat([s,o]),u=>{u?c(u):a||c()}))c();else{let u=()=>c();this.clangdStdin.once("drain",u)}})}handleClangdData(e){for(this.clangdBuffer=this.clangdBuffer.length===0?e:Buffer.concat([this.clangdBuffer,e]);;){let t=this.clangdBuffer.indexOf(`\r
1281
1283
  \r
1282
- `);if(t<0)return;let r=this.clangdBuffer.slice(0,t).toString("ascii"),i=/content-length:\s*(\d+)/i.exec(r);if(!i){this.clangdBuffer=this.clangdBuffer.slice(t+4);continue}let o=parseInt(i[1],10),s=t+4+o;if(this.clangdBuffer.length<s)return;let a=this.clangdBuffer.slice(t+4,s).toString("utf8");this.clangdBuffer=this.clangdBuffer.slice(s);try{let c=JSON.parse(a);this.dispatchMessage(c)}catch(c){h.error(`[CppCheck] Failed to parse C++ LSP JSON message: ${c}`)}}}dispatchMessage(e){if(typeof e.id=="number"){let t=this.pendingRequests.get(e.id);t&&(this.pendingRequests.delete(e.id),clearTimeout(t.timer),e.error?t.reject(new Error(e.error.message??JSON.stringify(e.error))):t.resolve(e.result??null));return}if(e.method==="textDocument/publishDiagnostics"&&e.params){let t=e.params,r=t.uri;if(!r)return;let i=Og(r),o=this.diagnosticWaiters.get(i);if(o){this.diagnosticWaiters.delete(i),clearTimeout(o.timer);let s=Array.isArray(t.diagnostics)?t.diagnostics:[];h.info(`[CppCheck] Received C++ diagnostics for ${i} (${s.length} entries)`),o.resolve(s)}}}failAll(e){for(let[,t]of this.pendingRequests)clearTimeout(t.timer),t.reject(e);this.pendingRequests.clear();for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear()}async acquireFileCheckLock(){let e=this.fileCheckLock,t;return this.fileCheckLock=new Promise(r=>{t=r}),await e,t}};function Og(n){try{let e=new URL(n);if(e.protocol==="file:"){let t=decodeURIComponent(e.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(t)&&(t=t.slice(1)),nt(t)}}catch{}return n}function Lg(n){let e=W.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function Ng(n,e){let t=W.join(n,e.name);return e.isDirectory()?e.name===".cxx"||ul(t):Lg(t)}function ul(n){if(!R.existsSync(n))return!1;try{return R.readdirSync(n,{withFileTypes:!0}).some(t=>Ng(n,t))}catch{}return!1}function pl(n){let t=new ke(n).getAllModuleInfo(),r=[];for(let i of t){let o=b.resolvePathWithinRoot(n,i.srcPath);ul(o)&&r.push(i)}return r}function _g(n){let e=[],r=new ke(n).getAllModuleInfo();for(let i of r){let o=b.resolvePathWithinRoot(n,i.srcPath),s=W.join(o,".cxx");R.existsSync(s)&&ml(s,e)}return e}function ml(n,e){try{let t=R.readdirSync(n,{withFileTypes:!0});for(let r of t){let i=W.join(n,r.name);r.isDirectory()?ml(i,e):r.name==="compile_commands.json"&&e.push(i)}}catch{}}function Hg(n){let e=[];for(let t of n)try{let r=R.readFileSync(t,"utf8"),i=JSON.parse(r);e.push(...i)}catch{}return e}function Fg(n,e){let t=W.join(n,...fo.slice(0,-1));R.mkdirSync(t,{recursive:!0});let r=W.join(t,"compile_commands.json");R.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function jg(n){let e=_g(n);if(e.length>0){let t=Hg(e);Fg(n,t),h.info(`[CppCheck] compile_commands.json \u5DF2\u751F\u6210\uFF0C\u5171 ${t.length} \u6761\u7F16\u8BD1\u547D\u4EE4`)}else h.warn("[CppCheck] \u672A\u627E\u5230\u4EFB\u4F55 compile_commands.json \u6587\u4EF6")}function $g(n){let e=new Set;for(let t of n)if(t.file)try{e.add(R.realpathSync(t.file))}catch{e.add(t.file)}return e}function Wg(n,e){try{let t=R.realpathSync(n);if(!e.has(t))return h.info(`[CppCheck] File not covered by compile_commands.json: ${n}`),!1}catch{}return!0}function Bg(n,e){if(!R.existsSync(n))return!1;try{let t=R.readFileSync(n,"utf8"),r=JSON.parse(t),i=$g(r);for(let o of e)if(!Wg(o,i))return!1;return!0}catch(t){return h.warn(`[CppCheck] Failed to read/parse compile_commands.json: ${t}`),!1}}async function Ug(n,e,t){let r=W.join(le(e),"sdk"),i=process.execPath||"node",o=W.join(le(e),"tools");h.info(`CppCheck devecoPath: ${e}, contentRoot: ${le(e)}, sdkPath: ${r}, toolsDir: ${o}`);let s=W.join(o,"hvigor","bin","hvigorw.js");for(let a of t){let c=["--mode","module","-p",`module=${a.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"].join(" ");h.info(`[CppCheck] Running compileNative for module: ${a.name}`);let l=await Eo(n,i,s,r,c);l.success?h.info(`[CppCheck] compileNative ${a.name} \u6210\u529F`):h.warn(`[CppCheck] compileNative ${a.name} \u5931\u8D25: ${l.output}`)}}async function zg(n,e){let t=pl(n);if(t.length===0){h.info("[CppCheck] \u672A\u53D1\u73B0\u542BC++\u7684\u6A21\u5757\uFF0C\u8DF3\u8FC7\u521D\u59CB\u5316");return}h.info(`[CppCheck] \u53D1\u73B0 ${t.length} \u4E2A\u542BC++\u7684\u6A21\u5757: ${t.map(r=>r.name).join(", ")}`),await Ug(n,e,t),jg(n)}var Nt=class{projectPath;devecoPath;clangdProcess=null;client=null;initializedProjectPath=null;initializing=!1;initPromise=null;pollHandle=null;backendReady=!1;constructor(e,t){this.projectPath=e,this.devecoPath=ar(t??"")??t??null}static getToolDefinition(){return{name:"check_cpp_files",description:"\u5BF9\u4F20\u5165\u7684 C/C++ \u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5\u5E76\u8FD4\u56DE clangd \u8BCA\u65AD\u4FE1\u606F\u3002",inputSchema:Io.object({files:Io.array(Io.string()).describe('\u5F85\u68C0\u67E5\u7684 C/C++ \u6587\u4EF6\u8DEF\u5F84\u5217\u8868\uFF0C\u683C\u5F0F\u4E3A ["file1.cpp","file2.hpp",...]')})}}isInitializing(){return this.initializing}isInitialized(){return this.client!==null&&this.initializedProjectPath!==null}async handleCall(e){let t=[],r=[],i=this.collectValidFiles(e.files,t);if(i.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
1284
+ `);if(t<0)return;let r=this.clangdBuffer.slice(0,t).toString("ascii"),i=/content-length:\s*(\d+)/i.exec(r);if(!i){this.clangdBuffer=this.clangdBuffer.slice(t+4);continue}let o=parseInt(i[1],10),s=t+4+o;if(this.clangdBuffer.length<s)return;let a=this.clangdBuffer.slice(t+4,s).toString("utf8");this.clangdBuffer=this.clangdBuffer.slice(s);try{let c=JSON.parse(a);this.dispatchMessage(c)}catch(c){h.error(`[CppCheck] Failed to parse C++ LSP JSON message: ${c}`)}}}dispatchMessage(e){if(typeof e.id=="number"){let t=this.pendingRequests.get(e.id);t&&(this.pendingRequests.delete(e.id),clearTimeout(t.timer),e.error?t.reject(new Error(e.error.message??JSON.stringify(e.error))):t.resolve(e.result??null));return}if(e.method==="textDocument/publishDiagnostics"&&e.params){let t=e.params,r=t.uri;if(!r)return;let i=Kg(r),o=this.diagnosticWaiters.get(i);if(o){this.diagnosticWaiters.delete(i),clearTimeout(o.timer);let s=Array.isArray(t.diagnostics)?t.diagnostics:[];h.info(`[CppCheck] Received C++ diagnostics for ${i} (${s.length} entries)`),o.resolve(s)}}}failAll(e){for(let[,t]of this.pendingRequests)clearTimeout(t.timer),t.reject(e);this.pendingRequests.clear();for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear()}async acquireFileCheckLock(){let e=this.fileCheckLock,t;return this.fileCheckLock=new Promise(r=>{t=r}),await e,t}};function Kg(n){try{let e=new URL(n);if(e.protocol==="file:"){let t=decodeURIComponent(e.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(t)&&(t=t.slice(1)),at(t)}}catch{}return n}function Zg(n){let e=B.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function Xg(n,e){let t=B.join(n,e.name);return e.isDirectory()?e.name===".cxx"||wl(t):Zg(t)}function wl(n){if(!M.existsSync(n))return!1;try{return M.readdirSync(n,{withFileTypes:!0}).some(t=>Xg(n,t))}catch{}return!1}function bl(n){let t=new Oe(n).getAllModuleInfo(),r=[];for(let i of t){let o=b.resolvePathWithinRoot(n,i.srcPath);wl(o)&&r.push(i)}return r}function Qg(n){let e=[],r=new Oe(n).getAllModuleInfo();for(let i of r){let o=b.resolvePathWithinRoot(n,i.srcPath),s=B.join(o,".cxx");M.existsSync(s)&&Sl(s,e)}return e}function Sl(n,e){try{let t=M.readdirSync(n,{withFileTypes:!0});for(let r of t){let i=B.join(n,r.name);r.isDirectory()?Sl(i,e):r.name==="compile_commands.json"&&e.push(i)}}catch{}}function ey(n){let e=[];for(let t of n)try{let r=M.readFileSync(t,"utf8"),i=JSON.parse(r);e.push(...i)}catch{}return e}function ty(n,e){let t=B.join(n,...Do.slice(0,-1));M.mkdirSync(t,{recursive:!0});let r=B.join(t,"compile_commands.json");M.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function ny(n){let e=Qg(n);if(e.length>0){let t=ey(e);ty(n,t),h.info(`[CppCheck] compile_commands.json \u5DF2\u751F\u6210\uFF0C\u5171 ${t.length} \u6761\u7F16\u8BD1\u547D\u4EE4`)}else h.warn("[CppCheck] \u672A\u627E\u5230\u4EFB\u4F55 compile_commands.json \u6587\u4EF6")}function ry(n){let e=new Set;for(let t of n)if(t.file)try{e.add(M.realpathSync(t.file))}catch{e.add(t.file)}return e}function iy(n,e){try{let t=M.realpathSync(n);if(!e.has(t))return h.info(`[CppCheck] File not covered by compile_commands.json: ${n}`),!1}catch{}return!0}function oy(n,e){if(!M.existsSync(n))return!1;try{let t=M.readFileSync(n,"utf8"),r=JSON.parse(t),i=ry(r);for(let o of e)if(!iy(o,i))return!1;return!0}catch(t){return h.warn(`[CppCheck] Failed to read/parse compile_commands.json: ${t}`),!1}}async function sy(n,e,t){let r=B.join(de(e),"sdk"),i=process.execPath||"node",o=B.join(de(e),"tools");h.info(`CppCheck devecoPath: ${e}, contentRoot: ${de(e)}, sdkPath: ${r}, toolsDir: ${o}`);let s=B.join(o,"hvigor","bin","hvigorw.js");for(let a of t){let c=["--mode","module","-p",`module=${a.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"].join(" ");h.info(`[CppCheck] Running compileNative for module: ${a.name}`);let l=await Mo(n,i,s,r,c);l.success?h.info(`[CppCheck] compileNative ${a.name} \u6210\u529F`):h.warn(`[CppCheck] compileNative ${a.name} \u5931\u8D25: ${l.output}`)}}async function ay(n,e){let t=bl(n);if(t.length===0){h.info("[CppCheck] \u672A\u53D1\u73B0\u542BC++\u7684\u6A21\u5757\uFF0C\u8DF3\u8FC7\u521D\u59CB\u5316");return}h.info(`[CppCheck] \u53D1\u73B0 ${t.length} \u4E2A\u542BC++\u7684\u6A21\u5757: ${t.map(r=>r.name).join(", ")}`),await sy(n,e,t),ny(n)}var Bt=class{projectPath;devecoPath;clangdProcess=null;client=null;initializedProjectPath=null;initializing=!1;initPromise=null;pollHandle=null;backendReady=!1;constructor(e,t){this.projectPath=e,this.devecoPath=fr(t??"")??t??null}static getToolDefinition(){return{name:"check_cpp_files",description:"\u5BF9\u4F20\u5165\u7684 C/C++ \u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5\u5E76\u8FD4\u56DE clangd \u8BCA\u65AD\u4FE1\u606F\u3002",inputSchema:No.object({files:No.array(No.string()).describe('\u5F85\u68C0\u67E5\u7684 C/C++ \u6587\u4EF6\u8DEF\u5F84\u5217\u8868\uFF0C\u683C\u5F0F\u4E3A ["file1.cpp","file2.hpp",...]')})}}isInitializing(){return this.initializing}isInitialized(){return this.client!==null&&this.initializedProjectPath!==null}async handleCall(e){let t=[],r=[],i=this.collectValidFiles(e.files,t);if(i.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
1283
1285
  `):"\u6CA1\u6709\u6709\u6548\u7684 C/C++ \u6587\u4EF6"}],isError:!0};let o;try{o=await this.ensureInitializedWithFiles(i)}catch(a){return t.push(a.message),{content:[{type:"text",text:t.join(`
1284
1286
  `)}],isError:!0}}return await this.runDiagnosticsForFiles(o,i,t,r)&&this.shutdown().catch(a=>{h.warn(`[CppCheck] shutdown after diagnostic failure: ${a}`)}),this.formatCallResult(t,r)}async runDiagnosticsForFiles(e,t,r,i){let o=!1;for(let s of t)try{let a=await e.checkFile(s);a.length===0?i.push(`${s} => \u65E0\u8BCA\u65AD`):i.push(`${s} => Diagnostic: ${JSON.stringify(a)}`)}catch(a){o=!0,r.push(`${s} => \u83B7\u53D6\u8BCA\u65AD\u5931\u8D25: ${a.message}`)}return o}formatCallResult(e,t){let r=e.length>0;return!r&&t.length===0&&t.push("\u6CA1\u6709\u8FD4\u56DE\u4EFB\u4F55\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:[t.join(`
1285
1287
  `),e.join(`
1286
1288
  `)].filter(o=>o.trim().length>0).join(`
1287
- `).trim()}],isError:r}}async ensureInitializedWithFiles(e){let t=de(this.projectPath);if(this.prepareCppCheck(t,e)){this.client&&this.initializedProjectPath&&(h.info("[CppCheck] Re-initializing C++ project due to file changes"),await this.shutdown());let i=this.devecoPath??Te();if(!i)throw new Error("DevEco Studio installation path not found");this.devecoPath=i,await zg(t,i)}else if(this.client&&this.initializedProjectPath){let i=de(this.projectPath);if(this.initializedProjectPath===i)return this.client;await this.shutdown()}return this.doEnsureInitialized()}prepareCppCheck(e,t){let r=sr(e);return R.existsSync(r)?pl(e).length===0?(h.info("[CppCheck] No cpp modules found, no initialization needed"),!1):Bg(r,t)?(h.info("[CppCheck] All files covered, no initialization needed"),!1):(h.info("[CppCheck] Files not fully covered by compile_commands.json, needs initialization"),!0):(h.info("[CppCheck] compile_commands.json not found, needs initialization"),!0)}async doEnsureInitialized(){if(this.initPromise&&(await this.initPromise,this.client))return this.client;if(this.initializing=!0,this.initPromise=this.doInitialize().finally(()=>{this.initializing=!1,this.initPromise=null}),await this.initPromise,!this.client)throw new Error("C++ LSP failed to initialize");return this.client}async doInitialize(){let e=this.resolveProjectRoot();this.client=new Do,await this.client.initialize(e),this.initializedProjectPath=e,h.info(`[CppCheck] Client initialized in wrapper mode for workspace: ${e}`),this.startPollingForClangd(e)}resolveProjectRoot(){let e=Ae(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);return this.projectPath=e,de(e)}startPollingForClangd(e){let t=sr(e);if(R.existsSync(t)){h.info("[CppCheck] compile_commands.json found, spawning clangd immediately"),this.spawnAndConnectClangd(e).catch(r=>{h.error(`[CppCheck] Immediate clangd spawn failed: ${r}`)});return}h.info("[CppCheck] compile_commands.json not found, starting poll..."),this.pollHandle=setInterval(()=>{if(!this.client||this.client.isClosed()||this.backendReady){this.stopPolling();return}R.existsSync(t)&&(this.stopPolling(),h.info("[CppCheck] compile_commands.json found via poll, spawning clangd..."),this.spawnAndConnectClangd(e).catch(r=>{h.error(`[CppCheck] Clangd spawn from poll failed: ${r}`)}))},Mg)}stopPolling(){this.pollHandle&&(clearInterval(this.pollHandle),this.pollHandle=null)}async spawnAndConnectClangd(e){let{clangdPath:t,compileCommandsDir:r}=this.resolveClangdPaths(e);h.info(`[CppCheck] Starting clangd for workspace: ${e} (clangd=${t})`);let i=this.spawnClangd(t,e,r);this.clangdProcess=i;try{await this.client.connectClangdProcess(i.stdin,i.stdout),this.backendReady=!0,h.info(`[CppCheck] clangd connected for workspace: ${e}`)}catch(o){if(h.error(`[CppCheck] Failed to connect clangd: ${o}`),this.clangdProcess&&!this.clangdProcess.killed){try{this.clangdProcess.kill()}catch{}this.clangdProcess=null}throw o}}resolveClangdPaths(e){let t=this.devecoPath??Te();if(!t)throw new Error("DevEco Studio installation path not found");this.devecoPath=t;let r=Oc(t);if(!r)throw new Error("clangd executable not found inside DevEco Studio SDK");let i=sr(e),o=W.dirname(i);return{clangdPath:r,compileCommandsDir:o}}spawnClangd(e,t,r){let i=xg(e,[`--compile-commands-dir=${r}`],{cwd:t,stdio:["pipe","pipe","pipe"]});if(!i.stdin||!i.stdout||!i.stderr)throw new Error("Failed to start clangd: stdio not available");return i.stderr.on("data",o=>{let s=o.toString("utf8").trimEnd();s&&h.warn(`[CppLsp stderr] ${s}`)}),i.on("exit",(o,s)=>{h.warn(`[CppCheck] clangd exited code=${o} signal=${s??"null"}`),this.clangdProcess===i&&(this.clangdProcess=null,this.backendReady=!1)}),i.on("error",o=>{h.error(`[CppCheck] clangd spawn error: ${o}`)}),i}collectValidFiles(e,t){let r=this.projectPath,i=[];for(let o of e){let s=W.isAbsolute(o)?o:W.join(r,o);if(!R.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!R.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${o}`);continue}if(!cr(s)){t.push(`\u4E0D\u662F\u53D7\u652F\u6301\u7684 C/C++ \u6587\u4EF6: ${o}`);continue}try{i.push(R.realpathSync(s))}catch{i.push(s)}}return i}async shutdown(){this.stopPolling();let e=this.client,t=this.clangdProcess;if(this.client=null,this.clangdProcess=null,this.initializedProjectPath=null,this.backendReady=!1,e)try{await e.close()}catch(r){h.warn(`[CppCheck] client.close() failed: ${r}`)}if(t&&!t.killed)try{t.kill()}catch(r){h.warn(`[CppCheck] failed to kill clangd: ${r}`)}}};import*as Ht from"fs";import*as _t from"path";var qg=1e3;function hl(n,e){if(e)return d.info(`[SyncGuard] ${C.ENV_FORCE_SYNC}=1, forcing sync`),{required:!0,reason:`${C.ENV_FORCE_SYNC}=1`};let t=_t.join(n,tl);if(!Ht.existsSync(t))return d.info(`[SyncGuard] Baseline file not found: ${t}`),{required:!0,reason:"sync baseline file not found: "+t};let r=Ht.statSync(t).mtimeMs;d.info(`[SyncGuard] Sync baseline: ${new Date(r).toISOString()} (${t})`);let i=Gg(n);if(i===null)return d.warn("[SyncGuard] Failed to parse build-profile.json5, falling back to sync"),{required:!0,reason:"failed to parse build-profile.json5"};let o=_t.join(n,C.OH_PACKAGE_JSON5),s=Ao(o,r,"root");if(s.required)return d.info(`[SyncGuard] Root check: ${s.reason}`),s;let a=_t.join(n,"build-profile.json5"),c=Ao(a,r,"build-profile");if(c.required)return d.info(`[SyncGuard] Build profile check: ${c.reason}`),c;for(let u of i){let f=_t.join(n,u.srcPath,C.OH_PACKAGE_JSON5),E=Ao(f,r,u.name);if(E.required)return d.info(`[SyncGuard] Module '${u.name}' check: ${E.reason}`),E}let l=`all oh-package.json5 files are up-to-date (sync baseline: ${new Date(r).toISOString()})`;return d.info(`[SyncGuard] ${l}`),{required:!1,reason:l}}function Ao(n,e,t){if(!Ht.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=Ht.statSync(n).mtimeMs;return r-e>qg?{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 Gg(n){let e=_t.join(n,"build-profile.json5");try{let t=te(e);if(typeof t!="object"||t===null)return null;let r=t.modules;return Array.isArray(r)?r.filter(i=>{if(typeof i!="object"||i===null)return!1;let o=i;return typeof o.name=="string"&&typeof o.srcPath=="string"}):null}catch{return null}}var xo=(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))(xo||{}),To=3,fl=600*1e3,qr=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;projectState=0;workspaceRoot="";sdkPath="";initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;constructor(e={}){this.config=e,dn(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),h.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",h.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,h.info(`Constructor: using configured path as startPath: '${t}'`));let i=Ae(t);h.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0,this.server=new Yg({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=po(),this.registerTools()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools()}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:V.object({files:V.array(V.string()).min(1).describe("List of source file paths to check, relative to the project root. Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}registerLspFeatureTools(){let e=V.object({file:V.string().describe("ArkTS (.ets) file path, relative to the project root"),line:V.number().describe("Line number (0-based)"),character:V.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature:i}of this.getPositionFeatures())this.toolRouter.add({name:t,description:r,inputSchema:e},async o=>this.handleLspFeatureCall(i,o));this.registerSymbolTools(),this.registerCallHierarchyTool()}getPositionFeatures(){return[{name:"hover",description:"Get hover information (type info, documentation) at a specific position in an ArkTS (.ets) 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:V.object({query:V.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) file. Useful for file overview, structured code breakdown, and large file slicing.",inputSchema:V.object({file:V.string().describe("ArkTS (.ets) file path, relative to the project root")})},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.',inputSchema:V.object({file:V.string().describe("ArkTS (.ets) file path, relative to the project root"),line:V.number().describe("Line number (0-based)"),character:V.number().describe("Character offset in the line (0-based)"),direction:V.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}validateContainment(e){let t=this.config.projectPath;if(t){let i=[];for(let o of e){let s=b.isPathContainedWithSymlink(o,t);s.contained||(h.warn(`Containment check failed: ${s.reason}`),i.push(s.reason))}return i.length>0?{content:[{type:"text",text:i.join(`
1288
- `)}],isError:!0}:null}let r=e.filter(i=>Ft.isAbsolute(i));return r.length>0?(h.warn(`Absolute paths rejected (no project root): ${r.join(", ")}`),{content:[{type:"text",text:r.map(i=>`Absolute path is not allowed: ${i}`).join(`
1289
- `)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(f=>typeof f=="string"):[];if(t.length===0)return h.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};let r=this.validateContainment(t);if(r)return r;let{etsFiles:i,cppFiles:o,unsupported:s}=Jg(t);s.length>0&&h.warn(`Unsupported file types in check request: ${s.join(", ")}`);let a=s.map(f=>`Unsupported file type: ${f} (only .ets and C/C++ source/header files are supported)`),c=[];i.length>0&&this.mergeCheckResult(await this.callArktsCheck(i),a,c),o.length>0&&this.mergeCheckResult(await this.callCppCheck(o),a,c);let l=a.length>0;return{content:[{type:"text",text:[c.join(`
1289
+ `).trim()}],isError:r}}async ensureInitializedWithFiles(e){let t=ue(this.projectPath);if(this.prepareCppCheck(t,e)){this.client&&this.initializedProjectPath&&(h.info("[CppCheck] Re-initializing C++ project due to file changes"),await this.shutdown());let i=this.devecoPath??be();if(!i)throw new Error("DevEco Studio installation path not found");this.devecoPath=i,await ay(t,i)}else if(this.client&&this.initializedProjectPath){let i=ue(this.projectPath);if(this.initializedProjectPath===i)return this.client;await this.shutdown()}return this.doEnsureInitialized()}prepareCppCheck(e,t){let r=hr(e);return M.existsSync(r)?bl(e).length===0?(h.info("[CppCheck] No cpp modules found, no initialization needed"),!1):oy(r,t)?(h.info("[CppCheck] All files covered, no initialization needed"),!1):(h.info("[CppCheck] Files not fully covered by compile_commands.json, needs initialization"),!0):(h.info("[CppCheck] compile_commands.json not found, needs initialization"),!0)}async doEnsureInitialized(){if(this.initPromise&&(await this.initPromise,this.client))return this.client;if(this.initializing=!0,this.initPromise=this.doInitialize().finally(()=>{this.initializing=!1,this.initPromise=null}),await this.initPromise,!this.client)throw new Error("C++ LSP failed to initialize");return this.client}async doInitialize(){let e=this.resolveProjectRoot();this.client=new _o,await this.client.initialize(e),this.initializedProjectPath=e,h.info(`[CppCheck] Client initialized in wrapper mode for workspace: ${e}`),this.startPollingForClangd(e)}resolveProjectRoot(){let e=Re(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);return this.projectPath=e,ue(e)}startPollingForClangd(e){let t=hr(e);if(M.existsSync(t)){h.info("[CppCheck] compile_commands.json found, spawning clangd immediately"),this.spawnAndConnectClangd(e).catch(r=>{h.error(`[CppCheck] Immediate clangd spawn failed: ${r}`)});return}h.info("[CppCheck] compile_commands.json not found, starting poll..."),this.pollHandle=setInterval(()=>{if(!this.client||this.client.isClosed()||this.backendReady){this.stopPolling();return}M.existsSync(t)&&(this.stopPolling(),h.info("[CppCheck] compile_commands.json found via poll, spawning clangd..."),this.spawnAndConnectClangd(e).catch(r=>{h.error(`[CppCheck] Clangd spawn from poll failed: ${r}`)}))},Jg)}stopPolling(){this.pollHandle&&(clearInterval(this.pollHandle),this.pollHandle=null)}async spawnAndConnectClangd(e){let{clangdPath:t,compileCommandsDir:r}=this.resolveClangdPaths(e);h.info(`[CppCheck] Starting clangd for workspace: ${e} (clangd=${t})`);let i=this.spawnClangd(t,e,r);this.clangdProcess=i;try{await this.client.connectClangdProcess(i.stdin,i.stdout),this.backendReady=!0,h.info(`[CppCheck] clangd connected for workspace: ${e}`)}catch(o){if(h.error(`[CppCheck] Failed to connect clangd: ${o}`),this.clangdProcess&&!this.clangdProcess.killed){try{this.clangdProcess.kill()}catch{}this.clangdProcess=null}throw o}}resolveClangdPaths(e){let t=this.devecoPath??be();if(!t)throw new Error("DevEco Studio installation path not found");this.devecoPath=t;let r=Wc(t);if(!r)throw new Error("clangd executable not found inside DevEco Studio SDK");let i=hr(e),o=B.dirname(i);return{clangdPath:r,compileCommandsDir:o}}spawnClangd(e,t,r){let i=Gg(e,[`--compile-commands-dir=${r}`],{cwd:t,stdio:["pipe","pipe","pipe"]});if(!i.stdin||!i.stdout||!i.stderr)throw new Error("Failed to start clangd: stdio not available");return i.stderr.on("data",o=>{let s=o.toString("utf8").trimEnd();s&&h.warn(`[CppLsp stderr] ${s}`)}),i.on("exit",(o,s)=>{h.warn(`[CppCheck] clangd exited code=${o} signal=${s??"null"}`),this.clangdProcess===i&&(this.clangdProcess=null,this.backendReady=!1)}),i.on("error",o=>{h.error(`[CppCheck] clangd spawn error: ${o}`)}),i}collectValidFiles(e,t){let r=this.projectPath,i=[];for(let o of e){let s=B.isAbsolute(o)?o:B.join(r,o);if(!M.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!M.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${o}`);continue}if(!gr(s)){t.push(`\u4E0D\u662F\u53D7\u652F\u6301\u7684 C/C++ \u6587\u4EF6: ${o}`);continue}try{i.push(M.realpathSync(s))}catch{i.push(s)}}return i}async shutdown(){this.stopPolling();let e=this.client,t=this.clangdProcess;if(this.client=null,this.clangdProcess=null,this.initializedProjectPath=null,this.backendReady=!1,e)try{await e.close()}catch(r){h.warn(`[CppCheck] client.close() failed: ${r}`)}if(t&&!t.killed)try{t.kill()}catch(r){h.warn(`[CppCheck] failed to kill clangd: ${r}`)}}};function El(n){let e=Yn(n);return d.info(`[SyncGuard] ${e.reason}`),e}var Fo=(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))(Fo||{}),Ho=3,Pl=600*1e3,Qr=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;projectState=0;workspaceRoot="";sdkPath="";initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;standardProtocolAvailable=!1;constructor(e={}){this.config=e,fn(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),h.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",h.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,h.info(`Constructor: using configured path as startPath: '${t}'`));let i=Re(t);h.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0,this.server=new cy({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=Eo(),this.standardProtocolAvailable=this.detectStandardProtocolAvailable(),this.registerTools()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools()}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:J.object({files:J.array(J.string()).min(1).describe("List of source file paths to check, relative to the project root. Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}registerLspFeatureTools(){if(!this.standardProtocolAvailable){h.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=J.object({file:J.string().describe("ArkTS (.ets) file path, relative to the project root"),line:J.number().describe("Line number (0-based)"),character:J.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature:i}of this.getPositionFeatures())this.toolRouter.add({name:t,description:r,inputSchema:e},async o=>this.handleLspFeatureCall(i,o));this.registerSymbolTools(),this.registerCallHierarchyTool()}getPositionFeatures(){return[{name:"hover",description:"Get hover information (type info, documentation) at a specific position in an ArkTS (.ets) 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:J.object({query:J.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) file. Useful for file overview, structured code breakdown, and large file slicing.",inputSchema:J.object({file:J.string().describe("ArkTS (.ets) file path, relative to the project root")})},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.',inputSchema:J.object({file:J.string().describe("ArkTS (.ets) file path, relative to the project root"),line:J.number().describe("Line number (0-based)"),character:J.number().describe("Character offset in the line (0-based)"),direction:J.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.devecoPath??be();if(!e)return h.info("Standard LSP protocol unavailable: DevEco Studio installation path not found"),!1;let t=It(e);if(!t)return h.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let r=ut.join(t,"ace-server","out","standardIndex","index.js"),i=Cl.existsSync(r);return h.info(`ArktsCheck protocol: ${i?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${i})`),i}catch(e){return h.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}validateContainment(e){let t=this.config.projectPath;if(t){let i=[];for(let o of e){let s=b.isPathContainedWithSymlink(o,t);s.contained||(h.warn(`Containment check failed: ${s.reason}`),i.push(s.reason))}return i.length>0?{content:[{type:"text",text:i.join(`
1290
+ `)}],isError:!0}:null}let r=e.filter(i=>ut.isAbsolute(i));return r.length>0?(h.warn(`Absolute paths rejected (no project root): ${r.join(", ")}`),{content:[{type:"text",text:r.map(i=>`Absolute path is not allowed: ${i}`).join(`
1291
+ `)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(f=>typeof f=="string"):[];if(t.length===0)return h.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};let r=this.validateContainment(t);if(r)return r;let{etsFiles:i,cppFiles:o,unsupported:s}=dy(t);s.length>0&&h.warn(`Unsupported file types in check request: ${s.join(", ")}`);let a=s.map(f=>`Unsupported file type: ${f} (only .ets and C/C++ source/header files are supported)`),c=[];i.length>0&&this.mergeCheckResult(await this.callArktsCheck(i),a,c),o.length>0&&this.mergeCheckResult(await this.callCppCheck(o),a,c);let l=a.length>0;return{content:[{type:"text",text:[c.join(`
1290
1292
  `),a.join(`
1291
1293
  `)].filter(f=>f.trim().length>0).join(`
1292
- `).trim()||"No diagnostics collected"}],isError:l}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS check rejected: project is ${xo[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e})}}async handleLspFeatureCall(e,t){let r=t.file,i=t.line,o=t.character;if(typeof r!="string"||typeof i!="number"||typeof o!="number")return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};let s=this.validateContainment([r]);return s||this.callArktsFeature(e,{file:r,line:i,character:o})}async handleWorkspaceSymbolCall(e){let t=e.query;return typeof t!="string"||t.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameter: query (non-empty string required)."}],isError:!0}:this.callArktsWorkspaceSymbol(t)}async handleDocumentSymbolCall(e){let t=e.file;if(typeof t!="string")return{content:[{type:"text",text:"Missing or invalid parameter: file (string required)."}],isError:!0};let r=this.validateContainment([t]);return r||this.routeArktsRequest("documentSymbol",()=>this.arktsCheckTool.handleDocumentSymbol(t))}async handleCallHierarchyCall(e){let t=e.file,r=e.line,i=e.character,o=e.direction;if(typeof t!="string"||typeof r!="number"||typeof i!="number")return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};if(o!=="incoming"&&o!=="outgoing")return{content:[{type:"text",text:'Parameter direction must be "incoming" or "outgoing".'}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest(`callHierarchy(${o})`,()=>this.arktsCheckTool.handleCallHierarchy({file:t,line:r,character:i,direction:o}))}async handleCodeActionCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e);if(!t)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};let o=this.validateContainment([t]);return o||this.routeArktsRequest("codeAction",()=>this.arktsCheckTool.handleCodeAction({file:t,line:r,character:i}))}async handleRenameCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e),o=e.newName;if(!t||typeof o!="string"||o.trim().length===0)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number), newName (non-empty string)."}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest("rename",()=>this.arktsCheckTool.handleRename({file:t,line:r,character:i,newName:o}))}async handleTypeHierarchyCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e),o=e.direction;if(!t)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};if(o!=="supertypes"&&o!=="subtypes")return{content:[{type:"text",text:'Parameter direction must be "supertypes" or "subtypes".'}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest(`typeHierarchy(${o})`,()=>this.arktsCheckTool.handleTypeHierarchy({file:t,line:r,character:i,direction:o}))}async handleCompletionItemResolveCall(e){let t=e.item;return t==null?{content:[{type:"text",text:"Missing parameter: item (completion item object required)."}],isError:!0}:this.routeArktsRequest("completionItemResolve",()=>this.arktsCheckTool.handleCompletionItemResolve(t))}extractPositionArgs(e){let t=e.file,r=e.line,i=e.character;return typeof t!="string"||typeof r!="number"||typeof i!="number"?{file:null,line:0,character:0}:{file:t,line:r,character:i}}async callArktsFeature(e,t){return this.routeArktsRequest(e,()=>this.arktsCheckTool.handleLspFeature(e,t))}async callArktsWorkspaceSymbol(e){return this.routeArktsRequest("workspaceSymbol",()=>this.arktsCheckTool.handleWorkspaceSymbol(e))}async routeArktsRequest(e,t){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS ${e} rejected: project is ${xo[this.projectState]}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS ${e} rejected: LSP is initializing`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return t()}}async handleIdleCheck(){if(this.ensureProjectReady(),this.config.projectPath){let e,t;return this.syncSkippedDueToLock?(e=`Another build process is running, sync deferred (waiting ${this.syncSkipStartedAt>0?Math.round((Date.now()-this.syncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,t="lock contention",this.syncSkippedDueToLock=!1):this.configChangedTriggeredResync?(e="Config file changed, resyncing project, please retry in 10 seconds",t="config changed",this.configChangedTriggeredResync=!1):(e="HarmonyOS project detected, syncing, please retry in 10 seconds",t="initial"),h.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(h.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(h.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=To?(h.error(`Init retry limit reached (${this.initRetryCount}/${To}), will not auto-retry`),{content:[{type:"text",text:"Project initialization failed multiple times. Please check project configuration and restart the MCP Server."}],isError:!0}):(h.info(`Error check: auto-retrying (${this.initRetryCount}/${To})`),this.ensureProjectReady(),{content:[{type:"text",text:"Project initialization failed, auto-retrying, please retry in 10 seconds"}],isError:!0})}async callCppCheck(e){if(!this.cppCheckTool){let t=this.config.projectPath?"C++ LSP is not ready, please retry later":"Project path is not configured. Set the PROJECT_PATH parameter or open a project in DevEco Studio.";return h.warn(`C++ check rejected: ${t}, files: ${e.join(", ")}`),{content:[{type:"text",text:t}],isError:!0}}return this.cppCheckTool.handleCall({files:e})}mergeCheckResult(e,t,r){let i=e.content.map(o=>o.text).filter(o=>o&&o.trim().length>0).join(`
1293
- `);i&&(e.isError?t.push(i):r.push(i))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{h.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool&&(this.cppCheckTool.shutdown().catch(t=>{h.warn("Failed to shutdown CppCheckTool during setProjectPath:",t)}),this.cppCheckTool=null),this.initPromise?(this.needsReinit=!0,h.info("Project path changed while init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{h.warn("Failed to re-init project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new Vg;if(await this.server.connect(e),h.info("devecocli-mcp-server started"),!this.config.debug){let t=Wc();t&&h.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=Ae(t);r?(h.info(`Detected project path from client root: ${r}`),this.config.projectPath=r,this.sdkPath=this.computeSdkPath()):h.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?h.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):h.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{h.warn("Background project init failed:",t)}),this.initializeCppCheck()}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return h.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return h.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){h.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,h.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{h.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{h.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}initializeCppCheck(){let e=this.config.projectPath;if(!e){h.warn("C++ LSP initialization skipped: project path is not configured");return}this.cppCheckTool=new Nt(e,this.config.devecoPath??null),h.info("CppCheckTool created (lazy initialization)")}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{h.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?Ae(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=Ae(this.originalProjectPath),t&&h.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.sdkPath=this.computeSdkPath(),this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&(this.sdkPath||(this.sdkPath=this.computeSdkPath()),!!await this.ensureProjectSynced())){this.projectState=3,this.arktsCheckTool=new Lt(this.config.projectPath,this.config.devecoPath??null,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{h.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,h.info("Project fully initialized, check tool is available")}catch(e){h.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=hl(e,this.config.forceSync??!1);return t.required?(h.info(`Sync required: ${t.reason}`),this.runSync(e)):(h.info(`Sync skipped: ${t.reason}`),!0)}async runSync(e){this.projectState=2,h.info("Starting project sync...");let t=await Ot.handleSyncProject(e,this.sdkPath);switch(t.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let r=Date.now()-this.syncSkipStartedAt,i=Math.round(r/1e3);return r>=fl?(h.error(`Sync skipped for ${i}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(h.warn(`Sync skipped: ${t.reason}, resetting to IDLE for retry (elapsed ${i}s / ${fl/1e3}s)`),this.projectState=0,!1)}case"failed":return h.error(`Project sync failed: ${t.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}computeSdkPath(){let e=ar(this.config.devecoPath??""),t=le(e);return Ft.join(t,"sdk")}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppCheckTool&&await this.cppCheckTool.shutdown();try{await this.server.close()}catch(e){h.warn("Failed to close MCP server connection:",e)}h.info("devecocli-mcp-server stopped"),$c(),jc()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function Jg(n){let e=[],t=[],r=[];for(let i of n)Ft.extname(i).toLowerCase()===".ets"?e.push(i):cr(i)?t.push(i):r.push(i);return{etsFiles:e,cppFiles:t,unsupported:r}}function ko(n={}){return new qr(n)}import*as Ro from"fs";import*as jt from"path";import{spawn as Kg}from"child_process";async function gl(n){dn(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:i,serverMaxSize:o}=await Zg(n),s=ty(e,t,r,i,o);h.info("ace-server started, bridging stdio (initialize is left to the client)"),ry(s)}async function Zg(n){let e=await Xg();e||(h.error("DevEco Studio not found. Ensure DevEco Studio is installed."),process.exit(1));let t=de(n.projectPath??process.cwd()),r=jt.join(le(e),"sdk"),i=or(e);i||(h.error("ace-server not found in DevEco Studio installation."),process.exit(1));let o=jt.resolve(i,"ace-server","out","standardIndex","index.js"),s=jt.join(St(),"lsp-server",String(Date.now()));Ro.mkdirSync(s,{recursive:!0});let a=Qg(t,r);return h.info(`projectPath=${t}, sdkPath=${r}, serverPath=${o}, logPath=${s}, serverMaxSize=${a}MB`),{projectPath:t,sdkPath:r,serverPath:o,logPath:s,serverMaxSize:a}}function Xg(){return L.new().then(n=>n.devecoStudioPath).catch(()=>Te())}function Qg(n,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=t?parseInt(t,10):NaN,i=Number.isFinite(r)&&r>0?r:void 0,o=ey(n,e),s=mr(o,i);return h.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${o}, override=${i??"none"})`),s}function ey(n,e){try{let t=[];return new ot(n,e).getAllDependencyMap(t).status==="OK"?t.length:new ke(n).getAllModuleInfo().length}catch{return 0}}function ty(n,e,t,r,i){let o=jt.join(e,"lspLog");Ro.mkdirSync(o,{recursive:!0});let s=ny(n,o,t,r,i),a=process.execPath??"node";return h.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),Kg(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function ny(n,e,t,r,i){let o=F(e);return["--expose-gc",`--max-old-space-size=${i}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${o}`,n,"--stdio",`--logger-path=${o}`,"--logger-level=TRACE",`--projectPath=${F(t)}`,`--sdkPath=${F(r)}`]}function ry(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{h.error(`[ace-server] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{h.info(`ace-server exited with code ${e}`),process.exit(e??0)})}async function oy(){let n=process.env.PROJECT_PATH||"",e=process.env.DEVECO_PATH,t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=process.env.DEBUG==="true"||process.env.DEBUG==="1",i=process.env.DEVECO_MCP_FORCE_SYNC==="1",o=await L.new(),s=n,a=e??o.devecoStudioPath,c=ko({projectPath:s,devecoPath:a,nodeMaxOldSpaceSize:t,debug:r,forceSync:i}),l=async()=>{await c.shutdown(),process.exit(0)};process.once("SIGINT",l),process.once("SIGTERM",l),process.platform==="win32"&&process.once("SIGBREAK",l);try{await c.start()}catch(u){console.error("Failed to start MCP server:",u),process.exit(1)}}var Mo=new iy("serve").description("Host bundled auxiliary protocol servers");Mo.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await oy()});Mo.command("lsp").description("Start a bundled LSP language server").option("--arkts","Start the ArkTS language server (ace-server)").option("--project-path <path>","HarmonyOS project root path",process.cwd()).action(async n=>{n.arkts||(console.error("Use --arkts to start the ArkTS language server."),process.exit(1)),await gl({projectPath:n.projectPath})});var yl=Mo;import{Command as Jw,InvalidArgumentError as vs}from"commander";import{red as yi,dim as Kw}from"colorette";import*as z from"fs";import*as lt from"path";import Lw from"adm-zip";import Nw from"proper-lockfile";import yu from"ora";import*as ve from"fs";import*as Cn from"path";var Ue=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],st={"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 Gr="1.8.0",Ok=80*1024*1024,vl=280,wl=6,bl=100,Sl=3,El=28,Oo=10,Pl=/API参考|APIReference/i,Sn=200,Cl=12,Il=4,Lo=8,Dl=6,Yr=700,No=250,_o=400,Al=1320,Tl=120,xl=450,kl=250,Rl=500,Ml=480,Ol=80,Ll=200,Nl=60,_l=200,Hl=40,Ho=120,$t=500,Fl=Object.fromEntries(Ue.map((n,e)=>[st[n],e])),ze=Object.fromEntries(Ue.map((n,e)=>[n,e]));import*as jl from"fs";import*as O from"path";import{homedir as $l}from"os";import{fileURLToPath as Wl}from"url";var Bl="deveco-cli",sy="docs";function Vr(){return O.join($l(),".local","share",Bl,sy)}function ae(){return O.join(Vr(),".index")}function Ul(){return O.join(ae(),"build.lock")}function Fo(){return O.join(ae(),"build-status.json")}function Jr(){return O.join(ae(),"build-meta.json")}function En(){return O.join(ae(),"search.db")}function Wt(){return O.join(ae(),".tmp")}function zl(){return O.join($l(),".local","share",Bl,"logs")}function ay(n,e){let t=e;for(;!t.endsWith(`${O.sep}dist`)&&t!==O.dirname(t);)t=O.dirname(t);return t}function ql(n,e){return O.dirname(ay(n,e))}function cy(){let n=Wl(import.meta.url),e=O.dirname(n);return n.includes(`${O.sep}dist${O.sep}`)?ql(n,e):O.join(e,"..","..","..")}function ly(...n){let e=Wl(import.meta.url),t=O.dirname(e);return e.includes(`${O.sep}dist${O.sep}`)?[O.join(ql(e,t),...n)]:[O.join(t,"..","..","..",...n)]}function Gl(...n){for(let e of ly(...n))if(jl.existsSync(e))return e;return null}function qe(){return Gl("docs.zip")}function jo(){return Gl("index.zip")}function Yl(){return O.join(cy(),"index","data")}import*as Me from"fs";import*as at from"path";var ct=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],$o=null;function Wo(n){$o=n}function Vl(){if($o)return $o;let n=ae();if(ct.every(i=>Me.existsSync(at.join(n,i))))return n;let t=Yl();if(ct.every(i=>Me.existsSync(at.join(t,i))))return t;throw new Error("Lexicon files not found. Install the documentation index first (index.zip).")}function Bt(n){let e=at.join(Vl(),n);return Me.readFileSync(e,"utf-8")}function Jl(n,e){return Me.readFileSync(at.join(e,n),"utf-8")}async function Kl(n,e=Vl()){await Me.promises.mkdir(n,{recursive:!0});for(let t of ct){let r=at.join(e,t),i=at.join(n,t);await Me.promises.copyFile(r,i)}}import*as Kr from"fs";import*as Zl from"path";import*as Xl from"yauzl";var Pn=null;function dy(n){return new Promise((e,t)=>{Xl.open(n,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(r,i)=>{if(r||!i){t(r??new Error(`Failed to open zip: ${n}`));return}e(i)})})}function uy(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function py(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",i=>{let o=uy(i);o.endsWith("/")||e.set(o,i),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function my(){Pn?.zipfile.close(),Pn=null}async function hy(n){let e=Zl.resolve(n),t=await Kr.promises.stat(e),r=Pn;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;my();let i=await dy(e),o=await py(i);return Pn={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:i,entries:o,readChain:Promise.resolve()},Pn}function fy(n,e){return new Promise((t,r)=>{n.openReadStream(e,(i,o)=>{if(i||!o){r(i??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];o.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),o.on("end",()=>{t(Buffer.concat(s))}),o.on("error",r)})})}async function gy(n,e){let t=n.readChain,r;n.readChain=new Promise(i=>{r=i}),await t;try{return await fy(n.zipfile,e)}finally{r()}}function yy(n){let e=n.replace(/\\/g,"/").replace(/\.md$/,"");return[`docs/${e}.md`,`${e}.md`,`docs/${e}`,e]}function vy(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function Ql(n){let e=qe();if(!e)throw new Error("docs.zip not found");let t=await hy(e),r=vy(t.entries,yy(n));if(!r)throw new Error(`Document not found: ${n}`);return(await gy(t,r)).toString("utf-8")}function Bo(){let n=qe();return n!==null&&Kr.existsSync(n)}import*as J from"fs";import*as Ge from"path";import ed from"adm-zip";var td=["search.db","build-meta.json",...ct],wy=["corpus.json","corpus-offsets.json","orama.dpack"];async function by(n){for(let e of wy)await J.promises.rm(Ge.join(n,e),{force:!0})}async function Sy(n){let e=await J.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await J.promises.rm(Ge.join(n,t.name),{recursive:!0,force:!0})}function Ey(n){let t=new ed(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 Py(n){let e=ae();await J.promises.mkdir(e,{recursive:!0});for(let t of td){let r=Ge.join(e,t);await J.promises.rm(r,{force:!0}),await J.promises.rename(Ge.join(n,t),r)}await by(e),await J.promises.rm(Wt(),{recursive:!0,force:!0})}function Uo(){let n=jo();return n!==null&&J.existsSync(n)}async function nd(n){let e=jo();if(!e)throw new Error("index.zip not found");let t=Ey(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=Wt();await J.promises.rm(r,{recursive:!0,force:!0}),await J.promises.mkdir(r,{recursive:!0});let i=new ed(e);for(let s of td){let a=i.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await J.promises.writeFile(Ge.join(r,s),a.getData())}let o=JSON.parse(await J.promises.readFile(Ge.join(r,"build-meta.json"),"utf-8"));if(!J.existsSync(Ge.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await Py(r),await J.promises.mkdir(Vr(),{recursive:!0}),await Sy(Vr()),o}import{createHash as rd}from"crypto";import*as id from"fs";async function Zr(n){return new Promise((e,t)=>{let r=rd("sha256"),i=id.createReadStream(n);i.on("data",o=>r.update(o)),i.on("error",t),i.on("end",()=>e(r.digest("hex")))})}function od(n){return rd("sha256").update(n,"utf8").digest("hex")}var zo=null;function Cy(){let n=Bt("harmonyos-synonyms.json");return JSON.parse(n)}function Iy(n){let e=new Map;for(let t of n){let r=t.map(i=>i.trim()).filter(Boolean);for(let i of r){let o=r.filter(s=>s!==i);e.set(i.toLowerCase(),o),i!==i.toLowerCase()&&e.set(i,o)}}return e}function Dy(){let n=Iy(Cy()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function Ay(){return zo||(zo=Dy()),zo}function qo(n,e){let t=Ay(),r=n.split(/\s+/).filter(Boolean),i=new Set,o=Number.isFinite(e)?e:r.length;for(let s=0;s<r.length&&i.size<o;s+=1){let a=r[s];i.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(i.size>=o)break;i.add(l)}}return[...i].join(" ")}function sd(n,e){let t=e?Jl(n,e):Bt(n);return od(t)}function Xr(n){return sd("harmonyos-synonyms.json",n)}function Qr(n){return sd("harmonyos-terms.txt",n)}var Ty={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function ei(){try{let n=await ve.promises.readFile(Fo(),"utf-8");return JSON.parse(n)}catch{return{...Ty}}}async function Go(n){let e=Fo();await ve.promises.mkdir(Cn.dirname(e),{recursive:!0}),await ve.promises.writeFile(e,JSON.stringify(n,null,2))}function ad(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 Ye(n){let t={...await ei(),...n,updatedAt:Date.now()};return await Go(t),t}async function Yo(){let n=qe();return n?Zr(n):null}async function Vo(){try{let n=await ve.promises.readFile(Jr(),"utf-8");return JSON.parse(n)}catch{return null}}async function Jo(n=!1){if(n)return"no-index";let e=await Vo();if(!e||e.segmentCount===0)return"no-index";let t=await Yo();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==Gr?"engine-upgraded":e.termsHash!==Qr()?"terms-changed":e.synonymsHash!==Xr()?"synonyms-changed":null}function In(){if(!Bo()||!ve.existsSync(En())||!ve.existsSync(Jr()))return!1;let n=Cn.dirname(En());if(!ct.every(e=>ve.existsSync(Cn.join(n,e))))return!1;try{let e=ve.readFileSync(Jr(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function Ko(n=!1){return n?!0:Bo()?In()?await Jo()!==null:!0:!1}async function cd(){let n=await ei();return["installing","indexing","persisting"].includes(n.state)}import*as K from"fs";import*as du from"os";import*as re from"path";var ld=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),Zo=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),dd=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"]),ud=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 xy=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,ky=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,Ry=/[A-Z][a-zA-Z0-9]{2,}/g,My=/@[A-Z][a-zA-Z0-9]*/g,Oy=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,pd=6,Ly=/^[a-z][a-z0-9]{2,}$/,Ny=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,_y=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,Hy=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,Fy=/^[A-Z][a-zA-Z0-9]+$/;function jy(n){return`"${n.replace(/"/g,'""')}"`}function An(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(jy).join(` ${e} `)}function Dn(n){return An(n,"OR")}function md(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?Dn([...t,...r]):`(${Dn(t)}) AND (${Dn(r)})`}function Tn(n){return _y.test(n)}function hd(n){return Hy.test(n)&&n.length>=pd}function $y(n){return Fy.test(n)}function xn(n){return Tn(n)||hd(n)||$y(n)}function Wy(n){let e=n.trim().toLowerCase();return ud.has(e)?!1:ld.has(e)}function By(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function ti(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function Xo(n){return[...n.matchAll(xy)].map(e=>e[0])}function Qo(n,e=pd){let t=[];for(let r of n.matchAll(ky))r[0].length>=e&&t.push(r[0]);return t}function Ut(n){return n.filter(e=>{let t=e.toLowerCase();return!n.some(r=>{if(r===e)return!1;let i=r.toLowerCase();return i.length>t.length&&i.endsWith(t)&&t.length>=4})})}function we(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function Uy(n){let e=new Set;we(e,n);let t=ti(n);return t&&we(e,t),Ut([...e])}function ni(n){if(Tn(n))return Uy(n);let e=new Set;return we(e,n),Ut([...e])}function ri(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(Ny);if(!t)return null;let r=t[1].toLowerCase(),i=t[2].toLowerCase();if(!Ly.test(r)||dd.has(r)||!Wy(i))return null;let o=By(r,i);return{first:r,second:i,camelCase:o,lower:o.toLowerCase()}}function es(n){let e=ri(n.trim());return!e||e.second!=="manager"?null:e}function zy(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function fd(n){let e=n.trim(),t=es(e);if(t&&Zo.has(t.first))return!0;if(hd(e)){let r=zy(e);return r!==null&&Zo.has(r)}return!1}function ts(n,e,t){let r=t.toLowerCase(),i=new RegExp(`@ohos\\.[^\\s(]*${t}`,"i");for(let o of[n,e])if(o&&(o.toLowerCase().includes(r)||i.test(o)))return!0;return!1}function ns(n){let e=n.trim();if(xn(e))return ni(e);let t=new Set;for(let r of Xo(n)){we(t,r);let i=ti(r);i&&we(t,i)}for(let r of Qo(n))we(t,r);for(let r of n.matchAll(My))t.add(r[0]);for(let r of n.matchAll(Oy))t.add(r[0]);for(let r of n.matchAll(Ry))r[0].length>=4&&t.add(r[0]);return Ut([...t])}function gd(n){let e=n.trim();if(xn(e))return ni(e);let t=new Set,r=ri(e);r&&we(t,r.camelCase);for(let i of ns(e))t.add(i);for(let i of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let o=i[0];o!==o.toLowerCase()&&t.add(o)}return Ut([...t])}function yd(n){return xn(n)}var N={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 vd(n){return N.pureApiSymbol.test(n.trim())}function kn(n){let e=n.trim();return N.stageModelExact.test(e)||N.stageModelEnglishExact.test(e)}function wd(n){let e=[];return kn(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),N.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),N.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 bd(n){return kn(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var qy=[{matches:n=>N.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>kn(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!kn(n)&&N.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>N.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>N.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>N.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>N.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>N.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=>N.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function Gy(n,e){for(let{catalog:t,multiplier:r}of e){let i=ze[t];n.set(i,(n.get(i)??1)*r)}}function Sd(n,e){for(let t of qy)t.matches(n)&&Gy(e,t.weights)}function Ed(n,e){if(e!==void 0)return!1;let t=n.trim();return Tn(t)||N.pureApiSymbol.test(t)||fd(t)}function Pd(n){let e=n.trim();if(Tn(e)||N.pureApiSymbol.test(e))return"harmonyos-references";if(kn(e)||N.uiAbilityLifecycleCatalog.test(e)||N.stateDecoratorCatalog.test(e)||N.stateManagement.test(e)||N.declarePermissionCatalog.test(e)||N.stageModelEntryPage.test(e)||N.routerRoute.test(e)||N.dialogPopupExact.test(e))return"harmonyos-guides"}import{Jieba as Yy}from"@node-rs/jieba";import{dict as Vy}from"@node-rs/jieba/dict.js";var ii=null,rs=null,is=null;function Jy(){if(ii)return ii;let n=Bt("harmonyos-stopwords.txt");return ii=new Set(n.split(`
1294
- `).map(e=>e.trim()).filter(Boolean)),ii}function Ky(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t]?.trim();if(!r)continue;let i=n[t+1]?.trim();if(r==="@"&&i&&/^[A-Z][a-zA-Z0-9]*$/.test(i)){e.push(`@${i}`),t+=1;continue}e.push(r)}return e}function Cd(n){let e=Jy(),t=[];for(let r of Ky(n)){let i=r.trim();!i||e.has(i)||(t.push(i.toLowerCase()),/[A-Z]/.test(i)&&/[a-zA-Z]/.test(i)&&t.push(i))}return t}async function Zy(){let n=Yy.withDict(Vy),e=Bt("harmonyos-terms.txt");return n.loadDict(Buffer.from(e,"utf-8")),n}async function Ve(){return rs||(is||(is=Zy().then(n=>(rs=n,n))),is)}async function Xy(n){let e=await Ve();return Cd(e.cutForSearch(n,!0))}async function Id(n){let e=await Ve();return Cd(e.cut(n,!0))}async function oi(n,e){let t=n.trim();if(!t||e<=0)return"";let r=(await Xy(t)).join(" ");return r.length<=e?r:r.slice(0,e)}async function Qy(n,e){let t=[];for(let i of n){let o=i.trim();o&&(t.push(o.toLowerCase()),/[A-Z]/.test(o)&&t.push(o))}let r=[...new Set(t)].join(" ");return r.length<=e?r:r.slice(0,e)}async function si(n){let e=!!n.sectionTitle.trim(),t=n.titleTokens.trim(),r=e?Ml:Al,i=e?Ll:xl,o=e?await Qy(n.apiSymbols,i):await oi(n.apiSymbols.join(" "),i),a=(await Promise.all([oi(t,e?Ol:Tl),Promise.resolve(o),oi(n.headingsText,e?Nl:kl),oi(n.bodySample,e?_l:Rl)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}function ev(n){return n.join(" ").replace(/\s+/g," ").trim().slice(0,Sn)}function os(n,e){let t=new Set,r=[];for(let i of[...n,...e]){let o=i.toLowerCase();if(!(!i||t.has(o))&&(t.add(o),r.push(i),r.length>=Cl))break}return r}function tv(n){return n.length>=2&&n.length<=Il}function nv(n,e){let t=qo(n,Lo),r=t.split(/\s+/).filter(Boolean),i=[e.first,...r.filter(a=>a!==e.second),e.lower,e.camelCase],o=[e.second,e.lower,e.camelCase],s=os(i,o);return{rawQuery:n,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:md(i,o)}}function rv(n,e){let t=os(ni(e),[]);return{rawQuery:n,expandedQuery:n,tokens:t,preferAnd:!1,ftsMatch:Dn(t)}}async function Dd(n){let e=ev(n),t=e.trim(),r=bd(t);if(r)return{rawQuery:e,expandedQuery:r.expandedQuery,tokens:r.tokens,preferAnd:!1};let i=ri(t);if(i)return nv(e,i);if(xn(t))return rv(e,t);let o=wd(e),s=[...ns(e),...o],c=yd(t)?e:qo(e,Lo),l=await Id(c),u=os(s,l);return{rawQuery:e,expandedQuery:c,tokens:u,preferAnd:o.length===0&&tv(u)}}var Ad=["harmonyos-releases","harmonyos-roadmap"],iv=new Set(Ad.map(n=>ze[n])),ov=Ad.map(n=>`${st[n]}/`);function sv(n){return iv.has(n)}function av(n){return ov.some(e=>n.startsWith(e))}function Td(n){let e=[],t=[];for(let r of n)sv(r.catalog_id)?t.push(r):e.push(r);return[...e,...t]}function xd(n){let e=[],t=[];for(let r of n)av(r.documentId)?t.push(r):e.push(r);return[...e,...t]}var cv=[{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 Rn(n,e,t){let r=ze[e];n.set(r,(n.get(r)??1)*t)}function lv(n,e){let t=n.trim(),r=/[\u4e00-\u9fff]/.test(t),i=/\b[A-Z][a-zA-Z0-9]{2,}\b/.test(t),o=/\b[a-z][a-zA-Z0-9]{3,}\b/.test(t);if(r&&(i||o)){Rn(e,"harmonyos-guides",1.45),Rn(e,"harmonyos-references",1.35);return}(i||o)&&Rn(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&Rn(e,"harmonyos-references",1.75)}function kd(n){let e=new Map,t=n.trim();if(!t)return e;let r=vd(t);lv(t,e),Sd(t,e);for(let i of cv)i.pattern.test(t)&&(i.skipForPureApiSymbol&&r||Rn(e,i.catalog,i.multiplier));return e}function Rd(n){return Pd(n)}function Md(n,e,t=200){let r=n.replace(/\s+/g," ").trim();if(r.length<=t)return r;let i=e.split(/\s+/).map(f=>f.trim()).filter(Boolean),o=0;for(let f of i){let E=r.toLowerCase().indexOf(f.toLowerCase());if(E>=0){o=E;break}}let s=Math.max(0,o-40),a=Math.min(r.length,s+t),c=r.slice(s,a).trim(),l=s>0?"...":"",u=a<r.length?"...":"";return`${l}${c}${u}`}var dv=`
1295
- SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, d.catalog_id,
1296
- bm25(segments_fts) AS bm25
1294
+ `).trim()||"No diagnostics collected"}],isError:l}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS check rejected: project is ${Fo[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e})}}async handleLspFeatureCall(e,t){let r=t.file,i=t.line,o=t.character;if(typeof r!="string"||typeof i!="number"||typeof o!="number")return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};let s=this.validateContainment([r]);return s||this.callArktsFeature(e,{file:r,line:i,character:o})}async handleWorkspaceSymbolCall(e){let t=e.query;return typeof t!="string"||t.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameter: query (non-empty string required)."}],isError:!0}:this.callArktsWorkspaceSymbol(t)}async handleDocumentSymbolCall(e){let t=e.file;if(typeof t!="string")return{content:[{type:"text",text:"Missing or invalid parameter: file (string required)."}],isError:!0};let r=this.validateContainment([t]);return r||this.routeArktsRequest("documentSymbol",()=>this.arktsCheckTool.handleDocumentSymbol(t))}async handleCallHierarchyCall(e){let t=e.file,r=e.line,i=e.character,o=e.direction;if(typeof t!="string"||typeof r!="number"||typeof i!="number")return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};if(o!=="incoming"&&o!=="outgoing")return{content:[{type:"text",text:'Parameter direction must be "incoming" or "outgoing".'}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest(`callHierarchy(${o})`,()=>this.arktsCheckTool.handleCallHierarchy({file:t,line:r,character:i,direction:o}))}async handleCodeActionCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e);if(!t)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};let o=this.validateContainment([t]);return o||this.routeArktsRequest("codeAction",()=>this.arktsCheckTool.handleCodeAction({file:t,line:r,character:i}))}async handleRenameCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e),o=e.newName;if(!t||typeof o!="string"||o.trim().length===0)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number), newName (non-empty string)."}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest("rename",()=>this.arktsCheckTool.handleRename({file:t,line:r,character:i,newName:o}))}async handleTypeHierarchyCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e),o=e.direction;if(!t)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};if(o!=="supertypes"&&o!=="subtypes")return{content:[{type:"text",text:'Parameter direction must be "supertypes" or "subtypes".'}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest(`typeHierarchy(${o})`,()=>this.arktsCheckTool.handleTypeHierarchy({file:t,line:r,character:i,direction:o}))}async handleCompletionItemResolveCall(e){let t=e.item;return t==null?{content:[{type:"text",text:"Missing parameter: item (completion item object required)."}],isError:!0}:this.routeArktsRequest("completionItemResolve",()=>this.arktsCheckTool.handleCompletionItemResolve(t))}extractPositionArgs(e){let t=e.file,r=e.line,i=e.character;return typeof t!="string"||typeof r!="number"||typeof i!="number"?{file:null,line:0,character:0}:{file:t,line:r,character:i}}async callArktsFeature(e,t){return this.routeArktsRequest(e,()=>this.arktsCheckTool.handleLspFeature(e,t))}async callArktsWorkspaceSymbol(e){return this.routeArktsRequest("workspaceSymbol",()=>this.arktsCheckTool.handleWorkspaceSymbol(e))}async routeArktsRequest(e,t){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS ${e} rejected: project is ${Fo[this.projectState]}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS ${e} rejected: LSP is initializing`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return t()}}async handleIdleCheck(){if(this.ensureProjectReady(),this.config.projectPath){let e,t;return this.syncSkippedDueToLock?(e=`Another build process is running, sync deferred (waiting ${this.syncSkipStartedAt>0?Math.round((Date.now()-this.syncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,t="lock contention",this.syncSkippedDueToLock=!1):this.configChangedTriggeredResync?(e="Config file changed, resyncing project, please retry in 10 seconds",t="config changed",this.configChangedTriggeredResync=!1):(e="HarmonyOS project detected, syncing, please retry in 10 seconds",t="initial"),h.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(h.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(h.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=Ho?(h.error(`Init retry limit reached (${this.initRetryCount}/${Ho}), will not auto-retry`),{content:[{type:"text",text:"Project initialization failed multiple times. Please check project configuration and restart the MCP Server."}],isError:!0}):(h.info(`Error check: auto-retrying (${this.initRetryCount}/${Ho})`),this.ensureProjectReady(),{content:[{type:"text",text:"Project initialization failed, auto-retrying, please retry in 10 seconds"}],isError:!0})}async callCppCheck(e){if(!this.cppCheckTool){let t=this.config.projectPath?"C++ LSP is not ready, please retry later":"Project path is not configured. Set the PROJECT_PATH parameter or open a project in DevEco Studio.";return h.warn(`C++ check rejected: ${t}, files: ${e.join(", ")}`),{content:[{type:"text",text:t}],isError:!0}}return this.cppCheckTool.handleCall({files:e})}mergeCheckResult(e,t,r){let i=e.content.map(o=>o.text).filter(o=>o&&o.trim().length>0).join(`
1295
+ `);i&&(e.isError?t.push(i):r.push(i))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{h.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool&&(this.cppCheckTool.shutdown().catch(t=>{h.warn("Failed to shutdown CppCheckTool during setProjectPath:",t)}),this.cppCheckTool=null),this.initPromise?(this.needsReinit=!0,h.info("Project path changed while init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{h.warn("Failed to re-init project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new ly;if(await this.server.connect(e),h.info("devecocli-mcp-server started"),!this.config.debug){let t=Kc();t&&h.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=Re(t);r?(h.info(`Detected project path from client root: ${r}`),this.config.projectPath=r,this.sdkPath=this.computeSdkPath()):h.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?h.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):h.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{h.warn("Background project init failed:",t)}),this.initializeCppCheck()}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return h.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return h.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){h.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,h.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{h.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{h.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}initializeCppCheck(){let e=this.config.projectPath;if(!e){h.warn("C++ LSP initialization skipped: project path is not configured");return}this.cppCheckTool=new Bt(e,this.config.devecoPath??null),h.info("CppCheckTool created (lazy initialization)")}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{h.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?Re(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=Re(this.originalProjectPath),t&&h.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.sdkPath=this.computeSdkPath(),this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&(this.sdkPath||(this.sdkPath=this.computeSdkPath()),!!await this.ensureProjectSynced())){this.projectState=3,this.arktsCheckTool=new $t(this.config.projectPath,this.config.devecoPath??null,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{h.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,h.info("Project fully initialized, check tool is available")}catch(e){h.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=El(e);return t.required?(h.info(`Sync required: ${t.reason}`),this.runSync(e)):(h.info(`Sync skipped: ${t.reason}`),!0)}async runSync(e){this.projectState=2,h.info("Starting project sync...");let t=await jt.handleSyncProject(e,this.sdkPath);switch(t.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let r=Date.now()-this.syncSkipStartedAt,i=Math.round(r/1e3);return r>=Pl?(h.error(`Sync skipped for ${i}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(h.warn(`Sync skipped: ${t.reason}, resetting to IDLE for retry (elapsed ${i}s / ${Pl/1e3}s)`),this.projectState=0,!1)}case"failed":return h.error(`Project sync failed: ${t.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}computeSdkPath(){let e=fr(this.config.devecoPath??""),t=de(e);return ut.join(t,"sdk")}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppCheckTool&&await this.cppCheckTool.shutdown();try{await this.server.close()}catch(e){h.warn("Failed to close MCP server connection:",e)}h.info("devecocli-mcp-server stopped"),Jc(),Yc()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function dy(n){let e=[],t=[],r=[];for(let i of n)ut.extname(i).toLowerCase()===".ets"?e.push(i):gr(i)?t.push(i):r.push(i);return{etsFiles:e,cppFiles:t,unsupported:r}}function jo(n={}){return new Qr(n)}import*as $o from"fs";import*as Wt from"path";import{spawn as uy}from"child_process";async function Dl(n){fn(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:i,serverMaxSize:o}=await py(n),s=gy(e,t,r,i,o);h.info("ace-server started, bridging stdio (initialize is left to the client)"),vy(s)}async function py(n){let e=await my();e||(h.error("DevEco Studio not found. Ensure DevEco Studio is installed."),process.exit(1));let t=ue(n.projectPath??process.cwd()),r=Wt.join(de(e),"sdk"),i=It(e);i||(h.error("ace-server not found in DevEco Studio installation."),process.exit(1));let o=Wt.resolve(i,"ace-server","out","standardIndex","index.js"),s=Wt.join(At(),"lsp-server",String(Date.now()));$o.mkdirSync(s,{recursive:!0});let a=hy(t,r);return h.info(`projectPath=${t}, sdkPath=${r}, serverPath=${o}, logPath=${s}, serverMaxSize=${a}MB`),{projectPath:t,sdkPath:r,serverPath:o,logPath:s,serverMaxSize:a}}function my(){return N.new().then(n=>n.devecoStudioPath).catch(()=>be())}function hy(n,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=t?parseInt(t,10):NaN,i=Number.isFinite(r)&&r>0?r:void 0,o=fy(n,e),s=Sr(o,i);return h.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${o}, override=${i??"none"})`),s}function fy(n,e){try{let t=[];return new dt(n,e).getAllDependencyMap(t).status==="OK"?t.length:new Oe(n).getAllModuleInfo().length}catch{return 0}}function gy(n,e,t,r,i){let o=Wt.join(e,"lspLog");$o.mkdirSync(o,{recursive:!0});let s=yy(n,o,t,r,i),a=process.execPath??"node";return h.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),uy(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function yy(n,e,t,r,i){let o=j(e);return["--expose-gc",`--max-old-space-size=${i}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${o}`,n,"--stdio",`--logger-path=${o}`,"--logger-level=TRACE",`--projectPath=${j(t)}`,`--sdkPath=${j(r)}`]}function vy(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{h.error(`[ace-server] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{h.info(`ace-server exited with code ${e}`),process.exit(e??0)})}async function by(){let n=process.env.PROJECT_PATH||"",e=process.env.DEVECO_PATH,t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=process.env.DEBUG==="true"||process.env.DEBUG==="1",i=await N.new(),o=n,s=e??i.devecoStudioPath,a=jo({projectPath:o,devecoPath:s,nodeMaxOldSpaceSize:t,debug:r}),c=async()=>{await a.shutdown(),process.exit(0)};process.once("SIGINT",c),process.once("SIGTERM",c),process.platform==="win32"&&process.once("SIGBREAK",c);try{await a.start()}catch(l){console.error("Failed to start MCP server:",l),process.exit(1)}}var Bo=new wy("serve").description("Host bundled auxiliary protocol servers");Bo.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await by()});Bo.command("lsp").description("Start a bundled LSP language server").option("--arkts","Start the ArkTS language server (ace-server)").option("--project-path <path>","HarmonyOS project root path",process.cwd()).action(async n=>{n.arkts||(console.error("Use --arkts to start the ArkTS language server."),process.exit(1)),await Dl({projectPath:n.projectPath})});var Il=Bo;import{Command as wb,InvalidArgumentError as As}from"commander";import{red as xi,dim as bb}from"colorette";import*as z from"fs";import*as Jt from"path";import rb from"adm-zip";import ib from"proper-lockfile";import Ru from"ora";import*as Ee from"fs";import*as Tn from"path";var Ve=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],pt={"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 ei="1.9.1",fR=48*1024*1024,Al=280,xl=6,Tl=100,kl=3,Rl=28,Wo=10,Ml=/API参考|APIReference/i,In=200,Ol=12,Ll=4,Uo=8,Nl=6,ti=700,zo=250,qo=400,_l=1320,Hl=120,Fl=450,jl=250,$l=500,Bl=480,Wl=80,Ul=200,zl=60,ql=200,Gl=40,Vl=200,Yl=200,Jl=40,Ut=500,Kl=Object.fromEntries(Ve.map((n,e)=>[pt[n],e])),Ye=Object.fromEntries(Ve.map((n,e)=>[n,e]));import*as Ql from"fs";import*as O from"path";import{fileURLToPath as ed}from"url";import*as ni from"path";import{homedir as Sy}from"os";var Ey="deveco-cli";function Xl(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function Py(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&Xl(n)!==""}function Zl(){return ni.join(Sy(),".local","share",Ey)}function ri(n){let e=ii();return Py()?[`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 ii(){let n=process.env.DEVECO_CLI_DATA_DIR;if(n===void 0||n==="")return Zl();let e=Xl(n);return e?ni.resolve(e):Zl()}var Cy="docs";function oi(){return O.join(ii(),Cy)}function te(){return O.join(oi(),".index")}function td(){return O.join(te(),"build.lock")}function Go(){return O.join(te(),"build-status.json")}function si(){return O.join(te(),"build-meta.json")}function An(){return O.join(te(),"search.db")}function zt(){return O.join(te(),".tmp")}function Dy(){return O.join(ii(),"logs")}function qt(){return O.join(Dy(),"doc-init.log")}function Iy(n,e){let t=e;for(;!t.endsWith(`${O.sep}dist`)&&t!==O.dirname(t);)t=O.dirname(t);return t}function nd(n,e){return O.dirname(Iy(n,e))}function Ay(){let n=ed(import.meta.url),e=O.dirname(n);return n.includes(`${O.sep}dist${O.sep}`)?nd(n,e):O.join(e,"..","..","..")}function xy(...n){let e=ed(import.meta.url),t=O.dirname(e);return e.includes(`${O.sep}dist${O.sep}`)?[O.join(nd(e,t),...n)]:[O.join(t,"..","..","..",...n)]}function rd(...n){for(let e of xy(...n))if(Ql.existsSync(e))return e;return null}function Je(){return rd("docs.zip")}function Vo(){return rd("index.zip")}function id(){return O.join(Ay(),"index","data")}import*as Ne from"fs";import*as mt from"path";var ht=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],ai=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function od(n){return n instanceof ai}var Yo=null;function Jo(n){Yo=n}function Ko(){if(Yo)return Yo;let n=te();if(ht.every(i=>Ne.existsSync(mt.join(n,i))))return n;let t=id();if(ht.every(i=>Ne.existsSync(mt.join(t,i))))return t;throw new ai("Lexicon files not found. Install the documentation index first (index.zip).")}function sd(){Ko()}function Gt(n){let e=mt.join(Ko(),n);return Ne.readFileSync(e,"utf-8")}function ad(n,e){return Ne.readFileSync(mt.join(e,n),"utf-8")}async function cd(n,e=Ko()){await Ne.promises.mkdir(n,{recursive:!0});for(let t of ht){let r=mt.join(e,t),i=mt.join(n,t);await Ne.promises.copyFile(r,i)}}import*as ci from"fs";import*as ld from"path";import*as dd from"yauzl";var xn=null;function Ty(n){return new Promise((e,t)=>{dd.open(n,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(r,i)=>{if(r||!i){t(r??new Error(`Failed to open zip: ${n}`));return}e(i)})})}function ky(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function Ry(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",i=>{let o=ky(i);o.endsWith("/")||e.set(o,i),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function My(){xn?.zipfile.close(),xn=null}async function Oy(n){let e=ld.resolve(n),t=await ci.promises.stat(e),r=xn;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;My();let i=await Ty(e),o=await Ry(i);return xn={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:i,entries:o,readChain:Promise.resolve()},xn}function Ly(n,e){return new Promise((t,r)=>{n.openReadStream(e,(i,o)=>{if(i||!o){r(i??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];o.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),o.on("end",()=>{t(Buffer.concat(s))}),o.on("error",r)})})}async function Ny(n,e){let t=n.readChain,r;n.readChain=new Promise(i=>{r=i}),await t;try{return await Ly(n.zipfile,e)}finally{r()}}function _y(n){let e=n.replace(/\\/g,"/").replace(/\.md$/,"");return[`docs/${e}.md`,`${e}.md`,`docs/${e}`,e]}function Hy(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function ud(n){let e=Je();if(!e)throw new Error("docs.zip not found");let t=await Oy(e),r=Hy(t.entries,_y(n));if(!r)throw new Error(`Document not found: ${n}`);return(await Ny(t,r)).toString("utf-8")}function Zo(){let n=Je();return n!==null&&ci.existsSync(n)}import*as K from"fs";import*as Ke from"path";import pd from"adm-zip";var md=["search.db","build-meta.json",...ht],Fy=["corpus.json","corpus-offsets.json","orama.dpack"];async function jy(n){for(let e of Fy)await K.promises.rm(Ke.join(n,e),{force:!0})}async function $y(n){let e=await K.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await K.promises.rm(Ke.join(n,t.name),{recursive:!0,force:!0})}function By(n){let t=new pd(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 Wy(n){let e=te();await K.promises.mkdir(e,{recursive:!0});for(let t of md){let r=Ke.join(e,t);await K.promises.rm(r,{force:!0}),await K.promises.rename(Ke.join(n,t),r)}await jy(e),await K.promises.rm(zt(),{recursive:!0,force:!0})}function Xo(){let n=Vo();return n!==null&&K.existsSync(n)}async function hd(n){let e=Vo();if(!e)throw new Error("index.zip not found");let t=By(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 K.promises.rm(r,{recursive:!0,force:!0}),await K.promises.mkdir(r,{recursive:!0});let i=new pd(e);for(let s of md){let a=i.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await K.promises.writeFile(Ke.join(r,s),a.getData())}let o=JSON.parse(await K.promises.readFile(Ke.join(r,"build-meta.json"),"utf-8"));if(!K.existsSync(Ke.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await Wy(r),await K.promises.mkdir(oi(),{recursive:!0}),await $y(oi()),o}import{createHash as fd}from"crypto";import*as gd from"fs";async function li(n){return new Promise((e,t)=>{let r=fd("sha256"),i=gd.createReadStream(n);i.on("data",o=>r.update(o)),i.on("error",t),i.on("end",()=>e(r.digest("hex")))})}function yd(n){return fd("sha256").update(n,"utf8").digest("hex")}var Qo=null;function Uy(){let n=Gt("harmonyos-synonyms.json");return JSON.parse(n)}function zy(n){let e=new Map;for(let t of n){let r=t.map(i=>i.trim()).filter(Boolean);for(let i of r){let o=r.filter(s=>s!==i);e.set(i.toLowerCase(),o),i!==i.toLowerCase()&&e.set(i,o)}}return e}function qy(){let n=zy(Uy()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function Gy(){return Qo||(Qo=qy()),Qo}function es(n,e){let t=Gy(),r=n.split(/\s+/).filter(Boolean),i=new Set,o=Number.isFinite(e)?e:r.length;for(let s=0;s<r.length&&i.size<o;s+=1){let a=r[s];i.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(i.size>=o)break;i.add(l)}}return[...i].join(" ")}function vd(n,e){let t=e?ad(n,e):Gt(n);return yd(t)}function di(n){return vd("harmonyos-synonyms.json",n)}function ui(n){return vd("harmonyos-terms.txt",n)}var Vy={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function pi(){try{let n=await Ee.promises.readFile(Go(),"utf-8");return JSON.parse(n)}catch{return{...Vy}}}async function ts(n){let e=Go();await Ee.promises.mkdir(Tn.dirname(e),{recursive:!0}),await Ee.promises.writeFile(e,JSON.stringify(n,null,2))}function wd(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 Ze(n){let t={...await pi(),...n,updatedAt:Date.now()};return await ts(t),t}async function ns(){let n=Je();return n?li(n):null}async function rs(){try{let n=await Ee.promises.readFile(si(),"utf-8");return JSON.parse(n)}catch{return null}}async function is(n=!1){if(n)return"no-index";let e=await rs();if(!e||e.segmentCount===0)return"no-index";let t=await ns();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==ei?"engine-upgraded":e.termsHash!==ui()?"terms-changed":e.synonymsHash!==di()?"synonyms-changed":null}function kn(){if(!Zo()||!Ee.existsSync(An())||!Ee.existsSync(si()))return!1;let n=Tn.dirname(An());if(!ht.every(e=>Ee.existsSync(Tn.join(n,e))))return!1;try{let e=Ee.readFileSync(si(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function os(n=!1){return n?!0:Zo()?kn()?await is()!==null:!0:!1}async function bd(){let n=await pi();return["installing","indexing","persisting"].includes(n.state)}import*as Z from"fs";import*as Cu from"os";import*as ie from"path";var Sd=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),ss=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),Ed=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"]),Pd=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 Yy=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,Jy=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,Ky=/[A-Z][a-zA-Z0-9]{2,}/g,Zy=/@[A-Z][a-zA-Z0-9]*/g,Xy=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,Cd=6,Qy=/^[a-z][a-z0-9]{2,}$/,ev=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,tv=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,nv=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,rv=/^[A-Z][a-zA-Z0-9]+$/;function iv(n){return`"${n.replace(/"/g,'""')}"`}function Mn(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(iv).join(` ${e} `)}function Rn(n){return Mn(n,"OR")}function Dd(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?Rn([...t,...r]):`(${Rn(t)}) AND (${Rn(r)})`}function On(n){return tv.test(n)}function Id(n){return nv.test(n)&&n.length>=Cd}function ov(n){return rv.test(n)}function Ln(n){return On(n)||Id(n)||ov(n)}function sv(n){let e=n.trim().toLowerCase();return Pd.has(e)?!1:Sd.has(e)}function av(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function mi(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function as(n){return[...n.matchAll(Yy)].map(e=>e[0])}function cs(n,e=Cd){let t=[];for(let r of n.matchAll(Jy))r[0].length>=e&&t.push(r[0]);return t}function Vt(n){return n.filter(e=>{let t=e.toLowerCase();return!n.some(r=>{if(r===e)return!1;let i=r.toLowerCase();return i.length>t.length&&i.endsWith(t)&&t.length>=4})})}function Pe(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function cv(n){let e=new Set;Pe(e,n);let t=mi(n);return t&&Pe(e,t),Vt([...e])}function hi(n){if(On(n))return cv(n);let e=new Set;return Pe(e,n),Vt([...e])}function fi(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(ev);if(!t)return null;let r=t[1].toLowerCase(),i=t[2].toLowerCase();if(!Qy.test(r)||Ed.has(r)||!sv(i))return null;let o=av(r,i);return{first:r,second:i,camelCase:o,lower:o.toLowerCase()}}function ls(n){let e=fi(n.trim());return!e||e.second!=="manager"?null:e}function lv(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function Ad(n){let e=n.trim(),t=ls(e);if(t&&ss.has(t.first))return!0;if(Id(e)){let r=lv(e);return r!==null&&ss.has(r)}return!1}function ds(n,e,t){let r=t.toLowerCase(),i=new RegExp(`@ohos\\.[^\\s(]*${t}`,"i");for(let o of[n,e])if(o&&(o.toLowerCase().includes(r)||i.test(o)))return!0;return!1}function us(n){let e=n.trim();if(Ln(e))return hi(e);let t=new Set;for(let r of as(n)){Pe(t,r);let i=mi(r);i&&Pe(t,i)}for(let r of cs(n))Pe(t,r);for(let r of n.matchAll(Zy))t.add(r[0]);for(let r of n.matchAll(Xy))t.add(r[0]);for(let r of n.matchAll(Ky))r[0].length>=4&&t.add(r[0]);return Vt([...t])}function xd(n){let e=n.trim();if(Ln(e))return hi(e);let t=new Set,r=fi(e);r&&Pe(t,r.camelCase);for(let i of us(e))t.add(i);for(let i of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let o=i[0];o!==o.toLowerCase()&&t.add(o)}return Vt([...t])}function Td(n){return Ln(n)}var _={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 kd(n){return _.pureApiSymbol.test(n.trim())}function Nn(n){let e=n.trim();return _.stageModelExact.test(e)||_.stageModelEnglishExact.test(e)}function Rd(n){let e=[];return Nn(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),_.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),_.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 Md(n){return Nn(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var dv=[{matches:n=>_.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>Nn(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!Nn(n)&&_.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>_.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>_.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>_.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>_.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>_.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=>_.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function uv(n,e){for(let{catalog:t,multiplier:r}of e){let i=Ye[t];n.set(i,(n.get(i)??1)*r)}}function Od(n,e){for(let t of dv)t.matches(n)&&uv(e,t.weights)}function Ld(n,e){if(e!==void 0)return!1;let t=n.trim();return On(t)||_.pureApiSymbol.test(t)||Ad(t)}function Nd(n){let e=n.trim();if(On(e)||_.pureApiSymbol.test(e))return"harmonyos-references";if(Nn(e)||_.uiAbilityLifecycleCatalog.test(e)||_.stateDecoratorCatalog.test(e)||_.stateManagement.test(e)||_.declarePermissionCatalog.test(e)||_.stageModelEntryPage.test(e)||_.routerRoute.test(e)||_.dialogPopupExact.test(e))return"harmonyos-guides"}import{Jieba as pv}from"@node-rs/jieba";import{dict as mv}from"@node-rs/jieba/dict.js";var gi=null,ps=null,ms=null;function hv(){if(gi)return gi;let n=Gt("harmonyos-stopwords.txt");return gi=new Set(n.split(`
1296
+ `).map(e=>e.trim()).filter(Boolean)),gi}function fv(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t]?.trim();if(!r)continue;let i=n[t+1]?.trim();if(r==="@"&&i&&/^[A-Z][a-zA-Z0-9]*$/.test(i)){e.push(`@${i}`),t+=1;continue}e.push(r)}return e}function _d(n){let e=hv(),t=[];for(let r of fv(n)){let i=r.trim();!i||e.has(i)||(t.push(i.toLowerCase()),/[A-Z]/.test(i)&&/[a-zA-Z]/.test(i)&&t.push(i))}return t}async function gv(){let n=pv.withDict(mv),e=Gt("harmonyos-terms.txt");return n.loadDict(Buffer.from(e,"utf-8")),n}async function Xe(){return ps||(ms||(ms=gv().then(n=>(ps=n,n))),ms)}async function yv(n){let e=await Xe();return _d(e.cutForSearch(n,!0))}async function Hd(n){let e=await Xe();return _d(e.cut(n,!0))}async function yi(n,e){let t=n.trim();if(!t||e<=0)return"";let r=(await yv(t)).join(" ");return r.length<=e?r:r.slice(0,e)}async function vv(n,e){let t=[];for(let i of n){let o=i.trim();o&&(t.push(o.toLowerCase()),/[A-Z]/.test(o)&&t.push(o))}let r=[...new Set(t)].join(" ");return r.length<=e?r:r.slice(0,e)}async function vi(n){let e=!!n.sectionTitle.trim(),t=n.titleTokens.trim(),r=e?Bl:_l,i=e?Ul:Fl,o=e?await vv(n.apiSymbols,i):await yi(n.apiSymbols.join(" "),i),a=(await Promise.all([yi(t,e?Wl:Hl),Promise.resolve(o),yi(n.headingsText,e?zl:jl),yi(n.bodySample,e?ql:$l)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}function wv(n){return n.join(" ").replace(/\s+/g," ").trim().slice(0,In)}function hs(n,e){let t=new Set,r=[];for(let i of[...n,...e]){let o=i.toLowerCase();if(!(!i||t.has(o))&&(t.add(o),r.push(i),r.length>=Ol))break}return r}function bv(n){return n.length>=2&&n.length<=Ll}function Sv(n,e){let t=es(n,Uo),r=t.split(/\s+/).filter(Boolean),i=[e.first,...r.filter(a=>a!==e.second),e.lower,e.camelCase],o=[e.second,e.lower,e.camelCase],s=hs(i,o);return{rawQuery:n,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:Dd(i,o)}}function Ev(n,e){let t=hs(hi(e),[]);return{rawQuery:n,expandedQuery:n,tokens:t,preferAnd:!1,ftsMatch:Rn(t)}}async function Fd(n){let e=wv(n),t=e.trim(),r=Md(t);if(r)return{rawQuery:e,expandedQuery:r.expandedQuery,tokens:r.tokens,preferAnd:!1};let i=fi(t);if(i)return Sv(e,i);if(Ln(t))return Ev(e,t);let o=Rd(e),s=[...us(e),...o],c=Td(t)?e:es(e,Uo),l=await Hd(c),u=hs(s,l);return{rawQuery:e,expandedQuery:c,tokens:u,preferAnd:o.length===0&&bv(u)}}var jd=["harmonyos-releases","harmonyos-roadmap"],Pv=new Set(jd.map(n=>Ye[n])),Cv=jd.map(n=>`${pt[n]}/`);function Dv(n){return Pv.has(n)}function Iv(n){return Cv.some(e=>n.startsWith(e))}function $d(n){let e=[],t=[];for(let r of n)Dv(r.catalog_id)?t.push(r):e.push(r);return[...e,...t]}function Bd(n){let e=[],t=[];for(let r of n)Iv(r.documentId)?t.push(r):e.push(r);return[...e,...t]}var Av=[{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 _n(n,e,t){let r=Ye[e];n.set(r,(n.get(r)??1)*t)}function xv(n,e){let t=n.trim(),r=/[\u4e00-\u9fff]/.test(t),i=/\b[A-Z][a-zA-Z0-9]{2,}\b/.test(t),o=/\b[a-z][a-zA-Z0-9]{3,}\b/.test(t);if(r&&(i||o)){_n(e,"harmonyos-guides",1.45),_n(e,"harmonyos-references",1.35);return}(i||o)&&_n(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&_n(e,"harmonyos-references",1.75)}function Wd(n){let e=new Map,t=n.trim();if(!t)return e;let r=kd(t);xv(t,e),Od(t,e);for(let i of Av)i.pattern.test(t)&&(i.skipForPureApiSymbol&&r||_n(e,i.catalog,i.multiplier));return e}function Ud(n){return Nd(n)}var Tv=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function zd(n,e){let t=-1;for(let r of Tv){let i=n.lastIndexOf(r);i>t&&(t=i)}return t>=e?t:-1}function qd(n,e){let t=n.trim();if(t.length<=e)return{text:t,excerptTruncated:!1};let r=t.slice(0,e),i=zd(r,e-20),o=i>=0?i:e;return{text:t.slice(0,o).trimEnd(),excerptTruncated:!0}}function Gd(n,e,t={}){let{maxLen:r=Yl,contextChars:i=Jl,excerptTruncated:o=!1}=t,s=n.replace(/\s+/g," ").trim();if(!s)return"";if(s.length<=r)return o?`${s}...`:s;let a=e.split(/\s+/).map(he=>he.trim()).filter(Boolean),c=0;for(let he of a){let Wn=s.toLowerCase().indexOf(he.toLowerCase());if(Wn>=0){c=Wn;break}}let l=Math.max(0,c-i),u=Math.min(s.length,l+r),f=s.slice(l,u),P=zd(f,r-25);P>=0&&(u=l+P);let C=s.slice(l,u).trim(),L=l>0?"...":"",ne=u<s.length||o?"...":"";return`${L}${C}${ne}`}var kv=`
1297
+ SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
1298
+ d.catalog_id, bm25(segments_fts) AS bm25
1297
1299
  FROM segments_fts
1298
1300
  JOIN segments s ON s.id = segments_fts.rowid
1299
1301
  JOIN documents d ON d.id = s.doc_id
1300
1302
  WHERE segments_fts MATCH ?
1301
1303
  ORDER BY bm25(segments_fts)
1302
1304
  LIMIT ?
1303
- `,uv=`
1304
- SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, d.catalog_id,
1305
- bm25(segments_fts) AS bm25
1305
+ `,Rv=`
1306
+ SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
1307
+ d.catalog_id, bm25(segments_fts) AS bm25
1306
1308
  FROM segments_fts
1307
1309
  JOIN segments s ON s.id = segments_fts.rowid
1308
1310
  JOIN documents d ON d.id = s.doc_id
1309
1311
  WHERE segments_fts MATCH ? AND d.catalog_id = ?
1310
1312
  ORDER BY bm25(segments_fts)
1311
1313
  LIMIT ?
1312
- `,pv=3.5,mv=1.4,hv=4,fv=1.8,gv=1.35,yv=3.5,vv=1.8,wv=120,Od=6;function as(n){return n.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function bv(n){return n.split(/[^\p{L}\p{N}@.]+/u).map(as).filter(e=>e.length>=2)}function Sv(n,e){return e.length>1&&e.every(t=>n.includes(t))}function Ev(n){return/^[a-z0-9]{1,4}$/.test(n.trim().toLowerCase())}function Pv(n,e){return n===e?yv:n.startsWith(e)||n.includes(`@ohos.${e}`)?vv:1}function Cv(n,e){let t=as(e);if(t.length<2)return 1;let r=as(n.doc_title);if(Ev(e))return Pv(r,t);if(r.includes(t))return hv;if(t.length>=Od&&r.includes(t.slice(0,Od)))return fv;let i=bv(e);return Sv(r,i)?gv:1}function Iv(n,e){return e<=1?n:n<0?n*e:n/e}function ai(n,e,t,r){let i=n.bm25/(e.get(n.catalog_id)??1);return i=Iv(i,Cv(n,t)),r&&ts(n.doc_title,n.section_title,r)&&(i/=pv,n.catalog_id===ze["harmonyos-references"]&&(i/=mv)),i}function ss(n,e,t,r){return n.reduce((i,o)=>ai(o,e,t,r)<ai(i,e,t,r)?o:i)}function Dv(n,e){return e.some(t=>n.section_title.includes(t)||n.doc_title.includes(t))}function Av(n,e,t,r,i){if(i){let o=n.filter(s=>ts(s.doc_title,s.section_title,i));if(o.length>0)return ss(o,t,r,i)}if(e.length>0){let o=n.filter(s=>Dv(s,e));if(o.length>0)return ss(o,t,r,i)}return ss(n,t,r,i)}function Ld(n,e,t,r,i){let o=kd(e),s=gd(e),c=es(e)?.camelCase,l=new Map;for(let M of n){let j=l.get(M.document_id)??[];j.push(M),l.set(M.document_id,j)}let u=[];for(let M of l.values())u.push(Av(M,s,o,t,c));let f=u.sort((M,j)=>ai(M,o,t,c)-ai(j,o,t,c));return(i?Td(f):f).slice(0,r)}function ci(n,e,t,r,i,o){let s=e?ze[e]:void 0,a=Math.max(t,t*Dl,wv),c=s===void 0?n.all(dv,r,a):n.all(uv,r,s,a);return(s===void 0?Ld(c,o,i,t,!0):Ld(c,o,i,t,!1)).map(u=>({title:u.doc_title,documentId:u.document_id,sectionTitle:u.section_title||void 0,snippet:Md(u.lead_text,i)}))}var li=`
1314
+ `,Mv=3.5,Ov=1.4,Lv=4,Nv=1.8,_v=1.35,Hv=3.5,Fv=1.8,jv=120,Vd=6;function gs(n){return n.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function $v(n){return n.split(/[^\p{L}\p{N}@.]+/u).map(gs).filter(e=>e.length>=2)}function Bv(n,e){return e.length>1&&e.every(t=>n.includes(t))}function Wv(n){return/^[a-z0-9]{1,4}$/.test(n.trim().toLowerCase())}function Uv(n,e){return n===e?Hv:n.startsWith(e)||n.includes(`@ohos.${e}`)?Fv:1}function zv(n,e){let t=gs(e);if(t.length<2)return 1;let r=gs(n.doc_title);if(Wv(e))return Uv(r,t);if(r.includes(t))return Lv;if(t.length>=Vd&&r.includes(t.slice(0,Vd)))return Nv;let i=$v(e);return Bv(r,i)?_v:1}function qv(n,e){return e<=1?n:n<0?n*e:n/e}function wi(n,e,t,r){let i=n.bm25/(e.get(n.catalog_id)??1);return i=qv(i,zv(n,t)),r&&ds(n.doc_title,n.section_title,r)&&(i/=Mv,n.catalog_id===Ye["harmonyos-references"]&&(i/=Ov)),i}function fs(n,e,t,r){return n.reduce((i,o)=>wi(o,e,t,r)<wi(i,e,t,r)?o:i)}function Gv(n,e){return e.some(t=>n.section_title.includes(t)||n.doc_title.includes(t))}function Vv(n,e,t,r,i){if(i){let o=n.filter(s=>ds(s.doc_title,s.section_title,i));if(o.length>0)return fs(o,t,r,i)}if(e.length>0){let o=n.filter(s=>Gv(s,e));if(o.length>0)return fs(o,t,r,i)}return fs(n,t,r,i)}function Yd(n,e,t,r,i){let o=Wd(e),s=xd(e),c=ls(e)?.camelCase,l=new Map;for(let C of n){let L=l.get(C.document_id)??[];L.push(C),l.set(C.document_id,L)}let u=[];for(let C of l.values())u.push(Vv(C,s,o,t,c));let f=u.sort((C,L)=>wi(C,o,t,c)-wi(L,o,t,c));return(i?$d(f):f).slice(0,r)}function bi(n,e,t,r,i,o){let s=e?Ye[e]:void 0,a=Math.max(t,t*Nl,jv),c=s===void 0?n.all(kv,r,a):n.all(Rv,r,s,a);return(s===void 0?Yd(c,o,i,t,!0):Yd(c,o,i,t,!1)).map(u=>({title:u.doc_title,documentId:u.document_id,sectionTitle:u.section_title||void 0,snippet:Gd(u.lead_text,i,{excerptTruncated:!!u.excerpt_truncated})}))}var Si=`
1313
1315
  CREATE TABLE documents (
1314
1316
  id INTEGER PRIMARY KEY,
1315
1317
  document_id TEXT NOT NULL UNIQUE,
@@ -1322,7 +1324,8 @@ CREATE TABLE segments (
1322
1324
  doc_id INTEGER NOT NULL REFERENCES documents(id),
1323
1325
  section_title TEXT NOT NULL DEFAULT '',
1324
1326
  lead_text TEXT NOT NULL DEFAULT '',
1325
- search_text TEXT NOT NULL
1327
+ search_text TEXT NOT NULL,
1328
+ excerpt_truncated INTEGER NOT NULL DEFAULT 0
1326
1329
  );
1327
1330
 
1328
1331
  CREATE VIRTUAL TABLE segments_fts USING fts5(
@@ -1346,14 +1349,18 @@ CREATE TRIGGER segments_au AFTER UPDATE ON segments BEGIN
1346
1349
  END;
1347
1350
 
1348
1351
  CREATE INDEX segments_doc_id_idx ON segments(doc_id);
1349
- `;var zt=null,cs=null;function Tv(){zt?.close(),zt=null,cs=null}function xv(n,e){if(zt&&cs===e)return zt;zt?.close();let t=new n(e,{readonly:!0,fileMustExist:!0});return zt=t,cs=e,t.pragma("mmap_size = 268435456"),t.pragma("cache_size = -8000"),t.pragma("query_only = ON"),t}function kv(n,e){let t=new n(e);return t.pragma("journal_mode = OFF"),t.pragma("synchronous = OFF"),t.pragma("temp_store = MEMORY"),t.exec(li),t}function Rv(n,e,t){let r=e.get(t.documentId);if(r!==void 0)return r;let o=n.prepare("SELECT id FROM documents WHERE document_id = ?").get(t.documentId);if(o)return e.set(t.documentId,o.id),o.id;let a=n.prepare(`
1352
+ `;var Yt=null,ys=null;function Yv(){Yt?.close(),Yt=null,ys=null}function Jv(n,e){if(Yt&&ys===e)return Yt;Yt?.close();let t=new n(e,{readonly:!0,fileMustExist:!0});return Yt=t,ys=e,t.pragma("mmap_size = 268435456"),t.pragma("cache_size = -8000"),t.pragma("query_only = ON"),t}function Kv(n,e){let t=new n(e);return t.pragma("journal_mode = OFF"),t.pragma("synchronous = OFF"),t.pragma("temp_store = MEMORY"),t.exec(Si),t}function Zv(n,e,t){let r=e.get(t.documentId);if(r!==void 0)return r;let o=n.prepare("SELECT id FROM documents WHERE document_id = ?").get(t.documentId);if(o)return e.set(t.documentId,o.id),o.id;let a=n.prepare(`
1350
1353
  INSERT INTO documents(document_id, catalog_id, doc_title)
1351
1354
  VALUES (?, ?, ?)
1352
- `).run(t.documentId,t.catalogId,t.docTitle),c=Number(a.lastInsertRowid);return e.set(t.documentId,c),c}async function Mv(n,e,t,r){await Ve();let i=kv(n,e),o=new Map,s=i.prepare(`
1353
- INSERT INTO segments(doc_id, section_title, lead_text, search_text)
1354
- VALUES (?, ?, ?, ?)
1355
- `),a=t.length;for(let c=0;c<a;c+=$t){let l=t.slice(c,c+$t),u=await Promise.all(l.map(async E=>({source:E,searchText:await si(E)})));i.transaction(E=>{for(let M of E){let j=Rv(i,o,M.source);s.run(j,M.source.sectionTitle,M.source.leadText,M.searchText)}})(u),await r?.(Math.min(c+l.length,a),a)}i.exec("ANALYZE"),i.exec("VACUUM"),i.close()}function Ov(n,e,t,r,i,o,s){let a=xv(n,e);return ci({all(c,...l){return a.prepare(c).all(...l)}},t,r,i,o,s)}async function Nd(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:Tv,buildSearchIndex:(t,r,i)=>Mv(e,t,r,i),searchIndex:(t,r,i,o,s,a,c)=>Promise.resolve(Ov(e,o,r,i,s,a,c))}}import{readFile as Lv,stat as Nv,writeFile as _v}from"fs/promises";var ls=null,Je=null;async function ds(){return ls||(ls=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),ls}function Hv(n){return{all(e,...t){let r=n.prepare(e);t.length>0&&r.bind(t);let i=[];for(;r.step();)i.push(r.get({}));return r.finalize(),i}}}async function Fv(n){let e=await Nv(n);if(Je&&Je.dbPath===n&&Je.mtimeMs===e.mtimeMs)return Je.db;Je?.db.close();let t=await ds(),r=t.capi,i=t.wasm,o=new Uint8Array(await Lv(n)),s=i.allocFromTypedArray(o),a=new t.oo1.DB(":memory:"),c=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE;return r.sqlite3_deserialize(a.pointer,"main",s,o.byteLength,o.byteLength,c),Je={dbPath:n,mtimeMs:e.mtimeMs,db:a},a}function _d(){Je?.db.close(),Je=null}async function jv(n,e,t,r){n.exec("BEGIN");for(let i of r){let o=t(i.source);e.bind([o,i.source.sectionTitle,i.source.leadText,i.searchText]),e.step(),e.reset()}n.exec("COMMIT")}function $v(n,e,t){return r=>{let i=e.get(r.documentId);if(i!==void 0)return i;let o=n.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(o!=null){let a=Number(o);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 Wv(n,e,t){await Ve();let r=await ds(),i=new r.oo1.DB(":memory:","c");i.exec(li);let o=new Map,s=i.prepare("INSERT INTO documents(document_id, catalog_id, doc_title) VALUES (?, ?, ?)"),a=i.prepare("INSERT INTO segments(doc_id, section_title, lead_text, search_text) VALUES (?, ?, ?, ?)"),c=$v(i,o,s),l=e.length;for(let f=0;f<l;f+=$t){let E=e.slice(f,f+$t),M=await Promise.all(E.map(async j=>({source:j,searchText:await si(j)})));await jv(i,a,c,M),await t?.(Math.min(f+E.length,l),l)}i.exec("ANALYZE");let u=r.capi.sqlite3_js_db_export(i);await _v(n,u),i.close(),_d()}async function Bv(n,e,t,r,i,o){let s=await Fv(n);return ci(Hv(s),e,t,r,i,o)}async function Hd(){return await ds(),{kind:"sqlite-wasm",resetCache:_d,buildSearchIndex:Wv,searchIndex:(n,e,t,r,i,o,s)=>Bv(r,e,t,i,o,s)}}var di=null,us=null;async function Uv(){try{let e=await Nd();return y("doc-index: using better-sqlite3 SQLite backend"),e}catch(e){y(`doc-index: better-sqlite3 unavailable (${e.message}); falling back to sqlite-wasm`)}let n=await Hd();return y("doc-index: using @sqlite.org/sqlite-wasm SQLite backend"),n}async function Mn(){return di||(di=Uv().then(n=>(us=n,n))),di}function Fd(){us?.resetCache(),di=null,us=null}async function zv(n,e,t,r,i,o,s){let a=await Mn(),c=s??En();return a.searchIndex(n,e,t,c,r,i,o)}function $d(){Fd()}async function Wd(n,e,t){await(await Mn()).buildSearchIndex(n,e,t)}function Bd(n,e,t){let r=new Set,i=[];for(let o of[...n,...e])if(!r.has(o.documentId)&&(r.add(o.documentId),i.push(o),i.length>=t))break;return i}function ui(n,e,t,r,i,o){return zv(n,e,t,i,r.expandedQuery,r.rawQuery,o)}async function qv(n,e,t,r,i){let o=await ui(n,e,t,r,An(r.tokens,"AND"),i);if(o.length>=t)return o;let s=await ui(n,e,t,r,An(r.tokens,"OR"),i);return Bd(o,s,t)}async function ps(n,e,t,r,i){return r.ftsMatch?ui(n,e,t,r,r.ftsMatch,i):r.preferAnd?qv(n,e,t,r,i):ui(n,e,t,r,An(r.tokens,"OR"),i)}async function Gv(n,e,t,r){let i=await ps(n,"harmonyos-references",e,t,r);if(i.length>=e)return i;let o=await ps(n,void 0,e,t,r);return Bd(i,o,e)}function jd(n,e){return e!==void 0?n:xd(n)}async function Ud(n,e,t=20,r){let i=await Dd(n);if(Ed(i.rawQuery,e)){let a=await Gv(n,t,i,r);return jd(a,e)}let o=e??Rd(i.rawQuery),s=await ps(n,o,t,i,r);return jd(s,e)}import{unified as Zd}from"unified";import Xd from"remark-parse";import Qd from"remark-gfm";import{toString as mi}from"mdast-util-to-string";var Yv=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,Vv=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,Jv=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,Kv=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,Zv=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function pi(n){let e=n.trim(),t=e.match(Kv);return t?t[1]:e}function Xv(n){let e=n.match(Yv);if(!e)return;let t=pi(e[1].trim());return{displayTitle:n,symbolName:t,searchExtras:[t,e[3]]}}function Qv(n){let e=pi(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 On(n){let e=n.trim();return e?Xv(e)??(()=>{let t=e.match(Vv);if(t){let r=t[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let t=e.match(Jv);if(!t)return;let r=t[1].trim(),i=t[2].trim();return{displayTitle:e,symbolName:i,searchExtras:[r,i]}})()??Qv(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function ew(n){if(n.length<2||n.length>36||Zv.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 zd(n){for(let e of n){let t=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(ew(t))return t}return""}function qd(n,e,t){let r=[n,...t.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var tw=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,Ln=/@[A-Z][a-zA-Z]+/g,nw=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,rw=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,iw=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,ow=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),sw=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),aw=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function eu(n,e){let t=new Set,r=[n,...e];for(let i of r){for(let o of Xo(i)){we(t,o);let s=ti(o);s&&we(t,s)}for(let o of Qo(i))we(t,o);for(let o of i.matchAll(tw)){let s=o[0];cw(s)&&t.add(s)}for(let o of i.matchAll(Ln))t.add(o[0])}return Ut([...t])}function cw(n){let e=n.trim();if(!e||Ln.test(e))return!!e;if(e.includes(".")){let t=e.split(".")[0]??"";return aw.has(t)?!1:/^[A-Z]/.test(t)}return ow.has(e)?!1:sw.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 Gd(n){let e=n.trim();return!!(!e||iw.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function tu(n,e){let t=e.jsonTitle?.trim(),r=pw(n,"").trim(),i=e.fileName.trim();return t&&!Gd(t)?t:r&&!Gd(r)?r:t||r||i}function nu(n){return nw.test(n.trim())}function ms(n){let e=n.trim().replace(/\([^)]*\)$/,""),t=pi(e);return rw.test(t)}function hi(n){let e=n.trim();return e?Ln.test(e)||nu(e)||ms(e)?!0:!!On(e).symbolName:!1}function lw(n){let e=n.trim();return!(!e||nu(e)||ms(e))}function dw(n){let e=new Set,t=[];for(let r of n){let i=r.trim();!lw(i)||e.has(i)||(e.add(i),t.push(i))}return t}function Yd(n){if(!n.includes("."))return 0;let e=n.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function uw(n,e){let t=Yd(n)-Yd(e);return t!==0?t:n.localeCompare(e)}function ru(n,e=[]){let t=[...new Set(e.map(o=>o.trim()).filter(Boolean))],r=new Set(t),i=[...new Set(n.map(o=>o.trim()).filter(Boolean))].filter(o=>!r.has(o));return i.sort(uw),[...t,...i].slice(0,Hl)}function fi(n){return n.replace(/\s+/g," ").trim()}function Vd(n){return n.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function pw(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 i=Vd(t[r].trim()),o=i.match(/^#+\s+(.+)$/);if(o)return Vd(o[1].trim());if(r+1<t.length){let s=t[r+1].trim();if(/^=+$/.test(s)||/^-+$/.test(s))return i}return i||e}function iu(n){let e=fi(n.join(" "));if(e.length<=Yr)return e;let t=e.slice(0,Yr);return e.length<=Yr+No?t:`${t} ${e.slice(-No)}`}function mw(n){let e=dw(n).join(" ");return e.length<=_o?e:e.slice(0,_o)}function ou(n){let e=fi(n);return e.length<=Ho?e:e.slice(0,Ho)}function su(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)su(r,e);return}let t=fi(mi(n));t&&e.bodyParts.push(t)}function hw(n){let e=Zd().use(Xd).use(Qd).parse(n),t=[],r=null,i=()=>{r&&((r.sectionTitle||r.bodyParts.length||r.codeBlocks.length)&&t.push(r),r=null)},o=()=>{r||(r={sectionTitle:"",bodyParts:[],codeBlocks:[]})};for(let s of e.children){if(s.type==="heading"){let a=s,c=mi(a).trim();if(a.depth>=4&&c&&hi(c)){i(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}o(),c&&r.bodyParts.push(c);continue}o(),su(s,r)}return i(),t.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:t}function fw(n){return Pl.test(n)}function gw(n){return n.filter(e=>e.sectionTitle&&hi(e.sectionTitle)).length}function yw(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 Jd(n){let e=n.trim();return!e||Ln.test(e)?Ln.test(e):/对象说明$|枚举说明$/.test(e)?!0:ms(e)}function vw(n){let e=n.filter(f=>!f.sectionTitle||!hi(f.sectionTitle)),t=n.filter(f=>f.sectionTitle&&hi(f.sectionTitle)),r=t.filter(f=>Jd(f.sectionTitle)),i=t.filter(f=>!Jd(f.sectionTitle)),o=Math.max(0,El-r.length),s=i.slice(0,o),a=i.slice(o),c=a.filter(f=>Kd(f.sectionTitle)),l=a.filter(f=>!Kd(f.sectionTitle)),u=[];for(let f=0;f<l.length;f+=Oo)u.push(yw(l.slice(f,f+Oo)));return[...e,...r,...s,...c,...u]}function ww(n,e,t){let r=n.split(/\r?\n/).length,i=gw(e);return i===0?!1:fw(t)?r>=bl&&i>=Sl:r>=vl&&i>=wl}var bw=/^\[h2\][A-Za-z]/;function Kd(n){return bw.test(n.trim())}function au(n){if(!n.includes(" | ")){let t=On(n);return t.symbolName?[t.symbolName]:[]}let e=[];for(let t of n.split(" | ")){let r=On(t.trim()).symbolName;r&&e.push(r)}return e}function Sw(n,e,t,r){let i=au(n),o=eu(t,r);return e.symbolName&&o.push(e.symbolName),ru([...i,...o],i)}function Ew(n,e){let t=iu(n.bodyParts),r=n.sectionTitle.trim(),i=On(r),o=zd(n.bodyParts),s=qd(r,o,i),a=au(r),c=r?a.length>0?`${e.docTitle} ${a.join(" ")}`:`${e.docTitle} ${i.symbolName??r}`:e.docTitle,l=[e.docTitle,s,...n.bodyParts].join(" ");return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:Sw(r,i,l,n.codeBlocks),bodySample:t,leadText:ou(t)}}function cu(n,e){for(let t of n){if(t.type==="heading"){let i=mi(t).trim();i&&e.headings.push(i);continue}if(t.type==="code"){e.codeBlocks.push(t.value??"");continue}if("children"in t&&Array.isArray(t.children)){cu(t.children,e);continue}let r=fi(mi(t));r&&e.bodyParts.push(r)}}function Pw(n){let e=Zd().use(Xd).use(Qd).parse(n),t={headings:[],bodyParts:[],codeBlocks:[]};return cu(e.children,t),t}function Cw(n,e){let t=Pw(n),r=e.docTitle?.trim()||e.documentId,i=iu(t.bodyParts),o=[r,...t.headings,i].join(" ");return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:mw(t.headings),apiSymbols:ru(eu(o,t.codeBlocks)),bodySample:i,leadText:ou(i)}}function lu(n,e){let t=e.docTitle?.trim()||e.documentId,r=hw(n);return ww(n,r,e.documentId)?vw(r).filter(i=>i.sectionTitle||i.bodyParts.length>0||i.codeBlocks.length>0).map(i=>Ew(i,{...e,docTitle:t})):[Cw(n,{...e,docTitle:t})]}async function Iw(n){let e=[];async function t(r){let i=await K.promises.readdir(r,{withFileTypes:!0});for(let o of i){if(o.name.startsWith("."))continue;let s=re.join(r,o.name);o.isDirectory()?await t(s):o.isFile()&&o.name.endsWith(".md")&&e.push(s)}}return await t(n),e}function Dw(n,e){let t=re.relative(e,n).split(re.sep).join("/").split("/");if(t[0]==="docs"&&(t=t.slice(1)),t.length<2)return null;let r=t[0],i=Fl[r];if(i===void 0)return null;let o=t[t.length-1].replace(/\.md$/,"");return t[t.length-1]=o,{documentId:t.join("/"),catalogId:i,docTitle:o}}async function Aw(n){let e=n.replace(/\.md$/,".json");try{let t=await K.promises.readFile(e,"utf-8");return JSON.parse(t).title?.trim()||void 0}catch{return}}async function Tw(n,e){let t=Dw(n,e);if(!t)return[];let r=await K.promises.readFile(n,"utf-8"),i=tu(r,{jsonTitle:await Aw(n),fileName:t.docTitle});return lu(r,{...t,docTitle:i})}async function xw(n,e,t){let r=re.join(e,"search.db");return await Wd(r,n,async(i,o)=>{await t?.({current:i,total:o,message:`Building search index\u2026 ${i.toLocaleString()} / ${o.toLocaleString()} segments`})}),n.length}async function kw(n){let e=await Iw(n),t=[];for(let r of e){let i=await Tw(r,n);t.push(...i)}return t}function Rw(n,e){return{indexVersion:Gr,docsZipSha256:n.docsZipSha256,termsHash:n.termsHash,synonymsHash:n.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:n.builtBy}}async function uu(n){n.lexiconDir&&Wo(n.lexiconDir);try{let e=await kw(n.docsDir);await n.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await K.promises.mkdir(n.tmpDir,{recursive:!0});let t=await xw(e,n.tmpDir,n.onProgress),r=Rw(n,t);return await K.promises.writeFile(re.join(n.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await Kl(n.tmpDir),r}finally{n.lexiconDir&&Wo(null)}}async function pu(){return K.promises.mkdtemp(re.join(du.tmpdir(),"deveco-docs-"))}async function Mw(n,e){try{await K.promises.rename(n,e)}catch(t){let r=t.code;if(r!=="EPERM"&&r!=="EXDEV")throw t;await K.promises.cp(n,e,{recursive:!0}),await K.promises.rm(n,{recursive:!0,force:!0})}}async function mu(n){let e=re.join(n,"docs");try{await K.promises.access(e)}catch{return}let t=new Set(["docs","docs.zip"]);for(let r of await K.promises.readdir(e,{withFileTypes:!0})){if(t.has(r.name))continue;let i=re.join(e,r.name),o=re.join(n,r.name);await K.promises.rm(o,{recursive:!0,force:!0}),await Mw(i,o)}await K.promises.rm(re.join(e,"docs"),{recursive:!0,force:!0}),await K.promises.rm(re.join(e,"docs.zip"),{force:!0}),await K.promises.rm(e,{recursive:!0,force:!0})}var gi=class extends Error{constructor(e){super(e),this.name="NativeDepsError"}};function Ow(){return["Chinese tokenizer (@node-rs/jieba) failed to load.","",`Node.js: ${process.version} (required: >=18)`,"","Try:"," 1. Reinstall: npm uninstall -g @deveco-test/deveco-cli && npm install -g <package.tgz>"," 2. Use Node.js 18 or newer"," 3. Configure npm registry/proxy if your network blocks optional platform packages"].join(`
1356
- `)}async function hu(){try{await Ve()}catch(n){let e=n instanceof Error?n.message:String(n);throw new gi(`${Ow()}
1355
+ `).run(t.documentId,t.catalogId,t.docTitle),c=Number(a.lastInsertRowid);return e.set(t.documentId,c),c}async function Xv(n,e,t,r){await Xe();let i=Kv(n,e),o=new Map,s=i.prepare(`
1356
+ INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated)
1357
+ VALUES (?, ?, ?, ?, ?)
1358
+ `),a=t.length;for(let c=0;c<a;c+=Ut){let l=t.slice(c,c+Ut),u=await Promise.all(l.map(async P=>({source:P,searchText:await vi(P)})));i.transaction(P=>{for(let C of P){let L=Zv(i,o,C.source);s.run(L,C.source.sectionTitle,C.source.leadText,C.searchText,C.source.excerptTruncated?1:0)}})(u),await r?.(Math.min(c+l.length,a),a)}i.exec("ANALYZE"),i.exec("VACUUM"),i.close()}function Qv(n,e,t,r,i,o,s){let a=Jv(n,e);return bi({all(c,...l){return a.prepare(c).all(...l)}},t,r,i,o,s)}async function Jd(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:Yv,buildSearchIndex:(t,r,i)=>Xv(e,t,r,i),searchIndex:(t,r,i,o,s,a,c)=>Promise.resolve(Qv(e,o,r,i,s,a,c))}}import{readFile as ew,stat as tw,writeFile as nw}from"fs/promises";var vs=null,Qe=null;async function ws(){return vs||(vs=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),vs}function rw(n){return{all(e,...t){let r=n.prepare(e);t.length>0&&r.bind(t);let i=[];for(;r.step();)i.push(r.get({}));return r.finalize(),i}}}async function iw(n){let e=await tw(n);if(Qe&&Qe.dbPath===n&&Qe.mtimeMs===e.mtimeMs)return Qe.db;Qe?.db.close();let t=await ws(),r=t.capi,i=t.wasm,o=new Uint8Array(await ew(n)),s=i.allocFromTypedArray(o),a=new t.oo1.DB(":memory:"),c=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE;return r.sqlite3_deserialize(a.pointer,"main",s,o.byteLength,o.byteLength,c),Qe={dbPath:n,mtimeMs:e.mtimeMs,db:a},a}function Kd(){Qe?.db.close(),Qe=null}async function ow(n,e,t,r){n.exec("BEGIN");for(let i of r){let o=t(i.source);e.bind([o,i.source.sectionTitle,i.source.leadText,i.searchText,i.source.excerptTruncated?1:0]),e.step(),e.reset()}n.exec("COMMIT")}function sw(n,e,t){return r=>{let i=e.get(r.documentId);if(i!==void 0)return i;let o=n.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(o!=null){let a=Number(o);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 aw(n,e,t){await Xe();let r=await ws(),i=new r.oo1.DB(":memory:","c");i.exec(Si);let o=new Map,s=i.prepare("INSERT INTO documents(document_id, catalog_id, doc_title) VALUES (?, ?, ?)"),a=i.prepare("INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated) VALUES (?, ?, ?, ?, ?)"),c=sw(i,o,s),l=e.length;for(let f=0;f<l;f+=Ut){let P=e.slice(f,f+Ut),C=await Promise.all(P.map(async L=>({source:L,searchText:await vi(L)})));await ow(i,a,c,C),await t?.(Math.min(f+P.length,l),l)}i.exec("ANALYZE");let u=r.capi.sqlite3_js_db_export(i);await nw(n,u),i.close(),Kd()}async function cw(n,e,t,r,i,o){let s=await iw(n);return bi(rw(s),e,t,r,i,o)}async function Zd(){return await ws(),{kind:"sqlite-wasm",resetCache:Kd,buildSearchIndex:aw,searchIndex:(n,e,t,r,i,o,s)=>cw(r,e,t,i,o,s)}}var Ei=null,bs=null;async function lw(){try{let e=await Jd();return g("doc-index: using better-sqlite3 SQLite backend"),e}catch(e){g(`doc-index: better-sqlite3 unavailable (${e.message}); falling back to sqlite-wasm`)}let n=await Zd();return g("doc-index: using @sqlite.org/sqlite-wasm SQLite backend"),n}async function Hn(){return Ei||(Ei=lw().then(n=>(bs=n,n))),Ei}function Xd(){bs?.resetCache(),Ei=null,bs=null}async function dw(n,e,t,r,i,o,s){let a=await Hn(),c=s??An();return a.searchIndex(n,e,t,c,r,i,o)}function eu(){Xd()}async function tu(n,e,t){await(await Hn()).buildSearchIndex(n,e,t)}function nu(n,e,t){let r=new Set,i=[];for(let o of[...n,...e])if(!r.has(o.documentId)&&(r.add(o.documentId),i.push(o),i.length>=t))break;return i}function Pi(n,e,t,r,i,o){return dw(n,e,t,i,r.expandedQuery,r.rawQuery,o)}async function uw(n,e,t,r,i){let o=await Pi(n,e,t,r,Mn(r.tokens,"AND"),i);if(o.length>=t)return o;let s=await Pi(n,e,t,r,Mn(r.tokens,"OR"),i);return nu(o,s,t)}async function Ss(n,e,t,r,i){return r.ftsMatch?Pi(n,e,t,r,r.ftsMatch,i):r.preferAnd?uw(n,e,t,r,i):Pi(n,e,t,r,Mn(r.tokens,"OR"),i)}async function pw(n,e,t,r){let i=await Ss(n,"harmonyos-references",e,t,r);if(i.length>=e)return i;let o=await Ss(n,void 0,e,t,r);return nu(i,o,e)}function Qd(n,e){return e!==void 0?n:Bd(n)}async function ru(n,e,t=20,r){let i=await Fd(n);if(Ld(i.rawQuery,e)){let a=await pw(n,t,i,r);return Qd(a,e)}let o=e??Ud(i.rawQuery),s=await Ss(n,o,t,i,r);return Qd(s,e)}import{unified as uu}from"unified";import pu from"remark-parse";import mu from"remark-gfm";import{toString as Di}from"mdast-util-to-string";var mw=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,hw=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,fw=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,gw=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,yw=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function Ci(n){let e=n.trim(),t=e.match(gw);return t?t[1]:e}function vw(n){let e=n.match(mw);if(!e)return;let t=Ci(e[1].trim());return{displayTitle:n,symbolName:t,searchExtras:[t,e[3]]}}function ww(n){let e=Ci(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 Fn(n){let e=n.trim();return e?vw(e)??(()=>{let t=e.match(hw);if(t){let r=t[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let t=e.match(fw);if(!t)return;let r=t[1].trim(),i=t[2].trim();return{displayTitle:e,symbolName:i,searchExtras:[r,i]}})()??ww(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function bw(n){if(n.length<2||n.length>36||yw.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 iu(n){for(let e of n){let t=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(bw(t))return t}return""}function ou(n,e,t){let r=[n,...t.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var Sw=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,jn=/@[A-Z][a-zA-Z]+/g,Ew=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,Pw=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,Cw=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,Dw=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),Iw=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),Aw=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function hu(n,e){let t=new Set,r=[n,...e];for(let i of r){for(let o of as(i)){Pe(t,o);let s=mi(o);s&&Pe(t,s)}for(let o of cs(i))Pe(t,o);for(let o of i.matchAll(Sw)){let s=o[0];xw(s)&&t.add(s)}for(let o of i.matchAll(jn))t.add(o[0])}return Vt([...t])}function xw(n){let e=n.trim();if(!e||jn.test(e))return!!e;if(e.includes(".")){let t=e.split(".")[0]??"";return Aw.has(t)?!1:/^[A-Z]/.test(t)}return Dw.has(e)?!1:Iw.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 su(n){let e=n.trim();return!!(!e||Cw.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function fu(n,e){let t=e.jsonTitle?.trim(),r=Mw(n,"").trim(),i=e.fileName.trim();return t&&!su(t)?t:r&&!su(r)?r:t||r||i}function gu(n){return Ew.test(n.trim())}function Es(n){let e=n.trim().replace(/\([^)]*\)$/,""),t=Ci(e);return Pw.test(t)}function Ii(n){let e=n.trim();return e?jn.test(e)||gu(e)||Es(e)?!0:!!Fn(e).symbolName:!1}function Tw(n){let e=n.trim();return!(!e||gu(e)||Es(e))}function kw(n){let e=new Set,t=[];for(let r of n){let i=r.trim();!Tw(i)||e.has(i)||(e.add(i),t.push(i))}return t}function au(n){if(!n.includes("."))return 0;let e=n.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function Rw(n,e){let t=au(n)-au(e);return t!==0?t:n.localeCompare(e)}function yu(n,e=[]){let t=[...new Set(e.map(o=>o.trim()).filter(Boolean))],r=new Set(t),i=[...new Set(n.map(o=>o.trim()).filter(Boolean))].filter(o=>!r.has(o));return i.sort(Rw),[...t,...i].slice(0,Gl)}function Ai(n){return n.replace(/\s+/g," ").trim()}function cu(n){return n.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function Mw(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 i=cu(t[r].trim()),o=i.match(/^#+\s+(.+)$/);if(o)return cu(o[1].trim());if(r+1<t.length){let s=t[r+1].trim();if(/^=+$/.test(s)||/^-+$/.test(s))return i}return i||e}function vu(n){let e=Ai(n.join(" "));if(e.length<=ti)return e;let t=e.slice(0,ti);return e.length<=ti+zo?t:`${t} ${e.slice(-zo)}`}function Ow(n){let e=kw(n).join(" ");return e.length<=qo?e:e.slice(0,qo)}function wu(n){let e=Ai(n),{text:t,excerptTruncated:r}=qd(e,Vl);return{leadText:t,excerptTruncated:r}}function Lw(n,e){let{leadText:t,excerptTruncated:r}=wu(n);return{leadText:t,excerptTruncated:r||!!e.trim()}}function bu(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)bu(r,e);return}let t=Ai(Di(n));t&&e.bodyParts.push(t)}function Nw(n){let e=uu().use(pu).use(mu).parse(n),t=[],r=null,i=()=>{r&&((r.sectionTitle||r.bodyParts.length||r.codeBlocks.length)&&t.push(r),r=null)},o=()=>{r||(r={sectionTitle:"",bodyParts:[],codeBlocks:[]})};for(let s of e.children){if(s.type==="heading"){let a=s,c=Di(a).trim();if(a.depth>=4&&c&&Ii(c)){i(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}o(),c&&r.bodyParts.push(c);continue}o(),bu(s,r)}return i(),t.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:t}function _w(n){return Ml.test(n)}function Hw(n){return n.filter(e=>e.sectionTitle&&Ii(e.sectionTitle)).length}function Fw(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 lu(n){let e=n.trim();return!e||jn.test(e)?jn.test(e):/对象说明$|枚举说明$/.test(e)?!0:Es(e)}function jw(n){let e=n.filter(f=>!f.sectionTitle||!Ii(f.sectionTitle)),t=n.filter(f=>f.sectionTitle&&Ii(f.sectionTitle)),r=t.filter(f=>lu(f.sectionTitle)),i=t.filter(f=>!lu(f.sectionTitle)),o=Math.max(0,Rl-r.length),s=i.slice(0,o),a=i.slice(o),c=a.filter(f=>du(f.sectionTitle)),l=a.filter(f=>!du(f.sectionTitle)),u=[];for(let f=0;f<l.length;f+=Wo)u.push(Fw(l.slice(f,f+Wo)));return[...e,...r,...s,...c,...u]}function $w(n,e,t){let r=n.split(/\r?\n/).length,i=Hw(e);return i===0?!1:_w(t)?r>=Tl&&i>=kl:r>=Al&&i>=xl}var Bw=/^\[h2\][A-Za-z]/;function du(n){return Bw.test(n.trim())}function Su(n){if(!n.includes(" | ")){let t=Fn(n);return t.symbolName?[t.symbolName]:[]}let e=[];for(let t of n.split(" | ")){let r=Fn(t.trim()).symbolName;r&&e.push(r)}return e}function Ww(n,e,t,r){let i=Su(n),o=hu(t,r);return e.symbolName&&o.push(e.symbolName),yu([...i,...o],i)}function Uw(n,e){let t=vu(n.bodyParts),r=n.sectionTitle.trim(),i=Fn(r),o=iu(n.bodyParts),s=ou(r,o,i),a=Su(r),c=r?a.length>0?`${e.docTitle} ${a.join(" ")}`:`${e.docTitle} ${i.symbolName??r}`:e.docTitle,l=[e.docTitle,s,...n.bodyParts].join(" "),{leadText:u,excerptTruncated:f}=Lw(t,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:Ww(r,i,l,n.codeBlocks),bodySample:t,leadText:u,excerptTruncated:f}}function Eu(n,e){for(let t of n){if(t.type==="heading"){let i=Di(t).trim();i&&e.headings.push(i);continue}if(t.type==="code"){e.codeBlocks.push(t.value??"");continue}if("children"in t&&Array.isArray(t.children)){Eu(t.children,e);continue}let r=Ai(Di(t));r&&e.bodyParts.push(r)}}function zw(n){let e=uu().use(pu).use(mu).parse(n),t={headings:[],bodyParts:[],codeBlocks:[]};return Eu(e.children,t),t}function qw(n,e){let t=zw(n),r=e.docTitle?.trim()||e.documentId,i=vu(t.bodyParts),o=[r,...t.headings,i].join(" "),{leadText:s,excerptTruncated:a}=wu(i);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:Ow(t.headings),apiSymbols:yu(hu(o,t.codeBlocks)),bodySample:i,leadText:s,excerptTruncated:a}}function Pu(n,e){let t=e.docTitle?.trim()||e.documentId,r=Nw(n);return $w(n,r,e.documentId)?jw(r).filter(i=>i.sectionTitle||i.bodyParts.length>0||i.codeBlocks.length>0).map(i=>Uw(i,{...e,docTitle:t})):[qw(n,{...e,docTitle:t})]}async function Gw(n){let e=[];async function t(r){let i=await Z.promises.readdir(r,{withFileTypes:!0});for(let o of i){if(o.name.startsWith("."))continue;let s=ie.join(r,o.name);o.isDirectory()?await t(s):o.isFile()&&o.name.endsWith(".md")&&e.push(s)}}return await t(n),e}function Vw(n,e){let t=ie.relative(e,n).split(ie.sep).join("/").split("/");if(t[0]==="docs"&&(t=t.slice(1)),t.length<2)return null;let r=t[0],i=Kl[r];if(i===void 0)return null;let o=t[t.length-1].replace(/\.md$/,"");return t[t.length-1]=o,{documentId:t.join("/"),catalogId:i,docTitle:o}}async function Yw(n){let e=n.replace(/\.md$/,".json");try{let t=await Z.promises.readFile(e,"utf-8");return JSON.parse(t).title?.trim()||void 0}catch{return}}async function Jw(n,e){let t=Vw(n,e);if(!t)return[];let r=await Z.promises.readFile(n,"utf-8"),i=fu(r,{jsonTitle:await Yw(n),fileName:t.docTitle});return Pu(r,{...t,docTitle:i})}async function Kw(n,e,t){let r=ie.join(e,"search.db");return await tu(r,n,async(i,o)=>{await t?.({current:i,total:o,message:`Building search index\u2026 ${i.toLocaleString()} / ${o.toLocaleString()} segments`})}),n.length}async function Zw(n){let e=await Gw(n),t=[];for(let r of e){let i=await Jw(r,n);t.push(...i)}return t}function Xw(n,e){return{indexVersion:ei,docsZipSha256:n.docsZipSha256,termsHash:n.termsHash,synonymsHash:n.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:n.builtBy}}async function Du(n){n.lexiconDir&&Jo(n.lexiconDir);try{let e=await Zw(n.docsDir);await n.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await Z.promises.mkdir(n.tmpDir,{recursive:!0});let t=await Kw(e,n.tmpDir,n.onProgress),r=Xw(n,t);return await Z.promises.writeFile(ie.join(n.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await cd(n.tmpDir),r}finally{n.lexiconDir&&Jo(null)}}async function Iu(){return Z.promises.mkdtemp(ie.join(Cu.tmpdir(),"deveco-docs-"))}async function Qw(n,e){try{await Z.promises.rename(n,e)}catch(t){let r=t.code;if(r!=="EPERM"&&r!=="EXDEV")throw t;await Z.promises.cp(n,e,{recursive:!0}),await Z.promises.rm(n,{recursive:!0,force:!0})}}async function Au(n){let e=ie.join(n,"docs");try{await Z.promises.access(e)}catch{return}let t=new Set(["docs","docs.zip"]);for(let r of await Z.promises.readdir(e,{withFileTypes:!0})){if(t.has(r.name))continue;let i=ie.join(e,r.name),o=ie.join(n,r.name);await Z.promises.rm(o,{recursive:!0,force:!0}),await Qw(i,o)}await Z.promises.rm(ie.join(e,"docs"),{recursive:!0,force:!0}),await Z.promises.rm(ie.join(e,"docs.zip"),{force:!0}),await Z.promises.rm(e,{recursive:!0,force:!0})}var $n=class extends Error{constructor(e){super(e),this.name="NativeDepsError"}};function eb(){let n=qt(),e=te();return["Documentation search index is not installed yet.","",...ri(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(`
1359
+ `)}function tb(){let n=qt();return["Chinese tokenizer (@node-rs/jieba) failed to load.","",`Node.js: ${process.version} (required: >=18)`,"",...ri(n),"","Try:"," 1. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 2. Use Node.js 18 or newer"," 3. Configure npm registry/proxy if your network blocks optional platform packages"].join(`
1360
+ `)}function nb(n){let e=qt();return[n,"",...ri(e)].join(`
1361
+ `)}async function xu(){try{sd()}catch(n){throw od(n)?new $n(`${eb()}
1357
1362
 
1358
- Detail: ${e}`)}try{await Mn()}catch(n){let e=n instanceof Error?n.message:String(n);throw new gi(e)}}var hs=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function _w(n){return new Promise(e=>setTimeout(e,n))}async function Hw(n){let e=process.env.DEVECO_DOC_INIT_LOG??lt.join(zl(),"doc-init.log");await z.promises.mkdir(lt.dirname(e),{recursive:!0}),await z.promises.appendFile(e,`${new Date().toISOString()} ${n}
1359
- `)}async function Fw(n){let e=qe();if(!e)throw new Error("docs.zip not found");await z.promises.rm(n,{recursive:!0,force:!0}),await z.promises.mkdir(n,{recursive:!0}),new Lw(e).extractAllTo(n,!0),await mu(n)}async function jw(){let n=ae(),e=Wt(),t=await z.promises.readdir(e);for(let r of t){let i=lt.join(n,r);await z.promises.rm(i,{force:!0}),await z.promises.rename(lt.join(e,r),i)}await z.promises.rm(e,{recursive:!0,force:!0}),await z.promises.rm(lt.join(n,"orama.dpack"),{force:!0})}async function $w(n,e){e?.start("Installing documentation index\u2026"),await Ye({state:"installing",phase:1,phaseLabel:"Installing index",message:"Installing documentation index\u2026"}),await nd(n),e&&(e.text="Documentation index installed.")}async function Ww(n,e,t){let r=Wt(),i=await pu();await z.promises.mkdir(ae(),{recursive:!0}),await z.promises.rm(r,{recursive:!0,force:!0}),t?.start("Building search index\u2026"),await Ye({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"});try{await Fw(i),await uu({docsDir:i,tmpDir:r,docsZipSha256:e,termsHash:Qr(),synonymsHash:Xr(),builtBy:n.builtBy??"doc-init",onProgress:async o=>{t&&(t.text=o.message),await Ye({state:"indexing",current:o.current,total:o.total,message:o.message})}})}finally{await z.promises.rm(i,{recursive:!0,force:!0})}await Ye({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await jw(),$d()}async function fu(n){await Ye({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function Bw(n){let e=await Vo(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await Ye({state:"done",message:t,error:null})}async function Uw(n,e){let t=n instanceof Error?n.message:String(n);throw await Ye({state:"error",error:t}),await Hw(`ERROR: ${t}`),e?.fail(t),n}async function zw(){let n=ae();await z.promises.mkdir(n,{recursive:!0});let e=Ul();return z.existsSync(e)||await z.promises.writeFile(e,"","utf-8"),e}async function qw(){let n=await zw();return Nw.lock(n,{stale:1800*1e3})}async function Gw(){let n=qe(),e=(n?await Zr(n):null)??await Yo();if(!e)throw new Error("docs.zip not found");return e}async function Yw(n,e){let t=await Gw(),r=n.force||await Ko(n.force),i=await Jo(n.force);if(!r&&!i&&In()){await Bw(e);return}if(Uo()&&!n.force){await $w(t,e),await fu(e);return}await Ww(n,t,e),await fu(e)}var fs=class{static async run(e={}){let t=e.background??!1,i=e.quiet??t?void 0:yu({text:"Checking documentation\u2026",color:"cyan"}),o;try{o=await qw(),await Go(ad("Starting documentation setup\u2026")),await Yw(e,i)}catch(s){return Uw(s,i)}finally{o&&await o()}}};async function Vw(n){for(;;){let e=await ei();if(e.state==="done"&&In())return;if(e.state==="error")throw new hs("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 _w(500)}}async function gu(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await fs.run({builtBy:"doc-init",force:e,quiet:!0})}async function Nn(){if(await hu(),In())return;let n=yu({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await cd()){await Vw(n),n.succeed("Documentation ready.");return}if(await Ko()){await gu(n),n.succeed("Documentation ready.");return}await gu(n,!0),n.succeed("Documentation ready.")}catch(e){throw n.fail(e.message),e}}var gs=class{async search(e,t,r=20){return await Nn(),Ud(e,t,r)}async readDocument(e){return await Nn(),Ql(e)}},ys=new gs;function vu(...n){return e=>{if(!n.includes(e))throw new vs(`Allowed values: ${n.join(", ")}`);return e}}function Zw(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new vs("Must be a positive integer.");return e}var Xw=vu("json","default"),Qw=vu("json","default"),vi=new Jw("docs").description("Search and read HarmonyOS documentation from local docs directory");vi.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",tb,"all").option("--format <fmt>","Output format (default, json)",Xw,"default").option("--limit <n>","Max number of results",Zw,20).action(async(n,e)=>{try{let t=eb(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,i=await ys.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(i,null,2)):nb(i)}catch(t){console.error(yi(t.message)),process.exit(1)}});vi.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error(yi("Document ID cannot be empty.")),process.exit(1));let t=await ys.readDocument(e);console.log(t)}catch(e){console.error(yi(e.message)),process.exit(1)}});vi.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",Qw,"default").action(async n=>{try{if(await Nn(),n.format==="json"){let e=Ue.map(t=>({name:t,title:st[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of Ue)console.log(` ${e.padEnd(20)} ${Kw(st[e])}`)}catch(e){console.error(yi(e.message)),process.exit(1)}});function eb(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>Sn)throw new Error(`Query exceeds ${Sn} characters.`);return e}function tb(n){if(n==="all")return"all";if(!Ue.includes(n))throw new vs(`Invalid catalog "${n}". Allowed: all, ${Ue.join(", ")}`);return n}function nb(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 wu=vi;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";rb();Z.name("devecocli").description("HarmonyOS application development command line tool").version("1.3.0-Test.2");Z.addCommand(xs);Z.addCommand(Hs);Z.addCommand(Ws);Z.addCommand(Qs);Z.addCommand(Pa);Z.addCommand(xa);Z.addCommand(ic);Z.addCommand(cc);Z.addCommand(vc);Z.addCommand(Dc);Z.addCommand(yl);Z.addCommand(wu);var ws=process.argv.slice(2);ws.length>=2&&ws[ws.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var ob=new Set(["update"]);Z.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==Z;)t=t.parent;ob.has(t.name())||await L.checkVersion()});Z.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(ib(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
1363
+ Detail: ${n.message}`):n}try{await Xe()}catch(n){let e=n instanceof Error?n.message:String(n);throw new $n(`${tb()}
1364
+
1365
+ Detail: ${e}`)}try{await Hn()}catch(n){let e=n instanceof Error?n.message:String(n);throw new $n(nb(e))}}var Ps=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function ob(n){return new Promise(e=>setTimeout(e,n))}async function sb(n){let e=qt();await z.promises.mkdir(Jt.dirname(e),{recursive:!0}),await z.promises.appendFile(e,`${new Date().toISOString()} ${n}
1366
+ `)}async function ab(n){let e=Je();if(!e)throw new Error("docs.zip not found");await z.promises.rm(n,{recursive:!0,force:!0}),await z.promises.mkdir(n,{recursive:!0}),new rb(e).extractAllTo(n,!0),await Au(n)}async function cb(){let n=te(),e=zt(),t=await z.promises.readdir(e);for(let r of t){let i=Jt.join(n,r);await z.promises.rm(i,{force:!0}),await z.promises.rename(Jt.join(e,r),i)}await z.promises.rm(e,{recursive:!0,force:!0}),await z.promises.rm(Jt.join(n,"orama.dpack"),{force:!0})}async function lb(n,e){e?.start("Installing documentation index\u2026"),await Ze({state:"installing",phase:1,phaseLabel:"Installing index",message:"Installing documentation index\u2026"}),await hd(n),e&&(e.text="Documentation index installed.")}async function db(n,e,t){let r=zt(),i=await Iu();await z.promises.mkdir(te(),{recursive:!0}),await z.promises.rm(r,{recursive:!0,force:!0}),t?.start("Building search index\u2026"),await Ze({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"});try{await ab(i),await Du({docsDir:i,tmpDir:r,docsZipSha256:e,termsHash:ui(),synonymsHash:di(),builtBy:n.builtBy??"doc-init",onProgress:async o=>{t&&(t.text=o.message),await Ze({state:"indexing",current:o.current,total:o.total,message:o.message})}})}finally{await z.promises.rm(i,{recursive:!0,force:!0})}await Ze({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await cb(),eu()}async function Tu(n){await Ze({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function ub(n){let e=await rs(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await Ze({state:"done",message:t,error:null})}async function pb(n,e){let t=n instanceof Error?n.message:String(n);throw await Ze({state:"error",error:t}),await sb(`ERROR: ${t}`),e?.fail(t),n}async function mb(){let n=te();await z.promises.mkdir(n,{recursive:!0});let e=td();return z.existsSync(e)||await z.promises.writeFile(e,"","utf-8"),e}async function hb(){let n=await mb();return ib.lock(n,{stale:1800*1e3})}async function fb(){let n=Je(),e=(n?await li(n):null)??await ns();if(!e)throw new Error("docs.zip not found");return e}async function gb(n,e){let t=await fb(),r=n.force||await os(n.force),i=await is(n.force);if(!r&&!i&&kn()){await ub(e);return}if(Xo()&&!n.force){await lb(t,e),await Tu(e);return}await db(n,t,e),await Tu(e)}var Cs=class{static async run(e={}){let t=e.background??!1,i=e.quiet??t?void 0:Ru({text:"Checking documentation\u2026",color:"cyan"}),o;try{o=await hb(),await ts(wd("Starting documentation setup\u2026")),await gb(e,i)}catch(s){return pb(s,i)}finally{o&&await o()}}};async function yb(n){for(;;){let e=await pi();if(e.state==="done"&&kn())return;if(e.state==="error")throw new Ps("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 ob(500)}}async function ku(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await Cs.run({builtBy:"doc-init",force:e,quiet:!0})}async function vb(){if(kn())return;let n=Ru({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await bd()){await yb(n),n.succeed("Documentation ready.");return}if(await os()){await ku(n),n.succeed("Documentation ready.");return}await ku(n,!0),n.succeed("Documentation ready.")}catch(e){throw n.fail(e.message),e}}async function Bn(){await vb(),await xu()}var Ds=class{async search(e,t,r=20){return await Bn(),ru(e,t,r)}async readDocument(e){return await Bn(),ud(e)}},Is=new Ds;function Mu(...n){return e=>{if(!n.includes(e))throw new As(`Allowed values: ${n.join(", ")}`);return e}}function Sb(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new As("Must be a positive integer.");return e}var Eb=Mu("json","default"),Pb=Mu("json","default"),Ti=new wb("docs").description("Search and read HarmonyOS documentation from local docs directory");Ti.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",Db,"all").option("--format <fmt>","Output format (default, json)",Eb,"default").option("--limit <n>","Max number of results",Sb,20).action(async(n,e)=>{try{let t=Cb(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,i=await Is.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(i,null,2)):Ib(i)}catch(t){console.error(xi(t.message)),process.exit(1)}});Ti.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error(xi("Document ID cannot be empty.")),process.exit(1));let t=await Is.readDocument(e);console.log(t)}catch(e){console.error(xi(e.message)),process.exit(1)}});Ti.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",Pb,"default").action(async n=>{try{if(await Bn(),n.format==="json"){let e=Ve.map(t=>({name:t,title:pt[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of Ve)console.log(` ${e.padEnd(20)} ${bb(pt[e])}`)}catch(e){console.error(xi(e.message)),process.exit(1)}});function Cb(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>In)throw new Error(`Query exceeds ${In} characters.`);return e}function Db(n){if(n==="all")return"all";if(!Ve.includes(n))throw new As(`Invalid catalog "${n}". Allowed: all, ${Ve.join(", ")}`);return n}function Ib(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 Ou=Ti;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";Ab();X.name("devecocli").description("HarmonyOS application development command line tool").version("1.3.0-Test.3");X.addCommand(Bs);X.addCommand(Js);X.addCommand(Qs);X.addCommand(ua);X.addCommand(Na);X.addCommand(Ba);X.addCommand(mc);X.addCommand(yc);X.addCommand(Ac);X.addCommand(Nc);X.addCommand(Il);X.addCommand(Ou);var xs=process.argv.slice(2);xs.length>=2&&xs[xs.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var Tb=new Set(["update"]);X.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==X;)t=t.parent;Tb.has(t.name())||await N.checkVersion()});X.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(xb(`Error: ${e}`)),process.exit(1)});