@deveco-test/hmos-deveco-cli 0.1.0-TD.4.2 → 0.1.0-TD.5

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,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{bootstrap as Bw}from"global-agent";import{program as Q}from"commander";import{red as Ww}from"colorette";import{Command as ju}from"commander";import{green as Os,red as ko,yellow as Ns}from"colorette";import j from"fs";import*as q from"path";import Re from"json5";import*as Eo from"fs";import*as $ from"path";function g(n){process.env.DEVECO_CLI_DEBUG&&console.log(`[DEBUG] ${n}`)}var P=class n{static ASCII_CONTROL_MAX=31;static ASCII_DELETE=127;static parsePositiveInteger(e,t="value"){let r=e.trim();if(!/^\d+$/.test(r))throw new Error(`${t} must be a positive integer`);let o=Number.parseInt(r,10);if(!Number.isInteger(o)||o<=0)throw new Error(`${t} must be a positive integer`);return o}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
2
+ import{bootstrap as Uw}from"global-agent";import{program as Q}from"commander";import{red as zw}from"colorette";import{Command as ju}from"commander";import{green as Os,red as ko,yellow as Ns}from"colorette";import j from"fs";import*as q from"path";import Re from"json5";import*as Eo from"fs";import*as $ from"path";function g(n){process.env.DEVECO_CLI_DEBUG&&console.log(`[DEBUG] ${n}`)}var P=class n{static ASCII_CONTROL_MAX=31;static ASCII_DELETE=127;static parsePositiveInteger(e,t="value"){let r=e.trim();if(!/^\d+$/.test(r))throw new Error(`${t} must be a positive integer`);let o=Number.parseInt(r,10);if(!Number.isInteger(o)||o<=0)throw new Error(`${t} must be a positive integer`);return o}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
3
3
  `)}static parseDurationToSeconds(e,t="value"){let o=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!o)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported).`);let i=o[1];if((o[2]??"s")==="s")return n.parsePositiveInteger(i,t);if(!/^\d+(?:\.\d)?$/.test(i))throw new Error(`${t} supports a maximum of 1 decimal place for minutes (e.g. 2.5m).`);let a=Number.parseFloat(i);if(!Number.isFinite(a)||a<=0)throw new Error(`${t} must be a positive duration.`);return Math.round(a*60)}static assertRelativeTimeRange(e,t){if(e!==void 0&&t!==void 0&&e<t)throw new Error("--from must be greater than or equal to --to when both are provided (e.g. --from 30s --to 10s)")}static filterLogsByRelativeWindow(e,t,r,o=new Date){if(!t&&!r)return e;let[i,s]=n.resolveTimeBounds(t,r,o),a=e.split(/\r?\n/),c=[],l=!1;for(let u of a){let h=n.extractTimestampFromLogLine(u,o);h&&(l=n.isWithinBounds(h,i,s)),l&&c.push(u)}return c.join(`
4
4
  `)}static resolveTimeBounds(e,t,r){let o=e?new Date(r.getTime()-e*1e3):null,i=t?new Date(r.getTime()-t*1e3):null;return o&&i?o<i?[o,i]:[i,o]:o?[o,r]:i?[null,i]:[null,null]}static isWithinBounds(e,t,r){let o=e.getTime(),i=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(i!==null&&o<i||s!==null&&o>s)}static extractTimestampFromLogLine(e,t){let r=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!r)return null;let o=t.getFullYear(),i=Number.parseInt(r[1],10)-1,s=Number.parseInt(r[2],10),a=Number.parseInt(r[3],10),c=Number.parseInt(r[4],10),l=Number.parseInt(r[5],10),u=r[6]??"0",h=Number.parseInt(u.padEnd(3,"0").slice(0,3),10),v=new Date(o,i,s,a,c,l,h);return v.getTime()>t.getTime()+1440*60*1e3&&v.setFullYear(o-1),v}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(r=>{let o=r.charCodeAt(0);return o<=n.ASCII_CONTROL_MAX||o===n.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let r=`'${e.replace(/'/g,"'\\''")}'`;return 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($.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=$.resolve($.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=$.normalize(e),o=$.relative(r,t);if(o.split($.sep)[0]===".."||$.isAbsolute(o))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||$.isAbsolute(e)}static isPathContained(e,t){let r=$.resolve(t,e),o=$.relative(t,r);return n.isPathEscaping(o)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){if($.isAbsolute(e))return{contained:!1,reason:`Absolute path is not allowed: ${e}`};let r=n.isPathContained(e,t);if(!r.contained)return r;let o;try{o=Eo.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let i=$.resolve(o,e),s;try{s=Eo.realpathSync(i)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${i}`}}return n.isPathContained(s,o)}};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 o=q.dirname(t);if(o===t)break;t=o}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=q.join(e,"build-profile.json5");if(!j.existsSync(t))return null;try{let r=j.readFileSync(t,"utf-8"),o=Re.parse(r);return o.app?o:null}catch(r){return console.error(`Error parsing ${t}:`,r),null}}getModuleType(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=P.resolvePathWithinRoot(this.rootDir,t.srcPath),o=q.join(r,"src","main","module.json5");if(!j.existsSync(o))return"entry";try{let i=j.readFileSync(o,"utf-8");return Re.parse(i)?.module?.type||"entry"}catch(i){return console.warn(`Warning: Failed to parse ${o}:`,i),"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=P.resolvePathWithinRoot(this.rootDir,t.srcPath),o=q.join(r,"build-profile.json5");if(!j.existsSync(o))throw new Error(`Build profile for module '${e}' not found at ${o}.`);let i=j.readFileSync(o,"utf-8");return Re.parse(i)}getBundleName(){let e=q.join(this.rootDir,"AppScope","app.json5");if(j.existsSync(e))try{let t=j.readFileSync(e,"utf-8"),r=Re.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 o=P.resolvePathWithinRoot(this.rootDir,r.srcPath),i=q.join(o,"src","main","module.json5");if(!j.existsSync(i))return"EntryAbility";try{let s=j.readFileSync(i,"utf-8"),c=Re.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 ${i}:`,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(o=>o.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=P.resolvePathWithinRoot(this.rootDir,t.srcPath),o=q.join(r,"oh-package.json5");if(!j.existsSync(o))return[];let i=[];try{let s=j.readFileSync(o,"utf-8"),c=Re.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 v=q.join(t.srcPath,u),I=P.resolvePathWithinRoot(this.rootDir,v),k=this.profile.modules.find(ee=>q.resolve(this.rootDir,ee.srcPath)===I);k&&i.push(k.name)}}catch{}return i}getModuleName(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)return e;let r=P.resolvePathWithinRoot(this.rootDir,t.srcPath),o=q.join(r,"src","main","module.json5");if(!j.existsSync(o))return e;try{let i=j.readFileSync(o,"utf-8");return Re.parse(i)?.module?.name||e}catch(i){return console.warn(`Warning: Failed to parse ${o}:`,i),e}}collectNonHarDependentModuleList(e){let t=[],r=[],o=new Set;for(r.push(e),o.add(e);r.length>0;){let i=r.shift();this.getModuleType(i)!=="har"&&t.push(i);let a=this.getModuleDependencies(i);for(let c of a)o.has(c)||(r.push(c),o.add(c))}return t}findArtifactPath(e,t,r,o="default"){this.validateProduct(o);let i=this.profile.modules.find(ee=>ee.name===e);if(!i)throw new Error(`Module '${e}' not found`);let a=this.getModuleType(e)==="shared",c=a?"hspName":"hapName",l=this.buildOutputPath(i.srcPath,o,["intermediates",a?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!j.existsSync(l))throw new Error(`Build metadata not found for module '${e}' at ${l}. Build the project first.`);let{packageName:u,isSigned:h}=this.parseOutputMetadata(l,c),v=u;if(!h){let ee=this.getSignedHapName(u,i.srcPath,o,t);ee&&(v=ee)}let I=a?"-signed.hsp":"-signed.hap";if(!r&&!v.endsWith(I))throw new Error(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`);let k=this.buildOutputPath(i.srcPath,o,["outputs",t,v]);if(!j.existsSync(k))throw new Error(`Generated package file not found in ${k}.`);return k}getSignedHapName(e,t,r,o){let i=null;if(e.endsWith("-unsigned.hap")?i=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(i=e.replace("-unsigned.hsp","-signed.hsp")),!i)return null;let s=this.buildOutputPath(t,r,["outputs",o,i]);return j.existsSync(s)?i:null}buildOutputPath(e,t,r){let o=P.resolvePathWithinRoot(this.rootDir,e),i=q.resolve(o,"build",t,...r);return P.ensurePathWithinRoot(this.rootDir,i)}parseOutputMetadata(e,t){let r=j.readFileSync(e,"utf-8"),o=Re.parse(r),i,s=!1;if(Array.isArray(o)){let a=o[0];a&&(i=a[t],s=a.isSigned===!0)}else o&&typeof o=="object"&&(i=o[t],s=o.isSigned===!0);if(!i)throw new Error(`Could not find ${t} in output_metadata.json at ${e}`);return this.validatePackageName(i),{packageName:i,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 Do}from"child_process";import M,{existsSync as Ss}from"fs";import*as E from"path";import*as B from"os";import Eu from"regedit";import{join as Ps}from"path";import{red as Iu}from"colorette";import*as bs from"os";function D(){return Io()==="openharmony"}function Io(){return bs.platform()}var Es="https://developer.huawei.com/consumer/cn/download/",Is="6.1.0",Du=["sdk","default","openharmony","native","llvm","bin","clangd"],Hn=n=>new Promise((e,t)=>{Eu.list(n,(r,o)=>{r?t(r):e(o)})}),_=class n{_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;_emulatorLauncherPath;_clangdPath;_lspServerPath;static _verifiedPaths=new Set;static _powerShellPath;static verifyAndCache(e){!e||e===""||D()||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}get clangdPath(){return n.verifyAndCache(this._clangdPath),this._clangdPath}get lspServerPath(){return n.verifyAndCache(this._lspServerPath),this._lspServerPath}constructor(e,t,r,o,i,s,a,c,l,u,h){this._devecoStudioPath=e,this._nodePath=t,this._ohpmJsPath=r,this._hvigorJsPath=o,this._javaPath=i,this._sdkPath=s,this._hdcPath=a,this._emulatorPath=c,this._emulatorLauncherPath=l,this._clangdPath=u,this._lspServerPath=h}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(){if(D())return;let e=await n.findDevEcoStudio();n.enforceStudioMinVersion(e)}static async new(e){if(D())return n.newForOpenHarmony();let t=e??await n.findDevEcoStudio(),{nodePath:r,ohpmJsPath:o,hvigorJsPath:i,javaPath:s,sdkPath:a,hdcPath:c,emulatorPath:l,clangdPath:u,lspServerPath:h}=n.resolveTools(t),v=n.getEmulatorExe(t);return new n(t,r,o,i,s,a,c,l,v??void 0,u,h)}static async newForOpenHarmony(){let e=process.env.COMMAND_LINE_TOOL_PATH;if(!e)throw new Error("COMMAND_LINE_TOOL_PATH environment variable is not set. ");let t=E.join(e,"node","bin","node"),r=E.join(e,"ohpm","bin","pm-cli.js"),o=E.join(e,"hvigor","bin","hvigorw.js");n.verifyTools(t,r,o);let i=E.join(e,"sdk"),s=E.join(e,"clangd","clangd"),a=E.join(e,"ace-server","out","index.js");if(!M.existsSync(s))throw new Error(`clangd not found at: ${s}`);if(!M.existsSync(a))throw new Error(`ace-server not found at: ${a}`);let c=n.resolveHdcPath(i,B.platform());return new n("",t,r,o,"",i,c,"",void 0,s,a)}static resolveLspServerPath(e){let t=B.platform();if(t==="linux")throw new Error("LSP server (ace-server) is not supported on Linux.");let r;if(t==="win32")r=E.join(e,"plugins","openharmony");else if(t==="darwin")r=E.join(e,"Contents","plugins","openharmony");else throw new Error(`LSP server (ace-server) is not supported on platform: ${t}`);let o=E.join(r,"ace-server","out","index.js");if(M.existsSync(o))return o;throw new Error(`LSP server (ace-server) not found at: ${o}`)}static devecoContentRootForClangd(e){return B.platform()==="darwin"&&e.endsWith(".app")?E.join(e,"Contents"):e}static clangdCandidatesFromDevecoHome(e){let t=new Set,r=[e,n.devecoContentRootForClangd(e)];for(let o of r){let i=E.join(o,...Du);t.add(B.platform()==="win32"?i+".exe":i)}return[...t]}static resolveClangdPath(e){let t=n.clangdCandidatesFromDevecoHome(e);for(let r of t)if(M.existsSync(r))return r;throw new Error(`clangd executable not found. Searched in:
5
5
  ${t.join(`
@@ -11,7 +11,7 @@ Please reinstall DevEco Studio or download the latest version from:
11
11
  `+Es)}return t.reduce((r,o)=>n.compareVersion(o.version,r.version)>0?o:r)}static assertMinVersion(e,t){n.compareVersion(t,Is)>=0||(g(`[ToolProvider] Selected DevEco Studio ${t} at ${e} \u2014 below minimum`),console.error(Iu(`Error: The detected DevEco Studio version is ${t}, which is below the minimum required version ${Is}. Upgrade to the latest version before using deveco-cli:`)+`
12
12
  `+Es),process.exit(1))}static isExistingDirectory(e){return!!e&&M.existsSync(e)&&M.statSync(e).isDirectory()}static resolveWindowsTools(e){let t=E.join(e,"tools");return{nodePath:E.join(t,"node","node.exe"),ohpmJsPath:E.join(t,"ohpm","bin","pm-cli.js"),hvigorJsPath:E.join(t,"hvigor","bin","hvigorw.js"),javaPath:E.join(e,"jbr","bin","java.exe"),sdkPath:E.join(e,"sdk")}}static resolveMacTools(e){let t=E.join(e,"Contents","tools");return{nodePath:E.join(t,"node","bin","node"),ohpmJsPath:E.join(t,"ohpm","bin","pm-cli.js"),hvigorJsPath:E.join(t,"hvigor","bin","hvigorw.js"),javaPath:E.join(e,"Contents","jbr","Contents","Home","bin","java"),sdkPath:E.join(e,"Contents","sdk")}}static resolveTools(e){let t=B.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 o=n.resolveHdcPath(r.sdkPath,t),i=n.resolveEmulatorPath(e,t),s=n.resolveClangdPath(e),a=n.resolveLspServerPath(e);return{...r,hdcPath:o,emulatorPath:i,clangdPath:s,lspServerPath:a}}static resolveHdcPath(e,t){let r=t==="win32"?".exe":"",o=[E.join(e,"default","openharmony","toolchains",`hdc${r}`),E.join(e,"toolchains",`hdc${r}`)];for(let i of o)if(M.existsSync(i))return i;throw new Error(`hdc executable not found. Searched in:
13
13
  ${o.join(`
14
- `)}`)}static resolveEmulatorPath(e,t){let r;if(t==="win32")r=E.join(e,"tools","emulator","Emulator.exe");else if(t==="darwin")r=E.join(e,"Contents","tools","emulator","Emulator");else throw new Error("Linux is not fully supported yet");if(!M.existsSync(r))throw new Error(`Emulator executable not found at: ${r}`);return r}static verifyTools(e,t,r,o){if(!M.existsSync(e))throw new Error(`Node executable not found at: ${e}`);if(!M.existsSync(t))throw new Error(`ohpm js file not found at: ${t}`);if(!M.existsSync(r))throw new Error(`hvigor js file not found at: ${r}`);if(o&&!M.existsSync(o))throw new Error(`java executable not found at: ${o}`)}static getEmulatorExe(e){let t=B.platform(),r;if(t==="win32")r=Ps(e,"tools","emulator","Emulator.exe");else if(t==="darwin")r=Ps(e,"Contents","tools","emulator","Emulator");else return;return Ss(r)?r:void 0}static isValidApiLevel(e,t){let r=t??23;return Number.isInteger(e)&&e>=17&&e<=r}static parseApiLevelFromFile(e){if(M.existsSync(e))try{let t=M.readFileSync(e,"utf-8"),r=JSON.parse(t),o=r?.apiVersion??r?.data?.apiVersion;if(typeof o!="string"&&typeof o!="number")return;let i=Number(o);return Number.isInteger(i)&&i>=17?i:void 0}catch{return}}static detectFromSdkPkg(e){let t=E.join(e,"default","sdk-pkg.json");return n.parseApiLevelFromFile(t)}static detectFromOhUniPackage(e){let t=[E.join(e,"default","openharmony","toolchains","oh-uni-package.json"),E.join(e,"default","openharmony","native","oh-uni-package.json"),E.join(e,"default","openharmony","previewer","oh-uni-package.json")];for(let r of t){let o=n.parseApiLevelFromFile(r);if(o!==void 0)return o}}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(B.platform()!=="win32")return n._powerShellPath="",n._powerShellPath;let e=E.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return Ss(e)?(g(`[ToolProvider] Found PowerShell at: ${e}`),n._powerShellPath=e,e):(n._powerShellPath="",n._powerShellPath)}static verifySignature(e){if(!M.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=B.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 E.extname(e).toLowerCase()===".exe";if(t==="darwin")try{return M.accessSync(e,M.constants.X_OK),!0}catch{return!1}return!1}static createSignatureScript(){let e=M.mkdtempSync(E.join(B.tmpdir(),"deveco-verify-")),t=E.join(e,"Verify-Signature.ps1");return M.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:o}=n.createSignatureScript();try{let i=Do(t,["-NoProfile","-ExecutionPolicy","Bypass","-File",o,e],{encoding:"utf-8",timeout:5e3,stdio:["pipe","pipe","ignore"]}),s=JSON.parse(i);return{signed:s?.Status===0,signer:s?.SignerCertificate?.Subject??void 0}}catch(i){return g(`[ToolProvider] verify Windows Signature, error msg: ${i}`),{signed:!0}}finally{try{M.rmSync(r,{recursive:!0,force:!0})}catch{}}}static verifyMacSignature(e){try{return Do("codesign",["-v",e],{encoding:"utf-8",timeout:5e3}),{signed:!0}}catch{return{signed:!1}}}};import{execa as Cu}from"execa";import*as pt from"path";import*as Ds from"os";var be=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let r={...process.env,DEVECO_SDK_HOME:e.sdkPath};if(e.javaPath){let o=pt.dirname(e.javaPath);r.PATH=`${o}${pt.delimiter}${process.env.PATH||""}`}D()&&(r.HVIGOR_USER_HOME=pt.join(Ds.homedir(),".hvigor")),this.env=r}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,o){let i=[...Array.from(o),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(i)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];await this.runHvigor(e)}async stopDaemon(){D()||await this.runHvigor(["--stop-daemon"])}async runHvigor(e){D()&&(e=e.includes("--no-daemon")?e:["--no-daemon",...e]);let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];g(`Executing: ${t} ${r.join(" ")}`),await Cu(t,r,{cwd:this.projectRoot,env:this.env,stdout:"inherit",stderr:"inherit"})}};import{execa as Au}from"execa";var Oe=class{toolProvider;projectRoot;constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=["--no-deprecation",this.toolProvider.ohpmJsPath,"install","--all"];g(`Executing: ${e} ${t.join(" ")}`),await Au(e,t,{cwd:this.projectRoot,stdout:"inherit",stderr:"inherit"})}};import{mkdir as Tu}from"fs/promises";import{dirname as xu,resolve as ku}from"path";import{execa as Mu}from"execa";import{lock as Co,check as Ib}from"proper-lockfile";function Ao(n){return ku(n,".hvigor",".build-lock")}function Ru(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function Cs(n){let e=xu(Ao(n));if(await Tu(e,{recursive:!0}),process.platform==="win32")try{await Mu("attrib",["+h",e])}catch{}}async function Ou(n,e){let t=new AbortController,r=Ru(e);await Cs(n);let o={lockfilePath:Ao(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await Co(n,{...o,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return r(),{release:await Co(n,{...o,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Xe(n,e,t){let{release:r,signal:o}=await Ou(n,t);try{return await e(o)}finally{await r()}}async function As(n,e){let t=new AbortController;await Cs(n);let r={lockfilePath:Ao(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},o;try{o=await Co(n,{...r,retries:0})}catch(i){if(i&&typeof i=="object"&&"code"in i&&i.code==="ELOCKED")return{acquired:!1};throw i}try{return{acquired:!0,result:await e(t.signal)}}finally{await o()}}import*as He from"fs";import*as Qe from"path";import Lu from"json5";var To={HTTP_TIMEOUT_MS:2e4},jn={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"};import{homedir as Ne}from"os";import Se from"path";import{xdgConfig as Nu}from"xdg-basedir";var W={"trae-cn":Se.join(Ne(),".trae-cn"),opencode:Se.join(Nu,"opencode"),cursor:Se.join(Ne(),".cursor"),codebuddy:Se.join(Ne(),".codebuddy"),qoder:Se.join(Ne(),".qoder"),"claude-code":Se.join(Ne(),".claude"),codex:Se.join(Ne(),".codex"),bitfun:Se.join(Ne(),".bitfun"),opendesk:Se.join(Ne(),".opendesk")};import Le from"path";var xo="https://matrix.openharmony.cn",ce={TAGS_API_URL:`${xo}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${xo}/api/registry/skill/skills`,SKILL_API_BASE:`${xo}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},Ts={"trae-cn":{path:Le.join(W["trae-cn"],"skills"),displayName:"trae-cn"},opencode:{path:Le.join(W.opencode,"skills"),displayName:"opencode"},cursor:{path:Le.join(W.cursor,"skills"),displayName:"cursor"},codebuddy:{path:Le.join(W.codebuddy,"skills"),displayName:"codebuddy"},qoder:{path:Le.join(W.qoder,"skills"),displayName:"qoder"},"claude-code":{path:Le.join(W["claude-code"],"skills"),projectPath:".claude/skills",displayName:"claude-code"},codex:{path:Le.join(W.codex,"skills"),displayName:"codex"}},xs={opencode:{path:Le.join(W.opencode,"skills"),displayName:"opencode"}};function Pe(){return D()?xs:Ts}import{homedir as Ut}from"os";import re from"path";var fe="deveco-mcp";var _e={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:re.join(W.opencode,"opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:re.join(process.platform==="win32"?re.join(process.env.APPDATA??re.join(Ut(),"AppData","Roaming"),"Trae CN","User"):re.join(Ut(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:re.join(W.cursor,"mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:re.join(W.codebuddy,"mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:re.join(process.platform==="win32"?re.join(process.env.APPDATA??re.join(Ut(),"AppData","Roaming"),"Qoder","SharedClientCache"):re.join(Ut(),"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:re.join(Ut(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:re.join(W.codex,"config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function Ms(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function ks(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Rs(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function Fn(n,e){return n.format==="opencode"?Ms(e):n.format==="claude-code"||n.format==="codex"?ks(e):Rs(e)}var le={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var _u=1e3;function Bn(n){g(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=Qe.join(n,le.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=Hu(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return g(`[ProjectCheck] ${l.reason}`),l}let o=Qe.join(n,le.OH_PACKAGE_JSON5),i=$n(o,t,"root");if(i.required)return g(`[ProjectCheck] Root check: ${i.reason}`),i;let s=Qe.join(n,le.BUILD_PROFILE_JSON5),a=$n(s,t,"build-profile");if(a.required)return g(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let u=Qe.join(n,l.srcPath,le.OH_PACKAGE_JSON5),h=$n(u,t,l.name);if(h.required)return g(`[ProjectCheck] Module '${l.name}' check: ${h.reason}`),h;let v=Qe.join(n,l.srcPath,le.BUILD_PROFILE_JSON5),I=$n(v,t,l.name);if(I.required)return g(`[ProjectCheck] Module '${l.name}' build-profile check: ${I.reason}`),I}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return g(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function $n(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>_u?{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 Hu(n){let e=Qe.join(n,le.BUILD_PROFILE_JSON5);try{let t=He.readFileSync(e,"utf-8");if(!t.trim())return null;let r=Lu.parse(t);if(typeof r!="object"||r===null)return null;let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}function Fu(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 $u(n,e){let t;if(e.modules&&e.modules.length>0)t=e.modules;else{let o=n.profile.modules,i=o.filter(s=>n.getModuleType(s.name)==="entry");if(o.length===1)t=[o[0].name];else if(i.length===1)t=[i[0].name];else throw i.length>1?new Error(`Multiple entry modules found (${i.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`):new Error(`No entry module found and multiple modules available (${o.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`)}let r=new Set;for(let o of t){let i=o.indexOf("@"),s=i!==-1?o.substring(0,i):o,a=i!==-1?o.substring(i+1):"default";r.add(`${s}@${a}`)}return Array.from(r)}function qt(n,e){let t=new Set;for(let r of e){let o=r.indexOf("@"),i=o!==-1?r.substring(0,o):r,s=n.getModuleType(i);s==="shared"?t.add("assembleHsp"):s==="har"?t.add("assembleHar"):t.add("assembleHap")}return t}function zt(n,e){let t=e,r=`${n} failed`;console.error(ko(r));let o=t.stdout||t.message;throw o&&console.error(o),t.stderr&&console.error(t.stderr),new Error(r,{cause:e})}async function Vt(n,e,t,r,o,i){if(Bn(i).required){console.log(`
14
+ `)}`)}static resolveEmulatorPath(e,t){let r;if(t==="win32")r=E.join(e,"tools","emulator","Emulator.exe");else if(t==="darwin")r=E.join(e,"Contents","tools","emulator","Emulator");else throw new Error("Linux is not fully supported yet");if(!M.existsSync(r))throw new Error(`Emulator executable not found at: ${r}`);return r}static verifyTools(e,t,r,o){if(!M.existsSync(e))throw new Error(`Node executable not found at: ${e}`);if(!M.existsSync(t))throw new Error(`ohpm js file not found at: ${t}`);if(!M.existsSync(r))throw new Error(`hvigor js file not found at: ${r}`);if(o&&!M.existsSync(o))throw new Error(`java executable not found at: ${o}`)}static getEmulatorExe(e){let t=B.platform(),r;if(t==="win32")r=Ps(e,"tools","emulator","Emulator.exe");else if(t==="darwin")r=Ps(e,"Contents","tools","emulator","Emulator");else return;return Ss(r)?r:void 0}static isValidApiLevel(e,t){let r=t??23;return Number.isInteger(e)&&e>=17&&e<=r}static parseApiLevelFromFile(e){if(M.existsSync(e))try{let t=M.readFileSync(e,"utf-8"),r=JSON.parse(t),o=r?.apiVersion??r?.data?.apiVersion;if(typeof o!="string"&&typeof o!="number")return;let i=Number(o);return Number.isInteger(i)&&i>=17?i:void 0}catch{return}}static detectFromSdkPkg(e){let t=E.join(e,"default","sdk-pkg.json");return n.parseApiLevelFromFile(t)}static detectFromOhUniPackage(e){let t=[E.join(e,"default","openharmony","toolchains","oh-uni-package.json"),E.join(e,"default","openharmony","native","oh-uni-package.json"),E.join(e,"default","openharmony","previewer","oh-uni-package.json")];for(let r of t){let o=n.parseApiLevelFromFile(r);if(o!==void 0)return o}}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(B.platform()!=="win32")return n._powerShellPath="",n._powerShellPath;let e=E.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return Ss(e)?(g(`[ToolProvider] Found PowerShell at: ${e}`),n._powerShellPath=e,e):(n._powerShellPath="",n._powerShellPath)}static verifySignature(e){if(!M.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=B.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 E.extname(e).toLowerCase()===".exe";if(t==="darwin")try{return M.accessSync(e,M.constants.X_OK),!0}catch{return!1}return!1}static createSignatureScript(){let e=M.mkdtempSync(E.join(B.tmpdir(),"deveco-verify-")),t=E.join(e,"Verify-Signature.ps1");return M.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:o}=n.createSignatureScript();try{let i=Do(t,["-NoProfile","-ExecutionPolicy","Bypass","-File",o,e],{encoding:"utf-8",timeout:5e3,stdio:["pipe","pipe","ignore"]}),s=JSON.parse(i);return{signed:s?.Status===0,signer:s?.SignerCertificate?.Subject??void 0}}catch(i){return g(`[ToolProvider] verify Windows Signature, error msg: ${i}`),{signed:!0}}finally{try{M.rmSync(r,{recursive:!0,force:!0})}catch{}}}static verifyMacSignature(e){try{return Do("codesign",["-v",e],{encoding:"utf-8",timeout:5e3}),{signed:!0}}catch{return{signed:!1}}}};import{execa as Cu}from"execa";import*as pt from"path";import*as Ds from"os";var be=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let r={...process.env,DEVECO_SDK_HOME:e.sdkPath};if(e.javaPath){let o=pt.dirname(e.javaPath);r.PATH=`${o}${pt.delimiter}${process.env.PATH||""}`}D()&&(r.HVIGOR_USER_HOME=pt.join(Ds.homedir(),".hvigor")),this.env=r}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,o){let i=[...Array.from(o),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(i)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];await this.runHvigor(e)}async stopDaemon(){D()||await this.runHvigor(["--stop-daemon"])}async runHvigor(e){D()&&(e=e.includes("--no-daemon")?e:["--no-daemon",...e]);let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];g(`Executing: ${t} ${r.join(" ")}`),await Cu(t,r,{cwd:this.projectRoot,env:this.env,stdout:"inherit",stderr:"inherit"})}};import{execa as Au}from"execa";var Oe=class{toolProvider;projectRoot;constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=["--no-deprecation",this.toolProvider.ohpmJsPath,"install","--all"];g(`Executing: ${e} ${t.join(" ")}`),await Au(e,t,{cwd:this.projectRoot,stdout:"inherit",stderr:"inherit"})}};import{mkdir as Tu}from"fs/promises";import{dirname as xu,resolve as ku}from"path";import{execa as Mu}from"execa";import{lock as Co,check as Cb}from"proper-lockfile";function Ao(n){return ku(n,".hvigor",".build-lock")}function Ru(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function Cs(n){let e=xu(Ao(n));if(await Tu(e,{recursive:!0}),process.platform==="win32")try{await Mu("attrib",["+h",e])}catch{}}async function Ou(n,e){let t=new AbortController,r=Ru(e);await Cs(n);let o={lockfilePath:Ao(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await Co(n,{...o,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return r(),{release:await Co(n,{...o,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Xe(n,e,t){let{release:r,signal:o}=await Ou(n,t);try{return await e(o)}finally{await r()}}async function As(n,e){let t=new AbortController;await Cs(n);let r={lockfilePath:Ao(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},o;try{o=await Co(n,{...r,retries:0})}catch(i){if(i&&typeof i=="object"&&"code"in i&&i.code==="ELOCKED")return{acquired:!1};throw i}try{return{acquired:!0,result:await e(t.signal)}}finally{await o()}}import*as He from"fs";import*as Qe from"path";import Lu from"json5";var To={HTTP_TIMEOUT_MS:2e4},jn={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"};import{homedir as Ne}from"os";import Se from"path";import{xdgConfig as Nu}from"xdg-basedir";var W={"trae-cn":Se.join(Ne(),".trae-cn"),opencode:Se.join(Nu,"opencode"),cursor:Se.join(Ne(),".cursor"),codebuddy:Se.join(Ne(),".codebuddy"),qoder:Se.join(Ne(),".qoder"),"claude-code":Se.join(Ne(),".claude"),codex:Se.join(Ne(),".codex"),bitfun:Se.join(Ne(),".bitfun"),opendesk:Se.join(Ne(),".opendesk")};import Le from"path";var xo="https://matrix.openharmony.cn",ce={TAGS_API_URL:`${xo}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${xo}/api/registry/skill/skills`,SKILL_API_BASE:`${xo}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},Ts={"trae-cn":{path:Le.join(W["trae-cn"],"skills"),displayName:"trae-cn"},opencode:{path:Le.join(W.opencode,"skills"),displayName:"opencode"},cursor:{path:Le.join(W.cursor,"skills"),displayName:"cursor"},codebuddy:{path:Le.join(W.codebuddy,"skills"),displayName:"codebuddy"},qoder:{path:Le.join(W.qoder,"skills"),displayName:"qoder"},"claude-code":{path:Le.join(W["claude-code"],"skills"),projectPath:".claude/skills",displayName:"claude-code"},codex:{path:Le.join(W.codex,"skills"),displayName:"codex"}},xs={opencode:{path:Le.join(W.opencode,"skills"),displayName:"opencode"}};function Pe(){return D()?xs:Ts}import{homedir as Ut}from"os";import re from"path";var fe="deveco-mcp";var _e={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:re.join(W.opencode,"opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:re.join(process.platform==="win32"?re.join(process.env.APPDATA??re.join(Ut(),"AppData","Roaming"),"Trae CN","User"):re.join(Ut(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:re.join(W.cursor,"mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:re.join(W.codebuddy,"mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:re.join(process.platform==="win32"?re.join(process.env.APPDATA??re.join(Ut(),"AppData","Roaming"),"Qoder","SharedClientCache"):re.join(Ut(),"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:re.join(Ut(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:re.join(W.codex,"config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function Ms(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function ks(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Rs(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function Fn(n,e){return n.format==="opencode"?Ms(e):n.format==="claude-code"||n.format==="codex"?ks(e):Rs(e)}var le={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var _u=1e3;function Bn(n){g(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=Qe.join(n,le.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=Hu(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return g(`[ProjectCheck] ${l.reason}`),l}let o=Qe.join(n,le.OH_PACKAGE_JSON5),i=$n(o,t,"root");if(i.required)return g(`[ProjectCheck] Root check: ${i.reason}`),i;let s=Qe.join(n,le.BUILD_PROFILE_JSON5),a=$n(s,t,"build-profile");if(a.required)return g(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let u=Qe.join(n,l.srcPath,le.OH_PACKAGE_JSON5),h=$n(u,t,l.name);if(h.required)return g(`[ProjectCheck] Module '${l.name}' check: ${h.reason}`),h;let v=Qe.join(n,l.srcPath,le.BUILD_PROFILE_JSON5),I=$n(v,t,l.name);if(I.required)return g(`[ProjectCheck] Module '${l.name}' build-profile check: ${I.reason}`),I}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return g(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function $n(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>_u?{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 Hu(n){let e=Qe.join(n,le.BUILD_PROFILE_JSON5);try{let t=He.readFileSync(e,"utf-8");if(!t.trim())return null;let r=Lu.parse(t);if(typeof r!="object"||r===null)return null;let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}function Fu(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 $u(n,e){let t;if(e.modules&&e.modules.length>0)t=e.modules;else{let o=n.profile.modules,i=o.filter(s=>n.getModuleType(s.name)==="entry");if(o.length===1)t=[o[0].name];else if(i.length===1)t=[i[0].name];else throw i.length>1?new Error(`Multiple entry modules found (${i.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`):new Error(`No entry module found and multiple modules available (${o.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`)}let r=new Set;for(let o of t){let i=o.indexOf("@"),s=i!==-1?o.substring(0,i):o,a=i!==-1?o.substring(i+1):"default";r.add(`${s}@${a}`)}return Array.from(r)}function qt(n,e){let t=new Set;for(let r of e){let o=r.indexOf("@"),i=o!==-1?r.substring(0,o):r,s=n.getModuleType(i);s==="shared"?t.add("assembleHsp"):s==="har"?t.add("assembleHar"):t.add("assembleHap")}return t}function zt(n,e){let t=e,r=`${n} failed`;console.error(ko(r));let o=t.stdout||t.message;throw o&&console.error(o),t.stderr&&console.error(t.stderr),new Error(r,{cause:e})}async function Vt(n,e,t,r,o,i){if(Bn(i).required){console.log(`
15
15
  [1/3] Running ohpm install...`);try{await n.installAll()}catch(a){zt("ohpm install",a)}console.log(`
16
16
  [2/3] Running hvigor sync...`);try{await e.sync(t,r)}catch(a){zt("hvigor sync",a)}console.log(`
17
17
  [3/3] Running hvigor build...`)}else console.log(`
@@ -20,48 +20,48 @@ ${o.join(`
20
20
  `+Os("Build completed successfully"))}catch(e){console.error(ko(e.message)),process.exit(1)}});Ls.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{try{let n=process.cwd(),e=Ze.discover(n);console.warn(Ns("Ensure the project source is trusted before proceeding."));let t=await _.new(),r=new be(t,e.rootDir);await Xe(e.rootDir,async()=>{console.log(`
21
21
  [1/2] Running hvigor clean...`);try{await r.clean()}catch(o){zt("hvigor clean",o)}console.log(`
22
22
  [2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(o){zt("hvigor --stop-daemon",o)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
23
- `+Os("Clean completed successfully."))}catch(n){console.error(ko(n.message)),process.exit(1)}});var _s=Ls;import{Command as Ep}from"commander";import{green as Ys,red as Ip,yellow as Dp}from"colorette";import{randomUUID as Qu}from"crypto";import{execa as ep}from"execa";import{execa as Xu}from"execa";import{execFile as Bu,spawn as Wu}from"child_process";import{promisify as Uu}from"util";var zu=Uu(Bu);function Hs(n,e,t){let o=n.replace(/\r\n/g,`
23
+ `+Os("Clean completed successfully."))}catch(n){console.error(ko(n.message)),process.exit(1)}});var _s=Ls;import{Command as Ip}from"commander";import{green as Ys,red as Dp,yellow as Cp}from"colorette";import{randomUUID as Qu}from"crypto";import{execa as ep}from"execa";import{execa as Xu}from"execa";import{execFile as Bu,spawn as Wu}from"child_process";import{promisify as Uu}from"util";var zu=Uu(Bu);function Hs(n,e,t){let o=n.replace(/\r\n/g,`
24
24
  `).split(`
25
25
  `),i=o.pop()??"",s=o.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),i}function js(n,e,t){let r=n.endsWith("\r")?n.slice(0,-1):n;r.length>0&&t.onData([r],e)}function qu(n,e){return{stdout:n.stdoutChunks.join(""),stderr:n.stderrChunks.join(""),exitCode:e??-1}}function Vu(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function Gu(n,e,t,r,o){n.stdout?.on("data",i=>{let s=i.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=Hs(e.stdoutLineBuffer+s,"stdout",t)}),n.stderr?.on("data",i=>{let s=i.toString();e.stderrChunks.push(s),e.stderrLineBuffer=Hs(e.stderrLineBuffer+s,"stderr",t)}),n.on("error",i=>{e.settled||(e.settled=!0,t.onError(i),o(i))}),n.on("close",i=>{if(e.settled)return;e.settled=!0,js(e.stdoutLineBuffer,"stdout",t),js(e.stderrLineBuffer,"stderr",t),t.onClose(i);let s=qu(e,i);r(s)})}async function Fs(n,e=[],t={}){try{let{stdout:r,stderr:o}=await zu(n,e,t);return{stdout:typeof r=="string"?r.trim():"",stderr:typeof o=="string"?o.trim():"",exitCode:0}}catch(r){let o=r;return{stdout:o.stdout?.trim()||"",stderr:o.stderr?.trim()||o.message,exitCode:typeof o.code=="number"?o.code:1}}}async function $s(n,e,t){return await new Promise((r,o)=>{let i=Wu(n,e,{stdio:["inherit","pipe","pipe"]}),s=Vu();Gu(i,s,t,r,o)})}function Bs(n){let e=n.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var Yu=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],Ju=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function mt(n){return n?Yu.some(e=>e.test(n))?"transient":Ju.some(e=>e.test(n))?"fatal":"ok":"ok"}var Mo=[800,1500,2500];function Ku(n){return new Promise(e=>setTimeout(e,n))}async function Gt(n,e){let t=1+Mo.length,r={stdout:"",stderr:"",exitCode:-1};for(let o=0;o<t;o++){if(r=await Fs(n,e),r.exitCode===0||mt(r.stderr)!=="transient"||o>=t-1)return r;g(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${Mo[o]}ms`),await Ku(Mo[o])}return r}async function Wn(n,e,t){let r=await Gt(n,["-t",e,"shell","param","get",t]);if(r.exitCode!==0)return;let o=r.stdout.trim();if(!(!o||mt(o)!=="ok"))return Bs(o)}var Ro="__DEVECO_PARAM_DELIM__";function Zu(n,e){let t=new Map,r=n.split(Ro);for(let o=0;o<e.length;o++){let i=(r[o]??"").trim();if(!i||mt(i)!=="ok")continue;let s=Bs(i);s&&t.set(e[o],s)}return t}async function ft(n,e,t){if(t.length===0)return new Map;if(t.length===1){let s=new Map,a=await Wn(n,e,t[0]);return a&&s.set(t[0],a),s}let r=t.map(s=>`param get ${s}`).join(`; echo ${Ro}; `)+`; echo ${Ro}`,o=await Gt(n,["-t",e,"shell",r]);if(o.exitCode===0){let s=Zu(o.stdout,t);if(s.size>0)return s}g(`Batched param fetch failed (exit=${o.exitCode}), falling back to individual calls for ${e}`);let i=new Map;for(let s of t){let a=await Wn(n,e,s);a&&i.set(s,a)}return i}function Yt(n){return n.startsWith("127.0.0.1:")}var Ws=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],K=class n{hdcPath;constructor(e){this.hdcPath=e}static from(e){return new n(e.hdcPath)}static withHdcPath(e){return new n(e)}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}stripBrandPrefix(e,t){let r=e.trim(),o=t?.trim();if(!r||!o)return r;let i=new RegExp(`^${this.escapeRegExp(o)}(\\s+|[-_]+)?`,"i");return r.replace(i,"").trim()||r}async executeHdc(e){return Xu(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let r of e.split(`
26
26
  `)){let o=r.trim();if(!o||o.startsWith("[Empty]"))continue;let i=o.split(/\s+/),s=i[0];if(!s||s.startsWith("[Empty]"))continue;let a=i.length>=2?i[1]:"device";if(a.toLowerCase()==="unauthorized"){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 o=e.get("const.product.model");if(o&&o!=="emulator"){let s=e.get("const.product.brand");return this.stripBrandPrefix(o,s)}let i=e.get("const.build.product");if(i&&i!=="emulator")return i}async getDeviceName(e){let t=await ft(this.hdcPath,e,[...Ws]);return this.extractDisplayName(t)??e}async getDeviceInfo(e,t){if(e.length===0)return null;if(t){let r=e.find(s=>s.serial===t);if(r)return r;let o=t.toLowerCase(),i=[];for(let s of e){let a=await this.getDeviceName(s.serial);a.toLowerCase()===o&&i.push({device:s,name:a})}if(i.length===1)return i[0].device;throw i.length>1?new Error(`Multiple devices match "${t}". Use a serial instead:
27
27
  `+i.map(s=>` - ${s.name} (${s.device.serial})`).join(`
28
28
  `)):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 ft(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=r.get("const.product.devicetype");let o=r.get("const.ohos.apiversion"),i=r.get("const.ohos.releasetype");o&&(t.osVersion=i?`API ${o} (${i})`:`API ${o}`)}catch{}return t}async listDevicesWithName(){let e=await this.listDevices();return Promise.all(e.map(async t=>({serial:t.serial,name:await this.getDeviceName(t.serial)})))}async getConnectedEntries(){let e=await this.listDevices();return Promise.all(e.map(t=>this.buildConnectedEntry(t.serial)))}async buildConnectedEntry(e){let t=D()?!1:Yt(e),r,o;try{let i=await ft(this.hdcPath,e,[...Ws]);r=this.extractDisplayName(i),o=i.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:o}}};var Jt=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=K.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;g(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:o}=await ep(r,e,{env:{...process.env}});return o}catch(o){if(t)throw o;return o.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){let r=await this.runHdc(["-t",e,"shell","bm","uninstall","-n",t],!1);if(r.includes("uninstall bundle successfully"))return!0;if(r.includes("uninstall missing installed bundle"))return!1;throw new Error(`Uninstall failed: ${r}`)}async installApp(e,t){if(t.length===0)return;let o=`/data/local/tmp/${Qu()}`;try{await this.runHdc(["-t",e,"shell","mkdir",o]);for(let s of t){let a=await this.runHdc(["-t",e,"file","send",s,o+"/"]);if(!a.startsWith("FileTransfer finish"))throw new Error(a)}let i=await this.runHdc(["-t",e,"shell","bm","install","-p",o]);if(!i.includes("install bundle successfully."))throw new Error(i);console.log("App installed successfully")}finally{await this.runHdc(["-t",e,"shell","rm","-rf",o],!1)}}async launchApp(e,t,r){let o=["-t",e,"shell","aa","start","-a",r,"-b",t];return await this.runHdc(o)}async connectTarget(e){await this.runHdc(["tconn",e])}async disconnectTarget(e){await this.runHdc(["tconn",e,"-remove"],!1)}async listRawTargets(){return(await this.runHdc(["list","targets"],!1)).split(`
29
- `).map(t=>t.trim()).filter(t=>t.length>0&&t!=="[Empty]")}async isDevEcoStudioRunningViaHdc(e){return(await this.runHdc(["-t",e,"shell","ps -ef | grep com.huawei.devecostudio | grep -v grep"],!1)).trim().length>0}async launchPreview(e,t,r,o,i,s,a,c,l){let h=JSON.stringify({bundleName:t,abilityName:r,moduleName:s,productName:o,productType:i,subProductType:a,instanceId:c,launchDeviceIndex:l,launchFlag:"{}",isCustom:!1,nativeDebuggable:!1,appDebuggable:!1}).replace(/'/g,"'\\''"),v=`aa start -a DevEcoViewerAbility -b com.huawei.devecostudio -m DevEcoViewer --pi instanceId ${c} --ps paramJson '${h}'`;return await this.runHdc(["-t",e,"shell",v])}};import{execa as Oo}from"execa";import*as Vs from"readline/promises";import{stdin as sp,stdout as ap}from"process";import{green as ht,red as qn,yellow as No}from"colorette";import zn from"fs";import*as Kt from"path";import cp from"json5";var tp=[{productIndex:0,productName:"Pura 90 Pro",productType:"phone",subProductType:"phone"},{productIndex:1,productName:"MatePad 11.5'S",productType:"tablet",subProductType:"tablet"},{productIndex:2,productName:"Mate X7",productType:"phone",subProductType:"foldable"},{productIndex:3,productName:"Pura X",productType:"phone",subProductType:"widefold"},{productIndex:4,productName:"Mate XT",productType:"phone",subProductType:"triplefold"}],Us={productIndex:0,productName:"phone",productType:"phone",subProductType:"phone"};async function np(){return[]}async function zs(){let n=await np();return n.length>0?n:tp}function Un(n){return n.toLowerCase().replace(/[\s\W]+/g,"")}var rp={phone:"Pura 90 Pro",tablet:"MatePad 11.5'S",pad:"MatePad 11.5'S",fold:"Mate X7",foldable:"Mate X7",widefold:"Pura X",wide:"Pura X",triplefold:"Mate XT",triple:"Mate XT",pura90:"Pura 90 Pro",pura90pro:"Pura 90 Pro",matepad:"MatePad 11.5'S",matex7:"Mate X7",purax:"Pura X",matext:"Mate XT"};function op(n,e){let t=n.length,r=e.length;if(t===0)return r;if(r===0)return t;let o=new Array(r+1),i=new Array(r+1);for(let s=0;s<=r;s++)o[s]=s;for(let s=1;s<=t;s++){i[0]=s;for(let a=1;a<=r;a++){let c=n[s-1]===e[a-1]?0:1;i[a]=Math.min(o[a]+1,i[a-1]+1,o[a-1]+c)}for(let a=0;a<=r;a++)o[a]=i[a]}return o[r]}function ip(n,e){let t=n.map(i=>({spec:i,dist:op(e,Un(i.productName))})),r=t.reduce((i,s)=>Math.min(i,s.dist),1/0);if(r>2)return;let o=t.filter(i=>i.dist===r);return o.length===1?{spec:o[0].spec,matchedName:o[0].spec.productName,fuzzy:!0,matchType:"fuzzy"}:{matchType:"none",ambiguous:o.map(i=>i.spec.productName)}}function qs(n,e){let t=Un(e);if(t.length===0)return{matchType:"none"};let r=n.find(a=>Un(a.productName)===t);if(r)return{spec:r,matchedName:r.productName,matchType:"exact"};let o=rp[t];if(o){let a=n.find(c=>c.productName===o);if(a)return{spec:a,matchedName:a.productName,matchType:"alias"}}let i=n.filter(a=>{let c=Un(a.productName);return c.includes(t)||t.includes(c)});if(i.length===1)return{spec:i[0],matchedName:i[0].productName,matchType:"substring"};if(i.length>1)return{matchType:"none",ambiguous:i.map(a=>a.productName)};let s=ip(n,t);return s||{matchType:"none"}}async function lp(){try{let n=Io();if(n==="win32"){let e=["devecostudio64.exe","devecostudio.exe"];for(let t of e){let{stdout:r}=await Oo("tasklist",["/FI",`IMAGENAME eq ${t}`,"/FO","CSV","/NH"],{reject:!1});if(/devecostudio/i.test(r))return!0}return!1}if(n==="darwin"){let{stdout:e}=await Oo("pgrep",["-x","DevEco Studio"],{reject:!1});return e.trim().length>0}if(n==="openharmony"||n==="linux"){let{stdout:e}=await Oo("pgrep",["-f","com.huawei.devecostudio"],{reject:!1});return e.trim().length>0}}catch{}return!1}async function dp(n,e){if(!D()){if(await lp()){console.log("DevEco Studio is already running.");return}throw new Error(`DevEco Studio is not running. The previewer requires DevEco Studio to be running.
29
+ `).map(t=>t.trim()).filter(t=>t.length>0&&t!=="[Empty]")}async isDevEcoStudioRunningViaHdc(e){return(await this.runHdc(["-t",e,"shell","ps -ef | grep com.huawei.devecostudio | grep -v grep"],!1)).trim().length>0}async launchPreview(e,t,r,o,i,s,a,c,l){let h=JSON.stringify({bundleName:t,abilityName:r,moduleName:s,productName:o,productType:i,subProductType:a,instanceId:c,launchDeviceIndex:l,launchFlag:"{}",isCustom:!1,nativeDebuggable:!1,appDebuggable:!1}).replace(/'/g,"'\\''"),v=`aa start -a DevEcoViewerAbility -b com.huawei.devecostudio -m DevEcoViewer --pi instanceId ${c} --ps paramJson '${h}'`;return await this.runHdc(["-t",e,"shell",v])}};import{execa as Oo}from"execa";import*as Vs from"readline/promises";import{stdin as sp,stdout as ap}from"process";import{green as ht,red as qn,yellow as No}from"colorette";import zn from"fs";import*as Kt from"path";import cp from"json5";var tp=[{productIndex:0,productName:"Pura 90 Pro",productType:"phone",subProductType:"phone"},{productIndex:1,productName:"MatePad 11.5'S",productType:"tablet",subProductType:"tablet"},{productIndex:2,productName:"Mate X7",productType:"phone",subProductType:"foldable"},{productIndex:3,productName:"Pura X",productType:"phone",subProductType:"widefold"},{productIndex:4,productName:"Mate XT",productType:"phone",subProductType:"triplefold"}],Us={productIndex:0,productName:"phone",productType:"phone",subProductType:"phone"};async function np(){return[]}async function zs(){let n=await np();return n.length>0?n:tp}function Un(n){return n.toLowerCase().replace(/[\s\W]+/g,"")}var rp={phone:"Pura 90 Pro",tablet:"MatePad 11.5'S",pad:"MatePad 11.5'S",fold:"Mate X7",foldable:"Mate X7",widefold:"Pura X",wide:"Pura X",triplefold:"Mate XT",triple:"Mate XT",pura90:"Pura 90 Pro",pura90pro:"Pura 90 Pro",matepad:"MatePad 11.5'S",matex7:"Mate X7",purax:"Pura X",matext:"Mate XT"};function op(n,e){let t=n.length,r=e.length;if(t===0)return r;if(r===0)return t;let o=new Array(r+1),i=new Array(r+1);for(let s=0;s<=r;s++)o[s]=s;for(let s=1;s<=t;s++){i[0]=s;for(let a=1;a<=r;a++){let c=n[s-1]===e[a-1]?0:1;i[a]=Math.min(o[a]+1,i[a-1]+1,o[a-1]+c)}for(let a=0;a<=r;a++)o[a]=i[a]}return o[r]}function ip(n,e){let t=n.map(i=>({spec:i,dist:op(e,Un(i.productName))})),r=t.reduce((i,s)=>Math.min(i,s.dist),1/0);if(r>2)return;let o=t.filter(i=>i.dist===r);return o.length===1?{spec:o[0].spec,matchedName:o[0].spec.productName,fuzzy:!0,matchType:"fuzzy"}:{matchType:"none",ambiguous:o.map(i=>i.spec.productName)}}function qs(n,e){let t=Un(e);if(t.length===0)return{matchType:"none"};let r=n.find(a=>Un(a.productName)===t);if(r)return{spec:r,matchedName:r.productName,matchType:"exact"};let o=rp[t];if(o){let a=n.find(c=>c.productName===o);if(a)return{spec:a,matchedName:a.productName,matchType:"alias"}}let i=n.filter(a=>{let c=Un(a.productName);return c.includes(t)||t.includes(c)});if(i.length===1)return{spec:i[0],matchedName:i[0].productName,matchType:"substring"};if(i.length>1)return{matchType:"none",ambiguous:i.map(a=>a.productName)};let s=ip(n,t);return s||{matchType:"none"}}async function lp(n){for(let e of n){let{stdout:t}=await Oo("tasklist",["/FI",`IMAGENAME eq ${e}`,"/FO","CSV","/NH"],{reject:!1});if(t.toLowerCase().includes(e.toLowerCase()))return!0}return!1}async function dp(){try{let n=Io();if(n==="win32")return lp(["devecostudio64.exe","devecostudio.exe"]);if(n==="darwin"){let{stdout:e}=await Oo("pgrep",["-x","DevEco Studio"],{reject:!1});return e.trim().length>0}if(n==="openharmony"||n==="linux"){let{stdout:e}=await Oo("pgrep",["-f","com.huawei.devecostudio"],{reject:!1});return e.trim().length>0}}catch{}return!1}async function up(n,e){if(!D()){if(await dp()){console.log("DevEco Studio is already running.");return}throw new Error(`DevEco Studio is not running. The previewer requires DevEco Studio to be running.
30
30
  Please start DevEco Studio manually, then retry.`)}if(!n||!e)throw new Error("Internal error: hdcAdapter and targetDeviceId are required for IDE detection on HarmonyOS.");if(await n.isDevEcoStudioRunningViaHdc(e)){console.log("DevEco Studio is already running.");return}throw new Error(`DevEco Studio is not running. The previewer requires DevEco Studio to be running.
31
- Please start DevEco Studio manually, then retry.`)}function up(n,e){if(n.count)throw new Error(`--count and --devices are mutually exclusive.
31
+ Please start DevEco Studio manually, then retry.`)}function pp(n,e){if(n.count)throw new Error(`--count and --devices are mutually exclusive.
32
32
  --count <n> : launch N previewers by list order
33
33
  --devices <names>: launch specified device types (comma-separated)
34
34
  Please specify only one of them.`);let t=n.devices.split(",").map(s=>s.trim()).filter(s=>s.length>0);if(t.length===0)throw new Error(`--devices is empty. Example: --devices "Pura 90 Pro,MatePad 11.5'S"`);let r=[],o=[];for(let s of t){let a=qs(e,s);if(a.spec)r.push(a.spec),a.matchType==="fuzzy"?console.warn(No(` [fuzzy] "${s}" \u2192 ${a.matchedName}`)):(a.matchType==="alias"||a.matchType==="substring")&&console.log(` [${a.matchType}] "${s}" \u2192 ${a.matchedName}`);else{if(a.ambiguous&&a.ambiguous.length>0)throw new Error(`Ambiguous device name "${s}". Candidates:
35
35
  `+a.ambiguous.map(c=>` - ${c}`).join(`
36
36
  `)+`
37
37
  Please specify a more precise name.`);o.push(s)}}if(o.length>0){let s=e.map(a=>a.productName).join(", ");throw new Error(`Device type(s) not found: ${o.join(", ")}
38
- Available: ${s}`)}let i=fp(r);return{targets:i,isMulti:i.length>1}}function pp(n,e){let t=parseInt(n.count,10);if(isNaN(t)||t<1)throw new Error(`Invalid --count value: ${n.count}. Must be a positive integer.`);let r=e.slice(0,t);return r.length<t&&console.warn(No(`Requested ${t} previewers but only ${r.length} device type(s) available. Will launch ${r.length} previewer(s).`)),{targets:r,isMulti:r.length>1}}function mp(n,e){let t=e.length>0?e:[Us];return n.devices?up(n,t):n.count?pp(n,t):{targets:[t[0]],isMulti:!1}}function fp(n){let e=new Set,t=[];for(let r of n)e.has(r.productName)||(e.add(r.productName),t.push(r));return t}async function hp(n){if(!process.stdin.isTTY)return;console.log(""),console.log("No device connected. To connect to this HarmonyOS device:"),console.log(' 1. Open "Settings \u2192 System \u2192 Developer options \u2192 Wireless debugging"'),console.log(" 2. Enable it and note the port number shown"),console.log(" 3. Enter the port below (or set DEVECO_HDC_PORT env var)"),console.log("");let e=Vs.createInterface({input:sp,output:ap});try{let t=await e.question("Wireless debugging port: ");if(t.trim()){let r=`127.0.0.1:${t.trim()}`;return await n.connectTarget(r),console.log(ht(`Connected to local device: ${r}`)),r}}catch{}finally{e.close()}}async function gp(n,e){if(e){let i=e.includes(":")?e:`127.0.0.1:${e}`;return await n.connectTarget(i),console.log(`Connected to local device: ${i}`),i}let t=process.env.DEVECO_HDC_PORT;if(t){let i=`127.0.0.1:${t}`;try{return await n.connectTarget(i),console.log(`Connected to local device via DEVECO_HDC_PORT: ${i}`),i}catch{console.warn(No(`DEVECO_HDC_PORT=${t} but connect failed, trying other methods...`))}}let r=await n.listRawTargets();if(r.length>0){let i=r[0];return g(`[preview] Found existing target: ${i}`),i}let o=await hp(n);if(o)return o;throw new Error(`Cannot connect to local HarmonyOS device.
38
+ Available: ${s}`)}let i=hp(r);return{targets:i,isMulti:i.length>1}}function mp(n,e){let t=parseInt(n.count,10);if(isNaN(t)||t<1)throw new Error(`Invalid --count value: ${n.count}. Must be a positive integer.`);let r=e.slice(0,t);return r.length<t&&console.warn(No(`Requested ${t} previewers but only ${r.length} device type(s) available. Will launch ${r.length} previewer(s).`)),{targets:r,isMulti:r.length>1}}function fp(n,e){let t=e.length>0?e:[Us];return n.devices?pp(n,t):n.count?mp(n,t):{targets:[t[0]],isMulti:!1}}function hp(n){let e=new Set,t=[];for(let r of n)e.has(r.productName)||(e.add(r.productName),t.push(r));return t}async function gp(n){if(!process.stdin.isTTY)return;console.log(""),console.log("No device connected. To connect to this HarmonyOS device:"),console.log(' 1. Open "Settings \u2192 System \u2192 Developer options \u2192 Wireless debugging"'),console.log(" 2. Enable it and note the port number shown"),console.log(" 3. Enter the port below (or set DEVECO_HDC_PORT env var)"),console.log("");let e=Vs.createInterface({input:sp,output:ap});try{let t=await e.question("Wireless debugging port: ");if(t.trim()){let r=`127.0.0.1:${t.trim()}`;return await n.connectTarget(r),console.log(ht(`Connected to local device: ${r}`)),r}}catch{}finally{e.close()}}async function yp(n,e){if(e){let i=e.includes(":")?e:`127.0.0.1:${e}`;return await n.connectTarget(i),console.log(`Connected to local device: ${i}`),i}let t=process.env.DEVECO_HDC_PORT;if(t){let i=`127.0.0.1:${t}`;try{return await n.connectTarget(i),console.log(`Connected to local device via DEVECO_HDC_PORT: ${i}`),i}catch{console.warn(No(`DEVECO_HDC_PORT=${t} but connect failed, trying other methods...`))}}let r=await n.listRawTargets();if(r.length>0){let i=r[0];return g(`[preview] Found existing target: ${i}`),i}let o=await gp(n);if(o)return o;throw new Error(`Cannot connect to local HarmonyOS device.
39
39
  Please either:
40
40
  1. Run with --device 127.0.0.1:<port>, or
41
41
  2. Set DEVECO_HDC_PORT env var, or
42
- 3. Open wireless debugging in system settings first.`)}async function yp(n,e){let t=await n.listDevices();if(t.length===0)throw new Error("No active devices found. Please start an emulator or connect a physical device.");if(!e&&t.length>1){let o=await n.listDevicesWithName();throw new Error("Multiple devices found. Please specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+o.map(i=>` - ${i.name} (${i.serial})`).join(`
43
- `))}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let o=await n.getDeviceName(r.serial);console.log(`Auto-selected device: ${o} (${r.serial})`)}return r.serial}function vp(n){if(!zn.existsSync(n))throw new Error(`app.json5 not found at ${n}`);let e=zn.readFileSync(n,"utf8"),t=cp.parse(e);return t.app?.multiAppMode?(console.log("[multi-preview] app.json5 already has multiAppMode, skipping injection."),()=>{}):(t.app||(t.app={}),t.app.multiAppMode={multiAppModeType:"appClone",maxCount:5},zn.writeFileSync(n,JSON.stringify(t,null,2),"utf8"),console.log(`[multi-preview] Injected multiAppMode into ${Kt.basename(n)}`),()=>{zn.writeFileSync(n,e,"utf8"),console.log(`[multi-preview] Restored original ${Kt.basename(n)}`)})}async function wp(n,e,t,r,o,i){let s=Kt.join(e.rootDir,"AppScope","app.json5"),a=vp(s);try{let c=n.product||"default",l=n.buildMode||"debug",u="default",h=o.includes("127.0.0.1")||o.includes("localhost");console.log(`
44
- [multi-preview] Building with multiAppMode (appClone) for multi-instance preview...`);let v=new Oe(t,e.rootDir),I=new be(t,e.rootDir),ee=e.collectNonHarDependentModuleList(i).map(Pu=>`${Pu}@${u}`),Me=qt(e,ee),ut={type:"modules",modulesToBuild:ee,moduleTasks:Me};await Xe(e.rootDir,async()=>{await Vt(v,I,c,l,ut,e.rootDir)},()=>console.log("Another build is already running. Waiting...")),console.log(ht("[multi-preview] Build completed."));let Wt=e.findArtifactPath(i,u,h,c);console.log(`[multi-preview] Installing multiAppMode hap to ${o}...`),await r.installApp(o,[Wt]),console.log(ht("[multi-preview] Installed multiAppMode hap."))}finally{a()}}function bp(n,e,t,r,o,i,s){console.log(`
45
- Launching DevEco Studio previewer on ${n}...`),console.log(` bundleName : ${e}`),console.log(` abilityName : ${t}`),console.log(` moduleName : ${r}`),console.log(` instanceId : ${o}`),console.log(` mode : ${i?"multi":"single"}`),console.log(` previewers : ${s.map(a=>a.productName).join(", ")}`)}async function Sp(n,e,t,r,o,i,s,a){let c=[];for(let l=0;l<e.length;l++){let u=e[l],h=t?l:-1;console.log(`
46
- [${l+1}/${e.length}] Launching ${u.productName} (${u.productType}/${u.subProductType})...`);try{let v=await n.launchPreview(r,o,i,u.productName,u.productType,s,u.subProductType,a,h),I=/start ability successfully/i.test(v);c.push({name:u.productName,success:I,output:v}),I?console.log(ht(` \u2713 ${u.productName}: ${v.trim()}`)):console.error(qn(` \u2717 ${u.productName}: ${v.trim()}`))}catch(v){let I=v.message;c.push({name:u.productName,success:!1,output:I}),console.error(qn(` \u2717 ${u.productName}: ${I}`))}}return c}function Pp(n){console.log(`
47
- `+"\u2500".repeat(50));let e=n.filter(r=>r.success).length,t=n.length-e;console.log(`Previewer launch summary: ${ht(String(e))} succeeded, ${t>0?qn(String(t)):"0"} failed.`);for(let r of n){let o=r.success?ht("\u2713"):qn("\u2717");console.log(` ${o} ${r.name}`)}return t===0}async function Gs(n,e,t,r,o,i){let s=D()?await gp(r,n.device):await yp(o,n.device),a=n.devices?.split(",").map(Wt=>Wt.trim()).filter(Wt=>Wt.length>0)||[],c=n.count?parseInt(n.count,10):0;(a.length>1||c>1)&&await wp(n,e,t,r,s,i),await dp(r,s);let u=e.getBundleName(),h=e.getMainAbility(i,n.ability),v=e.getModuleName(i),I=await zs(),{targets:k,isMulti:ee}=mp(n,I),Me=process.pid;bp(s,u,h,v,Me,ee,k);let ut=await Sp(r,k,ee,s,u,h,v,Me);return Pp(ut)}function Cp(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 Ap(n,e){let t=await n.listDevices();if(t.length===0)throw new Error(D()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device.");if(!e&&t.length>1){let o=await n.listDevicesWithName();throw new Error("Multiple devices found. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+o.map(i=>` - ${i.name} (${i.serial})`).join(`
48
- `))}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let o=await n.getDeviceName(r.serial);console.log(`Auto-selected device: ${o} (${r.serial})`)}return r.serial}function Tp(n,e){if(e&&e.length>0)return e;let t=n.profile.modules.filter(r=>{let o=n.getModuleType(r.name);return o==="entry"||o==="feature"||o==="shared"});if(t.length===1){let r=t[0].name;return console.log(`Auto-selected module: ${r}`),[r]}throw new Error(`Specify module(s) using --module <name> [<name>...].
42
+ 3. Open wireless debugging in system settings first.`)}async function vp(n,e){let t=await n.listDevices();if(t.length===0)throw new Error("No active devices found. Please start an emulator or connect a physical device.");if(!e&&t.length>1){let o=await n.listDevicesWithName();throw new Error("Multiple devices found. Please specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+o.map(i=>` - ${i.name} (${i.serial})`).join(`
43
+ `))}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let o=await n.getDeviceName(r.serial);console.log(`Auto-selected device: ${o} (${r.serial})`)}return r.serial}function wp(n){if(!zn.existsSync(n))throw new Error(`app.json5 not found at ${n}`);let e=zn.readFileSync(n,"utf8"),t=cp.parse(e);return t.app?.multiAppMode?(console.log("[multi-preview] app.json5 already has multiAppMode, skipping injection."),()=>{}):(t.app||(t.app={}),t.app.multiAppMode={multiAppModeType:"appClone",maxCount:5},zn.writeFileSync(n,JSON.stringify(t,null,2),"utf8"),console.log(`[multi-preview] Injected multiAppMode into ${Kt.basename(n)}`),()=>{zn.writeFileSync(n,e,"utf8"),console.log(`[multi-preview] Restored original ${Kt.basename(n)}`)})}async function bp(n,e,t,r,o,i){let s=Kt.join(e.rootDir,"AppScope","app.json5"),a=wp(s);try{let c=n.product||"default",l=n.buildMode||"debug",u="default",h=o.includes("127.0.0.1")||o.includes("localhost");console.log(`
44
+ [multi-preview] Building with multiAppMode (appClone) for multi-instance preview...`);let v=new Oe(t,e.rootDir),I=new be(t,e.rootDir),ee=e.collectNonHarDependentModuleList(i).map(Pu=>`${Pu}@${u}`),Me=qt(e,ee),ut={type:"modules",modulesToBuild:ee,moduleTasks:Me};await Xe(e.rootDir,async()=>{await Vt(v,I,c,l,ut,e.rootDir)},()=>console.log("Another build is already running. Waiting...")),console.log(ht("[multi-preview] Build completed."));let Wt=e.findArtifactPath(i,u,h,c);console.log(`[multi-preview] Installing multiAppMode hap to ${o}...`),await r.installApp(o,[Wt]),console.log(ht("[multi-preview] Installed multiAppMode hap."))}finally{a()}}function Sp(n,e,t,r,o,i,s){console.log(`
45
+ Launching DevEco Studio previewer on ${n}...`),console.log(` bundleName : ${e}`),console.log(` abilityName : ${t}`),console.log(` moduleName : ${r}`),console.log(` instanceId : ${o}`),console.log(` mode : ${i?"multi":"single"}`),console.log(` previewers : ${s.map(a=>a.productName).join(", ")}`)}async function Pp(n,e,t,r,o,i,s,a){let c=[];for(let l=0;l<e.length;l++){let u=e[l],h=t?l:-1;console.log(`
46
+ [${l+1}/${e.length}] Launching ${u.productName} (${u.productType}/${u.subProductType})...`);try{let v=await n.launchPreview(r,o,i,u.productName,u.productType,s,u.subProductType,a,h),I=/start ability successfully/i.test(v);c.push({name:u.productName,success:I,output:v}),I?console.log(ht(` \u2713 ${u.productName}: ${v.trim()}`)):console.error(qn(` \u2717 ${u.productName}: ${v.trim()}`))}catch(v){let I=v.message;c.push({name:u.productName,success:!1,output:I}),console.error(qn(` \u2717 ${u.productName}: ${I}`))}}return c}function Ep(n){console.log(`
47
+ `+"\u2500".repeat(50));let e=n.filter(r=>r.success).length,t=n.length-e;console.log(`Previewer launch summary: ${ht(String(e))} succeeded, ${t>0?qn(String(t)):"0"} failed.`);for(let r of n){let o=r.success?ht("\u2713"):qn("\u2717");console.log(` ${o} ${r.name}`)}return t===0}async function Gs(n,e,t,r,o,i){let s=D()?await yp(r,n.device):await vp(o,n.device),a=n.devices?.split(",").map(Wt=>Wt.trim()).filter(Wt=>Wt.length>0)||[],c=n.count?parseInt(n.count,10):0;(a.length>1||c>1)&&await bp(n,e,t,r,s,i),await up(r,s);let u=e.getBundleName(),h=e.getMainAbility(i,n.ability),v=e.getModuleName(i),I=await zs(),{targets:k,isMulti:ee}=fp(n,I),Me=process.pid;Sp(s,u,h,v,Me,ee,k);let ut=await Pp(r,k,ee,s,u,h,v,Me);return Ep(ut)}function Ap(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 Tp(n,e){let t=await n.listDevices();if(t.length===0)throw new Error(D()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device.");if(!e&&t.length>1){let o=await n.listDevicesWithName();throw new Error("Multiple devices found. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+o.map(i=>` - ${i.name} (${i.serial})`).join(`
48
+ `))}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let o=await n.getDeviceName(r.serial);console.log(`Auto-selected device: ${o} (${r.serial})`)}return r.serial}function xp(n,e){if(e&&e.length>0)return e;let t=n.profile.modules.filter(r=>{let o=n.getModuleType(r.name);return o==="entry"||o==="feature"||o==="shared"});if(t.length===1){let r=t[0].name;return console.log(`Auto-selected module: ${r}`),[r]}throw new Error(`Specify module(s) using --module <name> [<name>...].
49
49
  Available runnable modules:
50
50
  `+t.map(r=>` - ${r.name}`).join(`
51
- `))}function xp(n,e,t){if(t)return t;let r=e.find(({moduleName:i})=>n.getModuleType(i)==="entry");if(r)return n.getMainAbility(r.moduleName);let o=e.find(({moduleName:i})=>n.getModuleType(i)==="feature");if(o)return n.getMainAbility(o.moduleName)}async function kp(n,e,t,r,o,i){if(i&&(console.log(`Uninstalling ${t}...`),await n.uninstallApp(e,t)||console.log(`App ${t} not installed; skipping uninstallation.`)),console.log(`
51
+ `))}function kp(n,e,t){if(t)return t;let r=e.find(({moduleName:i})=>n.getModuleType(i)==="entry");if(r)return n.getMainAbility(r.moduleName);let o=e.find(({moduleName:i})=>n.getModuleType(i)==="feature");if(o)return n.getMainAbility(o.moduleName)}async function Mp(n,e,t,r,o,i){if(i&&(console.log(`Uninstalling ${t}...`),await n.uninstallApp(e,t)||console.log(`App ${t} not installed; skipping uninstallation.`)),console.log(`
52
52
  Installing artifacts to device ${e}...`),await n.installApp(e,r),o){console.log(`Launching ${t}/${o}...`);let s=await n.launchApp(e,t,o);console.log(Ys(`
53
53
  Application '${t}': ${s}`))}else console.log(`
54
- Application '${t}' installed successfully (no ability to launch).`)}var Mp=new Ep("run").description("Build and run the project on a connected device").option("--module <modules...>","Module(s) to run (format: module or module@target)").option("--device <device>","Target device name or serial").option("--product <product>","Product name (default: default)").option("--build-mode <mode>","Build mode (options: debug, release; default: debug)").option("--ability <ability>","Ability name to launch").option("--uninstall","Uninstall existing app before installation").option("--skip-build","Skip build step and deploy existing artifacts").option("--preview","Launch DevEco Studio previewer instead of installing/running the app").option("--count <n>","Previewer only: number of previewer windows to launch (multi-previewer mode)").option("--devices <names>",`Previewer only: comma-separated device product names (e.g. "Pura 90 Pro,MatePad 11.5'S"). Takes priority over --count`).action(async n=>{try{await _p(n)}catch(e){console.error(Ip(e.message)),process.exit(1)}});async function Rp(n,e,t,r,o){let i=new Oe(e,n.rootDir),s=new be(e,n.rootDir),a=new Set;for(let{moduleName:h,targetName:v}of t)for(let I of n.collectNonHarDependentModuleList(h))a.add(`${I}@${v}`);let c=[...a],l=qt(n,c),u={type:"modules",modulesToBuild:c,moduleTasks:l};await Xe(n.rootDir,()=>Vt(i,s,r,o,u,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion...")),console.log(`
55
- `+Ys("Build completed successfully."))}async function Op(n,e,t,r,o){let i=new Jt(t),s=K.from(t),a=r[0]?.moduleName||o[0];await Gs(n,e,t,i,s,a)||process.exit(1)}function Np(n,e){for(let{moduleName:t}of e){let r=n.getModuleType(t);if(r!=="entry"&&r!=="feature"&&r!=="shared")throw new Error(`Module '${t}' '${r}' is not runnable. Specify an entry or feature module.`)}}function Lp(n,e,t,r){let o=new Set;for(let{moduleName:i,targetName:s}of e){let a=n.collectNonHarDependentModuleList(i);for(let c of a)o.add(n.findArtifactPath(c,s,t,r));o.add(n.findArtifactPath(i,s,t,r))}return[...o]}async function _p(n){let e=Ze.discover(process.cwd());console.warn(Dp("Ensure the project source is trusted before proceeding."));let t=await _.new(),r=Tp(e,n.module),o=r.map(Cp);if(n.preview){await Op(n,e,t,o,r);return}Np(e,o);let i=new Jt(t),s=K.from(t),a=await Ap(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 Rp(e,t,o,l,u);let h=Lp(e,o,c,l),v=e.getBundleName(),I=xp(e,o,n.ability);await kp(i,a,v,h,I,!!n.uninstall)}var Js=Mp;import{Command as Hp}from"commander";import{green as Ks,red as Zs,cyan as Lo}from"colorette";import{execa as Xs}from"execa";function jp(){return"@deveco-test/hmos-deveco-cli"}function Fp(){return"0.1.0-TD.4.2"}var $p=new Hp("update").description("Update deveco-cli to latest").action(async()=>{let n=jp(),e=Fp();console.log(Lo("Checking for updates..."));try{let{stdout:t}=await Xs("npm",["view",n,"version"]),r=t.trim();if(r===e){console.log(Ks(`
54
+ Application '${t}' installed successfully (no ability to launch).`)}var Rp=new Ip("run").description("Build and run the project on a connected device").option("--module <modules...>","Module(s) to run (format: module or module@target)").option("--device <device>","Target device name or serial").option("--product <product>","Product name (default: default)").option("--build-mode <mode>","Build mode (options: debug, release; default: debug)").option("--ability <ability>","Ability name to launch").option("--uninstall","Uninstall existing app before installation").option("--skip-build","Skip build step and deploy existing artifacts").option("--preview","Launch DevEco Studio previewer instead of installing/running the app").option("--count <n>","Previewer only: number of previewer windows to launch (multi-previewer mode)").option("--devices <names>",`Previewer only: comma-separated device product names (e.g. "Pura 90 Pro,MatePad 11.5'S"). Takes priority over --count`).action(async n=>{try{await Hp(n)}catch(e){console.error(Dp(e.message)),process.exit(1)}});async function Op(n,e,t,r,o){let i=new Oe(e,n.rootDir),s=new be(e,n.rootDir),a=new Set;for(let{moduleName:h,targetName:v}of t)for(let I of n.collectNonHarDependentModuleList(h))a.add(`${I}@${v}`);let c=[...a],l=qt(n,c),u={type:"modules",modulesToBuild:c,moduleTasks:l};await Xe(n.rootDir,()=>Vt(i,s,r,o,u,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion...")),console.log(`
55
+ `+Ys("Build completed successfully."))}async function Np(n,e,t,r,o){let i=new Jt(t),s=K.from(t),a=r[0]?.moduleName||o[0];await Gs(n,e,t,i,s,a)||process.exit(1)}function Lp(n,e){for(let{moduleName:t}of e){let r=n.getModuleType(t);if(r!=="entry"&&r!=="feature"&&r!=="shared")throw new Error(`Module '${t}' '${r}' is not runnable. Specify an entry or feature module.`)}}function _p(n,e,t,r){let o=new Set;for(let{moduleName:i,targetName:s}of e){let a=n.collectNonHarDependentModuleList(i);for(let c of a)o.add(n.findArtifactPath(c,s,t,r));o.add(n.findArtifactPath(i,s,t,r))}return[...o]}async function Hp(n){let e=Ze.discover(process.cwd());console.warn(Cp("Ensure the project source is trusted before proceeding."));let t=await _.new(),r=xp(e,n.module),o=r.map(Ap);if(n.preview){await Np(n,e,t,o,r);return}Lp(e,o);let i=new Jt(t),s=K.from(t),a=await Tp(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 Op(e,t,o,l,u);let h=_p(e,o,c,l),v=e.getBundleName(),I=kp(e,o,n.ability);await Mp(i,a,v,h,I,!!n.uninstall)}var Js=Rp;import{Command as jp}from"commander";import{green as Ks,red as Zs,cyan as Lo}from"colorette";import{execa as Xs}from"execa";function Fp(){return"@deveco-test/hmos-deveco-cli"}function $p(){return"0.1.0-TD.5"}var Bp=new jp("update").description("Update deveco-cli to latest").action(async()=>{let n=Fp(),e=$p();console.log(Lo("Checking for updates..."));try{let{stdout:t}=await Xs("npm",["view",n,"version"]),r=t.trim();if(r===e){console.log(Ks(`
56
56
  ${n} is already up to date (version ${e}.)`));return}console.log(Lo(`
57
57
  New version found: ${r} (current: ${e})`)),console.log(Lo(`Updating ${n}...`)),await Xs("npm",["install","-g",`${n}@latest`],{stdio:"inherit"}),console.log(`
58
- `+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=$p;import{Command as cm}from"commander";import{execa as Fo}from"execa";function V(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as Bp}from"child_process";var Wp=2500;function Up(n,e,t,r,o,i){n.once("exit",s=>{if(i())return;clearTimeout(e);let a=t();s===0||s===null?r():o(a||`Emulator process exited with code ${s}`)})}function zp(n,e,t,r){let o=!1,i=()=>o,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{o||(o=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners(),n.stderr?.destroy(),n.unref(),t())},c=u=>{if(!o){o=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners();try{n.kill()}catch{}r(new Error(u))}},l=setTimeout(a,Wp);n.once("error",u=>c(u.message)),Up(n,l,s,a,c,i)}function ea(n,e,t){return g(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,o)=>{let i=[],s=Bp(n,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>i.push(a)),zp(s,i,r,o)})}import*as gt from"path";function qp(n){let e=new Set,t=[];for(let r of n){let o=JSON.stringify(r);e.has(o)||(e.add(o),t.push(r))}return t}function Vp(n){let e=n.instancePath?.trim();if(e)return gt.dirname(gt.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?gt.dirname(gt.normalize(t)).replace(/\\/g,"/"):""}function Gp(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function ta(n,e){return e?[...n,"-bootmode",e]:n}function Yp(n,e,t){let r=[ta(["-start",n],t)],o=Vp(e);if(o)for(let i of Gp(e.imageRoot))r.push(ta(["-hvd",n,"-path",o,...i],t));return qp(r)}async function na(n,e,t,r){let o=new Error("No start strategy ran"),i=Yp(n,e,r);for(let s of i)try{return await t(s),{ok:!0}}catch(a){o=a}return{ok:!1,lastError:o}}async function _o(n){return(await K.withHdcPath(n).listDevices()).map(t=>t.serial).filter(Yt)}async function Ho(n){let e=await _o(n);return e.length===0?[]:(await Promise.all(e.map(r=>Wn(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function ra(n,e){return(await Ho(n)).includes(e)}import*as vt from"path";import{existsSync as Jp,statSync as Kp}from"fs";function yt(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function Zp(n){let e=yt(n,["instancePath","instance_path","InstancePath","instancepath","instanceDir","instance_dir","InstanceDir","deployPath","deploy_path","deployedPath","deployed_path","workPath","work_path","dataPath","data_path"]);if(e)return e;for(let[t,r]of Object.entries(n)){if(typeof r!="string"||!r.trim())continue;let o=t.toLowerCase();if(o.includes("instance")&&(o.includes("path")||o.includes("dir"))||o==="deployedpath")return r.trim()}return""}function Xp(n){return yt(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function Qp(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=vt.dirname(vt.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let o=vt.join(t,r.name);Jp(o)&&Kp(o).isDirectory()&&(r.instancePath=o.replace(/\\/g,"/"))}}function em(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=Xp(t),o=yt(t,["deviceType","DeviceType","devicetype"]),i=yt(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:Zp(t),path:yt(t,["path","Path","hvdPath","hvd_path"]),imageRoot:yt(t,["imageRoot","image_root","ImageRoot"]),uuid:r||void 0,deviceType:o||void 0,osVersion:i||void 0}}).filter(t=>t.name):null}catch{return null}}function tm(n){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,r=null,o;for(;(o=t.exec(n))!==null;){let[,i,s]=o;if(i.toLowerCase()==="name")r&&e.push(r),r={name:s.trim()};else if(r){let a=i.toLowerCase();a==="isrunning"?r.isRunning=s.trim().toLowerCase()==="true":a==="instancepath"?r.instancePath=s.trim():a==="path"?r.path=s.trim():a==="imageroot"?r.imageRoot=s.trim():a==="devicetype"?r.deviceType=s.trim():a==="os.osversion"&&(r.osVersion=s.trim())}}return r&&e.push(r),e}function oa(n){let t=em(n)??tm(n);return Qp(t),t}function jo(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function nm(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function rm(n){if(!nm(n))return null;let e=jo(n,["osVersion","OsVersion","OSVersion"]),t=jo(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=jo(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function Vn(n){let e=n.trim();if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let r=[];for(let o of t){if(!o||typeof o!="object")continue;let i=rm(o);i&&r.push(i)}return r}catch{return[]}}function ia(n){let t=Vn(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var sa=/no images are available/i;function he(n){return n.normalize("NFKC").trim().toLowerCase()}function om(n){let e=n.message||"";return sa.test(e)}var wt=class n{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 Fo(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 oa(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),o=t.find(a=>V(a.name)===r);if(!o)throw new Error(`Emulator "${e}" not found.`);let i=o.name;if(await this.isAlreadyRunning(i,o))return"already-running";await this.assertSystemImageAvailable(o);let s=await na(i,o,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return"started";if(await this.isAlreadyRunning(i))return"already-running";throw new Error(`Unable to start emulator "${e}". All methods failed.
59
- Last error: ${s.lastError.message||"unknown"}`)}async isAlreadyRunning(e,t){return t?.isRunning===!0||t===void 0&&(await this.listEmulators()).find(o=>o.name===e)?.isRunning===!0?!0:ra(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=V(e),o=t.find(a=>V(a.name)===r);if(!o)throw new Error(`Emulator "${e}" not found.`);let i=o.name;return await this.isAlreadyRunning(i,o)?(await this.executeEmulator(["-stop",i]),"stopped"):"already-stopped"}async executeEmulatorInherit(e){let{exitCode:t}=await Fo(this.emulatorPath,e,{stdio:"inherit",env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1});if(t!==0)throw new Error(`Emulator exited with code ${t===null?"null":t}.`)}async installEmulatorImage(e){let t=["-install","-deviceType",e.deviceType,"-osVersion",e.osVersion];e.force&&t.push("-force"),await this.executeEmulatorInherit(t)}async uninstallEmulatorImage(e){let t=await this.resolveSoftwareVersionsForUninstall(e);if(t.length===0)throw new Error(`No downloaded image matches --os-version "${e.osVersion}" for --device-type "${e.deviceType}".`);let r;try{await this.runUninstallImageChecked(e.deviceType,e.osVersion)}catch(i){if(!om(i))throw i;r=i}(r!==void 0||await this.hasMatchingDownloadedImage(e))&&await this.runSoftwareVersionFallback(e,t,r)}async listEmulatorImages(e){let t=["-imageList"];e.deviceType&&t.push("-deviceType",e.deviceType),e.downloaded!==void 0&&t.push("-downloaded",e.downloaded?"true":"false");let{stdout:r}=await this.executeEmulator(t);return r}async listDownloadedImageOsVersions(){let e=await this.listEmulatorImages({downloaded:!0});return ia(e)}async hasMatchingDownloadedImage(e){return(await this.findMatchingDownloadedImages(e)).length>0}async runSoftwareVersionFallback(e,t,r){try{for(let o of t)await this.runUninstallImageChecked(e.deviceType,o)}catch(o){let i=r!==void 0?`Primary uninstall failed: ${r.message}
58
+ `+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=Bp;import{Command as lm}from"commander";import{execa as Fo}from"execa";function V(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as Wp}from"child_process";var Up=2500;function zp(n,e,t,r,o,i){n.once("exit",s=>{if(i())return;clearTimeout(e);let a=t();s===0||s===null?r():o(a||`Emulator process exited with code ${s}`)})}function qp(n,e,t,r){let o=!1,i=()=>o,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{o||(o=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners(),n.stderr?.destroy(),n.unref(),t())},c=u=>{if(!o){o=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners();try{n.kill()}catch{}r(new Error(u))}},l=setTimeout(a,Up);n.once("error",u=>c(u.message)),zp(n,l,s,a,c,i)}function ea(n,e,t){return g(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,o)=>{let i=[],s=Wp(n,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>i.push(a)),qp(s,i,r,o)})}import*as gt from"path";function Vp(n){let e=new Set,t=[];for(let r of n){let o=JSON.stringify(r);e.has(o)||(e.add(o),t.push(r))}return t}function Gp(n){let e=n.instancePath?.trim();if(e)return gt.dirname(gt.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?gt.dirname(gt.normalize(t)).replace(/\\/g,"/"):""}function Yp(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function ta(n,e){return e?[...n,"-bootmode",e]:n}function Jp(n,e,t){let r=[ta(["-start",n],t)],o=Gp(e);if(o)for(let i of Yp(e.imageRoot))r.push(ta(["-hvd",n,"-path",o,...i],t));return Vp(r)}async function na(n,e,t,r){let o=new Error("No start strategy ran"),i=Jp(n,e,r);for(let s of i)try{return await t(s),{ok:!0}}catch(a){o=a}return{ok:!1,lastError:o}}async function _o(n){return(await K.withHdcPath(n).listDevices()).map(t=>t.serial).filter(Yt)}async function Ho(n){let e=await _o(n);return e.length===0?[]:(await Promise.all(e.map(r=>Wn(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function ra(n,e){return(await Ho(n)).includes(e)}import*as vt from"path";import{existsSync as Kp,statSync as Zp}from"fs";function yt(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function Xp(n){let e=yt(n,["instancePath","instance_path","InstancePath","instancepath","instanceDir","instance_dir","InstanceDir","deployPath","deploy_path","deployedPath","deployed_path","workPath","work_path","dataPath","data_path"]);if(e)return e;for(let[t,r]of Object.entries(n)){if(typeof r!="string"||!r.trim())continue;let o=t.toLowerCase();if(o.includes("instance")&&(o.includes("path")||o.includes("dir"))||o==="deployedpath")return r.trim()}return""}function Qp(n){return yt(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function em(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=vt.dirname(vt.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let o=vt.join(t,r.name);Kp(o)&&Zp(o).isDirectory()&&(r.instancePath=o.replace(/\\/g,"/"))}}function tm(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=Qp(t),o=yt(t,["deviceType","DeviceType","devicetype"]),i=yt(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:Xp(t),path:yt(t,["path","Path","hvdPath","hvd_path"]),imageRoot:yt(t,["imageRoot","image_root","ImageRoot"]),uuid:r||void 0,deviceType:o||void 0,osVersion:i||void 0}}).filter(t=>t.name):null}catch{return null}}function nm(n){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,r=null,o;for(;(o=t.exec(n))!==null;){let[,i,s]=o;if(i.toLowerCase()==="name")r&&e.push(r),r={name:s.trim()};else if(r){let a=i.toLowerCase();a==="isrunning"?r.isRunning=s.trim().toLowerCase()==="true":a==="instancepath"?r.instancePath=s.trim():a==="path"?r.path=s.trim():a==="imageroot"?r.imageRoot=s.trim():a==="devicetype"?r.deviceType=s.trim():a==="os.osversion"&&(r.osVersion=s.trim())}}return r&&e.push(r),e}function oa(n){let t=tm(n)??nm(n);return em(t),t}function jo(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function rm(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function om(n){if(!rm(n))return null;let e=jo(n,["osVersion","OsVersion","OSVersion"]),t=jo(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=jo(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function Vn(n){let e=n.trim();if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let r=[];for(let o of t){if(!o||typeof o!="object")continue;let i=om(o);i&&r.push(i)}return r}catch{return[]}}function ia(n){let t=Vn(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var sa=/no images are available/i;function he(n){return n.normalize("NFKC").trim().toLowerCase()}function im(n){let e=n.message||"";return sa.test(e)}var wt=class n{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 Fo(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 oa(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),o=t.find(a=>V(a.name)===r);if(!o)throw new Error(`Emulator "${e}" not found.`);let i=o.name;if(await this.isAlreadyRunning(i,o))return"already-running";await this.assertSystemImageAvailable(o);let s=await na(i,o,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return"started";if(await this.isAlreadyRunning(i))return"already-running";throw new Error(`Unable to start emulator "${e}". All methods failed.
59
+ Last error: ${s.lastError.message||"unknown"}`)}async isAlreadyRunning(e,t){return t?.isRunning===!0||t===void 0&&(await this.listEmulators()).find(o=>o.name===e)?.isRunning===!0?!0:ra(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=V(e),o=t.find(a=>V(a.name)===r);if(!o)throw new Error(`Emulator "${e}" not found.`);let i=o.name;return await this.isAlreadyRunning(i,o)?(await this.executeEmulator(["-stop",i]),"stopped"):"already-stopped"}async executeEmulatorInherit(e){let{exitCode:t}=await Fo(this.emulatorPath,e,{stdio:"inherit",env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1});if(t!==0)throw new Error(`Emulator exited with code ${t===null?"null":t}.`)}async installEmulatorImage(e){let t=["-install","-deviceType",e.deviceType,"-osVersion",e.osVersion];e.force&&t.push("-force"),await this.executeEmulatorInherit(t)}async uninstallEmulatorImage(e){let t=await this.resolveSoftwareVersionsForUninstall(e);if(t.length===0)throw new Error(`No downloaded image matches --os-version "${e.osVersion}" for --device-type "${e.deviceType}".`);let r;try{await this.runUninstallImageChecked(e.deviceType,e.osVersion)}catch(i){if(!im(i))throw i;r=i}(r!==void 0||await this.hasMatchingDownloadedImage(e))&&await this.runSoftwareVersionFallback(e,t,r)}async listEmulatorImages(e){let t=["-imageList"];e.deviceType&&t.push("-deviceType",e.deviceType),e.downloaded!==void 0&&t.push("-downloaded",e.downloaded?"true":"false");let{stdout:r}=await this.executeEmulator(t);return r}async listDownloadedImageOsVersions(){let e=await this.listEmulatorImages({downloaded:!0});return ia(e)}async hasMatchingDownloadedImage(e){return(await this.findMatchingDownloadedImages(e)).length>0}async runSoftwareVersionFallback(e,t,r){try{for(let o of t)await this.runUninstallImageChecked(e.deviceType,o)}catch(o){let i=r!==void 0?`Primary uninstall failed: ${r.message}
60
60
  `:"";throw new Error(`${i}Fallback uninstall failed: ${o.message}`,{cause:o})}if(await this.hasMatchingDownloadedImage(e))throw new Error(`Image for --device-type "${e.deviceType}" and --os-version "${e.osVersion}" remains listed as downloaded after uninstallation.`)}async resolveSoftwareVersionsForUninstall(e){let t=await this.findMatchingDownloadedImages(e);return[...new Set(t.map(r=>r.softwareVersion).filter(Boolean))]}async findMatchingDownloadedImages(e){let t=await this.listEmulatorImages({deviceType:e.deviceType,downloaded:!0}),r=Vn(t),o=he(e.deviceType),i=he(e.osVersion);return r.filter(s=>he(s.deviceType)===o&&(he(s.osVersion)===i||he(s.softwareVersion)===i))}async hasDownloadedSystemImage(e,t){let r=await this.listEmulatorImages({downloaded:!0}),o=Vn(r),i=he(t),s=e?.trim()?he(e):void 0;return o.some(a=>he(a.osVersion)===i||he(a.softwareVersion)===i?s===void 0?!0:he(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){let{stdout:r,stderr:o,exitCode:i}=await Fo(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:20971520}),s=[r,o].filter(Boolean).join(`
61
61
  `).trim(),a=/Invalid command|无效命令|鏃犳晥鍛戒护/i.test(s)||/please attach the correct parameter/i.test(s),c=(t?.extraReject??[]).some(u=>u.test(s));if(i!==0||a||c)throw new Error(s||`emulator exited with code ${i===null?"null":i}`);if(t?.printOutputOnSuccess!==!1&&s){let u=(t?.transformOutput?t.transformOutput(s):s).trim();u&&console.log(u)}}async checkExistingVirtualDevice(e,t){let r=await this.listEmulators(),o=V(e),i=r.find(s=>V(s.name)===o);if(i)if(t)await this.deleteVirtualDevice(i.name);else throw new Error(`Emulator "${e}" already exists. Use \`--force\` to overwrite.`);return o}async createVirtualDevice(e){let t=await this.checkExistingVirtualDevice(e.name,e.force),r=["-create",e.name,"-deviceType",e.deviceType,"-osVersion",e.osVersion];if(await this.runEmulatorChecked(r,{extraReject:[/Device create fail/i,/already exists/i,/Invalid OS version/i,/cannot be empty/i],printOutputOnSuccess:!0,transformOutput:i=>i.split(/\r?\n/).map(s=>s.trim().startsWith("Device create success.")?"Device create success.":s).join(`
62
62
  `)}),!await this.waitForEmulatorPresenceByList(t))throw new Error(`Emulator "${e.name}" was reported as created, but it did not appear in the emulator list within the waiting period. Open the device manager list in DevEco Studio, then run this command again.`)}async waitForEmulatorPresenceByList(e,t=1e4,r=500){let o=Date.now()+t;for(;Date.now()<o;){if((await this.listEmulators()).some(a=>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),o=t.find(s=>V(s.name)===r);if(!o)throw new Error(`Emulator "${e}" not found.`);let i=o.name;if(o.isRunning===!0||await this.isAlreadyRunning(i,o))throw new Error(`Failed to delete device: ${i}
63
- The device may be running.`);return await this.runEmulatorChecked(["-delete",i,"-force"],{printOutputOnSuccess:!1}),i}};import{red as $o,yellow as ca,gray as la}from"colorette";import lm from"ora";import{red as im}from"colorette";function Gn(n,e){n?n.fail(e):console.error(im(e)),process.exit(1)}import{green as sm}from"colorette";function aa(n,e){return n+" ".repeat(Math.max(0,e-n.length))}function am(n,e){return n.map((t,r)=>{let o=t.length;for(let i of e){let s=i.cells[r]??"";o=Math.max(o,s.length)}return o})}function Zt(n,e){let t=am(n,e),r=[];r.push(n.map((o,i)=>aa(o,t[i])).join(" ")),r.push(t.map(o=>"-".repeat(o)).join(" "));for(let o of e){let i=o.cells.map((s,a)=>aa(s??"",t[a])).join(" ").trimEnd();r.push(o.highlight?sm(i):i)}return r.join(`
64
- `)}function dm(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 um=["Name","Serial","Kind","Device Type"];function pm(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function mm(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function fm(){console.log(ca(" No active devices.")),console.log(la(D()?" Connect a USB device with debugging enabled.":" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function hm(n){let t=[...n].sort(mm).map(pm);console.log(Zt(um,t))}async function gm(n,e){if(D()||!n.some(o=>o.isEmulator)||!e.emulatorPath)return;let r=await wt.from(e).getDeviceTypeByName();dm(n,r)}async function ym(n,e,t){try{let r=await n.getConnectedEntries();await gm(r,e),t?.stop(),r.length===0?fm():hm(r)}catch(r){Gn(t,`Failed to list devices: ${r.message}`)}}async function vm(n,e){let t=await n.listDevices();if(!(t.length<2)){console.error($o("Multiple devices connected. Specify a device with:"));for(let r of t){let o=await n.getDeviceName(r.serial);console.error(la(` ${e} -t ${r.serial} # ${o}`))}process.exit(1)}}async function wm(n,e){try{e||await vm(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 o=await n.getDeviceDetail(r.serial),i=await n.getDeviceName(r.serial);console.log(` Serial: ${r.serial}`),console.log(` Device Name: ${i}`),o.deviceType&&console.log(` Device Type: ${o.deviceType}`),o.osVersion&&console.log(` OS Version: ${o.osVersion}`)}catch(t){console.error($o(`Failed to show device details: ${t.message}`)),process.exit(1)}}async function da(){try{let n=await _.new();return{manager:K.from(n),toolProvider:n}}catch(n){console.error($o(`Failed to initialize device manager: ${n.message}`)),process.exit(1);return}}var Bo=new cm("device").description("Manage connected devices");Bo.command("list").description("List all connected devices").action(async()=>{let{manager:n,toolProvider:e}=await da(),t=lm({text:"Querying connected devices\u2026",color:"cyan"}).start();await ym(n,e,t)});Bo.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 wm(e,n.target)});var ua=Bo;import{Command as Vo,Option as Ca}from"commander";import{green as Jn,cyan as St,red as te,yellow as ge,gray as Qt}from"colorette";import jm from"ora";import bm from"readline/promises";import{execa as ma}from"execa";import*as je from"fs/promises";import*as Uo from"os";import*as et from"path";var Wo=`1/4:\r
63
+ The device may be running.`);return await this.runEmulatorChecked(["-delete",i,"-force"],{printOutputOnSuccess:!1}),i}};import{red as $o,yellow as ca,gray as la}from"colorette";import dm from"ora";import{red as sm}from"colorette";function Gn(n,e){n?n.fail(e):console.error(sm(e)),process.exit(1)}import{green as am}from"colorette";function aa(n,e){return n+" ".repeat(Math.max(0,e-n.length))}function cm(n,e){return n.map((t,r)=>{let o=t.length;for(let i of e){let s=i.cells[r]??"";o=Math.max(o,s.length)}return o})}function Zt(n,e){let t=cm(n,e),r=[];r.push(n.map((o,i)=>aa(o,t[i])).join(" ")),r.push(t.map(o=>"-".repeat(o)).join(" "));for(let o of e){let i=o.cells.map((s,a)=>aa(s??"",t[a])).join(" ").trimEnd();r.push(o.highlight?am(i):i)}return r.join(`
64
+ `)}function um(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 pm=["Name","Serial","Kind","Device Type"];function mm(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function fm(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function hm(){console.log(ca(" No active devices.")),console.log(la(D()?" Connect a USB device with debugging enabled.":" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function gm(n){let t=[...n].sort(fm).map(mm);console.log(Zt(pm,t))}async function ym(n,e){if(D()||!n.some(o=>o.isEmulator)||!e.emulatorPath)return;let r=await wt.from(e).getDeviceTypeByName();um(n,r)}async function vm(n,e,t){try{let r=await n.getConnectedEntries();await ym(r,e),t?.stop(),r.length===0?hm():gm(r)}catch(r){Gn(t,`Failed to list devices: ${r.message}`)}}async function wm(n,e){let t=await n.listDevices();if(!(t.length<2)){console.error($o("Multiple devices connected. Specify a device with:"));for(let r of t){let o=await n.getDeviceName(r.serial);console.error(la(` ${e} -t ${r.serial} # ${o}`))}process.exit(1)}}async function bm(n,e){try{e||await wm(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 o=await n.getDeviceDetail(r.serial),i=await n.getDeviceName(r.serial);console.log(` Serial: ${r.serial}`),console.log(` Device Name: ${i}`),o.deviceType&&console.log(` Device Type: ${o.deviceType}`),o.osVersion&&console.log(` OS Version: ${o.osVersion}`)}catch(t){console.error($o(`Failed to show device details: ${t.message}`)),process.exit(1)}}async function da(){try{let n=await _.new();return{manager:K.from(n),toolProvider:n}}catch(n){console.error($o(`Failed to initialize device manager: ${n.message}`)),process.exit(1);return}}var Bo=new lm("device").description("Manage connected devices");Bo.command("list").description("List all connected devices").action(async()=>{let{manager:n,toolProvider:e}=await da(),t=dm({text:"Querying connected devices\u2026",color:"cyan"}).start();await vm(n,e,t)});Bo.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 bm(e,n.target)});var ua=Bo;import{Command as Vo,Option as Ca}from"commander";import{green as Jn,cyan as St,red as te,yellow as ge,gray as Qt}from"colorette";import Fm from"ora";import Sm from"readline/promises";import{execa as ma}from"execa";import*as je from"fs/promises";import*as Uo from"os";import*as et from"path";var Wo=`1/4:\r
65
65
  ---------------------------------------\r
66
66
  Statement About HarmonyOS and Privacy\r
67
67
  \r
@@ -1231,61 +1231,61 @@ Part I: Chinese mainland.\r
1231
1231
  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
1232
1232
  \r
1233
1233
  Part III: Other countries and regions.\r
1234
- ---------------------------------------\r`;var Sm=new Set,Yn=new Map,zo="HarmonyOS_Software_Service_Agreement",fa=["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(`
1235
- `),ha=fa,qo="HarmonyOS_SDK_Agreement";function ga(n,e){return`${n}\0${e}`}function Pm(){Sm.clear(),Yn.clear()}var Em=fa,de=class extends Error{constructor(e=Em){super(e),this.name="EmulatorLicenseBlockedError"}};function ya(n,e){return[n??"",e??""].join(`
1236
- `)}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 Im(n){return`Emulator${n.trim()}`}function wa(n){let e=Im(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 et.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return et.join(Uo.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||et.join(Uo.homedir(),".cache");return et.join(t,"Huawei",e,".emu_config")}async function Dm(n,e,t){let r=ga(n,e),o=Yn.get(r);if(o!==void 0)return o;let i=await ma(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=ya(i.stdout,i.stderr).trim();if(i.exitCode!==0||!s)throw new de(t);return Yn.set(r,s),s}function Cm(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function Am(n){try{let e=JSON.parse(n);if(e&&typeof e=="object"&&!Array.isArray(e)){let t={};for(let[r,o]of Object.entries(e))t[r]={value:typeof o=="string"?o:String(o),delimiter:"json"};return t}}catch{return}}function Tm(n){let e=n.trim();if(!(!e||e.startsWith("#")))for(let t of["=",":"]){let r=e.indexOf(t);if(r<=0)continue;let o=e.slice(0,r).trim();if(!o||t===":"&&o.includes("//"))continue;let i=Cm(e.slice(r+1).trim());return{key:o,entry:{value:i,delimiter:t}}}}function xm(n){let e={};for(let t of n.split(/\r?\n/)){let r=Tm(t);r&&(e[r.key]=r.entry)}return e}function km(n){let e=n.trim();if(!e)return{};let t=Am(e);return t||xm(n)}function Mm(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function ba(n,e,t,r){let o=await Dm(n,e,r),i=va(o);if(!i)throw new de(r);let s=wa(i),a;try{a=await je.readFile(s,"utf8")}catch(u){throw u.code==="ENOENT"?new de(r):u}let l=km(a)[t];if(!l)throw new de(r);if(l.delimiter==="=")throw new de(r);if(!Mm(l.value))throw new de(r)}async function Sa(n,e){await ba(n,e,zo,ha)}async function Pa(n,e){await ba(n,e,qo,ha)}async function Rm(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 o=ga(n,e);return Yn.set(o,r),r}async function Om(n,e){let t=await Rm(n,e),r=va(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
1237
- ${t}.`);return wa(r)}function pa(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function Nm(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[zo]="agree",r[qo]="agree",await je.writeFile(n,`${JSON.stringify(r,null,2)}
1238
- `,"utf8"),!0}catch{}return!1}async function Lm(n,e){let t=zo,r=qo,o=[{k:t,re:new RegExp(`^\\s*${pa(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${pa(r)}\\s*[:=]`)}],i=e.length===0?[]:e.split(/\r?\n/),s=[],a=new Set;for(let c of i){let l=!1;for(let{k:u,re:h}of o)if(h.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(`
1234
+ ---------------------------------------\r`;var Pm=new Set,Yn=new Map,zo="HarmonyOS_Software_Service_Agreement",fa=["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(`
1235
+ `),ha=fa,qo="HarmonyOS_SDK_Agreement";function ga(n,e){return`${n}\0${e}`}function Em(){Pm.clear(),Yn.clear()}var Im=fa,de=class extends Error{constructor(e=Im){super(e),this.name="EmulatorLicenseBlockedError"}};function ya(n,e){return[n??"",e??""].join(`
1236
+ `)}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 Dm(n){return`Emulator${n.trim()}`}function wa(n){let e=Dm(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 et.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return et.join(Uo.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||et.join(Uo.homedir(),".cache");return et.join(t,"Huawei",e,".emu_config")}async function Cm(n,e,t){let r=ga(n,e),o=Yn.get(r);if(o!==void 0)return o;let i=await ma(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=ya(i.stdout,i.stderr).trim();if(i.exitCode!==0||!s)throw new de(t);return Yn.set(r,s),s}function Am(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function Tm(n){try{let e=JSON.parse(n);if(e&&typeof e=="object"&&!Array.isArray(e)){let t={};for(let[r,o]of Object.entries(e))t[r]={value:typeof o=="string"?o:String(o),delimiter:"json"};return t}}catch{return}}function xm(n){let e=n.trim();if(!(!e||e.startsWith("#")))for(let t of["=",":"]){let r=e.indexOf(t);if(r<=0)continue;let o=e.slice(0,r).trim();if(!o||t===":"&&o.includes("//"))continue;let i=Am(e.slice(r+1).trim());return{key:o,entry:{value:i,delimiter:t}}}}function km(n){let e={};for(let t of n.split(/\r?\n/)){let r=xm(t);r&&(e[r.key]=r.entry)}return e}function Mm(n){let e=n.trim();if(!e)return{};let t=Tm(e);return t||km(n)}function Rm(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function ba(n,e,t,r){let o=await Cm(n,e,r),i=va(o);if(!i)throw new de(r);let s=wa(i),a;try{a=await je.readFile(s,"utf8")}catch(u){throw u.code==="ENOENT"?new de(r):u}let l=Mm(a)[t];if(!l)throw new de(r);if(l.delimiter==="=")throw new de(r);if(!Rm(l.value))throw new de(r)}async function Sa(n,e){await ba(n,e,zo,ha)}async function Pa(n,e){await ba(n,e,qo,ha)}async function Om(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 o=ga(n,e);return Yn.set(o,r),r}async function Nm(n,e){let t=await Om(n,e),r=va(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
1237
+ ${t}.`);return wa(r)}function pa(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function Lm(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[zo]="agree",r[qo]="agree",await je.writeFile(n,`${JSON.stringify(r,null,2)}
1238
+ `,"utf8"),!0}catch{}return!1}async function _m(n,e){let t=zo,r=qo,o=[{k:t,re:new RegExp(`^\\s*${pa(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${pa(r)}\\s*[:=]`)}],i=e.length===0?[]:e.split(/\r?\n/),s=[],a=new Set;for(let c of i){let l=!1;for(let{k:u,re:h}of o)if(h.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(`
1239
1239
  `)+(s.length>0?`
1240
- `:""),"utf8")}async function _m(n){await je.mkdir(et.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 Nm(n,e,t)||await Lm(n,e)}async function Ea(n,e){return console.log(Wo),0}var Hm="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function Ia(n,e){if(console.log(Wo),!process.stdin.isTTY||!process.stdout.isTTY)return console.error("`devecocli emulator license accept` requires an interactive terminal."),1;let r=bm.createInterface({input:process.stdin,output:process.stdout}),o;try{o=await r.question(Hm)}finally{r.close()}let i=o.trim().toLowerCase();if(i!=="y"&&i!=="yes")return 1;try{let s=await Om(n,e);await _m(s),Pm()}catch(s){return console.error(s.message),1}return 0}var Fm=["ohos.qemu.hvd.name","const.product.name","const.product.model"];function $m(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 Bm(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 Wm(n,e){let t=o=>o.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(ge("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(ge("Run `devecocli emulator image download ...` followed by `devecocli emulator image list` and then copy an `osVersion` string exactly.")),new Error("No downloaded osVersion values parsed; cannot validate --os-version.");if(!e.some(o=>t(o)===r)){console.error(te("--os-version does not match any downloaded image (exact string required).")),console.log(ge("Use one of these --os-version values:"));for(let o of e)console.log(` ${o}`);throw new Error(`No downloaded image matches --os-version "${n}".`)}}var Um=["Name","Status","Serial","Device Type","OS Version"];function zm(n,e,t){return{cells:[n.name,t?"running":"stopped",e??"-",n.deviceType??"-",n.osVersion??"-"],highlight:t}}async function qm(n,e){let t=await Promise.all(e.map(async r=>{let o=await ft(n,r,Fm);return[r,o]}));return new Map(t)}async function Vm(n){let e=await _o(n),t=await qm(n,e);return{serials:e,params:t}}function Gm(n,e,t,r,o){if(e)for(let i of["const.product.name","const.product.model"]){let s=e.get(i);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),o.set(s,n);let c=r.indexOf(n);c!==-1&&r.splice(c,1);return}}function Ym(n,e,t){let r=new Map,o=new Map,i=[...n],s=[...t];for(let a of n){let c=e.get(a),l=c?.get("ohos.qemu.hvd.name");l&&o.set(l,a),t.length>0&&Gm(a,c,s,i,r)}for(let a=0;a<s.length&&a<i.length;a++)r.set(s[a],i[a]);return{productSerialMap:r,hvdSerialMap:o}}function Jm(n,e,t){let r=n.map(o=>({emu:o,serial:e.get(o.name)??t.get(o.name),effectiveRunning:o.isRunning===!0||t.has(o.name)}));return r.sort((o,i)=>o.effectiveRunning!==i.effectiveRunning?o.effectiveRunning?-1:1:o.emu.name.localeCompare(i.emu.name)),r.map(o=>zm(o.emu,o.serial,o.effectiveRunning))}async function Km(n,e,t){try{let[r,o]=await Promise.all([n.listEmulators(),Vm(e)]);if(r.length===0){t?.stop(),console.log(ge(" No emulator instances found."));return}let i=r.filter(l=>l.isRunning).map(l=>l.name),{productSerialMap:s,hvdSerialMap:a}=Ym(o.serials,o.params,i);t?.stop();let c=Jm(r,s,a);console.log(Zt(Um,c))}catch(r){Gn(t,`Failed to list emulators: ${r.message}`)}}function Aa(n,e,t){let r=!1;for(let o=0;o<n.length;o++){let i=n[o];if(i.status!=="rejected")continue;r=!0;let s=i.reason;console.error(te(`Failed to ${t} emulator "${e[o]}": ${s.message}`)),s.stdout&&console.error(Qt(s.stdout)),s.stderr&&console.error(Qt(s.stderr))}return r}var Zm=2e3,Xm=6e4;async function Qm(n,e){let t=V(e);return(await Ho(n)).some(o=>V(o)===t)}async function Ta(n,e,t,r=Xm,o=Zm){let i=Date.now()+r;for(;Date.now()<i;){if(await Qm(n,e)===t)return!0;await new Promise(a=>setTimeout(a,o))}return!1}async function ef(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(ge(`Emulator "${t}" is already running.`));return}console.log(St(`Starting emulator "${t}"...`));let o=await Ta(e,t,!0);console.log(o?Jn(`Emulator "${t}" started successfully.`):ge(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function tf(n,e,t){let r=await Promise.allSettled(t.map(i=>ef(n,e,i)));Aa(r,t,"start")&&process.exit(1)}async function nf(n,e){let t=e.trim();if(!Yt(t))return t;let r=await K.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 rf(n,e,t){let r=await nf(e,t);if(console.log(St(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(ge(`Emulator "${r}" is already stopped.`));return}let i=await Ta(e,r,!1);console.log(i?Jn(`Emulator "${r}" stopped successfully.`):ge(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function of(n,e,t){let r=await Promise.allSettled(t.map(i=>rf(n,e,i)));Aa(r,t,"stop")&&process.exit(1)}async function ye(){try{let n=await _.new();return{manager:wt.from(n),toolProvider:n}}catch(n){console.error(te(`Failed to initialize emulator: ${n.message}`)),process.exit(1);return}}var Fe=new Vo("emulator").description("Manage emulator instances"),sf=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Kn(n){let e=new Ca("--device-type <type>","Emulator device type").choices([...sf]);return n?e.makeOptionMandatory():e}function bt(n,e){for(let t of e)if(t in n)return n[t]}function Xt(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function Da(n){let e=Xt(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var af=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],cf="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function xa(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function ka(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let o=r,i=Xt(bt(o,["osVersion","OsVersion","OSVersion","os_version"])),s=Xt(bt(o,["deviceType","DeviceType","device_type"])),a=Da(bt(o,["downloaded","Downloaded","isDownloaded"])),c=Xt(bt(o,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=Xt(bt(o,["releaseType","ReleaseType","release_type"])),u=Da(bt(o,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[i,s,c,l,u,a],highlight:e&&a==="true"})}return t}function lf(n){let e=n.trim();if(!e)return!0;let t=xa(e);return t===null?!1:t.length===0?!0:ka(t,!0).length===0}function df(n,e){let t=n.trim();if(!t)return"";let r=xa(t);if(!r)return n.trimEnd();let o=ka(r,e);return Zt(af,o)}var Zn=new Vo("image").description("HarmonyOS emulator system images (download, list, remove)");Zn.command("download").description("Download system image").addOption(Kn(!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 ye();try{await Pa(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof de&&(console.error(te(r.message)),process.exit(1)),r}n.deviceType?.trim()||(console.error(te("Error: missing required option '--device-type <type>'")),process.exit(1)),n.osVersion?.trim()||(console.error(te("Error: misssing required option '--os-version <version>'")),process.exit(1));try{await e.installEmulatorImage({deviceType:n.deviceType.trim(),osVersion:n.osVersion.trim(),force:n.force===!0})}catch(r){console.error(te(`Failed to download system image: ${r.message}`)),process.exit(1)}});Zn.command("remove").description("Remove a downloaded system image").addOption(Kn(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let{manager:e}=await ye();try{await e.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})}catch(t){console.error(te(`Failed to remove system image: ${t.message}`)),process.exit(1)}});Zn.command("list").description("List system images").addOption(Kn(!1)).option("--all","List all images (local and remote)").addOption(new Ca("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await ye();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if(lf(r)){console.log(ge(cf));return}if(n.format==="json"){console.log(r.trimEnd());return}let o=df(r,n.all===!0);console.log(o)}catch(t){console.error(te(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});Fe.addCommand(Zn);var Go=new Vo("license").description("local emulator license");Go.command("view").description("Review agreement text(read-only)").action(async()=>{let{toolProvider:n}=await ye(),e=await Ea(n.emulatorPath,n.sdkPath);process.exit(e)});Go.command("accept").description("Review and accept agreements").action(async()=>{let{toolProvider:n}=await ye(),e=await Ia(n.emulatorPath,n.sdkPath);process.exit(e)});Fe.addCommand(Go);Fe.command("list").description("List all emulator instances").action(async()=>{let{manager:n,toolProvider:e}=await ye(),t=jm({text:"Listing emulators\u2026",color:"cyan"}).start();await Km(n,e.hdcPath,t)});Fe.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await ye();try{await Sa(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof de&&(console.error(te(r.message)),process.exit(1)),r}n?.length||(console.error(te("Error: missing required argument 'names'")),process.exit(1)),await tf(e,t.hdcPath,n)});Fe.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 ye();n?.length||(console.error(te("Error: missing required argument 'names'")),process.exit(1)),await of(e,t.hdcPath,n)});var Ma=Fe.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(Kn(!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");Ma.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
1240
+ `:""),"utf8")}async function Hm(n){await je.mkdir(et.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 Lm(n,e,t)||await _m(n,e)}async function Ea(n,e){return console.log(Wo),0}var jm="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function Ia(n,e){if(console.log(Wo),!process.stdin.isTTY||!process.stdout.isTTY)return console.error("`devecocli emulator license accept` requires an interactive terminal."),1;let r=Sm.createInterface({input:process.stdin,output:process.stdout}),o;try{o=await r.question(jm)}finally{r.close()}let i=o.trim().toLowerCase();if(i!=="y"&&i!=="yes")return 1;try{let s=await Nm(n,e);await Hm(s),Em()}catch(s){return console.error(s.message),1}return 0}var $m=["ohos.qemu.hvd.name","const.product.name","const.product.model"];function Bm(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 Wm(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 Um(n,e){let t=o=>o.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(ge("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(ge("Run `devecocli emulator image download ...` followed by `devecocli emulator image list` and then copy an `osVersion` string exactly.")),new Error("No downloaded osVersion values parsed; cannot validate --os-version.");if(!e.some(o=>t(o)===r)){console.error(te("--os-version does not match any downloaded image (exact string required).")),console.log(ge("Use one of these --os-version values:"));for(let o of e)console.log(` ${o}`);throw new Error(`No downloaded image matches --os-version "${n}".`)}}var zm=["Name","Status","Serial","Device Type","OS Version"];function qm(n,e,t){return{cells:[n.name,t?"running":"stopped",e??"-",n.deviceType??"-",n.osVersion??"-"],highlight:t}}async function Vm(n,e){let t=await Promise.all(e.map(async r=>{let o=await ft(n,r,$m);return[r,o]}));return new Map(t)}async function Gm(n){let e=await _o(n),t=await Vm(n,e);return{serials:e,params:t}}function Ym(n,e,t,r,o){if(e)for(let i of["const.product.name","const.product.model"]){let s=e.get(i);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),o.set(s,n);let c=r.indexOf(n);c!==-1&&r.splice(c,1);return}}function Jm(n,e,t){let r=new Map,o=new Map,i=[...n],s=[...t];for(let a of n){let c=e.get(a),l=c?.get("ohos.qemu.hvd.name");l&&o.set(l,a),t.length>0&&Ym(a,c,s,i,r)}for(let a=0;a<s.length&&a<i.length;a++)r.set(s[a],i[a]);return{productSerialMap:r,hvdSerialMap:o}}function Km(n,e,t){let r=n.map(o=>({emu:o,serial:e.get(o.name)??t.get(o.name),effectiveRunning:o.isRunning===!0||t.has(o.name)}));return r.sort((o,i)=>o.effectiveRunning!==i.effectiveRunning?o.effectiveRunning?-1:1:o.emu.name.localeCompare(i.emu.name)),r.map(o=>qm(o.emu,o.serial,o.effectiveRunning))}async function Zm(n,e,t){try{let[r,o]=await Promise.all([n.listEmulators(),Gm(e)]);if(r.length===0){t?.stop(),console.log(ge(" No emulator instances found."));return}let i=r.filter(l=>l.isRunning).map(l=>l.name),{productSerialMap:s,hvdSerialMap:a}=Jm(o.serials,o.params,i);t?.stop();let c=Km(r,s,a);console.log(Zt(zm,c))}catch(r){Gn(t,`Failed to list emulators: ${r.message}`)}}function Aa(n,e,t){let r=!1;for(let o=0;o<n.length;o++){let i=n[o];if(i.status!=="rejected")continue;r=!0;let s=i.reason;console.error(te(`Failed to ${t} emulator "${e[o]}": ${s.message}`)),s.stdout&&console.error(Qt(s.stdout)),s.stderr&&console.error(Qt(s.stderr))}return r}var Xm=2e3,Qm=6e4;async function ef(n,e){let t=V(e);return(await Ho(n)).some(o=>V(o)===t)}async function Ta(n,e,t,r=Qm,o=Xm){let i=Date.now()+r;for(;Date.now()<i;){if(await ef(n,e)===t)return!0;await new Promise(a=>setTimeout(a,o))}return!1}async function tf(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(ge(`Emulator "${t}" is already running.`));return}console.log(St(`Starting emulator "${t}"...`));let o=await Ta(e,t,!0);console.log(o?Jn(`Emulator "${t}" started successfully.`):ge(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function nf(n,e,t){let r=await Promise.allSettled(t.map(i=>tf(n,e,i)));Aa(r,t,"start")&&process.exit(1)}async function rf(n,e){let t=e.trim();if(!Yt(t))return t;let r=await K.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 of(n,e,t){let r=await rf(e,t);if(console.log(St(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(ge(`Emulator "${r}" is already stopped.`));return}let i=await Ta(e,r,!1);console.log(i?Jn(`Emulator "${r}" stopped successfully.`):ge(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function sf(n,e,t){let r=await Promise.allSettled(t.map(i=>of(n,e,i)));Aa(r,t,"stop")&&process.exit(1)}async function ye(){try{let n=await _.new();return{manager:wt.from(n),toolProvider:n}}catch(n){console.error(te(`Failed to initialize emulator: ${n.message}`)),process.exit(1);return}}var Fe=new Vo("emulator").description("Manage emulator instances"),af=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Kn(n){let e=new Ca("--device-type <type>","Emulator device type").choices([...af]);return n?e.makeOptionMandatory():e}function bt(n,e){for(let t of e)if(t in n)return n[t]}function Xt(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function Da(n){let e=Xt(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var cf=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],lf="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function xa(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function ka(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let o=r,i=Xt(bt(o,["osVersion","OsVersion","OSVersion","os_version"])),s=Xt(bt(o,["deviceType","DeviceType","device_type"])),a=Da(bt(o,["downloaded","Downloaded","isDownloaded"])),c=Xt(bt(o,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=Xt(bt(o,["releaseType","ReleaseType","release_type"])),u=Da(bt(o,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[i,s,c,l,u,a],highlight:e&&a==="true"})}return t}function df(n){let e=n.trim();if(!e)return!0;let t=xa(e);return t===null?!1:t.length===0?!0:ka(t,!0).length===0}function uf(n,e){let t=n.trim();if(!t)return"";let r=xa(t);if(!r)return n.trimEnd();let o=ka(r,e);return Zt(cf,o)}var Zn=new Vo("image").description("HarmonyOS emulator system images (download, list, remove)");Zn.command("download").description("Download system image").addOption(Kn(!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 ye();try{await Pa(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof de&&(console.error(te(r.message)),process.exit(1)),r}n.deviceType?.trim()||(console.error(te("Error: missing required option '--device-type <type>'")),process.exit(1)),n.osVersion?.trim()||(console.error(te("Error: misssing required option '--os-version <version>'")),process.exit(1));try{await e.installEmulatorImage({deviceType:n.deviceType.trim(),osVersion:n.osVersion.trim(),force:n.force===!0})}catch(r){console.error(te(`Failed to download system image: ${r.message}`)),process.exit(1)}});Zn.command("remove").description("Remove a downloaded system image").addOption(Kn(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let{manager:e}=await ye();try{await e.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})}catch(t){console.error(te(`Failed to remove system image: ${t.message}`)),process.exit(1)}});Zn.command("list").description("List system images").addOption(Kn(!1)).option("--all","List all images (local and remote)").addOption(new Ca("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await ye();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if(df(r)){console.log(ge(lf));return}if(n.format==="json"){console.log(r.trimEnd());return}let o=uf(r,n.all===!0);console.log(o)}catch(t){console.error(te(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});Fe.addCommand(Zn);var Go=new Vo("license").description("local emulator license");Go.command("view").description("Review agreement text(read-only)").action(async()=>{let{toolProvider:n}=await ye(),e=await Ea(n.emulatorPath,n.sdkPath);process.exit(e)});Go.command("accept").description("Review and accept agreements").action(async()=>{let{toolProvider:n}=await ye(),e=await Ia(n.emulatorPath,n.sdkPath);process.exit(e)});Fe.addCommand(Go);Fe.command("list").description("List all emulator instances").action(async()=>{let{manager:n,toolProvider:e}=await ye(),t=Fm({text:"Listing emulators\u2026",color:"cyan"}).start();await Zm(n,e.hdcPath,t)});Fe.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await ye();try{await Sa(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof de&&(console.error(te(r.message)),process.exit(1)),r}n?.length||(console.error(te("Error: missing required argument 'names'")),process.exit(1)),await nf(e,t.hdcPath,n)});Fe.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 ye();n?.length||(console.error(te("Error: missing required argument 'names'")),process.exit(1)),await sf(e,t.hdcPath,n)});var Ma=Fe.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(Kn(!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");Ma.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
1241
1241
  ${ge("Tip: ")}${Qt("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
1242
1242
  ${St('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
1243
1243
  ${St('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
1244
- `)}});Ma.action(async(n,e)=>{try{$m(n),Bm(e.osVersion);let{manager:t}=await ye(),r=await t.listDownloadedImageOsVersions();Wm(e.osVersion,r),console.log(St(`Creating emulator "${n}"...`)),await t.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(Jn(`Emulator "${n}" created successfully.`))}catch(t){console.error(te(`${t.message}`)),process.exit(1)}});Fe.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let{manager:e}=await ye();console.log(St(`Deleting emulator "${n}"...`));try{let t=await e.deleteVirtualDevice(n);console.log(Jn(`Emulator "${t}" deleted successfully.`))}catch(t){let r=t;console.error(te(r.message)),r.stdout&&console.error(Qt(r.stdout)),r.stderr&&console.error(Qt(r.stderr)),process.exit(1)}});var Ra=Fe;import{Command as If}from"commander";import{green as Df,red as on,cyan as ec,yellow as tc,dim as nc}from"colorette";import Cf from"p-limit";import uf from"ora";var tt=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=uf(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 Na from"path";import pf from"axios";var Yo=class{client;constructor(){let e={timeout:To.HTTP_TIMEOUT_MS,headers:{"User-Agent":jn.USER_AGENT,"accept-language":jn.ACCEPT_LANGUAGE},transformResponse:[t=>t],proxy:!1};this.client=pf.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}
1245
- ${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 Yo;var La=["DevEco"];async function Xn(){let n=await $e.get(ce.TAGS_API_URL),t=Qn(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 mf(n){let e=[],t=ce.DEFAULT_PAGE_SIZE,r=1;for(;;){let o=await $e.post(ce.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:r,pageSize:t,tagIds:[n]}}),i=Qn(o,"Skills API");if(e.push(...i.data.list),i.data.list.length<t)break;r++}return e}async function Jo(n){let e=new Map,t=n.map(o=>mf(o)),r=await Promise.all(t);for(let o of r)for(let i of o)e.has(i.id)||e.set(i.id,i);return Array.from(e.values()).filter(o=>o.tags?.every(i=>!La.includes(i.name)))}async function ff(n,e){let t=await $e.post(ce.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:ce.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return Qn(t,"Skills API").data.list}async function Ko(n,e){let t=new Map,r=e.map(i=>ff(n,i)),o=await Promise.all(r);for(let i of o)for(let s of i)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(i=>i.tags?.every(s=>!La.includes(s.name)))}function _a(n){let e=[],t=Pe();for(let[,r]of Object.entries(t)){let o=Na.join(r.path,n);Oa.existsSync(o)&&e.push(r.displayName)}return e.sort()}function Qn(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=$e.parseJson(n);if(t.code!==ce.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Ha(n){let e=`${ce.SKILL_API_BASE}/${n}/checksum`,t=await $e.get(e);return Qn(t,"Checksum API").data}import hf from"adm-zip";import gf from"crypto";import Fa from"fs";import H from"path";import{fileURLToPath as yf}from"url";import{red as vf}from"colorette";var Ee=Fa.promises;function Zo(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function ja(n,e){let t=H.resolve(e),r=H.resolve(n),o=H.relative(r,t);if(o.startsWith("..")||H.isAbsolute(o))throw new Error(`Path traversal detected: ${e}.`)}function Xo(n){return H.isAbsolute(n)?n:H.resolve(process.cwd(),n)}function wf(n){return gf.createHash("sha256").update(n).digest("hex")}async function bf(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=wf(n),o=e.sha256.toLowerCase();if(r!==o)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function $a(n){let e=`${ce.SKILL_API_BASE}/${n}/install?format=zip`,t=await $e.getBinary(e),r=await Ha(n);return await bf(t,r),t}async function Sf(n,e,t){Zo(t);let r=new hf(n),o=r.getEntries();try{await Ee.stat(e)}catch{await Ee.mkdir(e,{recursive:!0})}let i=H.join(e,t);ja(e,i);for(let s of o){let a=H.join(i,s.entryName);ja(i,a)}r.extractAllTo(i,!0)}async function Qo(n){let e=Pe();if(!e[n])throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(e).join(", ")}`);let r=W[n];try{return await Ee.access(r),!0}catch{return!1}}function ei(n){return Pe()[n].path}function ti(n,e){let r=Pe()[e],o="projectPath"in r?r.projectPath:H.join("."+e,"skills");return H.join(n,o)}async function Pf(n,e,t){Zo(e);let r=H.join(n,e);try{if(await Ee.access(r),t)await Ee.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 ni(n,e,t){await Sf(n,e,t),console.log(`Skill ${t} installed to ${H.join(e,t)}.`)}async function ri(n,e,t){let r=H.join(e,t);await Ee.mkdir(r,{recursive:!0});let o=H.join(r,H.basename(n));await Ee.copyFile(n,o),console.log(`Skill ${t} installed to ${r}.`)}function Ba(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(vf(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function Pt(n,e,t,r){try{let o=await e(),{shouldSkip:i}=await Pf(o,n,r);return i?{success:!0,skipped:!0}:(await t(o),{success:!0})}catch(o){return Ba(n,o,"Installation failed")}}async function oi(n,e){try{Zo(n);let t=await e(),r=H.join(t,n);try{await Ee.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await Ee.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 Wa(n,e,t,r=!1){return Pt(n,()=>ei(e),o=>ni(t,o,n),r)}async function Ua(n,e,t,r=!1){return Pt(n,()=>t,o=>ni(e,o,n),r)}async function za(n,e,t,r,o=!1){return Pt(n,()=>ti(t,r),i=>ni(e,i,n),o)}async function qa(n,e,t,r=!1){return Pt(n,()=>ei(t),o=>ri(e,o,n),r)}async function Va(n,e,t,r,o=!1){return Pt(n,()=>ti(t,r),i=>ri(e,i,n),o)}async function Ga(n,e,t,r=!1){return Pt(n,()=>t,o=>ri(e,o,n),r)}async function Ya(n,e){return oi(n,()=>ei(e))}async function Ja(n,e){return oi(n,()=>e)}async function Ka(n,e,t){return oi(n,()=>ti(e,t))}function Za(){let e=H.dirname(yf(import.meta.url));for(;;){let t=H.join(e,"SKILL.md");if(Fa.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 Xa from"fs";import{cyan as Ef}from"colorette";async function en(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await Qo(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function tn(){let n=[],e=Pe();for(let t of Object.keys(e))await Qo(t)&&n.push(t);return n}function nn(n){let e=n.filter(o=>o.success&&!o.skipped).length,t=n.filter(o=>o.skipped).length,r=n.filter(o=>!o.success).length;console.log(),console.log(Ef("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function Be(n,e,t){if(!Xa.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!Xa.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function rn(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?Xo(n):void 0,resolvedProject:e?Xo(e):void 0}}async function er(n,e,t){let r=[],o=[],i;if(e?i=e:t&&n.agent?o=(await en(n.agent)).map(a=>({project:t,agent:a})):t?o=(await tn()).map(a=>({project:t,agent:a})):n.agent?r=await en(n.agent):r=await tn(),!i&&r.length===0&&o.length===0)throw new Error("No agents found. Install an AI agent (opencode, etc.) or use `--path` for a custom location.");return{agents:r,projectAgents:o,customPath:i}}async function Af(n){let e=await Xn();if(n.all)return(await Jo(e)).map(r=>r.enName);{let r=(await Ko(n.skill,e)).find(o=>o.enName===n.skill);if(!r)throw new Error(`Skill "${n.skill}" not found`);return[r.enName]}}async function Tf(n,e,t,r){let o=[];if(t.customPath){let i=await Ua(n,e,t.customPath,r);return o.push(i),o}for(let i of t.agents){let s=await Wa(n,i,e,r);o.push(s)}for(let{project:i,agent:s}of t.projectAgents){let a=await za(n,e,i,s,r);o.push(a)}return o}function xf(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}=rn(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 kf(n,e,t){let r=await er(n,e,t);return{skillNames:await Af(n),targets:r}}async function Mf(n,e,t,r){let o=[],i=n.length,s=Cf(5),a=n.map(async c=>s(async()=>{try{let l=await $a(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=i>1?` (${c+1}/${i})`:"";r.start(`Installing ${l}${u}...`);let h=await a[c];if(!h.success){r.fail(),console.log(on(`${l}: Download failed - ${h.error}`)),o.push({success:!1});continue}r.stop();let v=await Tf(l,h.buffer,e,t);o.push(...v)}return o}async function Rf(n){let e=new tt;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=xf(n),{skillNames:o,targets:i}=await kf(n,t,r),s=await Mf(o,i,n.force||!1,e);e.stop(),nn(s)}catch(t){throw e.stop(),t}}function Of(n){let{resolvedPath:e,resolvedProject:t}=rn(n.path,n.project,n.agent);return t&&Be(t,"Project directory"),e&&Be(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function Nf(n,e){let t=new tt;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:o}=Of(e);t.stop();let i=await Lf(e,n,r,o);t.stop(),nn(i)}catch(r){throw t.stop(),r}}function Qa(n,e=""){if(n.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function tr(n,e){let t=[];for(let r of e){let o=r.type==="agent"?await Ya(n,r.agent):await Ka(n,r.project,r.agent);t.push(o)}return t}async function Lf(n,e,t,r){if(t)return[await Ja(e,t)];if(r&&n.agent){let a=(await en(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return tr(e,a)}if(r){let s=await tn();Qa(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return tr(e,a)}if(n.agent){let a=(await en(n.agent)).map(c=>({type:"agent",agent:c}));return tr(e,a)}let o=await tn();Qa(o,"or use --path for a custom location.");let i=o.map(s=>({type:"agent",agent:s}));return tr(e,i)}var sn=new If("skills").description("Manage HarmonyOS skills");sn.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 tt;try{e.start("Fetching skills...");let t=await Xn(),r=await Jo(t);if(r.length===0){e.stop(),console.log(tc("No skills available."));return}e.succeed(`Fetched ${r.length} skills`);for(let o of r)if(n.long){console.log(ec(o.enName)),console.log(nc(o.description));let i=_a(o.enName);i.length>0&&console.log(Df(`Installed for: ${i.join(", ")}`)),console.log()}else console.log(o.enName)}catch(t){e.stop(),console.error(on(t.message)),process.exit(1)}});sn.command("find <keyword>").description("Search skills by keyword").action(async n=>{let e=new tt;try{e.start("Searching skills...");let t=await Xn(),r=await Ko(n,t);if(r.length===0){console.log(tc(`No skills found matching '${n}'.`)),e.stop();return}e.succeed(`Found ${r.length} skills.`);for(let o of r)console.log(ec(o.enName)),console.log(nc(o.description)),console.log()}catch(t){e.stop(),console.error(on(t.message)),process.exit(1)}});sn.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 Rf(n)}catch(e){console.error(on(e.message)),process.exit(1)}});sn.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 Nf(n.skill,n)}catch(e){console.error(on(e.message)),process.exit(1)}});var rc=sn;import{Command as Hf,InvalidArgumentError as sc}from"commander";import{cyan as nr}from"colorette";function nt(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=mt(t);return r==="transient"?new Error(`${e}: Device communication channel unavailable. Retry in a few seconds.`):r==="fatal"?new Error(`${e}: ${t.trim()}`):null}var ii=[800,1500,2500];function _f(n){return new Promise(e=>setTimeout(e,n))}function oc(){return D()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device."}var rr=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=K.from(e)}createFollowLineHandler(){return(e,t)=>{if(t==="stderr"){for(let r of e)console.error(r);return}for(let r of e)console.log(r)}}findDeviceByArg(e,t){return e.find(r=>r.serial===t||r.name===t)}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
1244
+ `)}});Ma.action(async(n,e)=>{try{Bm(n),Wm(e.osVersion);let{manager:t}=await ye(),r=await t.listDownloadedImageOsVersions();Um(e.osVersion,r),console.log(St(`Creating emulator "${n}"...`)),await t.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(Jn(`Emulator "${n}" created successfully.`))}catch(t){console.error(te(`${t.message}`)),process.exit(1)}});Fe.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let{manager:e}=await ye();console.log(St(`Deleting emulator "${n}"...`));try{let t=await e.deleteVirtualDevice(n);console.log(Jn(`Emulator "${t}" deleted successfully.`))}catch(t){let r=t;console.error(te(r.message)),r.stdout&&console.error(Qt(r.stdout)),r.stderr&&console.error(Qt(r.stderr)),process.exit(1)}});var Ra=Fe;import{Command as Df}from"commander";import{green as Cf,red as on,cyan as ec,yellow as tc,dim as nc}from"colorette";import Af from"p-limit";import pf from"ora";var tt=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=pf(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 Na from"path";import mf from"axios";var Yo=class{client;constructor(){let e={timeout:To.HTTP_TIMEOUT_MS,headers:{"User-Agent":jn.USER_AGENT,"accept-language":jn.ACCEPT_LANGUAGE},transformResponse:[t=>t],proxy:!1};this.client=mf.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}
1245
+ ${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 Yo;var La=["DevEco"];async function Xn(){let n=await $e.get(ce.TAGS_API_URL),t=Qn(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 ff(n){let e=[],t=ce.DEFAULT_PAGE_SIZE,r=1;for(;;){let o=await $e.post(ce.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:r,pageSize:t,tagIds:[n]}}),i=Qn(o,"Skills API");if(e.push(...i.data.list),i.data.list.length<t)break;r++}return e}async function Jo(n){let e=new Map,t=n.map(o=>ff(o)),r=await Promise.all(t);for(let o of r)for(let i of o)e.has(i.id)||e.set(i.id,i);return Array.from(e.values()).filter(o=>o.tags?.every(i=>!La.includes(i.name)))}async function hf(n,e){let t=await $e.post(ce.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:ce.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return Qn(t,"Skills API").data.list}async function Ko(n,e){let t=new Map,r=e.map(i=>hf(n,i)),o=await Promise.all(r);for(let i of o)for(let s of i)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(i=>i.tags?.every(s=>!La.includes(s.name)))}function _a(n){let e=[],t=Pe();for(let[,r]of Object.entries(t)){let o=Na.join(r.path,n);Oa.existsSync(o)&&e.push(r.displayName)}return e.sort()}function Qn(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=$e.parseJson(n);if(t.code!==ce.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Ha(n){let e=`${ce.SKILL_API_BASE}/${n}/checksum`,t=await $e.get(e);return Qn(t,"Checksum API").data}import gf from"adm-zip";import yf from"crypto";import Fa from"fs";import H from"path";import{fileURLToPath as vf}from"url";import{red as wf}from"colorette";var Ee=Fa.promises;function Zo(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function ja(n,e){let t=H.resolve(e),r=H.resolve(n),o=H.relative(r,t);if(o.startsWith("..")||H.isAbsolute(o))throw new Error(`Path traversal detected: ${e}.`)}function Xo(n){return H.isAbsolute(n)?n:H.resolve(process.cwd(),n)}function bf(n){return yf.createHash("sha256").update(n).digest("hex")}async function Sf(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=bf(n),o=e.sha256.toLowerCase();if(r!==o)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function $a(n){let e=`${ce.SKILL_API_BASE}/${n}/install?format=zip`,t=await $e.getBinary(e),r=await Ha(n);return await Sf(t,r),t}async function Pf(n,e,t){Zo(t);let r=new gf(n),o=r.getEntries();try{await Ee.stat(e)}catch{await Ee.mkdir(e,{recursive:!0})}let i=H.join(e,t);ja(e,i);for(let s of o){let a=H.join(i,s.entryName);ja(i,a)}r.extractAllTo(i,!0)}async function Qo(n){let e=Pe();if(!e[n])throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(e).join(", ")}`);let r=W[n];try{return await Ee.access(r),!0}catch{return!1}}function ei(n){return Pe()[n].path}function ti(n,e){let r=Pe()[e],o="projectPath"in r?r.projectPath:H.join("."+e,"skills");return H.join(n,o)}async function Ef(n,e,t){Zo(e);let r=H.join(n,e);try{if(await Ee.access(r),t)await Ee.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 ni(n,e,t){await Pf(n,e,t),console.log(`Skill ${t} installed to ${H.join(e,t)}.`)}async function ri(n,e,t){let r=H.join(e,t);await Ee.mkdir(r,{recursive:!0});let o=H.join(r,H.basename(n));await Ee.copyFile(n,o),console.log(`Skill ${t} installed to ${r}.`)}function Ba(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(wf(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function Pt(n,e,t,r){try{let o=await e(),{shouldSkip:i}=await Ef(o,n,r);return i?{success:!0,skipped:!0}:(await t(o),{success:!0})}catch(o){return Ba(n,o,"Installation failed")}}async function oi(n,e){try{Zo(n);let t=await e(),r=H.join(t,n);try{await Ee.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await Ee.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 Wa(n,e,t,r=!1){return Pt(n,()=>ei(e),o=>ni(t,o,n),r)}async function Ua(n,e,t,r=!1){return Pt(n,()=>t,o=>ni(e,o,n),r)}async function za(n,e,t,r,o=!1){return Pt(n,()=>ti(t,r),i=>ni(e,i,n),o)}async function qa(n,e,t,r=!1){return Pt(n,()=>ei(t),o=>ri(e,o,n),r)}async function Va(n,e,t,r,o=!1){return Pt(n,()=>ti(t,r),i=>ri(e,i,n),o)}async function Ga(n,e,t,r=!1){return Pt(n,()=>t,o=>ri(e,o,n),r)}async function Ya(n,e){return oi(n,()=>ei(e))}async function Ja(n,e){return oi(n,()=>e)}async function Ka(n,e,t){return oi(n,()=>ti(e,t))}function Za(){let e=H.dirname(vf(import.meta.url));for(;;){let t=H.join(e,"SKILL.md");if(Fa.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 Xa from"fs";import{cyan as If}from"colorette";async function en(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await Qo(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function tn(){let n=[],e=Pe();for(let t of Object.keys(e))await Qo(t)&&n.push(t);return n}function nn(n){let e=n.filter(o=>o.success&&!o.skipped).length,t=n.filter(o=>o.skipped).length,r=n.filter(o=>!o.success).length;console.log(),console.log(If("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function Be(n,e,t){if(!Xa.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!Xa.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function rn(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?Xo(n):void 0,resolvedProject:e?Xo(e):void 0}}async function er(n,e,t){let r=[],o=[],i;if(e?i=e:t&&n.agent?o=(await en(n.agent)).map(a=>({project:t,agent:a})):t?o=(await tn()).map(a=>({project:t,agent:a})):n.agent?r=await en(n.agent):r=await tn(),!i&&r.length===0&&o.length===0)throw new Error("No agents found. Install an AI agent (opencode, etc.) or use `--path` for a custom location.");return{agents:r,projectAgents:o,customPath:i}}async function Tf(n){let e=await Xn();if(n.all)return(await Jo(e)).map(r=>r.enName);{let r=(await Ko(n.skill,e)).find(o=>o.enName===n.skill);if(!r)throw new Error(`Skill "${n.skill}" not found`);return[r.enName]}}async function xf(n,e,t,r){let o=[];if(t.customPath){let i=await Ua(n,e,t.customPath,r);return o.push(i),o}for(let i of t.agents){let s=await Wa(n,i,e,r);o.push(s)}for(let{project:i,agent:s}of t.projectAgents){let a=await za(n,e,i,s,r);o.push(a)}return o}function kf(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}=rn(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 Mf(n,e,t){let r=await er(n,e,t);return{skillNames:await Tf(n),targets:r}}async function Rf(n){try{let e=await $a(n);return{name:n,buffer:e,success:!0}}catch(e){let t=e instanceof Error?e.message:"unknown error";return{name:n,error:t,success:!1}}}async function Of(n,e,t,r){let o=[],i=n.length,s=Af(5),a=n.map(c=>s(()=>Rf(c)));for(let c=0;c<n.length;c++){let l=n[c],u=i>1?` (${c+1}/${i})`:"";r.start(`Installing ${l}${u}...`);let h=await a[c];if(!h.success){r.fail(),console.log(on(`${l}: Download failed - ${h.error}`)),o.push({success:!1});continue}r.stop();let v=await xf(l,h.buffer,e,t);o.push(...v)}return o}async function Nf(n){let e=new tt;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=kf(n),{skillNames:o,targets:i}=await Mf(n,t,r),s=await Of(o,i,n.force||!1,e);e.stop(),nn(s)}catch(t){throw e.stop(),t}}function Lf(n){let{resolvedPath:e,resolvedProject:t}=rn(n.path,n.project,n.agent);return t&&Be(t,"Project directory"),e&&Be(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function _f(n,e){let t=new tt;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:o}=Lf(e);t.stop();let i=await Hf(e,n,r,o);t.stop(),nn(i)}catch(r){throw t.stop(),r}}function Qa(n,e=""){if(n.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function tr(n,e){let t=[];for(let r of e){let o=r.type==="agent"?await Ya(n,r.agent):await Ka(n,r.project,r.agent);t.push(o)}return t}async function Hf(n,e,t,r){if(t)return[await Ja(e,t)];if(r&&n.agent){let a=(await en(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return tr(e,a)}if(r){let s=await tn();Qa(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return tr(e,a)}if(n.agent){let a=(await en(n.agent)).map(c=>({type:"agent",agent:c}));return tr(e,a)}let o=await tn();Qa(o,"or use --path for a custom location.");let i=o.map(s=>({type:"agent",agent:s}));return tr(e,i)}var sn=new Df("skills").description("Manage HarmonyOS skills");sn.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 tt;try{e.start("Fetching skills...");let t=await Xn(),r=await Jo(t);if(r.length===0){e.stop(),console.log(tc("No skills available."));return}e.succeed(`Fetched ${r.length} skills`);for(let o of r)if(n.long){console.log(ec(o.enName)),console.log(nc(o.description));let i=_a(o.enName);i.length>0&&console.log(Cf(`Installed for: ${i.join(", ")}`)),console.log()}else console.log(o.enName)}catch(t){e.stop(),console.error(on(t.message)),process.exit(1)}});sn.command("find <keyword>").description("Search skills by keyword").action(async n=>{let e=new tt;try{e.start("Searching skills...");let t=await Xn(),r=await Ko(n,t);if(r.length===0){console.log(tc(`No skills found matching '${n}'.`)),e.stop();return}e.succeed(`Found ${r.length} skills.`);for(let o of r)console.log(ec(o.enName)),console.log(nc(o.description)),console.log()}catch(t){e.stop(),console.error(on(t.message)),process.exit(1)}});sn.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 Nf(n)}catch(e){console.error(on(e.message)),process.exit(1)}});sn.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 _f(n.skill,n)}catch(e){console.error(on(e.message)),process.exit(1)}});var rc=sn;import{Command as Ff,InvalidArgumentError as sc}from"commander";import{cyan as nr}from"colorette";function nt(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=mt(t);return r==="transient"?new Error(`${e}: Device communication channel unavailable. Retry in a few seconds.`):r==="fatal"?new Error(`${e}: ${t.trim()}`):null}var ii=[800,1500,2500];function jf(n){return new Promise(e=>setTimeout(e,n))}function oc(){return D()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device."}var rr=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=K.from(e)}createFollowLineHandler(){return(e,t)=>{if(t==="stderr"){for(let r of e)console.error(r);return}for(let r of e)console.log(r)}}findDeviceByArg(e,t){return e.find(r=>r.serial===t||r.name===t)}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
1246
1246
  `)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let o=t[0];return g(nr(`Using device serial: ${o}`)),o}if(e&&t.includes(e))return g(nr(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let o=this.findDeviceByArg(r,e);if(o)return g(nr(`Using device: ${o.name} (${o.serial})`)),o.serial;let i=this.formatConnectedDeviceList(r);throw new Error(`Device '${e}' not found.
1247
1247
  Available devices:
1248
- ${i}`)}if(r.length===1){let o=r[0];return g(nr(`Using device: ${o.name} (${o.serial})`)),o.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(oc());return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error(oc());return e}async getPidForBundle(e,t,r){g(`Retrieving PID for bundle ${r}`),P.assertBundleName(r);let o=await Gt(e,["-t",t,"shell","pidof",r]),i=nt(o,"Failed to look up PID");if(i)throw i;if(o.exitCode===0&&o.stdout.trim()){let s=o.stdout.trim(),a=s.split(/\s+/)[0]||s;return 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 o=await Gt(e,["-t",t,"shell","hilog","-G",r]),i=nt(o,"Failed to resize hilog buffer");if(i)throw i;o.exitCode!==0&&console.error(`Failed to resize hilog buffer: ${o.stderr||o.stdout}`)}buildHilogCommand(e,t,r,o){let i=this.buildHilogShellCommand(r,o);return[e,["-t",t,"shell",i]]}buildHilogShellCommand(e,t){let r=["hilog"];return e.isFollow||r.push("-x"),e.tag&&(P.assertHilogToken(e.tag,"tag"),r.push("-T",e.tag)),e.level&&(P.assertHilogLevel(e.level),r.push("-L",e.level)),e.domain&&(P.assertHilogToken(e.domain,"domain"),r.push("-D",e.domain)),t&&r.push("-P",t),e.keyword&&(P.assertHilogKeyword(e.keyword),r.push("-e",P.quotePosixShellArg(e.keyword))),r.join(" ")}async followHilog(e,t,r,o,i){let a=await $s(e,t,{onData:r,onError:o,onClose:i});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}async runHilogWithSpawnRetry(e,t,r,o,i){let s=1+ii.length,a={stdout:"",stderr:"",exitCode:-1};for(let c=0;c<s;c++){if(a=await this.followHilog(e,t,r,o,i),a.exitCode===0||mt(a.stderr)!=="transient"||c>=s-1)return a;g(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${ii[c]}ms`),await _f(ii[c])}return a}async runHilogStreamingCollect(e,t,r){return this.runHilogWithSpawnRetry(e,t,()=>{},o=>{g(`Callback triggered when an error occurs during ${r}: ${o.message}`)},()=>{})}async printTailSnapshotIfNeeded(e,t,r,o){if(!r.tail&&!r.fromSeconds&&!r.toSeconds)return;let i={...r,isFollow:!1},[s,a]=this.buildHilogCommand(e,t,i,o);g(`Ready to run hilog snapshot command: ${s} ${a.join(" ")}`);let c=await this.runHilogStreamingCollect(s,a,"a hilog snapshot streaming read"),l=nt(c,"Failed to get hilog");if(l)throw l;if(c.exitCode!==0&&c.stderr)throw new Error(`Failed to get hilog: ${c.stderr}`);let u=P.filterLogsByRelativeWindow(c.stdout||c.stderr,r.fromSeconds,r.toSeconds);u=P.getLastLines(u,r.tail),u.trim()&&console.log(u)}async getHilogOnce(e,t,r,o){let[i,s]=this.buildHilogCommand(e,t,r,o);g(`Ready to run hilog command: ${i} ${s.join(" ")}`);let a=await this.runHilogStreamingCollect(i,s,"a single hilog streaming read"),c=nt(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=P.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return u=P.getLastLines(u,r.tail),u}async runHilogFollow(e,t,r,o){try{await this.printTailSnapshotIfNeeded(e,t,r,o)}catch(l){console.error(`Warning: Failed to fetch log snapshot, continuing with live stream: ${l.message}`)}let[i,s]=this.buildHilogCommand(e,t,r,o);g(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${i} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(i,s,this.createFollowLineHandler(),l=>{g(`Spawn error during hilog follow: ${l.message}`)},()=>{}),c=nt(a,"Failed to follow hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to follow hilog: ${a.stderr}`);return""}async getHilog(e,t){let r=this.toolProvider.hdcPath,o=t.bundleName?await this.getPidForBundle(r,e,t.bundleName):void 0;if(t.bundleName&&!o)throw new 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,o||""):await this.getHilogOnce(r,e,t,o||"")}async getCrashLog(e,t){g(`Fetching crash logs from device: ${e}`);let r=this.toolProvider.hdcPath,o=await this.listCrashLogs(r,e,t);if(o.length===0)return t?`No crash logs found for bundle '${t}'.`:"No crash logs found.";let s=[...o].sort((c,l)=>{let 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 o=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];g(`Running command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log list streaming read"),s=nt(i,"Failed to list crash logs");if(s)throw s;if(i.exitCode!==0)throw new Error(`Failed to list crash logs: ${i.stderr||i.stdout}`);return g(`Crash logs list output:
1248
+ ${i}`)}if(r.length===1){let o=r[0];return g(nr(`Using device: ${o.name} (${o.serial})`)),o.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(oc());return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error(oc());return e}async getPidForBundle(e,t,r){g(`Retrieving PID for bundle ${r}`),P.assertBundleName(r);let o=await Gt(e,["-t",t,"shell","pidof",r]),i=nt(o,"Failed to look up PID");if(i)throw i;if(o.exitCode===0&&o.stdout.trim()){let s=o.stdout.trim(),a=s.split(/\s+/)[0]||s;return 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 o=await Gt(e,["-t",t,"shell","hilog","-G",r]),i=nt(o,"Failed to resize hilog buffer");if(i)throw i;o.exitCode!==0&&console.error(`Failed to resize hilog buffer: ${o.stderr||o.stdout}`)}buildHilogCommand(e,t,r,o){let i=this.buildHilogShellCommand(r,o);return[e,["-t",t,"shell",i]]}buildHilogShellCommand(e,t){let r=["hilog"];return e.isFollow||r.push("-x"),e.tag&&(P.assertHilogToken(e.tag,"tag"),r.push("-T",e.tag)),e.level&&(P.assertHilogLevel(e.level),r.push("-L",e.level)),e.domain&&(P.assertHilogToken(e.domain,"domain"),r.push("-D",e.domain)),t&&r.push("-P",t),e.keyword&&(P.assertHilogKeyword(e.keyword),r.push("-e",P.quotePosixShellArg(e.keyword))),r.join(" ")}async followHilog(e,t,r,o,i){let a=await $s(e,t,{onData:r,onError:o,onClose:i});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}async runHilogWithSpawnRetry(e,t,r,o,i){let s=1+ii.length,a={stdout:"",stderr:"",exitCode:-1};for(let c=0;c<s;c++){if(a=await this.followHilog(e,t,r,o,i),a.exitCode===0||mt(a.stderr)!=="transient"||c>=s-1)return a;g(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${ii[c]}ms`),await jf(ii[c])}return a}async runHilogStreamingCollect(e,t,r){return this.runHilogWithSpawnRetry(e,t,()=>{},o=>{g(`Callback triggered when an error occurs during ${r}: ${o.message}`)},()=>{})}async printTailSnapshotIfNeeded(e,t,r,o){if(!r.tail&&!r.fromSeconds&&!r.toSeconds)return;let i={...r,isFollow:!1},[s,a]=this.buildHilogCommand(e,t,i,o);g(`Ready to run hilog snapshot command: ${s} ${a.join(" ")}`);let c=await this.runHilogStreamingCollect(s,a,"a hilog snapshot streaming read"),l=nt(c,"Failed to get hilog");if(l)throw l;if(c.exitCode!==0&&c.stderr)throw new Error(`Failed to get hilog: ${c.stderr}`);let u=P.filterLogsByRelativeWindow(c.stdout||c.stderr,r.fromSeconds,r.toSeconds);u=P.getLastLines(u,r.tail),u.trim()&&console.log(u)}async getHilogOnce(e,t,r,o){let[i,s]=this.buildHilogCommand(e,t,r,o);g(`Ready to run hilog command: ${i} ${s.join(" ")}`);let a=await this.runHilogStreamingCollect(i,s,"a single hilog streaming read"),c=nt(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=P.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return u=P.getLastLines(u,r.tail),u}async runHilogFollow(e,t,r,o){try{await this.printTailSnapshotIfNeeded(e,t,r,o)}catch(l){console.error(`Warning: Failed to fetch log snapshot, continuing with live stream: ${l.message}`)}let[i,s]=this.buildHilogCommand(e,t,r,o);g(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${i} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(i,s,this.createFollowLineHandler(),l=>{g(`Spawn error during hilog follow: ${l.message}`)},()=>{}),c=nt(a,"Failed to follow hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to follow hilog: ${a.stderr}`);return""}async getHilog(e,t){let r=this.toolProvider.hdcPath,o=t.bundleName?await this.getPidForBundle(r,e,t.bundleName):void 0;if(t.bundleName&&!o)throw new 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,o||""):await this.getHilogOnce(r,e,t,o||"")}async getCrashLog(e,t){g(`Fetching crash logs from device: ${e}`);let r=this.toolProvider.hdcPath,o=await this.listCrashLogs(r,e,t);if(o.length===0)return t?`No crash logs found for bundle '${t}'.`:"No crash logs found.";let s=[...o].sort((c,l)=>{let 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 o=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];g(`Running command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log list streaming read"),s=nt(i,"Failed to list crash logs");if(s)throw s;if(i.exitCode!==0)throw new Error(`Failed to list crash logs: ${i.stderr||i.stdout}`);return g(`Crash logs list output:
1249
1249
  ${i.stdout}`),this.parseCrashLogFilenames(i.stdout,r)}parseCrashLogFilenames(e,t){return e.split(`
1250
- `).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return P.assertCrashFilename(r),!0}catch{return!1}}).filter(r=>t?r.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){g(`Fetching latest crash log file: ${r}`);let o=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];g(`Executing command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log streaming read"),s=nt(i,"Failed to fetch crash log content");if(s)throw s;return i.exitCode!==0&&i.stderr&&console.error(`Warning: Failed to fetch crash logs: ${i.stderr}`),i.stdout+i.stderr}};import{cyan as si,red as ac}from"colorette";import jf from"ora";function Ff(n){try{return P.parsePositiveInteger(n,"tail")}catch{throw new sc("`tail` must be a positive integer.")}}function ic(n,e){try{return P.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 $f(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.");P.assertRelativeTimeRange(n.from,n.to)}async function Bf(n,e,t,r,o){return t.crash?await n.getCrashLog(e,t.bundleName):await n.getHilog(e,{level:t.level,bundleName:t.bundleName,keyword:t.keyword,isFollow:!!t.follow,tail:t.tail,fromSeconds:r,toSeconds:o})}function Wf(n,e,t,r){let o=P.filterLogsByRelativeWindow(n,t,r);return e.tail?P.getLastLines(o,e.tail):o}var Uf=new Hf("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",Ff).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>ic(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>ic(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await zf(n)});async function zf(n){let e=jf({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),$f(n);let r=n.from,o=n.to,i=await _.new(),s=new rr(i),a=await s.selectDevice(n.device);a||(t(),process.exit(1)),g(si(`deviceId: ${a}`)),g(si(`type: ${n.crash?"Crash logs":"Common logs"}`)),g(si("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await Bf(s,a,n,r,o);t(),n.crash&&c&&(c=Wf(c,n,r,o)),c&&console.log(c)}catch(r){t(),console.error(ac(r.message)),process.exit(1)}}var cc=Uf;import cn from"path";import Ie from"fs";import li from"process";import hc from"os";import{Command as rh}from"commander";import{green as pc,red as ai,cyan as oh,yellow as ci}from"colorette";import F from"fs-extra";import R from"path";import*as lc from"os";import{fileURLToPath as qf}from"url";var Vf={17:{sdkVersion:"5.0.5(17)",modelVersion:"5.0.5"},18:{sdkVersion:"5.1.0(18)",modelVersion:"5.1.0"},19:{sdkVersion:"5.1.1(19)",modelVersion:"5.1.1"},20:{sdkVersion:"6.0.0(20)",modelVersion:"6.0.0"},21:{sdkVersion:"6.0.1(21)",modelVersion:"6.0.1"},22:{sdkVersion:"6.0.2(22)",modelVersion:"6.0.2"},23:{sdkVersion:"6.1.0(23)",modelVersion:"6.1.0"},24:{sdkVersion:"6.1.1(24)",modelVersion:"6.1.1"}},Gf=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function Yf(){let n=import.meta.url,e=qf(n);if(e.includes("dist")){let i=R.dirname(e),s=R.dirname(i);return R.join(s,"templates","application")}let t=R.dirname(e),r=R.dirname(t),o=R.dirname(r);return R.join(o,"templates","application")}function dc(n,e){F.mkdirSync(e,{recursive:!0});for(let t of F.readdirSync(n,{withFileTypes:!0})){let r=R.join(n,t.name),o=R.join(e,t.name);if(t.isDirectory()){dc(r,o);continue}F.existsSync(o)||(F.mkdirSync(R.dirname(o),{recursive:!0}),F.copyFileSync(r,o))}}function an(n,e){let t=F.readFileSync(n,"utf-8"),r=t;for(let[o,i]of e)r=r.replaceAll(o,i);r!==t&&F.writeFileSync(n,r,"utf-8")}function Jf(n,e){if(e===22)return;let t=Vf[e];t&&(an(R.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),an(R.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),an(R.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function Kf(n){return Gf.filter(t=>!F.existsSync(R.join(n,t))).length===0}function Zf(){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 Xf(n){return lc.platform()==="darwin"?R.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):R.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function Qf(n,e){let t=Xf(e);if(!F.existsSync(t))return!1;let r=[["AppScope/resources/base/media/background.png","AppScope/resources/base/media/background.png"],["AppScope/resources/base/media/foreground.png","AppScope/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/background.png"],["entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/startIcon.png","entry/src/main/resources/base/media/startIcon.png"]];for(let[o,i]of r){let s=R.join(t,o),a=R.join(n,i);F.existsSync(s)&&(F.mkdirSync(R.dirname(a),{recursive:!0}),F.copyFileSync(s,a))}return!0}function eh(n){let e=Zf(),t=["AppScope/resources/base/media/background.png","AppScope/resources/base/media/foreground.png","entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/startIcon.png"];for(let r of t){let o=R.join(n,r);F.mkdirSync(R.dirname(o),{recursive:!0}),F.writeFileSync(o,e)}}function th(n,e){e&&Qf(n,e)||eh(n)}function nh(n){let e=[R.join(n,"gitignore.txt"),R.join(n,"entry","gitignore.txt")];for(let t of e)F.existsSync(t)&&F.renameSync(t,t.replace(/\/gitignore\.txt$/,"/.gitignore"))}function uc(n,e,t,r,o){let i=Yf();if(!F.existsSync(i))throw new Error(`Template directory not found: ${i}`);F.mkdirSync(n,{recursive:!0}),dc(i,n),nh(n),th(n,o),an(R.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),an(R.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),Jf(n,r);let s=Kf(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function ih(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 sh(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 o=e[r];if(!t.test(o))throw new Error(`Segment "${o}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(r===0){if(!/^[a-zA-Z]/.test(o))throw new Error(`First segment "${o}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(o))throw new Error(`Segment "${o}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(o))throw new Error(`Segment "${o}" must end with a letter or digit.`)}}function gc(n){if(hc.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function mc(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=hc.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(n)){let i=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new Error(`Project path can only contain ${i}.`)}let r=gc(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 ah(n){let e=n,t=cn.parse(n).root;for(;e!==t;){if(Ie.existsSync(e))return e;e=cn.dirname(e)}return Ie.existsSync(t)?t:null}function fc(n){let e=ah(n);if(!e)throw new Error(`No existing parent directory found for '${n}'. Cannot create project directory.`);try{Ie.accessSync(e,Ie.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=cn.join(e,`.deveco_write_test_${Date.now()}`);try{Ie.writeFileSync(t,"test"),Ie.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function ch(n){return`com.example.${n.toLowerCase()}`}function lh(n,e){if(e){let o=gc(e),i=cn.resolve(o);if(Ie.existsSync(i)){if(Ie.readdirSync(i).length>0)throw new Error(`Directory '${i}' is not empty. Cannot create project here.`)}else fc(i);return i}let t=li.cwd(),r=cn.join(t,n);if(Ie.existsSync(r))throw new Error(`Directory '${r}' already exists. Cannot create project here.`);return fc(r),r}function dh(n,e){let t=e?.getMaxApiLevel(),r=23;if(n.apiLevel){let o=Number(n.apiLevel);if(!Number.isInteger(o)||o<17)throw new Error(`Invalid API version ${n.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(o>t)throw new Error(`Invalid API version ${n.apiLevel}. Your SDK supports API version 17-${t}`)}else if(o>r){let i=D()?"commandLineTools":"DevEco Studio";throw new Error(`Invalid API version ${n.apiLevel}. Without ${i}, supported range is API version 17-${r}`)}return o}return t!==void 0?t:23}async function uh(){try{return await _.new()}catch(n){let e=n,t=D()?"Toolchain not found":"DevEco Studio not found";console.error(ci(`${t}: ${e.message}`)),D()?console.log(ci("Please install commandLineTools. Use placeholder API level instead.")):console.log(ci("Use placeholder API level instead."));return}}var ph=new rh("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(ai("Error: --app-name is required")),li.exit(1));let e=n.appName;ih(e);let t=n.bundleName||ch(e);sh(t),n.projectPath&&mc(n.projectPath);let r=lh(e,n.projectPath);mc(r),console.log(oh("Initializing project...")),console.log(`Project path: ${r}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let o=await uh(),i=dh(n,o);console.log(`API level: ${i}`);let s=o?.devecoStudioPath,a=uc(r,e,t,i,s);console.log(`
1250
+ `).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return P.assertCrashFilename(r),!0}catch{return!1}}).filter(r=>t?r.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){g(`Fetching latest crash log file: ${r}`);let o=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];g(`Executing command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log streaming read"),s=nt(i,"Failed to fetch crash log content");if(s)throw s;return i.exitCode!==0&&i.stderr&&console.error(`Warning: Failed to fetch crash logs: ${i.stderr}`),i.stdout+i.stderr}};import{cyan as si,red as ac}from"colorette";import $f from"ora";function Bf(n){try{return P.parsePositiveInteger(n,"tail")}catch{throw new sc("`tail` must be a positive integer.")}}function ic(n,e){try{return P.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 Wf(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.");P.assertRelativeTimeRange(n.from,n.to)}async function Uf(n,e,t,r,o){return t.crash?await n.getCrashLog(e,t.bundleName):await n.getHilog(e,{level:t.level,bundleName:t.bundleName,keyword:t.keyword,isFollow:!!t.follow,tail:t.tail,fromSeconds:r,toSeconds:o})}function zf(n,e,t,r){let o=P.filterLogsByRelativeWindow(n,t,r);return e.tail?P.getLastLines(o,e.tail):o}var qf=new Ff("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",Bf).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>ic(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>ic(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await Vf(n)});async function Vf(n){let e=$f({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),Wf(n);let r=n.from,o=n.to,i=await _.new(),s=new rr(i),a=await s.selectDevice(n.device);a||(t(),process.exit(1)),g(si(`deviceId: ${a}`)),g(si(`type: ${n.crash?"Crash logs":"Common logs"}`)),g(si("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await Uf(s,a,n,r,o);t(),n.crash&&c&&(c=zf(c,n,r,o)),c&&console.log(c)}catch(r){t(),console.error(ac(r.message)),process.exit(1)}}var cc=qf;import cn from"path";import Ie from"fs";import li from"process";import hc from"os";import{Command as ih}from"commander";import{green as pc,red as ai,cyan as sh,yellow as ci}from"colorette";import F from"fs-extra";import R from"path";import*as lc from"os";import{fileURLToPath as Gf}from"url";var Yf={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"}},Jf=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function Kf(){let n=import.meta.url,e=Gf(n);if(e.includes("dist")){let i=R.dirname(e),s=R.dirname(i);return R.join(s,"templates","application")}let t=R.dirname(e),r=R.dirname(t),o=R.dirname(r);return R.join(o,"templates","application")}function dc(n,e){F.mkdirSync(e,{recursive:!0});for(let t of F.readdirSync(n,{withFileTypes:!0})){let r=R.join(n,t.name),o=R.join(e,t.name);if(t.isDirectory()){dc(r,o);continue}F.existsSync(o)||(F.mkdirSync(R.dirname(o),{recursive:!0}),F.copyFileSync(r,o))}}function an(n,e){let t=F.readFileSync(n,"utf-8"),r=t;for(let[o,i]of e)r=r.replaceAll(o,i);r!==t&&F.writeFileSync(n,r,"utf-8")}function Zf(n,e){if(e===22)return;let t=Yf[e];t&&(an(R.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),an(R.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),an(R.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function Xf(n){return Jf.filter(t=>!F.existsSync(R.join(n,t))).length===0}function Qf(){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 eh(n){return lc.platform()==="darwin"?R.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):R.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function th(n,e){let t=eh(e);if(!F.existsSync(t))return!1;let r=[["AppScope/resources/base/media/background.png","AppScope/resources/base/media/background.png"],["AppScope/resources/base/media/foreground.png","AppScope/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/background.png"],["entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/startIcon.png","entry/src/main/resources/base/media/startIcon.png"]];for(let[o,i]of r){let s=R.join(t,o),a=R.join(n,i);F.existsSync(s)&&(F.mkdirSync(R.dirname(a),{recursive:!0}),F.copyFileSync(s,a))}return!0}function nh(n){let e=Qf(),t=["AppScope/resources/base/media/background.png","AppScope/resources/base/media/foreground.png","entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/startIcon.png"];for(let r of t){let o=R.join(n,r);F.mkdirSync(R.dirname(o),{recursive:!0}),F.writeFileSync(o,e)}}function rh(n,e){e&&th(n,e)||nh(n)}function oh(n){let e=[R.join(n,"gitignore.txt"),R.join(n,"entry","gitignore.txt")];for(let t of e)F.existsSync(t)&&F.renameSync(t,t.replace(/\/gitignore\.txt$/,"/.gitignore"))}function uc(n,e,t,r,o){let i=Kf();if(!F.existsSync(i))throw new Error(`Template directory not found: ${i}`);F.mkdirSync(n,{recursive:!0}),dc(i,n),oh(n),rh(n,o),an(R.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),an(R.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),Zf(n,r);let s=Xf(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function ah(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 ch(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 o=e[r];if(!t.test(o))throw new Error(`Segment "${o}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(r===0){if(!/^[a-zA-Z]/.test(o))throw new Error(`First segment "${o}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(o))throw new Error(`Segment "${o}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(o))throw new Error(`Segment "${o}" must end with a letter or digit.`)}}function gc(n){if(hc.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function mc(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=hc.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(n)){let i=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new Error(`Project path can only contain ${i}.`)}let r=gc(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 lh(n){let e=n,t=cn.parse(n).root;for(;e!==t;){if(Ie.existsSync(e))return e;e=cn.dirname(e)}return Ie.existsSync(t)?t:null}function fc(n){let e=lh(n);if(!e)throw new Error(`No existing parent directory found for '${n}'. Cannot create project directory.`);try{Ie.accessSync(e,Ie.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=cn.join(e,`.deveco_write_test_${Date.now()}`);try{Ie.writeFileSync(t,"test"),Ie.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function dh(n){return`com.example.${n.toLowerCase()}`}function uh(n,e){if(e){let o=gc(e),i=cn.resolve(o);if(Ie.existsSync(i)){if(Ie.readdirSync(i).length>0)throw new Error(`Directory '${i}' is not empty. Cannot create project here.`)}else fc(i);return i}let t=li.cwd(),r=cn.join(t,n);if(Ie.existsSync(r))throw new Error(`Directory '${r}' already exists. Cannot create project here.`);return fc(r),r}function ph(n,e){let t=e?.getMaxApiLevel(),r=23;if(n.apiLevel){let o=Number(n.apiLevel);if(!Number.isInteger(o)||o<17)throw new Error(`Invalid API version ${n.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(o>t)throw new Error(`Invalid API version ${n.apiLevel}. Your SDK supports API version 17-${t}`)}else if(o>r){let i=D()?"commandLineTools":"DevEco Studio";throw new Error(`Invalid API version ${n.apiLevel}. Without ${i}, supported range is API version 17-${r}`)}return o}return t!==void 0?t:23}async function mh(){try{return await _.new()}catch(n){let e=n,t=D()?"Toolchain not found":"DevEco Studio not found";console.error(ci(`${t}: ${e.message}`)),D()?console.log(ci("Please install commandLineTools. Use placeholder API level instead.")):console.log(ci("Use placeholder API level instead."));return}}var fh=new ih("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(ai("Error: --app-name is required")),li.exit(1));let e=n.appName;ah(e);let t=n.bundleName||dh(e);ch(t),n.projectPath&&mc(n.projectPath);let r=uh(e,n.projectPath);mc(r),console.log(sh("Initializing project...")),console.log(`Project path: ${r}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let o=await mh(),i=ph(n,o);console.log(`API level: ${i}`);let s=o?.devecoStudioPath,a=uc(r,e,t,i,s);console.log(`
1251
1251
  `+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(ai(`
1252
- Failed to create project.`)),console.error(ai(t.message)),li.exit(1)}}),yc=ph;import{Command as wh}from"commander";import{red as bh,cyan as Ic}from"colorette";import mh from"fs";import or from"path";import{cyan as fh}from"colorette";import*as ir from"smol-toml";var Et=mh.promises;async function hh(n){try{let e=await Et.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 gh(n){try{let e=await Et.readFile(n,"utf8");return e.trim()===""?{}:ir.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 yh(n,e){let t=or.dirname(n);await Et.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await Et.writeFile(n,r,"utf8")}async function vh(n,e){let t=or.dirname(n);await Et.mkdir(t,{recursive:!0});let r=ir.stringify(e);await Et.writeFile(n,r,"utf8")}function vc(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function wc(n,e,t,r,o){(!n[e]||typeof n[e]!="object")&&(n[e]={});let i=n[e];return t in i&&!o?!1:(i[t]=r,!0)}async function bc(n,e){return n.format==="codex"?gh(e):hh(e)}async function Sc(n,e,t){return n.format==="codex"?vh(e,t):yh(e,t)}async function Pc(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 o=await bc(r,r.globalConfigPath);if(vc(o,r.mcpServersKey,fe)&&!t)return console.log(`MCP server ${fe} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let i=Fn(r,void 0);return wc(o,r.mcpServersKey,fe,i,t),await Sc(r,r.globalConfigPath,o),console.log(`MCP server ${fe} configured in ${r.globalConfigPath}.`),{success:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${o.message}`}}}async function di(n,e,t=!1){let r=_e[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(_e).join(", ")}`};let o=or.isAbsolute(r.projectConfigPath)?r.projectConfigPath:or.join(e,r.projectConfigPath);try{let i=await bc(r,o);if(vc(i,r.mcpServersKey,fe)&&!t)return console.log(`MCP server ${fe} already configured in ${o}.`),{success:!0,skipped:!0,configPath:o,agentName:n,installType:"project"};let s=Fn(r,e);return wc(i,r.mcpServersKey,fe,s,t),await Sc(r,o,i),console.log(`MCP server ${fe} configured in ${o}.`),{success:!0,configPath:o,agentName:n,installType:"project"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${i.message}`}}}function Ec(n){let e=n.filter(o=>o.success&&!o.skipped).length,t=n.filter(o=>o.skipped).length,r=n.filter(o=>!o.success).length;console.log(),console.log(fh("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`);for(let o of n)!o.success&&o.error&&console.error(` - ${o.agentName??"unknown"}: ${o.error}`);r>0&&(process.exitCode=1)}var ui="deveco-cli";async function Sh(n,e,t){if(n.customPath)return[await Ga(ui,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>Va(ui,e,s,a,t.force)),...n.agents.map(s=>()=>qa(ui,e,s,t.force))],o=5,i=[];for(let s=0;s<r.length;s+=o){let a=r.slice(s,s+o);i.push(...await Promise.all(a.map(c=>c())))}return i}async function Ph(n,e,t){let r=[];for(let{project:o,agent:i}of n.projectAgents){let s=await di(i,o,t);r.push(s)}for(let o of n.agents){let i=await di(o,e,t);r.push(i)}return r}async function Eh(n,e){let t=[];for(let r of n){if(!_e[r])continue;let i=await Pc(r,process.cwd(),e);t.push(i)}return t}async function Ih(n,e,t){if(t.agent&&t.agent.split(",").map(l=>l.trim()).includes("qoder"))throw new Error("Qoder does not support MCP configuration via DevEco CLI. Use other supported agents instead.");let r=t.force??!1,o=n.projectAgents.filter(c=>c.agent!=="qoder"),i=n.agents.filter(c=>c!=="qoder"),s={...n,projectAgents:o,agents:i},a=e?await Ph(s,e,r):await Eh(s.agents,r);a.length>0&&(console.log(Ic("MCP Configuration:")),Ec(a))}async function Dh(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}=rn(n.path,n.project,n.agent);t&&Be(t,"Project directory",n.force),e&&Be(e,"Directory",n.force);let r=await er(n,e,t);if(n.mcp){await Ih(r,t,n);return}let o=Za(),i=await Sh(r,o,n);console.log(),i.length>0&&(console.log(Ic("Skill Installation:")),nn(i))}var Ch=new wh("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 Dh(n)}catch(e){console.error(bh(e.message)),process.exit(1)}}),Dc=Ch;import{Command as Ng}from"commander";import{McpServer as Mg}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Rg}from"@modelcontextprotocol/sdk/server/stdio.js";import*as qr from"path";import{z as xi}from"zod";var sr=class{tools=new Map;add(e,t){return this.tools.set(e.name,{definition:e,handler:t}),this}getAll(){return Array.from(this.tools.values())}registerToServer(e){for(let{definition:t,handler:r}of this.getAll())e.registerTool(t.name,{description:t.description,inputSchema:t.inputSchema},(async o=>r(o)))}};function pi(){return new sr}import*as xe from"fs";import*as we from"path";import{z as Di}from"zod";import U from"fs";import*as ar from"os";import*as L from"path";import Ah from"json5";var Th=3;function mi(n){if(!U.existsSync(n)||!U.statSync(n).isDirectory())return!1;let e=U.existsSync(L.join(n,"build-profile.json5")),t=U.existsSync(L.join(n,"hvigorfile.js"))||U.existsSync(L.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=U.readFileSync(L.join(n,"build-profile.json5"),"utf-8");return Ah.parse(r).app!==void 0}catch{return!1}}function Cc(n,e,t){if(e>=t)return null;let r=xh(n),o=kh(r);if(o)return o;for(let i of r){let s=Cc(i,e+1,t);if(s)return s}return null}function xh(n){try{let e=U.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(L.join(n,r.name));return t}catch{return[]}}function kh(n){for(let e of n)if(mi(e))return e;return null}function De(n){if(!n||n.trim()==="")return null;let e=L.resolve(n),t;try{t=U.realpathSync(e)}catch{t=e}if(!U.existsSync(t))return null;if(mi(t))return t;let r=t;for(let o=1;o<=3;o++){let i=L.dirname(r);if(i===r)break;if(mi(i))return i;r=i}if(U.statSync(t).isDirectory()){let o=Cc(t,0,Th);if(o)return o}return null}var fi=[D()?".bitfun":".idea",".deveco",D()?".cxx":"cxx","compile_commands.json"];function dn(n){return L.join(n,...fi)}function Ac(n){return new Promise(e=>setTimeout(e,n))}var Mh=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function cr(n){let e=L.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&Mh.has(e)}function Tc(n){return L.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function ve(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function hi(n){return ve(n)}function rt(n){let e=hi(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function ln(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)),rt(t)}}catch{}return n}function xc(n){let e=[],t=n.lastIndexOf("file:/");if(t>=0){let r=n.slice(t).replace(/^file:\/+/,"");if(r){let o=r.startsWith("/")?`file://${r}`:`file:///${r}`,i=ln(o);i!==n&&i!==ln(n)&&e.push(i)}}return e}function lr(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??L.join(ar.homedir(),"AppData","Local");return L.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?L.join(ar.homedir(),"Library","Logs","devecocli-mcp-server"):L.join(ar.homedir(),".local","share","devecocli-mcp-server","logs")}function kc(n,e){let t=Rh(e),r=Oh(t,n);if(r!==null)return r;let o=Date.now(),s=`${n.replace(/:/g,"\\:")}=${o}`,a=Nh(t,n,s);return Lh(e,a),o}function Rh(n){let e;try{e=U.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function Oh(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let i=parseInt(t.slice(r+1),10);return Number.isFinite(i)&&i>0?i:null}return null}function Nh(n,e,t){let r=!1,o=n.map(i=>{if(r)return i;let s=i.indexOf("=");return s<=0?i:i.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):i});return r||o.push(t),o}function Lh(n,e){try{U.mkdirSync(L.dirname(n),{recursive:!0})}catch{}try{U.writeFileSync(n,e.join(`
1252
+ Failed to create project.`)),console.error(ai(t.message)),li.exit(1)}}),yc=fh;import{Command as Sh}from"commander";import{red as Ph,cyan as Ic}from"colorette";import hh from"fs";import or from"path";import{cyan as gh}from"colorette";import*as ir from"smol-toml";var Et=hh.promises;async function yh(n){try{let e=await Et.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 vh(n){try{let e=await Et.readFile(n,"utf8");return e.trim()===""?{}:ir.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 wh(n,e){let t=or.dirname(n);await Et.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await Et.writeFile(n,r,"utf8")}async function bh(n,e){let t=or.dirname(n);await Et.mkdir(t,{recursive:!0});let r=ir.stringify(e);await Et.writeFile(n,r,"utf8")}function vc(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function wc(n,e,t,r,o){(!n[e]||typeof n[e]!="object")&&(n[e]={});let i=n[e];return t in i&&!o?!1:(i[t]=r,!0)}async function bc(n,e){return n.format==="codex"?vh(e):yh(e)}async function Sc(n,e,t){return n.format==="codex"?bh(e,t):wh(e,t)}async function Pc(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 o=await bc(r,r.globalConfigPath);if(vc(o,r.mcpServersKey,fe)&&!t)return console.log(`MCP server ${fe} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let i=Fn(r,void 0);return wc(o,r.mcpServersKey,fe,i,t),await Sc(r,r.globalConfigPath,o),console.log(`MCP server ${fe} configured in ${r.globalConfigPath}.`),{success:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${o.message}`}}}async function di(n,e,t=!1){let r=_e[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(_e).join(", ")}`};let o=or.isAbsolute(r.projectConfigPath)?r.projectConfigPath:or.join(e,r.projectConfigPath);try{let i=await bc(r,o);if(vc(i,r.mcpServersKey,fe)&&!t)return console.log(`MCP server ${fe} already configured in ${o}.`),{success:!0,skipped:!0,configPath:o,agentName:n,installType:"project"};let s=Fn(r,e);return wc(i,r.mcpServersKey,fe,s,t),await Sc(r,o,i),console.log(`MCP server ${fe} configured in ${o}.`),{success:!0,configPath:o,agentName:n,installType:"project"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${i.message}`}}}function Ec(n){let e=n.filter(o=>o.success&&!o.skipped).length,t=n.filter(o=>o.skipped).length,r=n.filter(o=>!o.success).length;console.log(),console.log(gh("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`);for(let o of n)!o.success&&o.error&&console.error(` - ${o.agentName??"unknown"}: ${o.error}`);r>0&&(process.exitCode=1)}var ui="deveco-cli";async function Eh(n,e,t){if(n.customPath)return[await Ga(ui,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>Va(ui,e,s,a,t.force)),...n.agents.map(s=>()=>qa(ui,e,s,t.force))],o=5,i=[];for(let s=0;s<r.length;s+=o){let a=r.slice(s,s+o);i.push(...await Promise.all(a.map(c=>c())))}return i}async function Ih(n,e,t){let r=[];for(let{project:o,agent:i}of n.projectAgents){let s=await di(i,o,t);r.push(s)}for(let o of n.agents){let i=await di(o,e,t);r.push(i)}return r}async function Dh(n,e){let t=[];for(let r of n){if(!_e[r])continue;let i=await Pc(r,process.cwd(),e);t.push(i)}return t}async function Ch(n,e,t){if(t.agent&&t.agent.split(",").map(l=>l.trim()).includes("qoder"))throw new Error("Qoder does not support MCP configuration via DevEco CLI. Use other supported agents instead.");let r=t.force??!1,o=n.projectAgents.filter(c=>c.agent!=="qoder"),i=n.agents.filter(c=>c!=="qoder"),s={...n,projectAgents:o,agents:i},a=e?await Ih(s,e,r):await Dh(s.agents,r);a.length>0&&(console.log(Ic("MCP Configuration:")),Ec(a))}async function Ah(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}=rn(n.path,n.project,n.agent);t&&Be(t,"Project directory",n.force),e&&Be(e,"Directory",n.force);let r=await er(n,e,t);if(n.mcp){await Ch(r,t,n);return}let o=Za(),i=await Eh(r,o,n);console.log(),i.length>0&&(console.log(Ic("Skill Installation:")),nn(i))}var Th=new Sh("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 Ah(n)}catch(e){console.error(Ph(e.message)),process.exit(1)}}),Dc=Th;import{Command as _g}from"commander";import{McpServer as Og}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Ng}from"@modelcontextprotocol/sdk/server/stdio.js";import*as qr from"path";import{z as xi}from"zod";var sr=class{tools=new Map;add(e,t){return this.tools.set(e.name,{definition:e,handler:t}),this}getAll(){return Array.from(this.tools.values())}registerToServer(e){for(let{definition:t,handler:r}of this.getAll())e.registerTool(t.name,{description:t.description,inputSchema:t.inputSchema},(async o=>r(o)))}};function pi(){return new sr}import*as xe from"fs";import*as we from"path";import{z as Di}from"zod";import U from"fs";import*as ar from"os";import*as L from"path";import xh from"json5";var kh=3;function mi(n){if(!U.existsSync(n)||!U.statSync(n).isDirectory())return!1;let e=U.existsSync(L.join(n,"build-profile.json5")),t=U.existsSync(L.join(n,"hvigorfile.js"))||U.existsSync(L.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=U.readFileSync(L.join(n,"build-profile.json5"),"utf-8");return xh.parse(r).app!==void 0}catch{return!1}}function Cc(n,e,t){if(e>=t)return null;let r=Mh(n),o=Rh(r);if(o)return o;for(let i of r){let s=Cc(i,e+1,t);if(s)return s}return null}function Mh(n){try{let e=U.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(L.join(n,r.name));return t}catch{return[]}}function Rh(n){for(let e of n)if(mi(e))return e;return null}function De(n){if(!n||n.trim()==="")return null;let e=L.resolve(n),t;try{t=U.realpathSync(e)}catch{t=e}if(!U.existsSync(t))return null;if(mi(t))return t;let r=t;for(let o=1;o<=3;o++){let i=L.dirname(r);if(i===r)break;if(mi(i))return i;r=i}if(U.statSync(t).isDirectory()){let o=Cc(t,0,kh);if(o)return o}return null}var fi=[D()?".bitfun":".idea",".deveco",D()?".cxx":"cxx","compile_commands.json"];function dn(n){return L.join(n,...fi)}function Ac(n){return new Promise(e=>setTimeout(e,n))}var Oh=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function cr(n){let e=L.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&Oh.has(e)}function Tc(n){return L.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function ve(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function hi(n){return ve(n)}function rt(n){let e=hi(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function ln(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)),rt(t)}}catch{}return n}function xc(n){let e=[],t=n.lastIndexOf("file:/");if(t>=0){let r=n.slice(t).replace(/^file:\/+/,"");if(r){let o=r.startsWith("/")?`file://${r}`:`file:///${r}`,i=ln(o);i!==n&&i!==ln(n)&&e.push(i)}}return e}function lr(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??L.join(ar.homedir(),"AppData","Local");return L.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?L.join(ar.homedir(),"Library","Logs","devecocli-mcp-server"):L.join(ar.homedir(),".local","share","devecocli-mcp-server","logs")}function kc(n,e){let t=Nh(e),r=Lh(t,n);if(r!==null)return r;let o=Date.now(),s=`${n.replace(/:/g,"\\:")}=${o}`,a=_h(t,n,s);return Hh(e,a),o}function Nh(n){let e;try{e=U.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function Lh(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let i=parseInt(t.slice(r+1),10);return Number.isFinite(i)&&i>0?i:null}return null}function _h(n,e,t){let r=!1,o=n.map(i=>{if(r)return i;let s=i.indexOf("=");return s<=0?i:i.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):i});return r||o.push(t),o}function Hh(n,e){try{U.mkdirSync(L.dirname(n),{recursive:!0})}catch{}try{U.writeFileSync(n,e.join(`
1253
1253
  `)+`
1254
- `,"utf8")}catch{}}function gi(n,e,t="[Cleanup]"){try{let r=L.dirname(n);if(!U.existsSync(r))return;let o=Date.now();for(let i of U.readdirSync(r,{withFileTypes:!0}))i.isDirectory()&&_h(L.join(r,i.name),o,e,t)}catch{}}function _h(n,e,t,r){try{let{mtimeMs:o}=U.statSync(n);if(e-o<=t)return;U.rmSync(n,{recursive:!0,force:!0});let i=Math.floor((e-o)/1e3);console.error(`${r} Removed expired dir (age ${Math.floor(i/86400)}d ${Math.floor(i%86400/3600)}h): ${n}`)}catch(o){console.error(`${r} Failed to remove expired dir ${n}: ${o}`)}}import*as T from"fs";import*as ur from"path";var Mc="mcp-server.log",Hh="mcp-server",jh={maxSize:10*1024*1024,maxFiles:4},yi=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={...jh,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=lr(),this.currentLogFile=ur.join(this.logDir,Mc),T.existsSync(this.logDir)||T.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${o}`}getRotatedFileName(e,t){return ur.join(this.logDir,`${Hh}-${e}.log.${t}`)}fileExists(e){try{return T.accessSync(e,T.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=T.readdirSync(this.logDir),t=[];for(let o of e)if(o===Mc||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(o)){let i=ur.join(this.logDir,o),s=T.statSync(i);t.push({name:o,mtime:s.mtime,path:i})}t.sort((o,i)=>i.mtime.getTime()-o.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let o=r;o<t.length;o++)try{T.unlinkSync(t[o].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&T.unlinkSync(t);for(let o=this.rotationOptions.maxFiles-1;o>=1;o--){let i=this.getRotatedFileName(e,o),s=this.getRotatedFileName(e,o+1);this.fileExists(i)&&T.renameSync(i,s)}let r=this.getRotatedFileName(e,1);T.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=T.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=T.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{T.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...r){if(this.mode==="silent"||n.LEVEL_ORDER[e]<n.LEVEL_ORDER[this.minLevel])return;let o=r.map(c=>typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),i=o?`${t} ${o}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] ${i}
1255
- `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);T.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{T.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},ie=null;function vi(n=!1){ie&&ie.dispose(),ie=new yi(n)}function Rc(){ie&&(ie.dispose(),ie=null)}function Oc(){ie&&ie.flush()}function Nc(){return ie?.getLogFilePath()??null}function Lc(){return ie?.getLogDirectory()??null}function dr(){return ie||vi(!1),ie}var f={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 _c(n){return"method"in n&&!("id"in n)}import{spawn as Bh}from"child_process";import{EventEmitter as Wh}from"events";import*as Dt from"fs";import*as qc from"path";import*as Hc from"util";var wi="";function jc(n){if(!n||n==="auto"||n==="stdout"||n==="none"){wi="";return}wi=n}function Fc(){return wi||(Lc()??"")}function pr(n,...e){if(e.length===0)return n;try{return Hc.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var d={info(n,...e){f.info(`[lsp] ${pr(n,...e)}`)},warn(n,...e){f.warn(`[lsp] ${pr(n,...e)}`)},error(n,...e){f.error(`[lsp] ${pr(n,...e)}`)},debug(n,...e){f.debug(`[lsp] ${pr(n,...e)}`)}};import*as pn from"fs";import*as mn from"os";import*as It from"path";import $h from"json5";var Fh={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"},mr={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",DEFINITION:"textDocument/definition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",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",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles"},b={...Fh,...mr},O="2.0",se={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"};var $c=8192,bi=100,Bc=.03,Wc=.7,un=900*1e3;function oe(n){if(!pn.existsSync(n))return null;try{let e=pn.readFileSync(n,"utf-8");return e.trim()?$h.parse(e):null}catch{return null}}function Uc(n,e){let t=Math.floor(mn.totalmem()/1048576),r=Math.floor(t*Wc),o,i;e!==void 0&&Number.isFinite(e)&&e>0?(o=e,i=`override(${e})`):(o=$c,n>bi&&(o+=(n-bi)*Bc*1024),i=`formula(moduleCount=${n})`);let s=r>0&&o>r;s&&(o=r);let a=Math.round(o);return d.info(`[computeLspServerMaxSize] source=${i}, physicalTotal=${t}MB, physicalCap(70%)=${r}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function Ce(n){try{let e=It.resolve(n),t=new URL(`file://${e}`).toString();if(mn.platform()==="win32"){let r=t.match(/^file:\/\/\/([A-Za-z]):/);if(r){let o=r[1].toUpperCase(),i=t.substring(`file:///${r[1]}:`.length);t=`file:///${o}%3A${i}`}}return t}catch{return n}}function fr(n){return n&&n.replace(/\\/g,"/")}function G(n){let e=It.normalize(n).replace(/\\/g,"/");if(mn.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function zc(n){return It.join(n,"build-profile.json5")}var hr=class extends Wh{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;ensureDirectories(){let t=qc.join(this.config.logPath,"lspLog");return Dt.existsSync(t)||Dt.mkdirSync(t,{recursive:!0}),Dt.existsSync(this.config.indexingDataLocation)||Dt.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let r=this.ensureDirectories();d.info(`[LspClient] serverMaxSize=${t}MB`);let o=G(r),i=["--expose-gc",`--max-old-space-size=${t}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${o}`,this.config.serverPath,"--stdio",`--logger-path=${o}`,"--logger-level=TRACE"];d.info(`[LspClient] Starting process: node ${i.join(" ")}`);let s=this.config.nodePath;d.info(`[LspClient] nodePath: ${s}`),this.process=Bh(s,i,{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 o=this.buildLspMessage(t);this.process.stdin.write(o,"utf8")}send(t,r,o){let i={jsonrpc:"2.0",method:t,params:r};o!==void 0&&(i.id=o),this.sendRaw(JSON.stringify(i),t)}buildLspMessage(t){return`Content-Length: ${Buffer.from(t,"utf8").length}\r
1254
+ `,"utf8")}catch{}}function gi(n,e,t="[Cleanup]"){try{let r=L.dirname(n);if(!U.existsSync(r))return;let o=Date.now();for(let i of U.readdirSync(r,{withFileTypes:!0}))i.isDirectory()&&jh(L.join(r,i.name),o,e,t)}catch{}}function jh(n,e,t,r){try{let{mtimeMs:o}=U.statSync(n);if(e-o<=t)return;U.rmSync(n,{recursive:!0,force:!0});let i=Math.floor((e-o)/1e3);console.error(`${r} Removed expired dir (age ${Math.floor(i/86400)}d ${Math.floor(i%86400/3600)}h): ${n}`)}catch(o){console.error(`${r} Failed to remove expired dir ${n}: ${o}`)}}import*as T from"fs";import*as ur from"path";var Mc="mcp-server.log",Fh="mcp-server",$h={maxSize:10*1024*1024,maxFiles:4},yi=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={...$h,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=lr(),this.currentLogFile=ur.join(this.logDir,Mc),T.existsSync(this.logDir)||T.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${o}`}getRotatedFileName(e,t){return ur.join(this.logDir,`${Fh}-${e}.log.${t}`)}fileExists(e){try{return T.accessSync(e,T.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=T.readdirSync(this.logDir),t=[];for(let o of e)if(o===Mc||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(o)){let i=ur.join(this.logDir,o),s=T.statSync(i);t.push({name:o,mtime:s.mtime,path:i})}t.sort((o,i)=>i.mtime.getTime()-o.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let o=r;o<t.length;o++)try{T.unlinkSync(t[o].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&T.unlinkSync(t);for(let o=this.rotationOptions.maxFiles-1;o>=1;o--){let i=this.getRotatedFileName(e,o),s=this.getRotatedFileName(e,o+1);this.fileExists(i)&&T.renameSync(i,s)}let r=this.getRotatedFileName(e,1);T.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=T.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=T.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{T.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...r){if(this.mode==="silent"||n.LEVEL_ORDER[e]<n.LEVEL_ORDER[this.minLevel])return;let o=r.map(c=>typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),i=o?`${t} ${o}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] ${i}
1255
+ `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);T.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{T.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},ie=null;function vi(n=!1){ie&&ie.dispose(),ie=new yi(n)}function Rc(){ie&&(ie.dispose(),ie=null)}function Oc(){ie&&ie.flush()}function Nc(){return ie?.getLogFilePath()??null}function Lc(){return ie?.getLogDirectory()??null}function dr(){return ie||vi(!1),ie}var f={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 _c(n){return"method"in n&&!("id"in n)}import{spawn as Uh}from"child_process";import{EventEmitter as zh}from"events";import*as Dt from"fs";import*as qc from"path";import*as Hc from"util";var wi="";function jc(n){if(!n||n==="auto"||n==="stdout"||n==="none"){wi="";return}wi=n}function Fc(){return wi||(Lc()??"")}function pr(n,...e){if(e.length===0)return n;try{return Hc.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var d={info(n,...e){f.info(`[lsp] ${pr(n,...e)}`)},warn(n,...e){f.warn(`[lsp] ${pr(n,...e)}`)},error(n,...e){f.error(`[lsp] ${pr(n,...e)}`)},debug(n,...e){f.debug(`[lsp] ${pr(n,...e)}`)}};import*as pn from"fs";import*as mn from"os";import*as It from"path";import Wh from"json5";var Bh={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"},mr={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",DEFINITION:"textDocument/definition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",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",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles"},b={...Bh,...mr},O="2.0",se={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"};var $c=8192,bi=100,Bc=.03,Wc=.7,un=900*1e3;function oe(n){if(!pn.existsSync(n))return null;try{let e=pn.readFileSync(n,"utf-8");return e.trim()?Wh.parse(e):null}catch{return null}}function Uc(n,e){let t=Math.floor(mn.totalmem()/1048576),r=Math.floor(t*Wc),o,i;e!==void 0&&Number.isFinite(e)&&e>0?(o=e,i=`override(${e})`):(o=$c,n>bi&&(o+=(n-bi)*Bc*1024),i=`formula(moduleCount=${n})`);let s=r>0&&o>r;s&&(o=r);let a=Math.round(o);return d.info(`[computeLspServerMaxSize] source=${i}, physicalTotal=${t}MB, physicalCap(70%)=${r}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function Ce(n){try{let e=It.resolve(n),t=new URL(`file://${e}`).toString();if(mn.platform()==="win32"){let r=t.match(/^file:\/\/\/([A-Za-z]):/);if(r){let o=r[1].toUpperCase(),i=t.substring(`file:///${r[1]}:`.length);t=`file:///${o}%3A${i}`}}return t}catch{return n}}function fr(n){return n&&n.replace(/\\/g,"/")}function G(n){let e=It.normalize(n).replace(/\\/g,"/");if(mn.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function zc(n){return It.join(n,"build-profile.json5")}var hr=class extends zh{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;ensureDirectories(){let t=qc.join(this.config.logPath,"lspLog");return Dt.existsSync(t)||Dt.mkdirSync(t,{recursive:!0}),Dt.existsSync(this.config.indexingDataLocation)||Dt.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let r=this.ensureDirectories();d.info(`[LspClient] serverMaxSize=${t}MB`);let o=G(r),i=["--expose-gc",`--max-old-space-size=${t}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${o}`,this.config.serverPath,"--stdio",`--logger-path=${o}`,"--logger-level=TRACE"];d.info(`[LspClient] Starting process: node ${i.join(" ")}`);let s=this.config.nodePath;d.info(`[LspClient] nodePath: ${s}`),this.process=Uh(s,i,{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 o=this.buildLspMessage(t);this.process.stdin.write(o,"utf8")}send(t,r,o){let i={jsonrpc:"2.0",method:t,params:r};o!==void 0&&(i.id=o),this.sendRaw(JSON.stringify(i),t)}buildLspMessage(t){return`Content-Length: ${Buffer.from(t,"utf8").length}\r
1256
1256
  \r
1257
1257
  ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this.buffer.indexOf(`\r
1258
1258
  \r
1259
- `);if(r===-1)break;let i=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!i){d.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(i[1],10),a=r+4,c=a+s;if(this.buffer.length<c)break;let l=this.buffer.slice(a,c).toString("utf8"),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(o=>{let i=!1,s=()=>{i||(i=!0,clearTimeout(c),r.off("exit",a),o())},a=()=>s();r.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let r=t.search(/\S/);if(r<0||t[r]!=="{"&&t[r]!=="[")return null;let o=0,i=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(i){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(i=!1);continue}if(c==='"'){i=!0;continue}if(c==="{"||c==="["){o++;continue}if((c==="}"||c==="]")&&(o--,o===0)){let l=t.slice(r,a+1),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 gr=class{callbacks=new Map;timeouts=new Map;register(e,t){this.callbacks.set(e,t)}emit(e,t,r){d.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let o=this.callbacks.get(e);o&&(o(t,r),this.callbacks.delete(e))}registerTimeout(e,t,r,o){this.timeouts.has(e)&&clearTimeout(this.timeouts.get(e));let i=setTimeout(()=>{d.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`),o(),this.timeouts.delete(e)},r);this.timeouts.set(e,i)}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)}clear(e){this.clearTimeout(e),this.callbacks.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(`[Diagnostic] addMessage: duplicate message=${r}`);return}this.uniqueMessages.add(r),this.messages.push(new Si(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)}},Si=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var vr=class{map=new Map;register(e,t){let r=this.map.get(e);r||(r=new Set,this.map.set(e,r)),r.add(t)}unregister(e,t){let r=this.map.get(e);r&&(t!==void 0?r.delete(t):r.clear(),r.size===0&&this.map.delete(e))}invoke(e,...t){let r=this.map.get(e);if(r)for(let o of r)try{o(...t)}catch(i){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,i)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function y(n){return typeof n=="object"&&n!==null}function Pi(n){return Array.isArray(n)&&n.every(e=>typeof e=="string")}function Uh(n){if(!y(n))return!1;let e=n.textDocument;return y(e)&&typeof e.uri=="string"}function zh(n){return y(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function qh(n){return y(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 wr=class n{client;isInitialized=!1;stopOnce=null;callbacks=new vr;requestCallbacks=new gr;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;static EXPECTED_DIAGNOSTIC_TYPES=new Set([1e3,2e3,3e3,3001]);constructor(e){this.client=new hr(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 exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.EXIT,params:{}}),se.EXIT),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(b.BROADCAST),this.callbacks.register(b.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(b.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(b.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(b.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:O,method:b.INITIALIZED,params:{editors:e}}),se.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:O,id:0,result:{}}),se.EMPTY)}sendAsyncRequest(e,t,r,o){if(!y(t)){d.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!Uh(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 i=t.textDocument.uri,s=Ce(i);t.textDocument.uri=s,delete t.requestId;let a=o??e;d.info(`[LSP] sendAsyncRequest ${a}, filePath: ${i}`),this.client.sendRaw(JSON.stringify({jsonrpc:O,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(!zh(r)){d.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),b.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!y(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:O,method:b.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),se.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let o=Ce(t);e.textDocument.uri=o,d.info(`[LSP] onAsyncOpenFile, uri: ${o}`);let i=this.diagnosticMap.get(o);i||(i=new yr(o),this.diagnosticMap.set(o,i),this.registerDiagnosticTimeout(o,mr.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(i.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),se.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=Ce(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,mr.PUBLISH_DIAGNOSTICS)),d.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),se.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=Ce(e);d.info(`[LSP] didClose, uri: ${r}`);let o=this.diagnosticMap.get(r);if(!t&&(!o||o.isFromEditor)){d.info(`[LSP] closeFile skip, !diagnostic: ${!o}, isFromEditor: ${o?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.DID_CLOSE,params:{textDocument:{uri:r}}}),se.DID_CLOSE)}getDiagnosticMessage(e){let t=Ce(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 o of t)this.finalizeDiagnostic(o,b.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:O,method:b.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 b.MODULE_INIT_FINISH:return d.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(b.MODULE_INIT_FINISH),this.callbacks.unregister(b.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case b.INDEXING_PROGRESS_UPDATE:return d.info(`[LSP] onIndexingProgressUpdate: ${qh(t.params)}`),this.callbacks.invoke(b.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case b.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case b.ON_PACKAGE_CHANGE_FINISH:d.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case b.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case b.ON_ASYNC_HOVER:this.handleAsyncResponse(t,b.HOVER);return;case b.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,b.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case b.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,b.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;y(t)&&y(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:O,method:b.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(!y(r)){d.warn("[LSP] aceProject/onAsyncHover message invalid");return}let o=r.requestId;if(typeof o!="number"){d.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(o,t,r)}handleForceOpenFile(e){if(!e){d.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,b.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 o=this.diagnosticMap.get(t);if(!o){d.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let i=e.diagnostics||[];i.length!==0?i.forEach(s=>{this.normalizeDiagnostic(s),o.addMessage(r,JSON.stringify(s))}):o.setReceivedType(r),o.hasReceivedAllTypes(n.EXPECTED_DIAGNOSTIC_TYPES)&&this.finalizeDiagnostic(t,b.PUBLISH_DIAGNOSTICS,o.getMessages())}normalizeDiagnostic(e){if(delete e.source,e.severity!==void 0){let t=typeof e.severity=="number"?e.severity:parseInt(e.severity),r={1:"Error",2:"Warning",3:"Information",4:"Hint"};e.severityStr=r[t]||"Unknown",e.severity=e.severityStr}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let r=e[t];r&&typeof r.line=="number"&&(r.line=r.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,n.DIAGNOSTIC_TIMEOUT_MS,()=>{let r=this.diagnosticMap.get(e),o=r?r.getMessages():[];this.finalizeDiagnostic(e,t,o,o.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,o){let i={uri:e,diagnostics:r,...o?{errorMessage:o}:{}};this.requestCallbacks.emit(e,t,i),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import Ei from"path";import*as Cr from"path";var br=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var Sr=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var Pr=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 Ir=class{typeSetting=new Pr;parameterNames=new Er};var Dr=class{constructor(e,t,r,o){this.rootUri=e;this.lspServerWorkspacePath=G(Cr.dirname(t)),this.indexingDataLocation=G(o),this.loggerPath=G(Cr.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new br;gutterIconsSetting=new Sr;inlayHintsSetting=new Ir;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Vc from"path";var fn=class{productName="default";buildModeName="debug";targetName="default";arkTSVersion="1.1";resourceDirectories=[];targetESVersion="ES2021";maxFlowDepth=2e3;caseSensitiveCheck=!0;tsImportSendable=!1;compatibleSdkVersionStage="";useNormalizedOHMUrl=!0;reExportCheckMode="noCheck";skipOhModulesLint=!1;byteCodeHar=!0;obfuscationRuleOptionsEnable=!1;enableStrictCheckOHModules=!1;sourceRoots=[];constructor(e){e&&this.resourceDirectories.push(G(Vc.join(e,"src","main","resources")))}};var Vh="OS",Ct=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${Vh}`;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 fn(e)):this.buildProfileParam=new fn}toString(){return JSON.stringify(this)}};var At=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as ae from"path";import*as kt from"fs";var Ar=class{modulePath;dependencies={};dynamicDependencies={}};var ot=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 Tt=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 Ae from"path";import*as Tr from"fs";var xt=class{name="";version="";storePath="";dependencyPath="";path=""};var A={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:le.OH_PACKAGE_JSON5},hn=`${A.HVIGOR_CACHE}/${A.DEPENDENCY}`,it=`${A.DEPENDENCY}${A.JSON5}`,UC=le.SYNC_OUTPUT_PATH;var gn=class n{dependencyPath;modulePath;projectPath;static FILE_DEPENDENCY_PREFIX="file:";static PARAMETER_PREFIX="@param:";fileSpecPattern;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;static PACKAGE_JSON_PARSER_MAP=new Map;dependencies=[];devDependencies=[];dynamicDependencies=[];static getInstance(e,t,r){let o=this.PACKAGE_JSON_PARSER_MAP.get(e);return o||(o=new n(e,t,r),this.PACKAGE_JSON_PARSER_MAP.set(e,o)),o}constructor(e,t,r){this.dependencyPath=e,this.modulePath=t,this.projectPath=r,this.fileSpecPattern=n.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=Ae.join(this.dependencyPath,A.OH_PACKAGE_JSON5),r=oe(t);r&&(this.dependencies=this.getDependencyList(r,A.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(r,A.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(r,A.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let r=[];if(!y(e))return r;let o=e[t];if(!y(o))return r;for(let[i,s]of Object.entries(o)){if(typeof s!="string"){d.error(`${i} package dependency value is not String ${t}`);continue}let a=new xt;a.name=i;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(n.PARAMETER_PREFIX)||this.parseDependencyPath(i,c,a,!1),r.push(a)}return r}parseDependencyPath(e,t,r,o){if(!(!e||!t))try{let i=Ae.normalize(Ae.join(this.modulePath,A.OH_MODULES_PATH,e));if(!(t.startsWith(n.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){r.dependencyPath=i;return}if(r.path=t,this.fileNameForOhpm.test(t)){r.dependencyPath=i;return}let s=t;if(t.startsWith(n.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(n.FILE_DEPENDENCY_PREFIX.length)),Ae.isAbsolute(s)){r.dependencyPath=i;return}if(!o){let a=Ae.resolve(this.modulePath,s);i=P.ensurePathWithinRoot(this.projectPath,a)}Tr.existsSync(i)&&Tr.statSync(i).isDirectory()&&(r.dependencyPath=i)}catch(i){d.error("parser dependency path is invalid",i)}}};import*as yn from"fs";import*as vn from"path";import Gh from"json5";var xr=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 vn.join(this.projectPath,A.OH_MODULES_PATH,A.OHPM_PATH,A.LOCK_JSON5_FILE)}readLockFile(e){if(!yn.existsSync(e))return d.error("lock file does not exist"),this.clearDependencies(),null;try{let t=yn.readFileSync(e,"utf8"),r=Gh.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(!y(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,A.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,A.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,A.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!y(e))return t;for(let[r,o]of Object.entries(e)){if(!y(o)){d.error(`${r} value is not json object`);continue}typeof o.storePath=="string"&&t.set(r,o.storePath)}return t}getDependencyList(e,t,r){if(!y(e))return[];for(let[o,i]of Object.entries(e))if(y(i)){let s=typeof i.name=="string"?i.name:"";if(r==="."&&s===""||s===r)return this.getFinalDependencyList(e,t,o)}return[]}getFinalDependencyList(e,t,r){let o=e[r];if(!y(o))return d.error("moduleJsonObject is null"),[];let i=[],s=o[t];if(!y(s))return[];for(let[a,c]of Object.entries(s)){if(!y(c))continue;let l=typeof c.specifier=="string"?c.specifier:"",u=typeof c.version=="string"?c.version:"",h=new xt;h.name=a,h.version=u.startsWith(n.FILE_DEPENDENCY_PREFIX)?u.substring(n.FILE_DEPENDENCY_PREFIX.length):u,this.parseDependencyPath(h,r,a,l,u);let v=`${a}@${u}`;this.storePathMap.has(v)&&(h.storePath=this.storePathMap.get(v)||""),i.push(h)}return i}parseDependencyPath(e,t,r,o,i){let s=P.resolvePathWithinRoot(this.projectPath,vn.join(t,A.OH_MODULES_PATH,r));try{let a=i.startsWith(n.FILE_DEPENDENCY_PREFIX)?i.substring(n.FILE_DEPENDENCY_PREFIX.length):i,c=vn.isAbsolute(a)?P.ensurePathWithinRoot(this.projectPath,a):P.resolvePathWithinRoot(this.projectPath,a);yn.existsSync(c)?(e.path=o,e.dependencyPath=this.fileNameForOhpm.test(i)?s:c):e.dependencyPath=s}catch(a){d.error("Invalid dependency path in lock.json5",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};var st=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=zc(this.projectRoot);try{let t=oe(e);if(typeof t!="object"||t===null)return[];let r=t.modules;return Array.isArray(r)?r.filter(o=>{if(typeof o!="object"||o===null)return!1;let i=o;return typeof i.name=="string"&&typeof i.srcPath=="string"}):[]}catch(t){return d.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};function Gc(n){return y(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var wn=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new st(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=ae.join(t,hn),o=ae.join(r,it);if(!kt.existsSync(r)||!kt.existsSync(o)){let c="Dependency map or JSON not found";return d.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let i=new Tt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(r,i),this.parseLockJson(i);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return 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];Gc(l)&&(this.parseSingleModule(l,r,i,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,o=ae.join(r,hn),i=ae.join(o,it);if(!kt.existsSync(o)||!kt.existsSync(i))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 Tt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(o,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(!Gc(l))continue;let u=l.name;if(s&&!s.has(u))continue;let h=P.resolvePathWithinRoot(this.projectPath,l.srcPath),v=ae.join(o,u),I=G(h),k=this.buildModuleDependencies(u,I,v,a);k.moduleName=u,t.push(k)}return t}parseSingleModule(e,t,r,o){let i=e.name,s=P.resolvePathWithinRoot(this.projectPath,e.srcPath),a=ae.join(t,i),c=G(s),l=new Ct(c),u=this.buildModuleDependencies(i,c,a,r);this.parseModuleJson5(c,l);let h=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=i,l.moduleType=i,l.packageName=i,l.moduleDependencies=u,l.moduleJsonParam=new At(h),o.push(l)}buildModuleDependencies(e,t,r,o){let i=new Tt(this.projectPath,e,t);gn.getInstance(r,t,this.projectPath).parseDependency(i),this.parseLockJson(i),i.finalDependencies.push(...o.finalDependencies),i.finalDevDependencies.push(...o.finalDevDependencies),i.finalDynamicDependencies.push(...o.finalDynamicDependencies),i.finalDependencies.push(...i.finalDevDependencies);let a=new Ar;return a.modulePath=t,this.toModuleDependencies(i,a),a}toModuleDependencies(e,t){let r={},o={};for(let i of e.finalDependencies)r[i.name]=new ot(i);for(let i of e.finalDynamicDependencies)o[i.name]=new ot(i);t.dependencies=r,t.dynamicDependencies=o}parseProjectDependencies(e,t){let r=ae.join(e,A.OH_PACKAGE_JSON5);if(!kt.existsSync(r))return;gn.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 xr(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=ae.join(e,"src","main","module.json5"),o=oe(r);if(!y(o)||!y(o.module))return;let i=o.module;t.permissions=this.parseRequestPermissions(i),t.deviceType=this.parseDeviceTypes(i)}parseRequestPermissions(e){let t=[];if(y(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)y(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=ae.join(e,"src","main","resources","base","profile","main_pages.json"),r=oe(t);return!y(r)||!Array.isArray(r.src)?[]:r.src.filter(o=>typeof o=="string")}parseSdkJson(e){let t=this.getSdkPkg();!y(t)||!y(t.data)||(typeof t.data.apiVersion=="string"&&(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=ae.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=oe(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!y(t)||!y(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!y(r)||typeof r.compatibleSdkVersion!="string")return;let[o,i]=this.parseBySplit(r.compatibleSdkVersion);e.compatibleSdkVersion=o,e.compatibleSdkLevel=i}getBuildProfile(){if(this.buildProfileCache===void 0){let e=ae.join(this.projectPath,"build-profile.json5");this.buildProfileCache=oe(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,""];let r=e.substring(0,t),o=e.substring(t+1,e.length-1);return[r,o]}parseDeviceTypes(e){return!y(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 kr=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 Yc=(w=>(w[w.File=1]="File",w[w.Module=2]="Module",w[w.Namespace=3]="Namespace",w[w.Package=4]="Package",w[w.Class=5]="Class",w[w.Method=6]="Method",w[w.Property=7]="Property",w[w.Field=8]="Field",w[w.Constructor=9]="Constructor",w[w.Enum=10]="Enum",w[w.Interface=11]="Interface",w[w.Function=12]="Function",w[w.Variable=13]="Variable",w[w.Constant=14]="Constant",w[w.String=15]="String",w[w.Number=16]="Number",w[w.Boolean=17]="Boolean",w[w.Array=18]="Array",w[w.Object=19]="Object",w[w.Key=20]="Key",w[w.Null=21]="Null",w[w.EnumMember=22]="EnumMember",w[w.Struct=23]="Struct",w[w.Event=24]="Event",w[w.Operator=25]="Operator",w[w.TypeParameter=26]="TypeParameter",w))(Yc||{}),Jc=()=>Object.values(Yc).filter(n=>typeof n=="number");var Mr=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Rr=class{applyEdit=!0;workspaceEdit=new Mr;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new kr(Jc());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Mt;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Or=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Nr=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 Kc=(S=>(S[S.Text=1]="Text",S[S.Method=2]="Method",S[S.Function=3]="Function",S[S.Constructor=4]="Constructor",S[S.Field=5]="Field",S[S.Variable=6]="Variable",S[S.Class=7]="Class",S[S.Interface=8]="Interface",S[S.Module=9]="Module",S[S.Property=10]="Property",S[S.Unit=11]="Unit",S[S.Value=12]="Value",S[S.Enum=13]="Enum",S[S.Keyword=14]="Keyword",S[S.Snippet=15]="Snippet",S[S.Color=16]="Color",S[S.File=17]="File",S[S.Reference=18]="Reference",S[S.Folder=19]="Folder",S[S.EnumMember=20]="EnumMember",S[S.Constant=21]="Constant",S[S.Struct=22]="Struct",S[S.Event=23]="Event",S[S.Operator=24]="Operator",S[S.TypeParameter=25]="TypeParameter",S))(Kc||{}),Zc=()=>Object.values(Kc).filter(n=>typeof n=="number");var _r=class{completionItemKind=new Nr(Zc());completionItem=new Lr;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Hr=class{synchronization=new Or;completion=new _r;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 jr=class{workspace=new Rr;textDocument=new Hr;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};function Rt(n){return y(n)?typeof n.line=="number"&&typeof n.character=="number":!1}function Xc(n){return y(n)?typeof n.uri=="string"&&typeof n.text=="string"&&typeof n.languageId=="string"&&typeof n.version=="number":!1}function Qc(n){if(!y(n)||typeof n.text!="string")return!1;let e=n.range;return y(e)?Rt(e.start)&&Rt(e.end):!1}var $r=class{messageHandle;serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}sdkPath;rootUri;nodeMaxOldSpaceSize;nodePath;constructor(e){this.sdkPath=e.sdkPath,this.rootUri=e.workspaceRoot,this.nodeMaxOldSpaceSize=e.nodeMaxOldSpaceSize,this.nodePath=e.nodePath,this.serverPath=e.arktsLangServerPath,this.logPath=Fc(),this.indexLogPath=e.indexLogPath||this.logPath,this.messageHandle=new wr({serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath,nodePath:this.nodePath}),this.messageHandle.setBroadcastToClients(t=>this.onLspMessage(t))}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 o=Ce(this.rootUri),i=new Dr(o,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new wn(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),i.modules=s;let l=Uc(s.length,this.nodeMaxOldSpaceSize);await this.messageHandle.start(l),this.currentParams=new Fr(o,i,new jr),this.messageHandle.sendInitialize(this.currentParams,1),this.messageHandle.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:O,method:b.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((u,h)=>{this.messageHandle.onIndexingProgressUpdate(h),this.messageHandle.onInitializationCompleted(u)},"LSP initialization",un),this.messageHandle.sendInitialized(e),r=!0}catch(o){this.lastStartErrorMessage=o instanceof Error?o.message:String(o),d.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(r)}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){let t=Ce(e);this.messageHandle.registerRequestCallback(t,(r,o)=>{let i=y(o)?o:{};d.info(`[LSP] onDiagnosticCompleted called, filePath: ${e}`);let s={jsonrpc:O,method:r,params:{uri:typeof i.uri=="string"?i.uri:t,diagnostics:Array.isArray(i.diagnostics)?i.diagnostics.filter(a=>typeof a=="string"):[],...typeof i.errorMessage=="string"?{errorMessage:i.errorMessage}:{}}};this.onLspMessage(s)})}registerRequestCallback(e,t){this.messageHandle.registerRequestCallback(t,(r,o)=>{d.info(`[LSP] onRequestCompleted called, requestId: ${t}, method: ${r}`);let i={jsonrpc:O,id:e,result:y(o)?o.result:void 0};this.onLspMessage(i)})}reloadDependenciesOnly(e){let t=e?.fullReload??!1,r=new wn(this.rootUri,this.sdkPath),o=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,o);return this.applyModuleModelsUpdate(u),d.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${u.length}`),this.lastDepsOnlyForDiff=l,l}let i=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(i.length===0&&s.size===0)return d.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];d.info(`[LspServerProxy] Module-level deps changed, parsing: [${i.join(", ")}]`);let a=r.getDependenciesOnly(i);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),d.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),r=new Map(this.lastDepsOnlyForDiff.map(o=>[o.moduleName??"",o]));for(let o of e){let i=o.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(i,t,r),c=o.dependencies??{},l=o.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(u,h)=>{(o.dependencies??={})[u]=this.makeDeleteEntry(u,h)}),this.markAddAndDeleteInDeps(a,l,(u,h)=>{(o.dynamicDependencies??={})[u]=this.makeDeleteEntry(u,h)})}}getOldDepsForModule(e,t,r){let o=t.get(e),i=o?.moduleDependencies?.dependencies??{},s=o?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(i).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(i=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:i,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let o of Object.keys(t))o in e||(t[o].type="add");for(let o of Object.keys(e))o in t||r(o,e[o])}makeDeleteEntry(e,t){return new ot({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Ct(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new At([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let o of e){let i=o.moduleName??"",s=t.get(i);s?(s.modulePath=o.modulePath,s.moduleDependencies=o):s=this.createMinimalModelFromDepsItem(o),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let o=new Map(r.map(s=>[s.moduleName??"",s])),i=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=o.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,o.delete(a)),i.push(s)}for(let[,s]of o)i.push(this.createMinimalModelFromDepsItem(s));return i}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=fr(Ei.join(t,"default/openharmony/ets/build-tools/ets-loader")),o=fr(Ei.join(t,"default/openharmony/ets/api")),i=fr(Ei.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=o,s.hosSdkPath=i}sendRequest(e){switch(e.method){case b.HOVER:this.handleHoverRequest(e);break;case b.DEFINITION:this.handleDefinitionRequest(e);break;case b.REFERENCES:this.handleReferencesRequest(e);break;default:d.warn(`Unhandled LSP request: ${e.method}`)}}handleHoverRequest(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/hover, params missing or not an object");return}let{textDocument:r,position:o,requestId:i}=t;if(!y(r)||typeof r.uri!="string"||!Rt(o)){d.error("Invalid client textDocument/hover, malformed or missing required parameters");return}if(typeof i!="number"){d.error("Invalid client textDocument/hover, requestId missing or not a number");return}this.registerRequestCallback(e.id,i),this.messageHandle.sendAsyncRequest(b.ON_ASYNC_HOVER,t,i,se.ON_ASYNC_HOVER)}handleDefinitionRequest(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/definition, params missing or not an object");return}let{textDocument:r,position:o}=t;if(!y(r)||typeof r.uri!="string"||!Rt(o)){d.error("Invalid client textDocument/definition, malformed or missing required parameters");return}let i=this.resolveRequestId(t.requestId,e.id);if(!Number.isFinite(i)){d.error("Invalid client textDocument/definition, requestId missing or not a valid number");return}this.registerRequestCallback(e.id,i),this.messageHandle.sendAsyncRequest(b.ON_ASYNC_DEFINITION,t,i,se.ON_ASYNC_DEFINITION)}handleReferencesRequest(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/references, params missing or not an object");return}let{textDocument:r,position:o}=t;if(!y(r)||typeof r.uri!="string"||!Rt(o)){d.error("Invalid client textDocument/references, malformed or missing required parameters");return}let i=this.resolveRequestId(t.requestId,e.id);if(!Number.isFinite(i)){d.error("Invalid client textDocument/references, requestId missing or not a valid number");return}this.registerRequestCallback(e.id,i),this.messageHandle.sendAsyncRequest(b.ON_ASYNC_FIND_USAGES,t,i,se.ON_ASYNC_FIND_USAGES)}resolveRequestId(e,t){let r=e??t;return typeof r=="number"?r:Number(r)}sendNotification(e){if(!_c(e)){d.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case b.DID_OPEN:this.handleDidOpenNotification(e);break;case b.DID_CHANGE:this.handleDidChangeNotification(e);break;case b.DID_CLOSE:this.handleDidCloseNotification(e);break;case b.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:this.handleDidChangePackageDependencies(e);break;case b.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;default:d.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/didOpen, params missing or not an object");return}let{textDocument:r,editorFiles:o}=t;if(!Xc(r)||!Pi(o)){d.error("Invalid client textDocument/didOpen, malformed or missing required parameters");return}let s={isFromEditor:typeof t.isFromEditor=="boolean"?t.isFromEditor:!1,editorFiles:o,textDocument:r};this.registerDiagnosticCallback(r.uri),this.messageHandle.onAsyncOpenFile(s)}handleDidChangeNotification(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/didChange, params missing or not an object");return}let{textDocument:r,contentChanges:o}=t;if(!y(r)||typeof r.uri!="string"||typeof r.version!="number"){d.error("Invalid client textDocument/didChange, malformed or missing required parameters");return}if(!Array.isArray(o)||!o.every(Qc)){d.error("Invalid client textDocument/didChange, contentChanges invalid");return}let i=r.uri,s=r.version;this.registerDiagnosticCallback(i),this.messageHandle.onAsyncDidChange({uri:i,version:s,contentChanges:o})}handleDidCloseNotification(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/didClose, params missing or not an object");return}let{textDocument:r}=t;if(!y(r)||typeof r.uri!="string"){d.error("Invalid client textDocument/didClose, malformed or missing required parameters");return}let o=typeof t.isManual=="boolean"?t.isManual:!1;this.messageHandle.closeFile(r.uri,o)}handleDidChangePackageDependencies(e){let t=e.params;if(!y(t)){d.error("Invalid client aceProject/onDidChangePakcageDependencies, params missing or not an object");return}let{moduleSet:r}=t;if(!Array.isArray(r)||r.length===0){d.error("Invalid client aceProject/onDidChangePakcageDependencies, malformed or missing required parameters");return}this.messageHandle.sendModuleDependencyUpdate(t)}handleDidChangeWatchedFiles(e){let t=e.params;if(!y(t)){d.error("Invalid client workspace/didChangeWatchedFiles, params missing or not an object");return}let{changes:r}=t;if(!Array.isArray(r)){d.error("Invalid client workspace/didChangeWatchedFiles, malformed or missing required parameters");return}this.messageHandle.onDidChangeWatchedFiles(r)}withResettableTimeout(e,t,r){return new Promise((o,i)=>{let s,a=()=>{s=setTimeout(()=>{i(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),o()},c)})}async dispose(){await this.messageHandle.stop()}};import*as Te from"fs";import*as We from"path";import{createHash as Yh}from"crypto";import{EventEmitter as Jh}from"events";var Br=class extends Jh{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r}projectRoot;watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),r=new Set(this.watchers.keys());for(let o of t)r.has(o)||this.watchFile(o);for(let o of r)t.has(o)||(this.unwatchFile(o),d.info(`[ConfigFileWatcher] Stopped watching: ${o}`));d.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!Te.existsSync(t)){d.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Te.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 o of t){let i=P.resolvePathWithinRoot(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:i,relativePath:o.srcPath,timestamp:r,moduleName:o.name})}}emitModuleRemovedEvents(t,r){for(let o of t){let i=P.resolvePathWithinRoot(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:i,relativePath:o.srcPath,timestamp:r,removedModuleName:o.name})}}emitModuleRenamedEvents(t,r){for(let o of t){let i=P.resolvePathWithinRoot(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:i,relativePath:o.after.srcPath,timestamp:r,moduleName:o.after.name,removedModuleName:o.before.name})}}emitModuleMovedEvents(t,r){for(let o of t){let i=P.resolvePathWithinRoot(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:i,relativePath:o.after.srcPath,timestamp:r,moduleName:o.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let r=Date.now();this.emitModuleAddedEvents(t.added,r),this.emitModuleRemovedEvents(t.removed,r),this.emitModuleRenamedEvents(t.renamed,r),this.emitModuleMovedEvents(t.moved,r)}onBuildProfileChanged(){let t="__build_profile__",r=this.debounceTimers.get(t);r&&clearTimeout(r);let o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(i);if(s===this.lastModulesSnapshot){d.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,i);this.lastModules=i,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,o)}computeModulesSnapshot(t){return t.map(o=>`${o.name}::${o.srcPath}`).sort().join("|")}diffModules(t,r){let o=this.buildModuleMatchState(r),i={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,o),this.matchRenamedModules(t,o,i),this.matchMovedModules(t,o,i),this.collectRemovedModules(t,o,i),this.collectAddedModules(r,o,i),i}buildModuleMatchState(t){let r=new Map,o=new Map;for(let i of t)r.set(i.srcPath,i),o.set(i.name,i);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:o}}matchExactModules(t,r){for(let o of t){let i=r.newBySrc.get(o.srcPath);i&&i.name===o.name&&(r.matchedOld.add(o),r.matchedNew.add(i))}}matchRenamedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newBySrc.get(i.srcPath);s&&!r.matchedNew.has(s)&&s.name!==i.name&&(o.renamed.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}matchMovedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newByName.get(i.name);s&&!r.matchedNew.has(s)&&s.srcPath!==i.srcPath&&(o.moved.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}collectRemovedModules(t,r,o){for(let i of t)r.matchedOld.has(i)||o.removed.push(i)}collectAddedModules(t,r,o){for(let i of t)r.matchedNew.has(i)||o.added.push(i)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=oe(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return d.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=We.join(this.projectRoot,A.OH_PACKAGE_JSON5);Te.existsSync(r)&&t.push(r);let o=this.parseModulesFromBuildProfile();for(let i of o){let s=P.resolvePathWithinRoot(this.projectRoot,i.srcPath),a=We.join(s,A.OH_PACKAGE_JSON5);Te.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return We.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Te.readFileSync(t,"utf-8");return Yh("sha256").update(r).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let r=this.computeFileHash(t);r&&this.contentHashes.set(t,r);let o=Te.watch(t,i=>{i==="change"&&this.onFileChanged(t)});o.on("error",i=>{d.error(`[ConfigFileWatcher] Watch error for ${t}: ${i.message}`)}),this.watchers.set(t,o)}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 o=this.debounceTimers.get(t);o&&(clearTimeout(o),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.computeFileHash(t);if(!i){d.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===i){d.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,i),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,o)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),d.info("[ConfigFileWatcher] All watchers stopped")}};import*as Ue from"fs";import*as ue from"path";import{createHash as Kh}from"crypto";import{EventEmitter as Zh}from"events";var Wr=class extends Zh{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=ue.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(!Ue.existsSync(this.depMapDir)){d.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=Ue.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 G(ue.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let o=r.replace(/\\/g,"/"),i;if(o===A.OH_PACKAGE_JSON5)i="root-oh-package";else if(o===it)i="dep-map-json";else{let a=o.match(/^([^/]+)\/oh-package\.json5$/);i=a?`module:${a[1]}`:""}if(!i)return;let s=ue.join(this.depMapDir,r);Ue.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=ue.join(this.depMapDir,A.OH_PACKAGE_JSON5),r=ue.join(this.depMapDir,it),o=this.parseModulesFromDepMap(),i=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...o.map(s=>({path:ue.join(this.depMapDir,s.name,A.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of i){if(!Ue.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=ue.join(this.depMapDir,it);try{let r=oe(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return 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,o,i){for(let s of t)s.startsWith("module:")?(o.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(o.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(i.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,o,i,s){for(let a of t)s.push(a.info),o.add(a.info.newName),i.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let o=new Set;for(let i of t)i.startsWith("dep-added:")&&o.add(i.substring(10));for(let i of r)o.add(i.info.newName);return o}emitIncrementalReload(t,r,o,i,s){d.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...o].join(",")}], added=[${[...i].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...o],addedModuleNames:[...i],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:r}=this.collectPendingState();if(t.length===0&&r.length===0)return;if(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 o=new Set,i=new Set,s=new Set,a=[];this.processTagsIntoSets(t,o,i,s),this.processRenameEntries(r,o,i,s,a);for(let l of i)s.delete(l);if(i.size===0&&s.size===0&&a.length===0){d.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(o,i,s,c,a)}normalizeSrcPath(t){return G(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(i=>[i.name,i])),o=new Map(t.map(i=>[this.normalizeSrcPath(i.srcPath),i]));return{byName:r,bySrcPath:o}}detectModuleRenames(t,r,o,i){for(let[s,a]of t){let c=r.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),o.add(a.name),i.add(c.name);let l=ue.join(this.depMapDir,a.name,A.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(l)),d.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,r,o,i){for(let[s,a]of t){if(o.has(s))continue;let c=r.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),o.add(s),i.add(s),d.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,o){for(let[i]of t)o.has(i)||r.has(i)||(this.pendingTags.push(`dep-added:${i}`),o.add(i))}detectRemovedModules(t,r,o){for(let[i]of t)if(!o.has(i)&&!r.has(i)){this.pendingTags.push(`dep-removed:${i}`),o.add(i);let s=ue.join(this.depMapDir,i,A.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(o=>o.startsWith("dep-")),r=this.pendingRenames.map(o=>`${o.kind}(${o.info.oldName}\u2192${o.info.newName})`);d.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:o}=this.buildModuleLookupMaps(this.lastModules),{byName:i,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(o,s,a,c),this.detectModuleMoves(r,i,a,c),this.detectAddedModules(i,r,c),this.detectRemovedModules(r,i,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=Ue.readFileSync(t,"utf-8");return Kh("sha256").update(r).digest("hex")}catch{return null}}};import*as el from"os";import*as tl from"path";import{spawn as Xh}from"child_process";var Qh=600*1e3;function eg(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 Ur(n){return n.join("")}function tg(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
1259
+ `);if(r===-1)break;let i=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!i){d.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(i[1],10),a=r+4,c=a+s;if(this.buffer.length<c)break;let l=this.buffer.slice(a,c).toString("utf8"),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(o=>{let i=!1,s=()=>{i||(i=!0,clearTimeout(c),r.off("exit",a),o())},a=()=>s();r.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let r=t.search(/\S/);if(r<0||t[r]!=="{"&&t[r]!=="[")return null;let o=0,i=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(i){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(i=!1);continue}if(c==='"'){i=!0;continue}if(c==="{"||c==="["){o++;continue}if((c==="}"||c==="]")&&(o--,o===0)){let l=t.slice(r,a+1),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 gr=class{callbacks=new Map;timeouts=new Map;register(e,t){this.callbacks.set(e,t)}emit(e,t,r){d.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let o=this.callbacks.get(e);o&&(o(t,r),this.callbacks.delete(e))}registerTimeout(e,t,r,o){this.timeouts.has(e)&&clearTimeout(this.timeouts.get(e));let i=setTimeout(()=>{d.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`),o(),this.timeouts.delete(e)},r);this.timeouts.set(e,i)}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)}clear(e){this.clearTimeout(e),this.callbacks.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(`[Diagnostic] addMessage: duplicate message=${r}`);return}this.uniqueMessages.add(r),this.messages.push(new Si(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)}},Si=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var vr=class{map=new Map;register(e,t){let r=this.map.get(e);r||(r=new Set,this.map.set(e,r)),r.add(t)}unregister(e,t){let r=this.map.get(e);r&&(t!==void 0?r.delete(t):r.clear(),r.size===0&&this.map.delete(e))}invoke(e,...t){let r=this.map.get(e);if(r)for(let o of r)try{o(...t)}catch(i){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,i)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function y(n){return typeof n=="object"&&n!==null}function Pi(n){return Array.isArray(n)&&n.every(e=>typeof e=="string")}function qh(n){if(!y(n))return!1;let e=n.textDocument;return y(e)&&typeof e.uri=="string"}function Vh(n){return y(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function Gh(n){return y(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 wr=class n{client;isInitialized=!1;stopOnce=null;callbacks=new vr;requestCallbacks=new gr;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;static EXPECTED_DIAGNOSTIC_TYPES=new Set([1e3,2e3,3e3,3001]);constructor(e){this.client=new hr(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 exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.EXIT,params:{}}),se.EXIT),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(b.BROADCAST),this.callbacks.register(b.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(b.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(b.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(b.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:O,method:b.INITIALIZED,params:{editors:e}}),se.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:O,id:0,result:{}}),se.EMPTY)}sendAsyncRequest(e,t,r,o){if(!y(t)){d.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!qh(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 i=t.textDocument.uri,s=Ce(i);t.textDocument.uri=s,delete t.requestId;let a=o??e;d.info(`[LSP] sendAsyncRequest ${a}, filePath: ${i}`),this.client.sendRaw(JSON.stringify({jsonrpc:O,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(!Vh(r)){d.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),b.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!y(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:O,method:b.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),se.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let o=Ce(t);e.textDocument.uri=o,d.info(`[LSP] onAsyncOpenFile, uri: ${o}`);let i=this.diagnosticMap.get(o);i||(i=new yr(o),this.diagnosticMap.set(o,i),this.registerDiagnosticTimeout(o,mr.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(i.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),se.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=Ce(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,mr.PUBLISH_DIAGNOSTICS)),d.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),se.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=Ce(e);d.info(`[LSP] didClose, uri: ${r}`);let o=this.diagnosticMap.get(r);if(!t&&(!o||o.isFromEditor)){d.info(`[LSP] closeFile skip, !diagnostic: ${!o}, isFromEditor: ${o?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.DID_CLOSE,params:{textDocument:{uri:r}}}),se.DID_CLOSE)}getDiagnosticMessage(e){let t=Ce(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 o of t)this.finalizeDiagnostic(o,b.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:O,method:b.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 b.MODULE_INIT_FINISH:return d.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(b.MODULE_INIT_FINISH),this.callbacks.unregister(b.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case b.INDEXING_PROGRESS_UPDATE:return d.info(`[LSP] onIndexingProgressUpdate: ${Gh(t.params)}`),this.callbacks.invoke(b.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case b.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case b.ON_PACKAGE_CHANGE_FINISH:d.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case b.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case b.ON_ASYNC_HOVER:this.handleAsyncResponse(t,b.HOVER);return;case b.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,b.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case b.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,b.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;y(t)&&y(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:O,method:b.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(!y(r)){d.warn("[LSP] aceProject/onAsyncHover message invalid");return}let o=r.requestId;if(typeof o!="number"){d.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(o,t,r)}handleForceOpenFile(e){if(!e){d.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,b.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 o=this.diagnosticMap.get(t);if(!o){d.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let i=e.diagnostics||[];i.length!==0?i.forEach(s=>{this.normalizeDiagnostic(s),o.addMessage(r,JSON.stringify(s))}):o.setReceivedType(r),o.hasReceivedAllTypes(n.EXPECTED_DIAGNOSTIC_TYPES)&&this.finalizeDiagnostic(t,b.PUBLISH_DIAGNOSTICS,o.getMessages())}normalizeDiagnostic(e){if(delete e.source,e.severity!==void 0){let t=typeof e.severity=="number"?e.severity:parseInt(e.severity),r={1:"Error",2:"Warning",3:"Information",4:"Hint"};e.severityStr=r[t]||"Unknown",e.severity=e.severityStr}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let r=e[t];r&&typeof r.line=="number"&&(r.line=r.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,n.DIAGNOSTIC_TIMEOUT_MS,()=>{let r=this.diagnosticMap.get(e),o=r?r.getMessages():[];this.finalizeDiagnostic(e,t,o,o.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,o){let i={uri:e,diagnostics:r,...o?{errorMessage:o}:{}};this.requestCallbacks.emit(e,t,i),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import Ei from"path";import*as Cr from"path";var br=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var Sr=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var Pr=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 Ir=class{typeSetting=new Pr;parameterNames=new Er};var Dr=class{constructor(e,t,r,o){this.rootUri=e;this.lspServerWorkspacePath=G(Cr.dirname(t)),this.indexingDataLocation=G(o),this.loggerPath=G(Cr.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new br;gutterIconsSetting=new Sr;inlayHintsSetting=new Ir;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Vc from"path";var fn=class{productName="default";buildModeName="debug";targetName="default";arkTSVersion="1.1";resourceDirectories=[];targetESVersion="ES2021";maxFlowDepth=2e3;caseSensitiveCheck=!0;tsImportSendable=!1;compatibleSdkVersionStage="";useNormalizedOHMUrl=!0;reExportCheckMode="noCheck";skipOhModulesLint=!1;byteCodeHar=!0;obfuscationRuleOptionsEnable=!1;enableStrictCheckOHModules=!1;sourceRoots=[];constructor(e){e&&this.resourceDirectories.push(G(Vc.join(e,"src","main","resources")))}};var Yh="OS",Ct=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${Yh}`;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 fn(e)):this.buildProfileParam=new fn}toString(){return JSON.stringify(this)}};var At=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as ae from"path";import*as kt from"fs";var Ar=class{modulePath;dependencies={};dynamicDependencies={}};var ot=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 Tt=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 Ae from"path";import*as Tr from"fs";var xt=class{name="";version="";storePath="";dependencyPath="";path=""};var A={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:le.OH_PACKAGE_JSON5},hn=`${A.HVIGOR_CACHE}/${A.DEPENDENCY}`,it=`${A.DEPENDENCY}${A.JSON5}`,qC=le.SYNC_OUTPUT_PATH;var gn=class n{dependencyPath;modulePath;projectPath;static FILE_DEPENDENCY_PREFIX="file:";static PARAMETER_PREFIX="@param:";fileSpecPattern;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;static PACKAGE_JSON_PARSER_MAP=new Map;dependencies=[];devDependencies=[];dynamicDependencies=[];static getInstance(e,t,r){let o=this.PACKAGE_JSON_PARSER_MAP.get(e);return o||(o=new n(e,t,r),this.PACKAGE_JSON_PARSER_MAP.set(e,o)),o}constructor(e,t,r){this.dependencyPath=e,this.modulePath=t,this.projectPath=r,this.fileSpecPattern=n.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=Ae.join(this.dependencyPath,A.OH_PACKAGE_JSON5),r=oe(t);r&&(this.dependencies=this.getDependencyList(r,A.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(r,A.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(r,A.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let r=[];if(!y(e))return r;let o=e[t];if(!y(o))return r;for(let[i,s]of Object.entries(o)){if(typeof s!="string"){d.error(`${i} package dependency value is not String ${t}`);continue}let a=new xt;a.name=i;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(n.PARAMETER_PREFIX)||this.parseDependencyPath(i,c,a,!1),r.push(a)}return r}parseDependencyPath(e,t,r,o){if(!(!e||!t))try{let i=Ae.normalize(Ae.join(this.modulePath,A.OH_MODULES_PATH,e));if(!(t.startsWith(n.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){r.dependencyPath=i;return}if(r.path=t,this.fileNameForOhpm.test(t)){r.dependencyPath=i;return}let s=t;if(t.startsWith(n.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(n.FILE_DEPENDENCY_PREFIX.length)),Ae.isAbsolute(s)){r.dependencyPath=i;return}if(!o){let a=Ae.resolve(this.modulePath,s);i=P.ensurePathWithinRoot(this.projectPath,a)}Tr.existsSync(i)&&Tr.statSync(i).isDirectory()&&(r.dependencyPath=i)}catch(i){d.error("parser dependency path is invalid",i)}}};import*as yn from"fs";import*as vn from"path";import Jh from"json5";var xr=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 vn.join(this.projectPath,A.OH_MODULES_PATH,A.OHPM_PATH,A.LOCK_JSON5_FILE)}readLockFile(e){if(!yn.existsSync(e))return d.error("lock file does not exist"),this.clearDependencies(),null;try{let t=yn.readFileSync(e,"utf8"),r=Jh.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(!y(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,A.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,A.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,A.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!y(e))return t;for(let[r,o]of Object.entries(e)){if(!y(o)){d.error(`${r} value is not json object`);continue}typeof o.storePath=="string"&&t.set(r,o.storePath)}return t}getDependencyList(e,t,r){if(!y(e))return[];for(let[o,i]of Object.entries(e))if(y(i)){let s=typeof i.name=="string"?i.name:"";if(r==="."&&s===""||s===r)return this.getFinalDependencyList(e,t,o)}return[]}getFinalDependencyList(e,t,r){let o=e[r];if(!y(o))return d.error("moduleJsonObject is null"),[];let i=[],s=o[t];if(!y(s))return[];for(let[a,c]of Object.entries(s)){if(!y(c))continue;let l=typeof c.specifier=="string"?c.specifier:"",u=typeof c.version=="string"?c.version:"",h=new xt;h.name=a,h.version=u.startsWith(n.FILE_DEPENDENCY_PREFIX)?u.substring(n.FILE_DEPENDENCY_PREFIX.length):u,this.parseDependencyPath(h,r,a,l,u);let v=`${a}@${u}`;this.storePathMap.has(v)&&(h.storePath=this.storePathMap.get(v)||""),i.push(h)}return i}parseDependencyPath(e,t,r,o,i){let s=P.resolvePathWithinRoot(this.projectPath,vn.join(t,A.OH_MODULES_PATH,r));try{let a=i.startsWith(n.FILE_DEPENDENCY_PREFIX)?i.substring(n.FILE_DEPENDENCY_PREFIX.length):i,c=vn.isAbsolute(a)?P.ensurePathWithinRoot(this.projectPath,a):P.resolvePathWithinRoot(this.projectPath,a);yn.existsSync(c)?(e.path=o,e.dependencyPath=this.fileNameForOhpm.test(i)?s:c):e.dependencyPath=s}catch(a){d.error("Invalid dependency path in lock.json5",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};var st=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=zc(this.projectRoot);try{let t=oe(e);if(typeof t!="object"||t===null)return[];let r=t.modules;return Array.isArray(r)?r.filter(o=>{if(typeof o!="object"||o===null)return!1;let i=o;return typeof i.name=="string"&&typeof i.srcPath=="string"}):[]}catch(t){return d.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};function Gc(n){return y(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var wn=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new st(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=ae.join(t,hn),o=ae.join(r,it);if(!kt.existsSync(r)||!kt.existsSync(o)){let c="Dependency map or JSON not found";return d.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let i=new Tt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(r,i),this.parseLockJson(i);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return 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];Gc(l)&&(this.parseSingleModule(l,r,i,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,o=ae.join(r,hn),i=ae.join(o,it);if(!kt.existsSync(o)||!kt.existsSync(i))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 Tt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(o,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(!Gc(l))continue;let u=l.name;if(s&&!s.has(u))continue;let h=P.resolvePathWithinRoot(this.projectPath,l.srcPath),v=ae.join(o,u),I=G(h),k=this.buildModuleDependencies(u,I,v,a);k.moduleName=u,t.push(k)}return t}parseSingleModule(e,t,r,o){let i=e.name,s=P.resolvePathWithinRoot(this.projectPath,e.srcPath),a=ae.join(t,i),c=G(s),l=new Ct(c),u=this.buildModuleDependencies(i,c,a,r);this.parseModuleJson5(c,l);let h=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=i,l.moduleType=i,l.packageName=i,l.moduleDependencies=u,l.moduleJsonParam=new At(h),o.push(l)}buildModuleDependencies(e,t,r,o){let i=new Tt(this.projectPath,e,t);gn.getInstance(r,t,this.projectPath).parseDependency(i),this.parseLockJson(i),i.finalDependencies.push(...o.finalDependencies),i.finalDevDependencies.push(...o.finalDevDependencies),i.finalDynamicDependencies.push(...o.finalDynamicDependencies),i.finalDependencies.push(...i.finalDevDependencies);let a=new Ar;return a.modulePath=t,this.toModuleDependencies(i,a),a}toModuleDependencies(e,t){let r={},o={};for(let i of e.finalDependencies)r[i.name]=new ot(i);for(let i of e.finalDynamicDependencies)o[i.name]=new ot(i);t.dependencies=r,t.dynamicDependencies=o}parseProjectDependencies(e,t){let r=ae.join(e,A.OH_PACKAGE_JSON5);if(!kt.existsSync(r))return;gn.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 xr(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=ae.join(e,"src","main","module.json5"),o=oe(r);if(!y(o)||!y(o.module))return;let i=o.module;t.permissions=this.parseRequestPermissions(i),t.deviceType=this.parseDeviceTypes(i)}parseRequestPermissions(e){let t=[];if(y(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)y(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=ae.join(e,"src","main","resources","base","profile","main_pages.json"),r=oe(t);return!y(r)||!Array.isArray(r.src)?[]:r.src.filter(o=>typeof o=="string")}parseSdkJson(e){let t=this.getSdkPkg();!y(t)||!y(t.data)||(typeof t.data.apiVersion=="string"&&(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=ae.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=oe(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!y(t)||!y(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!y(r)||typeof r.compatibleSdkVersion!="string")return;let[o,i]=this.parseBySplit(r.compatibleSdkVersion);e.compatibleSdkVersion=o,e.compatibleSdkLevel=i}getBuildProfile(){if(this.buildProfileCache===void 0){let e=ae.join(this.projectPath,"build-profile.json5");this.buildProfileCache=oe(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,""];let r=e.substring(0,t),o=e.substring(t+1,e.length-1);return[r,o]}parseDeviceTypes(e){return!y(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 kr=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 Yc=(w=>(w[w.File=1]="File",w[w.Module=2]="Module",w[w.Namespace=3]="Namespace",w[w.Package=4]="Package",w[w.Class=5]="Class",w[w.Method=6]="Method",w[w.Property=7]="Property",w[w.Field=8]="Field",w[w.Constructor=9]="Constructor",w[w.Enum=10]="Enum",w[w.Interface=11]="Interface",w[w.Function=12]="Function",w[w.Variable=13]="Variable",w[w.Constant=14]="Constant",w[w.String=15]="String",w[w.Number=16]="Number",w[w.Boolean=17]="Boolean",w[w.Array=18]="Array",w[w.Object=19]="Object",w[w.Key=20]="Key",w[w.Null=21]="Null",w[w.EnumMember=22]="EnumMember",w[w.Struct=23]="Struct",w[w.Event=24]="Event",w[w.Operator=25]="Operator",w[w.TypeParameter=26]="TypeParameter",w))(Yc||{}),Jc=()=>Object.values(Yc).filter(n=>typeof n=="number");var Mr=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Rr=class{applyEdit=!0;workspaceEdit=new Mr;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new kr(Jc());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Mt;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Or=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Nr=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 Kc=(S=>(S[S.Text=1]="Text",S[S.Method=2]="Method",S[S.Function=3]="Function",S[S.Constructor=4]="Constructor",S[S.Field=5]="Field",S[S.Variable=6]="Variable",S[S.Class=7]="Class",S[S.Interface=8]="Interface",S[S.Module=9]="Module",S[S.Property=10]="Property",S[S.Unit=11]="Unit",S[S.Value=12]="Value",S[S.Enum=13]="Enum",S[S.Keyword=14]="Keyword",S[S.Snippet=15]="Snippet",S[S.Color=16]="Color",S[S.File=17]="File",S[S.Reference=18]="Reference",S[S.Folder=19]="Folder",S[S.EnumMember=20]="EnumMember",S[S.Constant=21]="Constant",S[S.Struct=22]="Struct",S[S.Event=23]="Event",S[S.Operator=24]="Operator",S[S.TypeParameter=25]="TypeParameter",S))(Kc||{}),Zc=()=>Object.values(Kc).filter(n=>typeof n=="number");var _r=class{completionItemKind=new Nr(Zc());completionItem=new Lr;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Hr=class{synchronization=new Or;completion=new _r;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 jr=class{workspace=new Rr;textDocument=new Hr;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};function Rt(n){return y(n)?typeof n.line=="number"&&typeof n.character=="number":!1}function Xc(n){return y(n)?typeof n.uri=="string"&&typeof n.text=="string"&&typeof n.languageId=="string"&&typeof n.version=="number":!1}function Qc(n){if(!y(n)||typeof n.text!="string")return!1;let e=n.range;return y(e)?Rt(e.start)&&Rt(e.end):!1}var $r=class{messageHandle;serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}sdkPath;rootUri;nodeMaxOldSpaceSize;nodePath;constructor(e){this.sdkPath=e.sdkPath,this.rootUri=e.workspaceRoot,this.nodeMaxOldSpaceSize=e.nodeMaxOldSpaceSize,this.nodePath=e.nodePath,this.serverPath=e.arktsLangServerPath,this.logPath=Fc(),this.indexLogPath=e.indexLogPath||this.logPath,this.messageHandle=new wr({serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath,nodePath:this.nodePath}),this.messageHandle.setBroadcastToClients(t=>this.onLspMessage(t))}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 o=Ce(this.rootUri),i=new Dr(o,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new wn(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),i.modules=s;let l=Uc(s.length,this.nodeMaxOldSpaceSize);await this.messageHandle.start(l),this.currentParams=new Fr(o,i,new jr),this.messageHandle.sendInitialize(this.currentParams,1),this.messageHandle.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:O,method:b.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((u,h)=>{this.messageHandle.onIndexingProgressUpdate(h),this.messageHandle.onInitializationCompleted(u)},"LSP initialization",un),this.messageHandle.sendInitialized(e),r=!0}catch(o){this.lastStartErrorMessage=o instanceof Error?o.message:String(o),d.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(r)}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){let t=Ce(e);this.messageHandle.registerRequestCallback(t,(r,o)=>{let i=y(o)?o:{};d.info(`[LSP] onDiagnosticCompleted called, filePath: ${e}`);let s={jsonrpc:O,method:r,params:{uri:typeof i.uri=="string"?i.uri:t,diagnostics:Array.isArray(i.diagnostics)?i.diagnostics.filter(a=>typeof a=="string"):[],...typeof i.errorMessage=="string"?{errorMessage:i.errorMessage}:{}}};this.onLspMessage(s)})}registerRequestCallback(e,t){this.messageHandle.registerRequestCallback(t,(r,o)=>{d.info(`[LSP] onRequestCompleted called, requestId: ${t}, method: ${r}`);let i={jsonrpc:O,id:e,result:y(o)?o.result:void 0};this.onLspMessage(i)})}reloadDependenciesOnly(e){let t=e?.fullReload??!1,r=new wn(this.rootUri,this.sdkPath),o=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,o);return this.applyModuleModelsUpdate(u),d.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${u.length}`),this.lastDepsOnlyForDiff=l,l}let i=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(i.length===0&&s.size===0)return d.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];d.info(`[LspServerProxy] Module-level deps changed, parsing: [${i.join(", ")}]`);let a=r.getDependenciesOnly(i);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),d.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),r=new Map(this.lastDepsOnlyForDiff.map(o=>[o.moduleName??"",o]));for(let o of e){let i=o.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(i,t,r),c=o.dependencies??{},l=o.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(u,h)=>{(o.dependencies??={})[u]=this.makeDeleteEntry(u,h)}),this.markAddAndDeleteInDeps(a,l,(u,h)=>{(o.dynamicDependencies??={})[u]=this.makeDeleteEntry(u,h)})}}getOldDepsForModule(e,t,r){let o=t.get(e),i=o?.moduleDependencies?.dependencies??{},s=o?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(i).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(i=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:i,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let o of Object.keys(t))o in e||(t[o].type="add");for(let o of Object.keys(e))o in t||r(o,e[o])}makeDeleteEntry(e,t){return new ot({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Ct(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new At([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let o of e){let i=o.moduleName??"",s=t.get(i);s?(s.modulePath=o.modulePath,s.moduleDependencies=o):s=this.createMinimalModelFromDepsItem(o),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let o=new Map(r.map(s=>[s.moduleName??"",s])),i=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=o.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,o.delete(a)),i.push(s)}for(let[,s]of o)i.push(this.createMinimalModelFromDepsItem(s));return i}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=fr(Ei.join(t,"default/openharmony/ets/build-tools/ets-loader")),o=fr(Ei.join(t,"default/openharmony/ets/api")),i=fr(Ei.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=o,s.hosSdkPath=i}sendRequest(e){switch(e.method){case b.HOVER:this.handleHoverRequest(e);break;case b.DEFINITION:this.handleDefinitionRequest(e);break;case b.REFERENCES:this.handleReferencesRequest(e);break;default:d.warn(`Unhandled LSP request: ${e.method}`)}}handleHoverRequest(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/hover, params missing or not an object");return}let{textDocument:r,position:o,requestId:i}=t;if(!y(r)||typeof r.uri!="string"||!Rt(o)){d.error("Invalid client textDocument/hover, malformed or missing required parameters");return}if(typeof i!="number"){d.error("Invalid client textDocument/hover, requestId missing or not a number");return}this.registerRequestCallback(e.id,i),this.messageHandle.sendAsyncRequest(b.ON_ASYNC_HOVER,t,i,se.ON_ASYNC_HOVER)}handleDefinitionRequest(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/definition, params missing or not an object");return}let{textDocument:r,position:o}=t;if(!y(r)||typeof r.uri!="string"||!Rt(o)){d.error("Invalid client textDocument/definition, malformed or missing required parameters");return}let i=this.resolveRequestId(t.requestId,e.id);if(!Number.isFinite(i)){d.error("Invalid client textDocument/definition, requestId missing or not a valid number");return}this.registerRequestCallback(e.id,i),this.messageHandle.sendAsyncRequest(b.ON_ASYNC_DEFINITION,t,i,se.ON_ASYNC_DEFINITION)}handleReferencesRequest(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/references, params missing or not an object");return}let{textDocument:r,position:o}=t;if(!y(r)||typeof r.uri!="string"||!Rt(o)){d.error("Invalid client textDocument/references, malformed or missing required parameters");return}let i=this.resolveRequestId(t.requestId,e.id);if(!Number.isFinite(i)){d.error("Invalid client textDocument/references, requestId missing or not a valid number");return}this.registerRequestCallback(e.id,i),this.messageHandle.sendAsyncRequest(b.ON_ASYNC_FIND_USAGES,t,i,se.ON_ASYNC_FIND_USAGES)}resolveRequestId(e,t){let r=e??t;return typeof r=="number"?r:Number(r)}sendNotification(e){if(!_c(e)){d.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case b.DID_OPEN:this.handleDidOpenNotification(e);break;case b.DID_CHANGE:this.handleDidChangeNotification(e);break;case b.DID_CLOSE:this.handleDidCloseNotification(e);break;case b.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:this.handleDidChangePackageDependencies(e);break;case b.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;default:d.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/didOpen, params missing or not an object");return}let{textDocument:r,editorFiles:o}=t;if(!Xc(r)||!Pi(o)){d.error("Invalid client textDocument/didOpen, malformed or missing required parameters");return}let s={isFromEditor:typeof t.isFromEditor=="boolean"?t.isFromEditor:!1,editorFiles:o,textDocument:r};this.registerDiagnosticCallback(r.uri),this.messageHandle.onAsyncOpenFile(s)}handleDidChangeNotification(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/didChange, params missing or not an object");return}let{textDocument:r,contentChanges:o}=t;if(!y(r)||typeof r.uri!="string"||typeof r.version!="number"){d.error("Invalid client textDocument/didChange, malformed or missing required parameters");return}if(!Array.isArray(o)||!o.every(Qc)){d.error("Invalid client textDocument/didChange, contentChanges invalid");return}let i=r.uri,s=r.version;this.registerDiagnosticCallback(i),this.messageHandle.onAsyncDidChange({uri:i,version:s,contentChanges:o})}handleDidCloseNotification(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/didClose, params missing or not an object");return}let{textDocument:r}=t;if(!y(r)||typeof r.uri!="string"){d.error("Invalid client textDocument/didClose, malformed or missing required parameters");return}let o=typeof t.isManual=="boolean"?t.isManual:!1;this.messageHandle.closeFile(r.uri,o)}handleDidChangePackageDependencies(e){let t=e.params;if(!y(t)){d.error("Invalid client aceProject/onDidChangePakcageDependencies, params missing or not an object");return}let{moduleSet:r}=t;if(!Array.isArray(r)||r.length===0){d.error("Invalid client aceProject/onDidChangePakcageDependencies, malformed or missing required parameters");return}this.messageHandle.sendModuleDependencyUpdate(t)}handleDidChangeWatchedFiles(e){let t=e.params;if(!y(t)){d.error("Invalid client workspace/didChangeWatchedFiles, params missing or not an object");return}let{changes:r}=t;if(!Array.isArray(r)){d.error("Invalid client workspace/didChangeWatchedFiles, malformed or missing required parameters");return}this.messageHandle.onDidChangeWatchedFiles(r)}withResettableTimeout(e,t,r){return new Promise((o,i)=>{let s,a=()=>{s=setTimeout(()=>{i(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),o()},c)})}async dispose(){await this.messageHandle.stop()}};import*as Te from"fs";import*as We from"path";import{createHash as Kh}from"crypto";import{EventEmitter as Zh}from"events";var Br=class extends Zh{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r}projectRoot;watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),r=new Set(this.watchers.keys());for(let o of t)r.has(o)||this.watchFile(o);for(let o of r)t.has(o)||(this.unwatchFile(o),d.info(`[ConfigFileWatcher] Stopped watching: ${o}`));d.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!Te.existsSync(t)){d.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Te.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 o of t){let i=P.resolvePathWithinRoot(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:i,relativePath:o.srcPath,timestamp:r,moduleName:o.name})}}emitModuleRemovedEvents(t,r){for(let o of t){let i=P.resolvePathWithinRoot(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:i,relativePath:o.srcPath,timestamp:r,removedModuleName:o.name})}}emitModuleRenamedEvents(t,r){for(let o of t){let i=P.resolvePathWithinRoot(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:i,relativePath:o.after.srcPath,timestamp:r,moduleName:o.after.name,removedModuleName:o.before.name})}}emitModuleMovedEvents(t,r){for(let o of t){let i=P.resolvePathWithinRoot(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:i,relativePath:o.after.srcPath,timestamp:r,moduleName:o.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let r=Date.now();this.emitModuleAddedEvents(t.added,r),this.emitModuleRemovedEvents(t.removed,r),this.emitModuleRenamedEvents(t.renamed,r),this.emitModuleMovedEvents(t.moved,r)}onBuildProfileChanged(){let t="__build_profile__",r=this.debounceTimers.get(t);r&&clearTimeout(r);let o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(i);if(s===this.lastModulesSnapshot){d.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,i);this.lastModules=i,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,o)}computeModulesSnapshot(t){return t.map(o=>`${o.name}::${o.srcPath}`).sort().join("|")}diffModules(t,r){let o=this.buildModuleMatchState(r),i={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,o),this.matchRenamedModules(t,o,i),this.matchMovedModules(t,o,i),this.collectRemovedModules(t,o,i),this.collectAddedModules(r,o,i),i}buildModuleMatchState(t){let r=new Map,o=new Map;for(let i of t)r.set(i.srcPath,i),o.set(i.name,i);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:o}}matchExactModules(t,r){for(let o of t){let i=r.newBySrc.get(o.srcPath);i&&i.name===o.name&&(r.matchedOld.add(o),r.matchedNew.add(i))}}matchRenamedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newBySrc.get(i.srcPath);s&&!r.matchedNew.has(s)&&s.name!==i.name&&(o.renamed.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}matchMovedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newByName.get(i.name);s&&!r.matchedNew.has(s)&&s.srcPath!==i.srcPath&&(o.moved.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}collectRemovedModules(t,r,o){for(let i of t)r.matchedOld.has(i)||o.removed.push(i)}collectAddedModules(t,r,o){for(let i of t)r.matchedNew.has(i)||o.added.push(i)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=oe(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return d.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=We.join(this.projectRoot,A.OH_PACKAGE_JSON5);Te.existsSync(r)&&t.push(r);let o=this.parseModulesFromBuildProfile();for(let i of o){let s=P.resolvePathWithinRoot(this.projectRoot,i.srcPath),a=We.join(s,A.OH_PACKAGE_JSON5);Te.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return We.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Te.readFileSync(t,"utf-8");return Kh("sha256").update(r).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let r=this.computeFileHash(t);r&&this.contentHashes.set(t,r);let o=Te.watch(t,i=>{i==="change"&&this.onFileChanged(t)});o.on("error",i=>{d.error(`[ConfigFileWatcher] Watch error for ${t}: ${i.message}`)}),this.watchers.set(t,o)}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 o=this.debounceTimers.get(t);o&&(clearTimeout(o),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.computeFileHash(t);if(!i){d.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===i){d.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,i),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,o)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),d.info("[ConfigFileWatcher] All watchers stopped")}};import*as Ue from"fs";import*as ue from"path";import{createHash as Xh}from"crypto";import{EventEmitter as Qh}from"events";var Wr=class extends Qh{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=ue.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(!Ue.existsSync(this.depMapDir)){d.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=Ue.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 G(ue.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let o=r.replace(/\\/g,"/"),i;if(o===A.OH_PACKAGE_JSON5)i="root-oh-package";else if(o===it)i="dep-map-json";else{let a=o.match(/^([^/]+)\/oh-package\.json5$/);i=a?`module:${a[1]}`:""}if(!i)return;let s=ue.join(this.depMapDir,r);Ue.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=ue.join(this.depMapDir,A.OH_PACKAGE_JSON5),r=ue.join(this.depMapDir,it),o=this.parseModulesFromDepMap(),i=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...o.map(s=>({path:ue.join(this.depMapDir,s.name,A.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of i){if(!Ue.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=ue.join(this.depMapDir,it);try{let r=oe(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return 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,o,i){for(let s of t)s.startsWith("module:")?(o.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(o.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(i.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,o,i,s){for(let a of t)s.push(a.info),o.add(a.info.newName),i.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let o=new Set;for(let i of t)i.startsWith("dep-added:")&&o.add(i.substring(10));for(let i of r)o.add(i.info.newName);return o}emitIncrementalReload(t,r,o,i,s){d.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...o].join(",")}], added=[${[...i].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...o],addedModuleNames:[...i],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:r}=this.collectPendingState();if(t.length===0&&r.length===0)return;if(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 o=new Set,i=new Set,s=new Set,a=[];this.processTagsIntoSets(t,o,i,s),this.processRenameEntries(r,o,i,s,a);for(let l of i)s.delete(l);if(i.size===0&&s.size===0&&a.length===0){d.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(o,i,s,c,a)}normalizeSrcPath(t){return G(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(i=>[i.name,i])),o=new Map(t.map(i=>[this.normalizeSrcPath(i.srcPath),i]));return{byName:r,bySrcPath:o}}detectModuleRenames(t,r,o,i){for(let[s,a]of t){let c=r.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),o.add(a.name),i.add(c.name);let l=ue.join(this.depMapDir,a.name,A.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(l)),d.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,r,o,i){for(let[s,a]of t){if(o.has(s))continue;let c=r.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),o.add(s),i.add(s),d.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,o){for(let[i]of t)o.has(i)||r.has(i)||(this.pendingTags.push(`dep-added:${i}`),o.add(i))}detectRemovedModules(t,r,o){for(let[i]of t)if(!o.has(i)&&!r.has(i)){this.pendingTags.push(`dep-removed:${i}`),o.add(i);let s=ue.join(this.depMapDir,i,A.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(o=>o.startsWith("dep-")),r=this.pendingRenames.map(o=>`${o.kind}(${o.info.oldName}\u2192${o.info.newName})`);d.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:o}=this.buildModuleLookupMaps(this.lastModules),{byName:i,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(o,s,a,c),this.detectModuleMoves(r,i,a,c),this.detectAddedModules(i,r,c),this.detectRemovedModules(r,i,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=Ue.readFileSync(t,"utf-8");return Xh("sha256").update(r).digest("hex")}catch{return null}}};import*as el from"os";import*as tl from"path";import{spawn as eg}from"child_process";var tg=600*1e3;function ng(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 Ur(n){return n.join("")}function rg(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
1260
1260
  Output so far:
1261
- `+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function ng(n,e,t){return new Promise(r=>{let o=Xh(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:i,stderr:s}=eg(o),a=setTimeout(()=>{o.kill();let c=[Ur(i),Ur(s)].filter(Boolean).join(`
1261
+ `+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function og(n,e,t){return new Promise(r=>{let o=eg(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:i,stderr:s}=ng(o),a=setTimeout(()=>{o.kill();let c=[Ur(i),Ur(s)].filter(Boolean).join(`
1262
1262
  `).trim();r({success:!1,output:`Build process timeout after 10 minutes.
1263
1263
  Output so far:
1264
- `+c,exitCode:-1})},Qh);o.on("close",(c,l)=>{clearTimeout(a);let u=[Ur(i),Ur(s)].filter(Boolean).join(`
1265
- `).trim()||"";r(tg(c,l,u))}),o.on("error",c=>{clearTimeout(a),r({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function Ii(n,e,t,r,o){let i={...process.env,DEVECO_SDK_HOME:r};return D()&&(i.HVIGOR_USER_HOME=tl.join(el.homedir(),".hvigor")),await ng([e,[t,...o]],n,i)}var rg=["--sync","-p","product=default","--analyze=normal","--parallel","--incremental","--no-daemon"];async function nl(n,e){try{return(await Ii(n,e.nodePath,e.hvigorJsPath,e.sdkPath,rg)).success}catch(t){return d.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}import{spawn as og}from"child_process";var ig=["install","--all"];async function sg(n,e,t,r){return new Promise(o=>{let i=og(n,e,{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";i.stdout?.on("data",c=>{s+=c.toString()}),i.stderr?.on("data",c=>{a+=c.toString()}),i.on("close",c=>{let l=[s,a].filter(Boolean).join(`
1264
+ `+c,exitCode:-1})},tg);o.on("close",(c,l)=>{clearTimeout(a);let u=[Ur(i),Ur(s)].filter(Boolean).join(`
1265
+ `).trim()||"";r(rg(c,l,u))}),o.on("error",c=>{clearTimeout(a),r({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function Ii(n,e,t,r,o){let i={...process.env,DEVECO_SDK_HOME:r};return D()&&(i.HVIGOR_USER_HOME=tl.join(el.homedir(),".hvigor")),await og([e,[t,...o]],n,i)}var ig=["--sync","-p","product=default","--analyze=normal","--parallel","--incremental","--no-daemon"];async function nl(n,e){try{return(await Ii(n,e.nodePath,e.hvigorJsPath,e.sdkPath,ig)).success}catch(t){return d.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}import{spawn as sg}from"child_process";var ag=["install","--all"];async function cg(n,e,t,r){return new Promise(o=>{let i=sg(n,e,{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";i.stdout?.on("data",c=>{s+=c.toString()}),i.stderr?.on("data",c=>{a+=c.toString()}),i.on("close",c=>{let l=[s,a].filter(Boolean).join(`
1266
1266
  `);o({exitCode:c??-1,output:l})}),i.on("error",c=>{let l=[s,a].filter(Boolean).join(`
1267
1267
  `);o({exitCode:-1,output:l+`
1268
- `+c.message})})})}function ag(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>d.info("[ohpm] %s",e))}async function rl(n,e){try{let{exitCode:t,output:r}=await sg(e.nodePath,[e.ohpmJsPath,...ig],n,e.sdkPath);return ag(r),t===0?(d.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(d.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",t),d.error("ohpm \u8F93\u51FA: %s",r),!1)}catch(t){return d.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var ol={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,ol.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,ol.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)}static async handleSyncProject(e,t){if(d.info("[ArktsLspManager] Received arkts/syncProject"),!e)return d.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let r=await As(e,async()=>await rl(e,t)?await nl(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 $r(this.config);t.setOnMessage(r=>this.handleLspMessage(r)),t.start(e,r=>this.handleLspInitialized(r)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)d.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:O,method:b.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:O,method:b.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:O,method:b.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Br(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(o=>({modulePath:o.modulePath??"",dependencies:o.dependencies??{},dynamicDependencies:o.dynamicDependencies??{}}));this.lspProxy.sendNotification({jsonrpc:O,method:b.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT,params:{moduleSet:r}}),this.onMessage({jsonrpc:O,method:b.ARKTS_SYNC_COMPLETED,params:{success:!0}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){d.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var cg=120*1e3,lg=10080*60*1e3,dg=7200*60*1e3,Nt=class{manager=null;diagnosticWaiters=new Map;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;toolProvider;nodeMaxOldSpaceSize;onConfigChangedCallback=null;constructor(e,t,r){this.projectPath=e,this.toolProvider=t,this.nodeMaxOldSpaceSize=r}setOnConfigChanged(e){this.onConfigChangedCallback=e}static getToolDefinition(){return{name:"check_ets_files",description:"\u5BF9\u4F20\u5165\u7684ets\u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5(ArkTS-Check)\u5E76\u5B9E\u65F6\u8FD4\u56DE\u8BCA\u65AD\u4FE1\u606F\u3002",inputSchema:Di.object({files:Di.array(Di.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,devecoStudioPath:t,arktsLangServerPath:r}=this.resolveProjectAndDeveco(),o=ve(e),{logPath:i,indexPath:s}=this.getLogAndIndexPath(o);setImmediate(()=>{gi(s,lg,"[ArkTS-Check]"),gi(i,dg,"[ArkTS-Check]")}),jc(i);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a;f.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${c??"undefined \u2192 dynamic formula applies"}`);let l=this.toolProvider.sdkPath;f.info(`ArktsCheck devecoStudioPath: ${t}, sdkPath: ${l}`),this.manager=new Ot({sdkPath:l,arktsLangServerPath:r,workspaceRoot:G(o),indexLogPath:s,nodeMaxOldSpaceSize:c,nodePath:this.toolProvider.nodePath}),this.manager.setOnMessage(u=>this.handleLspMessage(u)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((u,h)=>{this.initResolve=u,this.initReject=h,this.armInitTimer(un),this.manager.start([]).catch(v=>{let I=v instanceof Error?v:new Error(String(v));this.failInit(I)})})}resolveProjectAndDeveco(){let e=De(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.toolProvider.devecoStudioPath??"";f.debug(`DevEco Studio installation path: ${t}`);let r=this.toolProvider.lspServerPath;if(!r)throw new Error("arkts-lang-server path not found");return{harmonyRoot:e,devecoStudioPath:t,arktsLangServerPath:r}}armInitTimer(e){this.initDeadlineTimer&&clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=setTimeout(()=>{let t=this.initReject;this.clearInitHandlers(),t?.(new Error("LSP initialize timeout"))},e)}clearInitHandlers(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async checkFile(e){this.initialized||await this.initialize();let t=ln(rt(e)),r=hi(e),o=await xe.promises.readFile(e,"utf8"),s=`deveco.apptool.${we.extname(e).replace(/^\./,"")||"plaintext"}`,a=new Promise((l,u)=>{let h=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&u(new Error("Wait for diagnostics timeout"))},cg);this.diagnosticWaiters.set(t,{resolve:l,reject:u,timer:h})}),c={textDocument:{uri:r,text:o,languageId:s,version:o.length},editorFiles:[r],isFromEditor:!1};f.debug(`textDocument/didOpen uri=${r} content_len=${o.length}`),this.sendNotification("textDocument/didOpen",c);try{return await a}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:r},isManual:!1})}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],r=[],o=this.collectValidFiles(e.files,t);return o.length===0?{content:[{type:"text",text:t.length>0?t.join(`
1269
- `):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],isError:!0}:(await this.runDiagnosticsForFiles(o,t,r),this.formatCallResult(t,r))}buildNotReadyResponse(){return{content:[{type:"text",text:this.initializing?"LSP \u6B63\u5728\u521D\u59CB\u5316\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5":this.projectPath?"LSP\u672A\u521D\u59CB\u5316":"\u6CA1\u6709\u914D\u7F6E\u5DE5\u7A0B\u8DEF\u5F84\uFF0C\u8BF7\u914D\u7F6EPROJECT_PATH\u53C2\u6570"}],isError:!0}}collectValidFiles(e,t){let r=this.projectPath,o=[];for(let i of e){let s=we.isAbsolute(i)?i:we.join(r,i);if(!xe.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${i}`);continue}if(!xe.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${i}`);continue}if(!s.endsWith(".ets")){t.push(`\u4E0D\u662F .ets \u6587\u4EF6: ${i}`);continue}o.push(s)}return o}async runDiagnosticsForFiles(e,t,r){for(let o of e){await Ac(500);try{let i=await this.checkFile(o);r.push(ug(o,i))}catch(i){t.push(`${o} => wait for diagnostics failed: ${i.message}`)}}}formatCallResult(e,t){let r=[];e.length>0&&r.push(e.join(`
1268
+ `+c.message})})})}function lg(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>d.info("[ohpm] %s",e))}async function rl(n,e){try{let{exitCode:t,output:r}=await cg(e.nodePath,[e.ohpmJsPath,...ag],n,e.sdkPath);return lg(r),t===0?(d.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(d.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",t),d.error("ohpm \u8F93\u51FA: %s",r),!1)}catch(t){return d.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var ol={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,ol.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,ol.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)}static async handleSyncProject(e,t){if(d.info("[ArktsLspManager] Received arkts/syncProject"),!e)return d.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let r=await As(e,async()=>await rl(e,t)?await nl(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 $r(this.config);t.setOnMessage(r=>this.handleLspMessage(r)),t.start(e,r=>this.handleLspInitialized(r)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)d.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:O,method:b.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:O,method:b.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:O,method:b.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Br(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(o=>({modulePath:o.modulePath??"",dependencies:o.dependencies??{},dynamicDependencies:o.dynamicDependencies??{}}));this.lspProxy.sendNotification({jsonrpc:O,method:b.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT,params:{moduleSet:r}}),this.onMessage({jsonrpc:O,method:b.ARKTS_SYNC_COMPLETED,params:{success:!0}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){d.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var dg=120*1e3,ug=10080*60*1e3,pg=7200*60*1e3,Nt=class{manager=null;diagnosticWaiters=new Map;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;toolProvider;nodeMaxOldSpaceSize;onConfigChangedCallback=null;constructor(e,t,r){this.projectPath=e,this.toolProvider=t,this.nodeMaxOldSpaceSize=r}setOnConfigChanged(e){this.onConfigChangedCallback=e}static getToolDefinition(){return{name:"check_ets_files",description:"\u5BF9\u4F20\u5165\u7684ets\u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5(ArkTS-Check)\u5E76\u5B9E\u65F6\u8FD4\u56DE\u8BCA\u65AD\u4FE1\u606F\u3002",inputSchema:Di.object({files:Di.array(Di.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,devecoStudioPath:t,arktsLangServerPath:r}=this.resolveProjectAndDeveco(),o=ve(e),{logPath:i,indexPath:s}=this.getLogAndIndexPath(o);setImmediate(()=>{gi(s,ug,"[ArkTS-Check]"),gi(i,pg,"[ArkTS-Check]")}),jc(i);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a;f.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${c??"undefined \u2192 dynamic formula applies"}`);let l=this.toolProvider.sdkPath;f.info(`ArktsCheck devecoStudioPath: ${t}, sdkPath: ${l}`),this.manager=new Ot({sdkPath:l,arktsLangServerPath:r,workspaceRoot:G(o),indexLogPath:s,nodeMaxOldSpaceSize:c,nodePath:this.toolProvider.nodePath}),this.manager.setOnMessage(u=>this.handleLspMessage(u)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((u,h)=>{this.initResolve=u,this.initReject=h,this.armInitTimer(un),this.manager.start([]).catch(v=>{let I=v instanceof Error?v:new Error(String(v));this.failInit(I)})})}resolveProjectAndDeveco(){let e=De(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.toolProvider.devecoStudioPath??"";f.debug(`DevEco Studio installation path: ${t}`);let r=this.toolProvider.lspServerPath;if(!r)throw new Error("arkts-lang-server path not found");return{harmonyRoot:e,devecoStudioPath:t,arktsLangServerPath:r}}armInitTimer(e){this.initDeadlineTimer&&clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=setTimeout(()=>{let t=this.initReject;this.clearInitHandlers(),t?.(new Error("LSP initialize timeout"))},e)}clearInitHandlers(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async checkFile(e){this.initialized||await this.initialize();let t=ln(rt(e)),r=hi(e),o=await xe.promises.readFile(e,"utf8"),s=`deveco.apptool.${we.extname(e).replace(/^\./,"")||"plaintext"}`,a=new Promise((l,u)=>{let h=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&u(new Error("Wait for diagnostics timeout"))},dg);this.diagnosticWaiters.set(t,{resolve:l,reject:u,timer:h})}),c={textDocument:{uri:r,text:o,languageId:s,version:o.length},editorFiles:[r],isFromEditor:!1};f.debug(`textDocument/didOpen uri=${r} content_len=${o.length}`),this.sendNotification("textDocument/didOpen",c);try{return await a}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:r},isManual:!1})}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],r=[],o=this.collectValidFiles(e.files,t);return o.length===0?{content:[{type:"text",text:t.length>0?t.join(`
1269
+ `):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],isError:!0}:(await this.runDiagnosticsForFiles(o,t,r),this.formatCallResult(t,r))}buildNotReadyResponse(){return{content:[{type:"text",text:this.initializing?"LSP \u6B63\u5728\u521D\u59CB\u5316\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5":this.projectPath?"LSP\u672A\u521D\u59CB\u5316":"\u6CA1\u6709\u914D\u7F6E\u5DE5\u7A0B\u8DEF\u5F84\uFF0C\u8BF7\u914D\u7F6EPROJECT_PATH\u53C2\u6570"}],isError:!0}}collectValidFiles(e,t){let r=this.projectPath,o=[];for(let i of e){let s=we.isAbsolute(i)?i:we.join(r,i);if(!xe.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${i}`);continue}if(!xe.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${i}`);continue}if(!s.endsWith(".ets")){t.push(`\u4E0D\u662F .ets \u6587\u4EF6: ${i}`);continue}o.push(s)}return o}async runDiagnosticsForFiles(e,t,r){for(let o of e){await Ac(500);try{let i=await this.checkFile(o);r.push(mg(o,i))}catch(i){t.push(`${o} => wait for diagnostics failed: ${i.message}`)}}}formatCallResult(e,t){let r=[];e.length>0&&r.push(e.join(`
1270
1270
  `)),t.length>0&&r.push(t.join(`
1271
1271
  `));let o=r.join(`
1272
- `).trim(),i=e.length>0;return!i&&t.length===0&&(o="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:o}],isError:i}}async shutdown(){if(this.failAllPending(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(e){f.warn(`Failed to dispose ArktsLspManager: ${e}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null,this.clearInitHandlers()}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":case"textDocument/didOpen":this.handleDiagnosticsNotification(t.params);break;case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(un),f.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{f.info("Received arkts/initialized");let o=this.initResolve;this.clearInitHandlers(),o?.();break}case"arkts/initializationFailed":{let i=t.params?.message??"unknown";f.error(`LSP initialization failed: ${i}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${i}`));break}case"workspace/didChangeConfiguration":f.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.resolveDiagnosticWaiter(t);if(!r)return;if(typeof e.errorMessage=="string"){f.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let o=e.diagnostics,i=Array.isArray(o)?o.length:0;f.debug(`diagnostics received uri=${t} count=${i}`),r.resolve(Array.isArray(o)?o:[])}resolveDiagnosticWaiter(e){let t=ln(e),r=this.popDiagnosticWaiter(t);if(r)return r;for(let o of xc(e)){let i=this.popDiagnosticWaiter(o);if(i)return i}}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}failAllPending(e){for(let[,r]of this.diagnosticWaiters)clearTimeout(r.timer),r.reject(e);this.diagnosticWaiters.clear();let t=this.initReject;this.clearInitHandlers(),t?.(e)}getLogAndIndexPath(e){try{let t=we.join(lr(),"ArkTSCheck"),r=we.join(t,"mapping-config.properties"),o=kc(e,r),i=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=we.join(t,"lsp-log",String(o),i),a=we.join(t,"lsp-index",String(o));return xe.mkdirSync(s,{recursive:!0}),xe.mkdirSync(a,{recursive:!0}),{logPath:ve(s),indexPath:ve(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function ug(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 pg}from"child_process";import*as C from"fs";import*as Z from"path";import{z as Ci}from"zod";var il=60*1e3,mg=30*1e3,fg=new Set(["textDocument/didOpen","textDocument/didChange","textDocument/didClose","textDocument/didSave"]),hg=1e3,Ti=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=>{f.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=ve(this.projectPath),o=rt(r),i=Z.basename(r)||"workspace",s={processId:null,clientInfo:{name:"devecocli-mcp-server",version:"0.1.0-TD.4.2"},rootPath:r,rootUri:o,workspaceFolders:[{uri:o,name:i}],capabilities:{}};await this.sendRequestToClangd("initialize",s,il),await this.sendNotificationToClangd("initialized",{}),this.backendReady=!0,this.wrapperState="proxying";for(let a of this.queuedDocumentNotifications)await this.writeToClangd(a);this.queuedDocumentNotifications.length=0,f.info("[CppCheck] clangd backend ready, switched to proxying mode")}async waitForBackendReady(){if(this.backendReady)return;let e=il,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=C.realpathSync(e)}catch{t=e}let r=rt(t),o=Tc(t),i=await C.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}`))},mg);this.diagnosticWaiters.set(r,{resolve:a,reject:c,timer:l})});try{await this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,languageId:o,version:1,text:i}})}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=>{f.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){f.warn(`[CppCheck] shutdown request failed: ${e}`)}try{await this.sendNotificationToClangd("exit",null)}catch(e){f.warn(`[CppCheck] exit notification failed: ${e}`)}try{this.clangdStdin.end()}catch(e){f.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}fg.has(e)&&this.queuedDocumentNotifications.push(r)}async closeFile(e){await this.sendNotification("textDocument/didClose",{textDocument:{uri:e}})}async sendRequestToClangd(e,t,r){let o=this.nextRequestId++;return new Promise((i,s)=>{let a=setTimeout(()=>{this.pendingRequests.delete(o)&&s(new Error(`Timed out waiting for ${e} response`))},r);this.pendingRequests.set(o,{resolve:i,reject:s,timer:a}),this.writeToClangd({jsonrpc:"2.0",id:o,method:e,params:t??void 0}).catch(c=>{this.pendingRequests.delete(o)&&(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 o;try{o=JSON.stringify(e)}catch(u){r(new Error(`Failed to encode LSP message: ${u}`));return}let i=Buffer.from(o,"utf8"),s=Buffer.from(`Content-Length: ${i.length}\r
1272
+ `).trim(),i=e.length>0;return!i&&t.length===0&&(o="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:o}],isError:i}}async shutdown(){if(this.failAllPending(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(e){f.warn(`Failed to dispose ArktsLspManager: ${e}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null,this.clearInitHandlers()}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":case"textDocument/didOpen":this.handleDiagnosticsNotification(t.params);break;case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(un),f.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{f.info("Received arkts/initialized");let o=this.initResolve;this.clearInitHandlers(),o?.();break}case"arkts/initializationFailed":{let i=t.params?.message??"unknown";f.error(`LSP initialization failed: ${i}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${i}`));break}case"workspace/didChangeConfiguration":f.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.resolveDiagnosticWaiter(t);if(!r)return;if(typeof e.errorMessage=="string"){f.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let o=e.diagnostics,i=Array.isArray(o)?o.length:0;f.debug(`diagnostics received uri=${t} count=${i}`),r.resolve(Array.isArray(o)?o:[])}resolveDiagnosticWaiter(e){let t=ln(e),r=this.popDiagnosticWaiter(t);if(r)return r;for(let o of xc(e)){let i=this.popDiagnosticWaiter(o);if(i)return i}}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}failAllPending(e){for(let[,r]of this.diagnosticWaiters)clearTimeout(r.timer),r.reject(e);this.diagnosticWaiters.clear();let t=this.initReject;this.clearInitHandlers(),t?.(e)}getLogAndIndexPath(e){try{let t=we.join(lr(),"ArkTSCheck"),r=we.join(t,"mapping-config.properties"),o=kc(e,r),i=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=we.join(t,"lsp-log",String(o),i),a=we.join(t,"lsp-index",String(o));return xe.mkdirSync(s,{recursive:!0}),xe.mkdirSync(a,{recursive:!0}),{logPath:ve(s),indexPath:ve(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function mg(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 fg}from"child_process";import*as C from"fs";import*as Z from"path";import{z as Ci}from"zod";var il=60*1e3,hg=30*1e3,gg=new Set(["textDocument/didOpen","textDocument/didChange","textDocument/didClose","textDocument/didSave"]),yg=1e3,Ti=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=>{f.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=ve(this.projectPath),o=rt(r),i=Z.basename(r)||"workspace",s={processId:null,clientInfo:{name:"devecocli-mcp-server",version:"0.1.0-TD.5"},rootPath:r,rootUri:o,workspaceFolders:[{uri:o,name:i}],capabilities:{}};await this.sendRequestToClangd("initialize",s,il),await this.sendNotificationToClangd("initialized",{}),this.backendReady=!0,this.wrapperState="proxying";for(let a of this.queuedDocumentNotifications)await this.writeToClangd(a);this.queuedDocumentNotifications.length=0,f.info("[CppCheck] clangd backend ready, switched to proxying mode")}async waitForBackendReady(){if(this.backendReady)return;let e=il,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=C.realpathSync(e)}catch{t=e}let r=rt(t),o=Tc(t),i=await C.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}`))},hg);this.diagnosticWaiters.set(r,{resolve:a,reject:c,timer:l})});try{await this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,languageId:o,version:1,text:i}})}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=>{f.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){f.warn(`[CppCheck] shutdown request failed: ${e}`)}try{await this.sendNotificationToClangd("exit",null)}catch(e){f.warn(`[CppCheck] exit notification failed: ${e}`)}try{this.clangdStdin.end()}catch(e){f.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}gg.has(e)&&this.queuedDocumentNotifications.push(r)}async closeFile(e){await this.sendNotification("textDocument/didClose",{textDocument:{uri:e}})}async sendRequestToClangd(e,t,r){let o=this.nextRequestId++;return new Promise((i,s)=>{let a=setTimeout(()=>{this.pendingRequests.delete(o)&&s(new Error(`Timed out waiting for ${e} response`))},r);this.pendingRequests.set(o,{resolve:i,reject:s,timer:a}),this.writeToClangd({jsonrpc:"2.0",id:o,method:e,params:t??void 0}).catch(c=>{this.pendingRequests.delete(o)&&(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 o;try{o=JSON.stringify(e)}catch(u){r(new Error(`Failed to encode LSP message: ${u}`));return}let i=Buffer.from(o,"utf8"),s=Buffer.from(`Content-Length: ${i.length}\r
1273
1273
  \r
1274
1274
  `,"ascii"),a=!1,c=u=>{a||(a=!0,u?r(u):t())};if(this.clangdStdin.write(Buffer.concat([s,i]),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
1275
1275
  \r
1276
- `);if(t<0)return;let r=this.clangdBuffer.slice(0,t).toString("ascii"),o=/content-length:\s*(\d+)/i.exec(r);if(!o){this.clangdBuffer=this.clangdBuffer.slice(t+4);continue}let i=parseInt(o[1],10),s=t+4+i;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){f.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 o=gg(r),i=this.diagnosticWaiters.get(o);if(i){this.diagnosticWaiters.delete(o),clearTimeout(i.timer);let s=Array.isArray(t.diagnostics)?t.diagnostics:[];f.info(`[CppCheck] Received C++ diagnostics for ${o} (${s.length} entries)`),i.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 gg(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)),rt(t)}}catch{}return n}function yg(n){let e=Z.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function vg(n,e){let t=Z.join(n,e.name);return e.isDirectory()?e.name===".cxx"||sl(t):yg(t)}function sl(n){if(!C.existsSync(n))return!1;try{return C.readdirSync(n,{withFileTypes:!0}).some(t=>vg(n,t))}catch{}return!1}function al(n){let t=new st(n).getAllModuleInfo(),r=[];for(let o of t){let i=P.resolvePathWithinRoot(n,o.srcPath);sl(i)&&r.push(o)}return r}function wg(n){let e=[],r=new st(n).getAllModuleInfo();for(let o of r){let i=P.resolvePathWithinRoot(n,o.srcPath),s=Z.join(i,".cxx");C.existsSync(s)&&cl(s,e)}return e}function cl(n,e){try{let t=C.readdirSync(n,{withFileTypes:!0});for(let r of t){let o=Z.join(n,r.name);r.isDirectory()?cl(o,e):r.name==="compile_commands.json"&&e.push(o)}}catch{}}function bg(n){let e=[];for(let t of n)try{let r=C.readFileSync(t,"utf8"),o=JSON.parse(r);e.push(...o)}catch{}return e}function Sg(n,e){let t=Z.join(n,...fi.slice(0,-1));C.mkdirSync(t,{recursive:!0});let r=Z.join(t,"compile_commands.json");C.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function Pg(n){let e=wg(n);if(e.length>0){let t=bg(e);Sg(n,t),f.info(`[CppCheck] compile_commands.json \u5DF2\u751F\u6210\uFF0C\u5171 ${t.length} \u6761\u7F16\u8BD1\u547D\u4EE4`)}else f.warn("[CppCheck] \u672A\u627E\u5230\u4EFB\u4F55 compile_commands.json \u6587\u4EF6")}var Ai="/data/app/sdk.org/sdk_1.0.0";function Eg(n,e){if(!D())return;let t=dn(n);if(!C.existsSync(t))return;let r=C.readFileSync(t,"utf8");if(!r.includes(Ai))return;let o=r.replaceAll(Ai,e);C.writeFileSync(t,o,"utf8"),f.info(`[CppCheck] Patched SDK path in compile_commands.json: ${Ai} -> ${e}`)}function Ig(n){let e=new Set;for(let t of n)if(t.file)try{e.add(C.realpathSync(t.file))}catch{e.add(t.file)}return e}function Dg(n,e){try{let t=C.realpathSync(n);if(!e.has(t))return f.info(`[CppCheck] File not covered by compile_commands.json: ${n}`),!1}catch{}return!0}function Cg(n,e){if(!C.existsSync(n))return!1;try{let t=C.readFileSync(n,"utf8"),r=JSON.parse(t),o=Ig(r);for(let i of e)if(!Dg(i,o))return!1;return!0}catch(t){return f.warn(`[CppCheck] Failed to read/parse compile_commands.json: ${t}`),!1}}async function Ag(n,e,t=""){let r=xg(n),o=t?` (${t})`:"";f.info(`[CppCheck] Running compileNative for module: ${n.name}${o}`);let i=await e(r);i.success?f.info(`[CppCheck] compileNative ${n.name} \u6210\u529F`):f.warn(`[CppCheck] compileNative ${n.name} \u5931\u8D25: ${i.output}`)}async function Tg(n,e,t){let r=t.sdkPath,o=t.nodePath,i=t.hvigorJsPath;f.info(`CppCheck devecoStudioPath: ${t?.devecoStudioPath}, sdkPath: ${r}, nodePath: ${o}, hvigorPath: ${i}`);let s=async a=>Ii(n,o,i,r,a);for(let a of e)await Ag(a,s)}function xg(n){return["--mode","module","-p",`module=${n.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"]}async function kg(n,e){let t=al(n);if(t.length===0){f.info("[CppCheck] \u672A\u53D1\u73B0\u542BC++\u7684\u6A21\u5757\uFF0C\u8DF3\u8FC7\u521D\u59CB\u5316");return}f.info(`[CppCheck] \u53D1\u73B0 ${t.length} \u4E2A\u542BC++\u7684\u6A21\u5757: ${t.map(r=>r.name).join(", ")}`),await Tg(n,t,e),Pg(n)}var Lt=class{projectPath;toolProvider;clangdProcess=null;client=null;initializedProjectPath=null;initializing=!1;initPromise=null;pollHandle=null;backendReady=!1;constructor(e,t){this.projectPath=e,this.toolProvider=t}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:Ci.object({files:Ci.array(Ci.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=[],o=this.collectValidFiles(e.files,t);if(o.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
1276
+ `);if(t<0)return;let r=this.clangdBuffer.slice(0,t).toString("ascii"),o=/content-length:\s*(\d+)/i.exec(r);if(!o){this.clangdBuffer=this.clangdBuffer.slice(t+4);continue}let i=parseInt(o[1],10),s=t+4+i;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){f.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 o=vg(r),i=this.diagnosticWaiters.get(o);if(i){this.diagnosticWaiters.delete(o),clearTimeout(i.timer);let s=Array.isArray(t.diagnostics)?t.diagnostics:[];f.info(`[CppCheck] Received C++ diagnostics for ${o} (${s.length} entries)`),i.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 vg(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)),rt(t)}}catch{}return n}function wg(n){let e=Z.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function bg(n,e){let t=Z.join(n,e.name);return e.isDirectory()?e.name===".cxx"||sl(t):wg(t)}function sl(n){if(!C.existsSync(n))return!1;try{return C.readdirSync(n,{withFileTypes:!0}).some(t=>bg(n,t))}catch{}return!1}function al(n){let t=new st(n).getAllModuleInfo(),r=[];for(let o of t){let i=P.resolvePathWithinRoot(n,o.srcPath);sl(i)&&r.push(o)}return r}function Sg(n){let e=[],r=new st(n).getAllModuleInfo();for(let o of r){let i=P.resolvePathWithinRoot(n,o.srcPath),s=Z.join(i,".cxx");C.existsSync(s)&&cl(s,e)}return e}function cl(n,e){try{let t=C.readdirSync(n,{withFileTypes:!0});for(let r of t){let o=Z.join(n,r.name);r.isDirectory()?cl(o,e):r.name==="compile_commands.json"&&e.push(o)}}catch{}}function Pg(n){let e=[];for(let t of n)try{let r=C.readFileSync(t,"utf8"),o=JSON.parse(r);e.push(...o)}catch{}return e}function Eg(n,e){let t=Z.join(n,...fi.slice(0,-1));C.mkdirSync(t,{recursive:!0});let r=Z.join(t,"compile_commands.json");C.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function Ig(n){let e=Sg(n);if(e.length>0){let t=Pg(e);Eg(n,t),f.info(`[CppCheck] compile_commands.json \u5DF2\u751F\u6210\uFF0C\u5171 ${t.length} \u6761\u7F16\u8BD1\u547D\u4EE4`)}else f.warn("[CppCheck] \u672A\u627E\u5230\u4EFB\u4F55 compile_commands.json \u6587\u4EF6")}var Ai="/data/app/sdk.org/sdk_1.0.0";function Dg(n,e){if(!D())return;let t=dn(n);if(!C.existsSync(t))return;let r=C.readFileSync(t,"utf8");if(!r.includes(Ai))return;let o=r.replaceAll(Ai,e);C.writeFileSync(t,o,"utf8"),f.info(`[CppCheck] Patched SDK path in compile_commands.json: ${Ai} -> ${e}`)}function Cg(n){let e=new Set;for(let t of n)if(t.file)try{e.add(C.realpathSync(t.file))}catch{e.add(t.file)}return e}function Ag(n,e){try{let t=C.realpathSync(n);if(!e.has(t))return f.info(`[CppCheck] File not covered by compile_commands.json: ${n}`),!1}catch{}return!0}function Tg(n,e){if(!C.existsSync(n))return!1;try{let t=C.readFileSync(n,"utf8"),r=JSON.parse(t),o=Cg(r);for(let i of e)if(!Ag(i,o))return!1;return!0}catch(t){return f.warn(`[CppCheck] Failed to read/parse compile_commands.json: ${t}`),!1}}async function xg(n,e,t=""){let r=Mg(n),o=t?` (${t})`:"";f.info(`[CppCheck] Running compileNative for module: ${n.name}${o}`);let i=await e(r);i.success?f.info(`[CppCheck] compileNative ${n.name} \u6210\u529F`):f.warn(`[CppCheck] compileNative ${n.name} \u5931\u8D25: ${i.output}`)}async function kg(n,e,t){let r=t.sdkPath,o=t.nodePath,i=t.hvigorJsPath;f.info(`CppCheck devecoStudioPath: ${t?.devecoStudioPath}, sdkPath: ${r}, nodePath: ${o}, hvigorPath: ${i}`);let s=async a=>Ii(n,o,i,r,a);for(let a of e)await xg(a,s)}function Mg(n){return["--mode","module","-p",`module=${n.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"]}async function Rg(n,e){let t=al(n);if(t.length===0){f.info("[CppCheck] \u672A\u53D1\u73B0\u542BC++\u7684\u6A21\u5757\uFF0C\u8DF3\u8FC7\u521D\u59CB\u5316");return}f.info(`[CppCheck] \u53D1\u73B0 ${t.length} \u4E2A\u542BC++\u7684\u6A21\u5757: ${t.map(r=>r.name).join(", ")}`),await kg(n,t,e),Ig(n)}var Lt=class{projectPath;toolProvider;clangdProcess=null;client=null;initializedProjectPath=null;initializing=!1;initPromise=null;pollHandle=null;backendReady=!1;constructor(e,t){this.projectPath=e,this.toolProvider=t}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:Ci.object({files:Ci.array(Ci.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=[],o=this.collectValidFiles(e.files,t);if(o.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
1277
1277
  `):"\u6CA1\u6709\u6709\u6548\u7684 C/C++ \u6587\u4EF6"}],isError:!0};let i;try{i=await this.ensureInitializedWithFiles(o)}catch(a){return t.push(a.message),{content:[{type:"text",text:t.join(`
1278
1278
  `)}],isError:!0}}return await this.runDiagnosticsForFiles(i,o,t,r)&&this.shutdown().catch(a=>{f.warn(`[CppCheck] shutdown after diagnostic failure: ${a}`)}),this.formatCallResult(t,r)}async runDiagnosticsForFiles(e,t,r,o){let i=!1;for(let s of t)try{let a=await e.checkFile(s);a.length===0?o.push(`${s} => \u65E0\u8BCA\u65AD`):o.push(`${s} => Diagnostic: ${JSON.stringify(a)}`)}catch(a){i=!0,r.push(`${s} => \u83B7\u53D6\u8BCA\u65AD\u5931\u8D25: ${a.message}`)}return i}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(`
1279
1279
  `),e.join(`
1280
1280
  `)].filter(i=>i.trim().length>0).join(`
1281
- `).trim()}],isError:r}}async ensureInitializedWithFiles(e){let t=ve(this.projectPath),r=this.prepareCppCheck(t,e);if(Eg(t,this.toolProvider.sdkPath),r)this.client&&this.initializedProjectPath&&(f.info("[CppCheck] Re-initializing C++ project due to file changes"),await this.shutdown()),await kg(t,this.toolProvider);else if(this.client&&this.initializedProjectPath){let o=ve(this.projectPath);if(this.initializedProjectPath===o)return this.client;await this.shutdown()}return this.doEnsureInitialized()}prepareCppCheck(e,t){let r=dn(e);return C.existsSync(r)?al(e).length===0?(f.info("[CppCheck] No cpp modules found, no initialization needed"),!1):Cg(r,t)?(f.info("[CppCheck] All files covered, no initialization needed"),!1):(f.info("[CppCheck] Files not fully covered by compile_commands.json, needs initialization"),!0):(f.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 Ti,await this.client.initialize(e),this.initializedProjectPath=e,f.info(`[CppCheck] Client initialized in wrapper mode for workspace: ${e}`),this.startPollingForClangd(e)}resolveProjectRoot(){let e=De(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);return this.projectPath=e,ve(e)}startPollingForClangd(e){let t=dn(e);if(C.existsSync(t)){f.info("[CppCheck] compile_commands.json found, spawning clangd immediately"),this.spawnAndConnectClangd(e).catch(r=>{f.error(`[CppCheck] Immediate clangd spawn failed: ${r}`)});return}f.info("[CppCheck] compile_commands.json not found, starting poll..."),this.pollHandle=setInterval(()=>{if(!this.client||this.client.isClosed()||this.backendReady){this.stopPolling();return}C.existsSync(t)&&(this.stopPolling(),f.info("[CppCheck] compile_commands.json found via poll, spawning clangd..."),this.spawnAndConnectClangd(e).catch(r=>{f.error(`[CppCheck] Clangd spawn from poll failed: ${r}`)}))},hg)}stopPolling(){this.pollHandle&&(clearInterval(this.pollHandle),this.pollHandle=null)}async spawnAndConnectClangd(e){let{clangdPath:t,compileCommandsDir:r}=this.resolveClangdPaths(e);f.info(`[CppCheck] Starting clangd for workspace: ${e} (clangd=${t})`);let o=this.spawnClangd(t,e,r);this.clangdProcess=o;try{await this.client.connectClangdProcess(o.stdin,o.stdout),this.backendReady=!0,f.info(`[CppCheck] clangd connected for workspace: ${e}`)}catch(i){if(f.error(`[CppCheck] Failed to connect clangd: ${i}`),this.clangdProcess&&!this.clangdProcess.killed){try{this.clangdProcess.kill()}catch{}this.clangdProcess=null}throw i}}resolveClangdPaths(e){let t=this.toolProvider.clangdPath;if(!t)throw new Error("clangd executable not found");let r=dn(e),o=Z.dirname(r);return{clangdPath:t,compileCommandsDir:o}}spawnClangd(e,t,r){let o=pg(e,[`--compile-commands-dir=${r}`],{cwd:t,stdio:["pipe","pipe","pipe"]});if(!o.stdin||!o.stdout||!o.stderr)throw new Error("Failed to start clangd: stdio not available");return o.stderr.on("data",i=>{let s=i.toString("utf8").trimEnd();s&&f.warn(`[CppLsp stderr] ${s}`)}),o.on("exit",(i,s)=>{f.warn(`[CppCheck] clangd exited code=${i} signal=${s??"null"}`),this.clangdProcess===o&&(this.clangdProcess=null,this.backendReady=!1)}),o.on("error",i=>{f.error(`[CppCheck] clangd spawn error: ${i}`)}),o}collectValidFiles(e,t){let r=this.projectPath,o=[];for(let i of e){let s=Z.isAbsolute(i)?i:Z.join(r,i);if(!C.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${i}`);continue}if(!C.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${i}`);continue}if(!cr(s)){t.push(`\u4E0D\u662F\u53D7\u652F\u6301\u7684 C/C++ \u6587\u4EF6: ${i}`);continue}try{o.push(C.realpathSync(s))}catch{o.push(s)}}return o}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){f.warn(`[CppCheck] client.close() failed: ${r}`)}if(t&&!t.killed)try{t.kill()}catch(r){f.warn(`[CppCheck] failed to kill clangd: ${r}`)}}};function ll(n){let e=Bn(n);return d.info(`[SyncGuard] ${e.reason}`),e}var ul=(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))(ul||{}),ki=3,dl=600*1e3,zr=class{server;toolRouter;config;arktsCheckTool=null;cppCheckTool=null;projectState=0;workspaceRoot="";initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;toolProvider;constructor(e){this.config=e,this.toolProvider=e.toolProvider,vi(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),f.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",f.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,f.info(`Constructor: using configured path as startPath: '${t}'`));let o=De(t);f.info(`Constructor: findHarmonyProject('${t}') => ${o??"null"}`),this.config.projectPath=o??void 0,this.server=new Mg({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=pi(),this.registerTools()}getToolProvider(){return this.toolProvider}registerTools(){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:xi.object({files:xi.array(xi.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))}validateContainment(e){let t=this.config.projectPath;if(t){let o=[];for(let i of e){let s=P.isPathContainedWithSymlink(i,t);s.contained||(f.warn(`Containment check failed: ${s.reason}`),o.push(s.reason))}return o.length>0?{content:[{type:"text",text:o.join(`
1281
+ `).trim()}],isError:r}}async ensureInitializedWithFiles(e){let t=ve(this.projectPath),r=this.prepareCppCheck(t,e);if(Dg(t,this.toolProvider.sdkPath),r)this.client&&this.initializedProjectPath&&(f.info("[CppCheck] Re-initializing C++ project due to file changes"),await this.shutdown()),await Rg(t,this.toolProvider);else if(this.client&&this.initializedProjectPath){let o=ve(this.projectPath);if(this.initializedProjectPath===o)return this.client;await this.shutdown()}return this.doEnsureInitialized()}prepareCppCheck(e,t){let r=dn(e);return C.existsSync(r)?al(e).length===0?(f.info("[CppCheck] No cpp modules found, no initialization needed"),!1):Tg(r,t)?(f.info("[CppCheck] All files covered, no initialization needed"),!1):(f.info("[CppCheck] Files not fully covered by compile_commands.json, needs initialization"),!0):(f.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 Ti,await this.client.initialize(e),this.initializedProjectPath=e,f.info(`[CppCheck] Client initialized in wrapper mode for workspace: ${e}`),this.startPollingForClangd(e)}resolveProjectRoot(){let e=De(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);return this.projectPath=e,ve(e)}startPollingForClangd(e){let t=dn(e);if(C.existsSync(t)){f.info("[CppCheck] compile_commands.json found, spawning clangd immediately"),this.spawnAndConnectClangd(e).catch(r=>{f.error(`[CppCheck] Immediate clangd spawn failed: ${r}`)});return}f.info("[CppCheck] compile_commands.json not found, starting poll..."),this.pollHandle=setInterval(()=>{if(!this.client||this.client.isClosed()||this.backendReady){this.stopPolling();return}C.existsSync(t)&&(this.stopPolling(),f.info("[CppCheck] compile_commands.json found via poll, spawning clangd..."),this.spawnAndConnectClangd(e).catch(r=>{f.error(`[CppCheck] Clangd spawn from poll failed: ${r}`)}))},yg)}stopPolling(){this.pollHandle&&(clearInterval(this.pollHandle),this.pollHandle=null)}async spawnAndConnectClangd(e){let{clangdPath:t,compileCommandsDir:r}=this.resolveClangdPaths(e);f.info(`[CppCheck] Starting clangd for workspace: ${e} (clangd=${t})`);let o=this.spawnClangd(t,e,r);this.clangdProcess=o;try{await this.client.connectClangdProcess(o.stdin,o.stdout),this.backendReady=!0,f.info(`[CppCheck] clangd connected for workspace: ${e}`)}catch(i){if(f.error(`[CppCheck] Failed to connect clangd: ${i}`),this.clangdProcess&&!this.clangdProcess.killed){try{this.clangdProcess.kill()}catch{}this.clangdProcess=null}throw i}}resolveClangdPaths(e){let t=this.toolProvider.clangdPath;if(!t)throw new Error("clangd executable not found");let r=dn(e),o=Z.dirname(r);return{clangdPath:t,compileCommandsDir:o}}spawnClangd(e,t,r){let o=fg(e,[`--compile-commands-dir=${r}`],{cwd:t,stdio:["pipe","pipe","pipe"]});if(!o.stdin||!o.stdout||!o.stderr)throw new Error("Failed to start clangd: stdio not available");return o.stderr.on("data",i=>{let s=i.toString("utf8").trimEnd();s&&f.warn(`[CppLsp stderr] ${s}`)}),o.on("exit",(i,s)=>{f.warn(`[CppCheck] clangd exited code=${i} signal=${s??"null"}`),this.clangdProcess===o&&(this.clangdProcess=null,this.backendReady=!1)}),o.on("error",i=>{f.error(`[CppCheck] clangd spawn error: ${i}`)}),o}collectValidFiles(e,t){let r=this.projectPath,o=[];for(let i of e){let s=Z.isAbsolute(i)?i:Z.join(r,i);if(!C.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${i}`);continue}if(!C.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${i}`);continue}if(!cr(s)){t.push(`\u4E0D\u662F\u53D7\u652F\u6301\u7684 C/C++ \u6587\u4EF6: ${i}`);continue}try{o.push(C.realpathSync(s))}catch{o.push(s)}}return o}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){f.warn(`[CppCheck] client.close() failed: ${r}`)}if(t&&!t.killed)try{t.kill()}catch(r){f.warn(`[CppCheck] failed to kill clangd: ${r}`)}}};function ll(n){let e=Bn(n);return d.info(`[SyncGuard] ${e.reason}`),e}var ul=(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))(ul||{}),ki=3,dl=600*1e3,zr=class{server;toolRouter;config;arktsCheckTool=null;cppCheckTool=null;projectState=0;workspaceRoot="";initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;toolProvider;constructor(e){this.config=e,this.toolProvider=e.toolProvider,vi(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),f.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",f.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,f.info(`Constructor: using configured path as startPath: '${t}'`));let o=De(t);f.info(`Constructor: findHarmonyProject('${t}') => ${o??"null"}`),this.config.projectPath=o??void 0,this.server=new Og({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=pi(),this.registerTools()}getToolProvider(){return this.toolProvider}registerTools(){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:xi.object({files:xi.array(xi.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))}validateContainment(e){let t=this.config.projectPath;if(t){let o=[];for(let i of e){let s=P.isPathContainedWithSymlink(i,t);s.contained||(f.warn(`Containment check failed: ${s.reason}`),o.push(s.reason))}return o.length>0?{content:[{type:"text",text:o.join(`
1282
1282
  `)}],isError:!0}:null}let r=e.filter(o=>qr.isAbsolute(o));return r.length>0?(f.warn(`Absolute paths rejected (no project root): ${r.join(", ")}`),{content:[{type:"text",text:r.map(o=>`Absolute path is not allowed: ${o}`).join(`
1283
- `)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(h=>typeof h=="string"):[];if(t.length===0)return f.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:o,cppFiles:i,unsupported:s}=Og(t);s.length>0&&f.warn(`Unsupported file types in check request: ${s.join(", ")}`);let a=s.map(h=>`Unsupported file type: ${h} (only .ets and C/C++ source/header files are supported)`),c=[];o.length>0&&this.mergeCheckResult(await this.callArktsCheck(o),a,c),i.length>0&&this.mergeCheckResult(await this.callCppCheck(i),a,c);let l=a.length>0;return{content:[{type:"text",text:[c.join(`
1283
+ `)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(h=>typeof h=="string"):[];if(t.length===0)return f.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:o,cppFiles:i,unsupported:s}=Lg(t);s.length>0&&f.warn(`Unsupported file types in check request: ${s.join(", ")}`);let a=s.map(h=>`Unsupported file type: ${h} (only .ets and C/C++ source/header files are supported)`),c=[];o.length>0&&this.mergeCheckResult(await this.callArktsCheck(o),a,c),i.length>0&&this.mergeCheckResult(await this.callCppCheck(i),a,c);let l=a.length>0;return{content:[{type:"text",text:[c.join(`
1284
1284
  `),a.join(`
1285
1285
  `)].filter(h=>h.trim().length>0).join(`
1286
- `).trim()||"No diagnostics collected"}],isError:l}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return f.warn(`ArkTS check rejected: project is ${ul[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return f.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 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"),f.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(f.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}):(f.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>=ki?(f.error(`Init retry limit reached (${this.initRetryCount}/${ki}), will not auto-retry`),{content:[{type:"text",text:"Project initialization failed multiple times. Please check project configuration and restart the MCP Server."}],isError:!0}):(f.info(`Error check: auto-retrying (${this.initRetryCount}/${ki})`),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 f.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 o=e.content.map(i=>i.text).filter(i=>i&&i.trim().length>0).join(`
1287
- `);o&&(e.isError?t.push(o):r.push(o))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{f.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool&&(this.cppCheckTool.shutdown().catch(t=>{f.warn("Failed to shutdown CppCheckTool during setProjectPath:",t)}),this.cppCheckTool=null),this.initPromise?(this.needsReinit=!0,f.info("Project path changed while init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{f.warn("Failed to re-init project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new Rg;if(await this.server.connect(e),f.info("devecocli-mcp-server started"),!this.config.debug){let t=Nc();t&&f.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=De(t);r?(f.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):f.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?f.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):f.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{f.warn("Background project init failed:",t)}),this.initializeCppCheck()}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return f.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return f.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){f.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,f.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{f.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{f.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){f.warn("C++ LSP initialization skipped: project path is not configured");return}this.cppCheckTool=new Lt(e,this.toolProvider),f.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=>{f.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?De(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=De(this.originalProjectPath),t&&f.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&await this.ensureProjectSynced()){this.projectState=3,this.arktsCheckTool=new Nt(this.config.projectPath,this.toolProvider,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{f.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,f.info("Project fully initialized, check tool is available")}catch(e){f.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=ll(e);return t.required?(f.info(`Sync required: ${t.reason}`),this.runSync(e)):(f.info(`Sync skipped: ${t.reason}`),!0)}async runSync(e){this.projectState=2,f.info("Starting project sync...");let t=await Ot.handleSyncProject(e,this.toolProvider);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,o=Math.round(r/1e3);return r>=dl?(f.error(`Sync skipped for ${o}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(f.warn(`Sync skipped: ${t.reason}, resetting to IDLE for retry (elapsed ${o}s / ${dl/1e3}s)`),this.projectState=0,!1)}case"failed":return f.error(`Project sync failed: ${t.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppCheckTool&&await this.cppCheckTool.shutdown();try{await this.server.close()}catch(e){f.warn("Failed to close MCP server connection:",e)}f.info("devecocli-mcp-server stopped"),Oc(),Rc()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function Og(n){let e=[],t=[],r=[];for(let o of n)qr.extname(o).toLowerCase()===".ets"?e.push(o):cr(o)?t.push(o):r.push(o);return{etsFiles:e,cppFiles:t,unsupported:r}}function Mi(n){return new zr(n)}async function Lg(){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",o=await _.new(e),s=Mi({toolProvider:o,projectPath:n,nodeMaxOldSpaceSize:t,debug:r}),a=async()=>{await s.shutdown(),process.exit(0)};process.once("SIGINT",a),process.once("SIGTERM",a),process.platform==="win32"&&process.once("SIGBREAK",a);try{await s.start()}catch(c){console.error("Failed to start MCP server:",c),process.exit(1)}}var pl=new Ng("serve").description("Host bundled auxiliary protocol servers");pl.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await Lg()});var ml=pl;import{Command as Ow,InvalidArgumentError as vs}from"commander";import{red as So,dim as Nw}from"colorette";import*as z from"fs";import*as Bt from"path";import yw from"adm-zip";import vw from"proper-lockfile";import wu from"ora";import*as pe from"fs";import*as In from"path";var ze=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],at={"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 Vr="1.9.1",Ak=48*1024*1024,fl=280,hl=6,gl=100,yl=3,vl=28,Ri=10,wl=/API参考|APIReference/i,Sn=200,bl=12,Sl=4,Oi=8,Pl=6,Gr=700,Ni=250,Li=400,El=1320,Il=120,Dl=450,Cl=250,Al=500,Tl=480,xl=80,kl=200,Ml=60,Rl=200,Ol=40,Nl=200,Ll=200,_l=40,_t=500,Hl=Object.fromEntries(ze.map((n,e)=>[at[n],e])),qe=Object.fromEntries(ze.map((n,e)=>[n,e]));import*as $l from"fs";import*as x from"path";import{fileURLToPath as Bl}from"url";import*as Yr from"path";import{homedir as _g}from"os";var Hg="deveco-cli";function Fl(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function jg(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&Fl(n)!==""}function jl(){return Yr.join(_g(),".local","share",Hg)}function Jr(n){let e=Kr();return jg()?[`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 Kr(){let n=process.env.DEVECO_CLI_DATA_DIR;if(n===void 0||n==="")return jl();let e=Fl(n);return e?Yr.resolve(e):jl()}var Fg="docs";function Zr(){return x.join(Kr(),Fg)}function X(){return x.join(Zr(),".index")}function Wl(){return x.join(X(),"build.lock")}function _i(){return x.join(X(),"build-status.json")}function Xr(){return x.join(X(),"build-meta.json")}function Pn(){return x.join(X(),"search.db")}function Ht(){return x.join(X(),".tmp")}function $g(){return x.join(Kr(),"logs")}function jt(){return x.join($g(),"doc-init.log")}function Bg(n,e){let t=e;for(;!t.endsWith(`${x.sep}dist`)&&t!==x.dirname(t);)t=x.dirname(t);return t}function Ul(n,e){return x.dirname(Bg(n,e))}function Wg(){let n=Bl(import.meta.url),e=x.dirname(n);return n.includes(`${x.sep}dist${x.sep}`)?Ul(n,e):x.join(e,"..","..","..")}function Ug(...n){let e=Bl(import.meta.url),t=x.dirname(e);return e.includes(`${x.sep}dist${x.sep}`)?[x.join(Ul(e,t),...n)]:[x.join(t,"..","..","..",...n)]}function zl(...n){for(let e of Ug(...n))if($l.existsSync(e))return e;return null}function Ve(){return zl("docs.zip")}function Hi(){return zl("index.zip")}function ql(){return x.join(Wg(),"index","data")}import*as ke from"fs";import*as ct from"path";var lt=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Qr=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function Vl(n){return n instanceof Qr}var ji=null;function Fi(n){ji=n}function $i(){if(ji)return ji;let n=X();if(lt.every(o=>ke.existsSync(ct.join(n,o))))return n;let t=ql();if(lt.every(o=>ke.existsSync(ct.join(t,o))))return t;throw new Qr("Lexicon files not found. Install the documentation index first (index.zip).")}function Gl(){$i()}function dt(n){let e=ct.join($i(),n);return ke.readFileSync(e,"utf-8")}function Yl(n,e){return ke.readFileSync(ct.join(e,n),"utf-8")}async function Jl(n,e=$i()){await ke.promises.mkdir(n,{recursive:!0});for(let t of lt){let r=ct.join(e,t),o=ct.join(n,t);await ke.promises.copyFile(r,o)}}import*as eo from"fs";import*as Kl from"path";import*as Zl from"yauzl";var En=null;function zg(n){return new Promise((e,t)=>{Zl.open(n,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(r,o)=>{if(r||!o){t(r??new Error(`Failed to open zip: ${n}`));return}e(o)})})}function qg(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function Vg(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",o=>{let i=qg(o);i.endsWith("/")||e.set(i,o),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function Gg(){En?.zipfile.close(),En=null}async function Yg(n){let e=Kl.resolve(n),t=await eo.promises.stat(e),r=En;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;Gg();let o=await zg(e),i=await Vg(o);return En={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:o,entries:i,readChain:Promise.resolve()},En}function Jg(n,e){return new Promise((t,r)=>{n.openReadStream(e,(o,i)=>{if(o||!i){r(o??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];i.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),i.on("end",()=>{t(Buffer.concat(s))}),i.on("error",r)})})}async function Kg(n,e){let t=n.readChain,r;n.readChain=new Promise(o=>{r=o}),await t;try{return await Jg(n.zipfile,e)}finally{r()}}function Zg(n){let e=n.replace(/\\/g,"/").replace(/\.md$/,"");return[`docs/${e}.md`,`${e}.md`,`docs/${e}`,e]}function Xg(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function Xl(n){let e=Ve();if(!e)throw new Error("docs.zip not found");let t=await Yg(e),r=Xg(t.entries,Zg(n));if(!r)throw new Error(`Document not found: ${n}`);return(await Kg(t,r)).toString("utf-8")}function Bi(){let n=Ve();return n!==null&&eo.existsSync(n)}import*as Y from"fs";import*as Ge from"path";import Ql from"adm-zip";var ed=["search.db","build-meta.json",...lt],Qg=["corpus.json","corpus-offsets.json","orama.dpack"];async function ey(n){for(let e of Qg)await Y.promises.rm(Ge.join(n,e),{force:!0})}async function ty(n){let e=await Y.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await Y.promises.rm(Ge.join(n,t.name),{recursive:!0,force:!0})}function ny(n){let t=new Ql(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 ry(n){let e=X();await Y.promises.mkdir(e,{recursive:!0});for(let t of ed){let r=Ge.join(e,t);await Y.promises.rm(r,{force:!0}),await Y.promises.rename(Ge.join(n,t),r)}await ey(e),await Y.promises.rm(Ht(),{recursive:!0,force:!0})}function Wi(){let n=Hi();return n!==null&&Y.existsSync(n)}async function td(n){let e=Hi();if(!e)throw new Error("index.zip not found");let t=ny(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=Ht();await Y.promises.rm(r,{recursive:!0,force:!0}),await Y.promises.mkdir(r,{recursive:!0});let o=new Ql(e);for(let s of ed){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await Y.promises.writeFile(Ge.join(r,s),a.getData())}let i=JSON.parse(await Y.promises.readFile(Ge.join(r,"build-meta.json"),"utf-8"));if(!Y.existsSync(Ge.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await ry(r),await Y.promises.mkdir(Zr(),{recursive:!0}),await ty(Zr()),i}import{createHash as nd}from"crypto";import*as rd from"fs";async function to(n){return new Promise((e,t)=>{let r=nd("sha256"),o=rd.createReadStream(n);o.on("data",i=>r.update(i)),o.on("error",t),o.on("end",()=>e(r.digest("hex")))})}function od(n){return nd("sha256").update(n,"utf8").digest("hex")}var Ui=null;function oy(){let n=dt("harmonyos-synonyms.json");return JSON.parse(n)}function iy(n){let e=new Map;for(let t of n){let r=t.map(o=>o.trim()).filter(Boolean);for(let o of r){let i=r.filter(s=>s!==o);e.set(o.toLowerCase(),i),o!==o.toLowerCase()&&e.set(o,i)}}return e}function sy(){let n=iy(oy()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function ay(){return Ui||(Ui=sy()),Ui}function zi(n,e){let t=ay(),r=n.split(/\s+/).filter(Boolean),o=new Set,i=Number.isFinite(e)?e:r.length;for(let s=0;s<r.length&&o.size<i;s+=1){let a=r[s];o.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(o.size>=i)break;o.add(l)}}return[...o].join(" ")}function id(n,e){let t=e?Yl(n,e):dt(n);return od(t)}function no(n){return id("harmonyos-synonyms.json",n)}function ro(n){return id("harmonyos-terms.txt",n)}var cy={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function oo(){try{let n=await pe.promises.readFile(_i(),"utf-8");return JSON.parse(n)}catch{return{...cy}}}async function qi(n){let e=_i();await pe.promises.mkdir(In.dirname(e),{recursive:!0}),await pe.promises.writeFile(e,JSON.stringify(n,null,2))}function sd(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 oo(),...n,updatedAt:Date.now()};return await qi(t),t}async function Vi(){let n=Ve();return n?to(n):null}async function Gi(){try{let n=await pe.promises.readFile(Xr(),"utf-8");return JSON.parse(n)}catch{return null}}async function Yi(n=!1){if(n)return"no-index";let e=await Gi();if(!e||e.segmentCount===0)return"no-index";let t=await Vi();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==Vr?"engine-upgraded":e.termsHash!==ro()?"terms-changed":e.synonymsHash!==no()?"synonyms-changed":null}function Dn(){if(!Bi()||!pe.existsSync(Pn())||!pe.existsSync(Xr()))return!1;let n=In.dirname(Pn());if(!lt.every(e=>pe.existsSync(In.join(n,e))))return!1;try{let e=pe.readFileSync(Xr(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function Ji(n=!1){return n?!0:Bi()?Dn()?await Yi()!==null:!0:!1}async function ad(){let n=await oo();return["installing","indexing","persisting"].includes(n.state)}import*as J from"fs";import*as pu from"os";import*as ne from"path";var cd=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),Ki=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),ld=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"]),dd=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 ly=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,dy=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,uy=/[A-Z][a-zA-Z0-9]{2,}/g,py=/@[A-Z][a-zA-Z0-9]*/g,my=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,ud=6,fy=/^[a-z][a-z0-9]{2,}$/,hy=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,gy=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,yy=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,vy=/^[A-Z][a-zA-Z0-9]+$/;function wy(n){return`"${n.replace(/"/g,'""')}"`}function An(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(wy).join(` ${e} `)}function Cn(n){return An(n,"OR")}function pd(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?Cn([...t,...r]):`(${Cn(t)}) AND (${Cn(r)})`}function Tn(n){return gy.test(n)}function md(n){return yy.test(n)&&n.length>=ud}function by(n){return vy.test(n)}function xn(n){return Tn(n)||md(n)||by(n)}function Sy(n){let e=n.trim().toLowerCase();return dd.has(e)?!1:cd.has(e)}function Py(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function io(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function Zi(n){return[...n.matchAll(ly)].map(e=>e[0])}function Xi(n,e=ud){let t=[];for(let r of n.matchAll(dy))r[0].length>=e&&t.push(r[0]);return t}function Ft(n){return n.filter(e=>{let t=e.toLowerCase();return!n.some(r=>{if(r===e)return!1;let o=r.toLowerCase();return o.length>t.length&&o.endsWith(t)&&t.length>=4})})}function me(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function Ey(n){let e=new Set;me(e,n);let t=io(n);return t&&me(e,t),Ft([...e])}function so(n){if(Tn(n))return Ey(n);let e=new Set;return me(e,n),Ft([...e])}function ao(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(hy);if(!t)return null;let r=t[1].toLowerCase(),o=t[2].toLowerCase();if(!fy.test(r)||ld.has(r)||!Sy(o))return null;let i=Py(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function Qi(n){let e=ao(n.trim());return!e||e.second!=="manager"?null:e}function Iy(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=Qi(e);if(t&&Ki.has(t.first))return!0;if(md(e)){let r=Iy(e);return r!==null&&Ki.has(r)}return!1}function es(n,e,t){let r=t.toLowerCase(),o=new RegExp(`@ohos\\.[^\\s(]*${t}`,"i");for(let i of[n,e])if(i&&(i.toLowerCase().includes(r)||o.test(i)))return!0;return!1}function ts(n){let e=n.trim();if(xn(e))return so(e);let t=new Set;for(let r of Zi(n)){me(t,r);let o=io(r);o&&me(t,o)}for(let r of Xi(n))me(t,r);for(let r of n.matchAll(py))t.add(r[0]);for(let r of n.matchAll(my))t.add(r[0]);for(let r of n.matchAll(uy))r[0].length>=4&&t.add(r[0]);return Ft([...t])}function hd(n){let e=n.trim();if(xn(e))return so(e);let t=new Set,r=ao(e);r&&me(t,r.camelCase);for(let o of ts(e))t.add(o);for(let o of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let i=o[0];i!==i.toLowerCase()&&t.add(i)}return Ft([...t])}function gd(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 yd(n){return N.pureApiSymbol.test(n.trim())}function kn(n){let e=n.trim();return N.stageModelExact.test(e)||N.stageModelEnglishExact.test(e)}function vd(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 wd(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 Dy=[{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 Cy(n,e){for(let{catalog:t,multiplier:r}of e){let o=qe[t];n.set(o,(n.get(o)??1)*r)}}function bd(n,e){for(let t of Dy)t.matches(n)&&Cy(e,t.weights)}function Sd(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"}var co=null,rs=null,os=null,Ed=!1,ns=null;function Ay(){if(co)return co;let n=dt("harmonyos-stopwords.txt");return co=new Set(n.split(`
1288
- `).map(e=>e.trim()).filter(Boolean)),co}function Ty(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t]?.trim();if(!r)continue;let o=n[t+1]?.trim();if(r==="@"&&o&&/^[A-Z][a-zA-Z0-9]*$/.test(o)){e.push(`@${o}`),t+=1;continue}e.push(r)}return e}function Id(n){let e=Ay(),t=[];for(let r of Ty(n)){let o=r.trim();!o||e.has(o)||(t.push(o.toLowerCase()),/[A-Z]/.test(o)&&/[a-zA-Z]/.test(o)&&t.push(o))}return t}async function xy(){let n=await import("jieba-wasm");rs=n.cut,os=n.cut_for_search;let e=dt("harmonyos-terms.txt");n.with_dict(e)}async function ky(){let{Jieba:n}=await import("@node-rs/jieba"),e=dt("harmonyos-terms.txt"),t=n.withDict(Buffer.from(e,"utf-8"));rs=t.cut.bind(t),os=t.cutForSearch.bind(t)}async function Je(){if(!Ed)return ns||(ns=(D()?xy():ky()).then(()=>{Ed=!0})),ns}async function My(n){return await Je(),Id(os(n,!0))}async function Dd(n){return await Je(),Id(rs(n,!0))}async function lo(n,e){let t=n.trim();if(!t||e<=0)return"";let r=(await My(t)).join(" ");return r.length<=e?r:r.slice(0,e)}async function Ry(n,e){let t=[];for(let o of n){let i=o.trim();i&&(t.push(i.toLowerCase()),/[A-Z]/.test(i)&&t.push(i))}let r=[...new Set(t)].join(" ");return r.length<=e?r:r.slice(0,e)}async function uo(n){let e=!!n.sectionTitle.trim(),t=n.titleTokens.trim(),r=e?Tl:El,o=e?kl:Dl,i=e?await Ry(n.apiSymbols,o):await lo(n.apiSymbols.join(" "),o),a=(await Promise.all([lo(t,e?xl:Il),Promise.resolve(i),lo(n.headingsText,e?Ml:Cl),lo(n.bodySample,e?Rl:Al)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}function Oy(n){return n.join(" ").replace(/\s+/g," ").trim().slice(0,Sn)}function is(n,e){let t=new Set,r=[];for(let o of[...n,...e]){let i=o.toLowerCase();if(!(!o||t.has(i))&&(t.add(i),r.push(o),r.length>=bl))break}return r}function Ny(n){return n.length>=2&&n.length<=Sl}function Ly(n,e){let t=zi(n,Oi),r=t.split(/\s+/).filter(Boolean),o=[e.first,...r.filter(a=>a!==e.second),e.lower,e.camelCase],i=[e.second,e.lower,e.camelCase],s=is(o,i);return{rawQuery:n,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:pd(o,i)}}function _y(n,e){let t=is(so(e),[]);return{rawQuery:n,expandedQuery:n,tokens:t,preferAnd:!1,ftsMatch:Cn(t)}}async function Cd(n){let e=Oy(n),t=e.trim(),r=wd(t);if(r)return{rawQuery:e,expandedQuery:r.expandedQuery,tokens:r.tokens,preferAnd:!1};let o=ao(t);if(o)return Ly(e,o);if(xn(t))return _y(e,t);let i=vd(e),s=[...ts(e),...i],c=gd(t)?e:zi(e,Oi),l=await Dd(c),u=is(s,l);return{rawQuery:e,expandedQuery:c,tokens:u,preferAnd:i.length===0&&Ny(u)}}var Ad=["harmonyos-releases","harmonyos-roadmap"],Hy=new Set(Ad.map(n=>qe[n])),jy=Ad.map(n=>`${at[n]}/`);function Fy(n){return Hy.has(n)}function $y(n){return jy.some(e=>n.startsWith(e))}function Td(n){let e=[],t=[];for(let r of n)Fy(r.catalog_id)?t.push(r):e.push(r);return[...e,...t]}function xd(n){let e=[],t=[];for(let r of n)$y(r.documentId)?t.push(r):e.push(r);return[...e,...t]}var By=[{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 Mn(n,e,t){let r=qe[e];n.set(r,(n.get(r)??1)*t)}function Wy(n,e){let t=n.trim(),r=/[\u4e00-\u9fff]/.test(t),o=/\b[A-Z][a-zA-Z0-9]{2,}\b/.test(t),i=/\b[a-z][a-zA-Z0-9]{3,}\b/.test(t);if(r&&(o||i)){Mn(e,"harmonyos-guides",1.45),Mn(e,"harmonyos-references",1.35);return}(o||i)&&Mn(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&Mn(e,"harmonyos-references",1.75)}function kd(n){let e=new Map,t=n.trim();if(!t)return e;let r=yd(t);Wy(t,e),bd(t,e);for(let o of By)o.pattern.test(t)&&(o.skipForPureApiSymbol&&r||Mn(e,o.catalog,o.multiplier));return e}function Md(n){return Pd(n)}var Uy=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function Rd(n,e){let t=-1;for(let r of Uy){let o=n.lastIndexOf(r);o>t&&(t=o)}return t>=e?t:-1}function Od(n,e){let t=n.trim();if(t.length<=e)return{text:t,excerptTruncated:!1};let r=t.slice(0,e),o=Rd(r,e-20),i=o>=0?o:e;return{text:t.slice(0,i).trimEnd(),excerptTruncated:!0}}function Nd(n,e,t={}){let{maxLen:r=Ll,contextChars:o=_l,excerptTruncated:i=!1}=t,s=n.replace(/\s+/g," ").trim();if(!s)return"";if(s.length<=r)return i?`${s}...`:s;let a=e.split(/\s+/).map(Me=>Me.trim()).filter(Boolean),c=0;for(let Me of a){let ut=s.toLowerCase().indexOf(Me.toLowerCase());if(ut>=0){c=ut;break}}let l=Math.max(0,c-o),u=Math.min(s.length,l+r),h=s.slice(l,u),v=Rd(h,r-25);v>=0&&(u=l+v);let I=s.slice(l,u).trim(),k=l>0?"...":"",ee=u<s.length||i?"...":"";return`${k}${I}${ee}`}var zy=`
1286
+ `).trim()||"No diagnostics collected"}],isError:l}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return f.warn(`ArkTS check rejected: project is ${ul[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return f.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e});default:return{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],isError:!0}}}async handleIdleCheck(){if(this.ensureProjectReady(),this.config.projectPath){let e,t;return this.syncSkippedDueToLock?(e=`Another build process is running, sync deferred (waiting ${this.syncSkipStartedAt>0?Math.round((Date.now()-this.syncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,t="lock contention",this.syncSkippedDueToLock=!1):this.configChangedTriggeredResync?(e="Config file changed, resyncing project, please retry in 10 seconds",t="config changed",this.configChangedTriggeredResync=!1):(e="HarmonyOS project detected, syncing, please retry in 10 seconds",t="initial"),f.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(f.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}):(f.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>=ki?(f.error(`Init retry limit reached (${this.initRetryCount}/${ki}), will not auto-retry`),{content:[{type:"text",text:"Project initialization failed multiple times. Please check project configuration and restart the MCP Server."}],isError:!0}):(f.info(`Error check: auto-retrying (${this.initRetryCount}/${ki})`),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 f.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 o=e.content.map(i=>i.text).filter(i=>i&&i.trim().length>0).join(`
1287
+ `);o&&(e.isError?t.push(o):r.push(o))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{f.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool&&(this.cppCheckTool.shutdown().catch(t=>{f.warn("Failed to shutdown CppCheckTool during setProjectPath:",t)}),this.cppCheckTool=null),this.initPromise?(this.needsReinit=!0,f.info("Project path changed while init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{f.warn("Failed to re-init project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new Ng;if(await this.server.connect(e),f.info("devecocli-mcp-server started"),!this.config.debug){let t=Nc();t&&f.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=De(t);r?(f.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):f.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?f.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):f.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{f.warn("Background project init failed:",t)}),this.initializeCppCheck()}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return f.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return f.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){f.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,f.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{f.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{f.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){f.warn("C++ LSP initialization skipped: project path is not configured");return}this.cppCheckTool=new Lt(e,this.toolProvider),f.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=>{f.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?De(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=De(this.originalProjectPath),t&&f.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&await this.ensureProjectSynced()){this.projectState=3,this.arktsCheckTool=new Nt(this.config.projectPath,this.toolProvider,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{f.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,f.info("Project fully initialized, check tool is available")}catch(e){f.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=ll(e);return t.required?(f.info(`Sync required: ${t.reason}`),this.runSync(e)):(f.info(`Sync skipped: ${t.reason}`),!0)}async runSync(e){this.projectState=2,f.info("Starting project sync...");let t=await Ot.handleSyncProject(e,this.toolProvider);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,o=Math.round(r/1e3);return r>=dl?(f.error(`Sync skipped for ${o}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(f.warn(`Sync skipped: ${t.reason}, resetting to IDLE for retry (elapsed ${o}s / ${dl/1e3}s)`),this.projectState=0,!1)}case"failed":return f.error(`Project sync failed: ${t.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:{let r=t;return f.error(`Unknown sync result status: ${JSON.stringify(r)}`),this.projectState=5,!1}}}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppCheckTool&&await this.cppCheckTool.shutdown();try{await this.server.close()}catch(e){f.warn("Failed to close MCP server connection:",e)}f.info("devecocli-mcp-server stopped"),Oc(),Rc()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function Lg(n){let e=[],t=[],r=[];for(let o of n)qr.extname(o).toLowerCase()===".ets"?e.push(o):cr(o)?t.push(o):r.push(o);return{etsFiles:e,cppFiles:t,unsupported:r}}function Mi(n){return new zr(n)}async function Hg(){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",o=await _.new(e),s=Mi({toolProvider:o,projectPath:n,nodeMaxOldSpaceSize:t,debug:r}),a=async()=>{await s.shutdown(),process.exit(0)};process.once("SIGINT",a),process.once("SIGTERM",a),process.platform==="win32"&&process.once("SIGBREAK",a);try{await s.start()}catch(c){console.error("Failed to start MCP server:",c),process.exit(1)}}var pl=new _g("serve").description("Host bundled auxiliary protocol servers");pl.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await Hg()});var ml=pl;import{Command as Lw,InvalidArgumentError as vs}from"commander";import{red as So,dim as _w}from"colorette";import*as z from"fs";import*as Bt from"path";import ww from"adm-zip";import bw from"proper-lockfile";import wu from"ora";import*as pe from"fs";import*as In from"path";var ze=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],at={"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 Vr="1.9.1",xk=48*1024*1024,fl=280,hl=6,gl=100,yl=3,vl=28,Ri=10,wl=/API参考|APIReference/i,Sn=200,bl=12,Sl=4,Oi=8,Pl=6,Gr=700,Ni=250,Li=400,El=1320,Il=120,Dl=450,Cl=250,Al=500,Tl=480,xl=80,kl=200,Ml=60,Rl=200,Ol=40,Nl=200,Ll=200,_l=40,_t=500,Hl=Object.fromEntries(ze.map((n,e)=>[at[n],e])),qe=Object.fromEntries(ze.map((n,e)=>[n,e]));import*as $l from"fs";import*as x from"path";import{fileURLToPath as Bl}from"url";import*as Yr from"path";import{homedir as jg}from"os";var Fg="deveco-cli";function Fl(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function $g(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&Fl(n)!==""}function jl(){return Yr.join(jg(),".local","share",Fg)}function Jr(n){let e=Kr();return $g()?[`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 Kr(){let n=process.env.DEVECO_CLI_DATA_DIR;if(n===void 0||n==="")return jl();let e=Fl(n);return e?Yr.resolve(e):jl()}var Bg="docs";function Zr(){return x.join(Kr(),Bg)}function X(){return x.join(Zr(),".index")}function Wl(){return x.join(X(),"build.lock")}function _i(){return x.join(X(),"build-status.json")}function Xr(){return x.join(X(),"build-meta.json")}function Pn(){return x.join(X(),"search.db")}function Ht(){return x.join(X(),".tmp")}function Wg(){return x.join(Kr(),"logs")}function jt(){return x.join(Wg(),"doc-init.log")}function Ug(n,e){let t=e;for(;!t.endsWith(`${x.sep}dist`)&&t!==x.dirname(t);)t=x.dirname(t);return t}function Ul(n,e){return x.dirname(Ug(n,e))}function zg(){let n=Bl(import.meta.url),e=x.dirname(n);return n.includes(`${x.sep}dist${x.sep}`)?Ul(n,e):x.join(e,"..","..","..")}function qg(...n){let e=Bl(import.meta.url),t=x.dirname(e);return e.includes(`${x.sep}dist${x.sep}`)?[x.join(Ul(e,t),...n)]:[x.join(t,"..","..","..",...n)]}function zl(...n){for(let e of qg(...n))if($l.existsSync(e))return e;return null}function Ve(){return zl("docs.zip")}function Hi(){return zl("index.zip")}function ql(){return x.join(zg(),"index","data")}import*as ke from"fs";import*as ct from"path";var lt=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Qr=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function Vl(n){return n instanceof Qr}var ji=null;function Fi(n){ji=n}function $i(){if(ji)return ji;let n=X();if(lt.every(o=>ke.existsSync(ct.join(n,o))))return n;let t=ql();if(lt.every(o=>ke.existsSync(ct.join(t,o))))return t;throw new Qr("Lexicon files not found. Install the documentation index first (index.zip).")}function Gl(){$i()}function dt(n){let e=ct.join($i(),n);return ke.readFileSync(e,"utf-8")}function Yl(n,e){return ke.readFileSync(ct.join(e,n),"utf-8")}async function Jl(n,e=$i()){await ke.promises.mkdir(n,{recursive:!0});for(let t of lt){let r=ct.join(e,t),o=ct.join(n,t);await ke.promises.copyFile(r,o)}}import*as eo from"fs";import*as Kl from"path";import*as Zl from"yauzl";var En=null;function Vg(n){return new Promise((e,t)=>{Zl.open(n,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(r,o)=>{if(r||!o){t(r??new Error(`Failed to open zip: ${n}`));return}e(o)})})}function Gg(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function Yg(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",o=>{let i=Gg(o);i.endsWith("/")||e.set(i,o),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function Jg(){En?.zipfile.close(),En=null}async function Kg(n){let e=Kl.resolve(n),t=await eo.promises.stat(e),r=En;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;Jg();let o=await Vg(e),i=await Yg(o);return En={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:o,entries:i,readChain:Promise.resolve()},En}function Zg(n,e){return new Promise((t,r)=>{n.openReadStream(e,(o,i)=>{if(o||!i){r(o??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];i.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),i.on("end",()=>{t(Buffer.concat(s))}),i.on("error",r)})})}async function Xg(n,e){let t=n.readChain,r;n.readChain=new Promise(o=>{r=o}),await t;try{return await Zg(n.zipfile,e)}finally{r()}}function Qg(n){let e=n.replace(/\\/g,"/").replace(/\.md$/,"");return[`docs/${e}.md`,`${e}.md`,`docs/${e}`,e]}function ey(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function Xl(n){let e=Ve();if(!e)throw new Error("docs.zip not found");let t=await Kg(e),r=ey(t.entries,Qg(n));if(!r)throw new Error(`Document not found: ${n}`);return(await Xg(t,r)).toString("utf-8")}function Bi(){let n=Ve();return n!==null&&eo.existsSync(n)}import*as Y from"fs";import*as Ge from"path";import Ql from"adm-zip";var ed=["search.db","build-meta.json",...lt],ty=["corpus.json","corpus-offsets.json","orama.dpack"];async function ny(n){for(let e of ty)await Y.promises.rm(Ge.join(n,e),{force:!0})}async function ry(n){let e=await Y.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await Y.promises.rm(Ge.join(n,t.name),{recursive:!0,force:!0})}function oy(n){let t=new Ql(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 iy(n){let e=X();await Y.promises.mkdir(e,{recursive:!0});for(let t of ed){let r=Ge.join(e,t);await Y.promises.rm(r,{force:!0}),await Y.promises.rename(Ge.join(n,t),r)}await ny(e),await Y.promises.rm(Ht(),{recursive:!0,force:!0})}function Wi(){let n=Hi();return n!==null&&Y.existsSync(n)}async function td(n){let e=Hi();if(!e)throw new Error("index.zip not found");let t=oy(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=Ht();await Y.promises.rm(r,{recursive:!0,force:!0}),await Y.promises.mkdir(r,{recursive:!0});let o=new Ql(e);for(let s of ed){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await Y.promises.writeFile(Ge.join(r,s),a.getData())}let i=JSON.parse(await Y.promises.readFile(Ge.join(r,"build-meta.json"),"utf-8"));if(!Y.existsSync(Ge.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await iy(r),await Y.promises.mkdir(Zr(),{recursive:!0}),await ry(Zr()),i}import{createHash as nd}from"crypto";import*as rd from"fs";async function to(n){return new Promise((e,t)=>{let r=nd("sha256"),o=rd.createReadStream(n);o.on("data",i=>r.update(i)),o.on("error",t),o.on("end",()=>e(r.digest("hex")))})}function od(n){return nd("sha256").update(n,"utf8").digest("hex")}var Ui=null;function sy(){let n=dt("harmonyos-synonyms.json");return JSON.parse(n)}function ay(n){let e=new Map;for(let t of n){let r=t.map(o=>o.trim()).filter(Boolean);for(let o of r){let i=r.filter(s=>s!==o);e.set(o.toLowerCase(),i),o!==o.toLowerCase()&&e.set(o,i)}}return e}function cy(){let n=ay(sy()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function ly(){return Ui||(Ui=cy()),Ui}function zi(n,e){let t=ly(),r=n.split(/\s+/).filter(Boolean),o=new Set,i=Number.isFinite(e)?e:r.length;for(let s=0;s<r.length&&o.size<i;s+=1){let a=r[s];o.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(o.size>=i)break;o.add(l)}}return[...o].join(" ")}function id(n,e){let t=e?Yl(n,e):dt(n);return od(t)}function no(n){return id("harmonyos-synonyms.json",n)}function ro(n){return id("harmonyos-terms.txt",n)}var dy={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function oo(){try{let n=await pe.promises.readFile(_i(),"utf-8");return JSON.parse(n)}catch{return{...dy}}}async function qi(n){let e=_i();await pe.promises.mkdir(In.dirname(e),{recursive:!0}),await pe.promises.writeFile(e,JSON.stringify(n,null,2))}function sd(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 oo(),...n,updatedAt:Date.now()};return await qi(t),t}async function Vi(){let n=Ve();return n?to(n):null}async function Gi(){try{let n=await pe.promises.readFile(Xr(),"utf-8");return JSON.parse(n)}catch{return null}}async function Yi(n=!1){if(n)return"no-index";let e=await Gi();if(!e||e.segmentCount===0)return"no-index";let t=await Vi();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==Vr?"engine-upgraded":e.termsHash!==ro()?"terms-changed":e.synonymsHash!==no()?"synonyms-changed":null}function Dn(){if(!Bi()||!pe.existsSync(Pn())||!pe.existsSync(Xr()))return!1;let n=In.dirname(Pn());if(!lt.every(e=>pe.existsSync(In.join(n,e))))return!1;try{let e=pe.readFileSync(Xr(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function Ji(n=!1){return n?!0:Bi()?Dn()?await Yi()!==null:!0:!1}async function ad(){let n=await oo();return["installing","indexing","persisting"].includes(n.state)}import*as J from"fs";import*as pu from"os";import*as ne from"path";var cd=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),Ki=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),ld=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"]),dd=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 uy=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,py=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,my=/[A-Z][a-zA-Z0-9]{2,}/g,fy=/@[A-Z][a-zA-Z0-9]*/g,hy=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,ud=6,gy=/^[a-z][a-z0-9]{2,}$/,yy=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,vy=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,wy=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,by=/^[A-Z][a-zA-Z0-9]+$/;function Sy(n){return`"${n.replace(/"/g,'""')}"`}function An(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(Sy).join(` ${e} `)}function Cn(n){return An(n,"OR")}function pd(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?Cn([...t,...r]):`(${Cn(t)}) AND (${Cn(r)})`}function Tn(n){return vy.test(n)}function md(n){return wy.test(n)&&n.length>=ud}function Py(n){return by.test(n)}function xn(n){return Tn(n)||md(n)||Py(n)}function Ey(n){let e=n.trim().toLowerCase();return dd.has(e)?!1:cd.has(e)}function Iy(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function io(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function Zi(n){return[...n.matchAll(uy)].map(e=>e[0])}function Xi(n,e=ud){let t=[];for(let r of n.matchAll(py))r[0].length>=e&&t.push(r[0]);return t}function Ft(n){return n.filter(e=>{let t=e.toLowerCase();return!n.some(r=>{if(r===e)return!1;let o=r.toLowerCase();return o.length>t.length&&o.endsWith(t)&&t.length>=4})})}function me(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function Dy(n){let e=new Set;me(e,n);let t=io(n);return t&&me(e,t),Ft([...e])}function so(n){if(Tn(n))return Dy(n);let e=new Set;return me(e,n),Ft([...e])}function ao(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(yy);if(!t)return null;let r=t[1].toLowerCase(),o=t[2].toLowerCase();if(!gy.test(r)||ld.has(r)||!Ey(o))return null;let i=Iy(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function Qi(n){let e=ao(n.trim());return!e||e.second!=="manager"?null:e}function Cy(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=Qi(e);if(t&&Ki.has(t.first))return!0;if(md(e)){let r=Cy(e);return r!==null&&Ki.has(r)}return!1}function es(n,e,t){let r=t.toLowerCase(),o=new RegExp(`@ohos\\.[^\\s(]*${t}`,"i");for(let i of[n,e])if(i&&(i.toLowerCase().includes(r)||o.test(i)))return!0;return!1}function ts(n){let e=n.trim();if(xn(e))return so(e);let t=new Set;for(let r of Zi(n)){me(t,r);let o=io(r);o&&me(t,o)}for(let r of Xi(n))me(t,r);for(let r of n.matchAll(fy))t.add(r[0]);for(let r of n.matchAll(hy))t.add(r[0]);for(let r of n.matchAll(my))r[0].length>=4&&t.add(r[0]);return Ft([...t])}function hd(n){let e=n.trim();if(xn(e))return so(e);let t=new Set,r=ao(e);r&&me(t,r.camelCase);for(let o of ts(e))t.add(o);for(let o of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let i=o[0];i!==i.toLowerCase()&&t.add(i)}return Ft([...t])}function gd(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 yd(n){return N.pureApiSymbol.test(n.trim())}function kn(n){let e=n.trim();return N.stageModelExact.test(e)||N.stageModelEnglishExact.test(e)}function vd(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 wd(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 Ay=[{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 Ty(n,e){for(let{catalog:t,multiplier:r}of e){let o=qe[t];n.set(o,(n.get(o)??1)*r)}}function bd(n,e){for(let t of Ay)t.matches(n)&&Ty(e,t.weights)}function Sd(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"}var co=null,rs=null,os=null,Ed=!1,ns=null;function xy(){if(co)return co;let n=dt("harmonyos-stopwords.txt");return co=new Set(n.split(`
1288
+ `).map(e=>e.trim()).filter(Boolean)),co}function ky(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t]?.trim();if(!r)continue;let o=n[t+1]?.trim();if(r==="@"&&o&&/^[A-Z][a-zA-Z0-9]*$/.test(o)){e.push(`@${o}`),t+=1;continue}e.push(r)}return e}function Id(n){let e=xy(),t=[];for(let r of ky(n)){let o=r.trim();!o||e.has(o)||(t.push(o.toLowerCase()),/[A-Z]/.test(o)&&/[a-zA-Z]/.test(o)&&t.push(o))}return t}async function My(){let n=await import("jieba-wasm");rs=n.cut,os=n.cut_for_search;let e=dt("harmonyos-terms.txt");n.with_dict(e)}async function Ry(){let{Jieba:n}=await import("@node-rs/jieba"),e=dt("harmonyos-terms.txt"),t=n.withDict(Buffer.from(e,"utf-8"));rs=t.cut.bind(t),os=t.cutForSearch.bind(t)}async function Je(){Ed||(ns||(ns=(D()?My():Ry()).then(()=>{Ed=!0})),await ns)}async function Oy(n){return await Je(),Id(os(n,!0))}async function Dd(n){return await Je(),Id(rs(n,!0))}async function lo(n,e){let t=n.trim();if(!t||e<=0)return"";let r=(await Oy(t)).join(" ");return r.length<=e?r:r.slice(0,e)}async function Ny(n,e){let t=[];for(let o of n){let i=o.trim();i&&(t.push(i.toLowerCase()),/[A-Z]/.test(i)&&t.push(i))}let r=[...new Set(t)].join(" ");return r.length<=e?r:r.slice(0,e)}async function uo(n){let e=!!n.sectionTitle.trim(),t=n.titleTokens.trim(),r=e?Tl:El,o=e?kl:Dl,i=e?await Ny(n.apiSymbols,o):await lo(n.apiSymbols.join(" "),o),a=(await Promise.all([lo(t,e?xl:Il),Promise.resolve(i),lo(n.headingsText,e?Ml:Cl),lo(n.bodySample,e?Rl:Al)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}function Ly(n){return n.join(" ").replace(/\s+/g," ").trim().slice(0,Sn)}function is(n,e){let t=new Set,r=[];for(let o of[...n,...e]){let i=o.toLowerCase();if(!(!o||t.has(i))&&(t.add(i),r.push(o),r.length>=bl))break}return r}function _y(n){return n.length>=2&&n.length<=Sl}function Hy(n,e){let t=zi(n,Oi),r=t.split(/\s+/).filter(Boolean),o=[e.first,...r.filter(a=>a!==e.second),e.lower,e.camelCase],i=[e.second,e.lower,e.camelCase],s=is(o,i);return{rawQuery:n,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:pd(o,i)}}function jy(n,e){let t=is(so(e),[]);return{rawQuery:n,expandedQuery:n,tokens:t,preferAnd:!1,ftsMatch:Cn(t)}}async function Cd(n){let e=Ly(n),t=e.trim(),r=wd(t);if(r)return{rawQuery:e,expandedQuery:r.expandedQuery,tokens:r.tokens,preferAnd:!1};let o=ao(t);if(o)return Hy(e,o);if(xn(t))return jy(e,t);let i=vd(e),s=[...ts(e),...i],c=gd(t)?e:zi(e,Oi),l=await Dd(c),u=is(s,l);return{rawQuery:e,expandedQuery:c,tokens:u,preferAnd:i.length===0&&_y(u)}}var Ad=["harmonyos-releases","harmonyos-roadmap"],Fy=new Set(Ad.map(n=>qe[n])),$y=Ad.map(n=>`${at[n]}/`);function By(n){return Fy.has(n)}function Wy(n){return $y.some(e=>n.startsWith(e))}function Td(n){let e=[],t=[];for(let r of n)By(r.catalog_id)?t.push(r):e.push(r);return[...e,...t]}function xd(n){let e=[],t=[];for(let r of n)Wy(r.documentId)?t.push(r):e.push(r);return[...e,...t]}var Uy=[{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 Mn(n,e,t){let r=qe[e];n.set(r,(n.get(r)??1)*t)}function zy(n,e){let t=n.trim(),r=/[\u4e00-\u9fff]/.test(t),o=/\b[A-Z][a-zA-Z0-9]{2,}\b/.test(t),i=/\b[a-z][a-zA-Z0-9]{3,}\b/.test(t);if(r&&(o||i)){Mn(e,"harmonyos-guides",1.45),Mn(e,"harmonyos-references",1.35);return}(o||i)&&Mn(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&Mn(e,"harmonyos-references",1.75)}function kd(n){let e=new Map,t=n.trim();if(!t)return e;let r=yd(t);zy(t,e),bd(t,e);for(let o of Uy)o.pattern.test(t)&&(o.skipForPureApiSymbol&&r||Mn(e,o.catalog,o.multiplier));return e}function Md(n){return Pd(n)}var qy=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function Rd(n,e){let t=-1;for(let r of qy){let o=n.lastIndexOf(r);o>t&&(t=o)}return t>=e?t:-1}function Od(n,e){let t=n.trim();if(t.length<=e)return{text:t,excerptTruncated:!1};let r=t.slice(0,e),o=Rd(r,e-20),i=o>=0?o:e;return{text:t.slice(0,i).trimEnd(),excerptTruncated:!0}}function Nd(n,e,t={}){let{maxLen:r=Ll,contextChars:o=_l,excerptTruncated:i=!1}=t,s=n.replace(/\s+/g," ").trim();if(!s)return"";if(s.length<=r)return i?`${s}...`:s;let a=e.split(/\s+/).map(Me=>Me.trim()).filter(Boolean),c=0;for(let Me of a){let ut=s.toLowerCase().indexOf(Me.toLowerCase());if(ut>=0){c=ut;break}}let l=Math.max(0,c-o),u=Math.min(s.length,l+r),h=s.slice(l,u),v=Rd(h,r-25);v>=0&&(u=l+v);let I=s.slice(l,u).trim(),k=l>0?"...":"",ee=u<s.length||i?"...":"";return`${k}${I}${ee}`}var Vy=`
1289
1289
  SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
1290
1290
  d.catalog_id, bm25(segments_fts) AS bm25
1291
1291
  FROM segments_fts
@@ -1294,7 +1294,7 @@ Output so far:
1294
1294
  WHERE segments_fts MATCH ?
1295
1295
  ORDER BY bm25(segments_fts)
1296
1296
  LIMIT ?
1297
- `,qy=`
1297
+ `,Gy=`
1298
1298
  SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
1299
1299
  d.catalog_id, bm25(segments_fts) AS bm25
1300
1300
  FROM segments_fts
@@ -1303,7 +1303,7 @@ Output so far:
1303
1303
  WHERE segments_fts MATCH ? AND d.catalog_id = ?
1304
1304
  ORDER BY bm25(segments_fts)
1305
1305
  LIMIT ?
1306
- `,Vy=3.5,Gy=1.4,Yy=4,Jy=1.8,Ky=1.35,Zy=3.5,Xy=1.8,Qy=120,Ld=6;function as(n){return n.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function ev(n){return n.split(/[^\p{L}\p{N}@.]+/u).map(as).filter(e=>e.length>=2)}function tv(n,e){return e.length>1&&e.every(t=>n.includes(t))}function nv(n){return/^[a-z0-9]{1,4}$/.test(n.trim().toLowerCase())}function rv(n,e){return n===e?Zy:n.startsWith(e)||n.includes(`@ohos.${e}`)?Xy:1}function ov(n,e){let t=as(e);if(t.length<2)return 1;let r=as(n.doc_title);if(nv(e))return rv(r,t);if(r.includes(t))return Yy;if(t.length>=Ld&&r.includes(t.slice(0,Ld)))return Jy;let o=ev(e);return tv(r,o)?Ky:1}function iv(n,e){return e<=1?n:n<0?n*e:n/e}function po(n,e,t,r){let o=n.bm25/(e.get(n.catalog_id)??1);return o=iv(o,ov(n,t)),r&&es(n.doc_title,n.section_title,r)&&(o/=Vy,n.catalog_id===qe["harmonyos-references"]&&(o/=Gy)),o}function ss(n,e,t,r){return n.reduce((o,i)=>po(i,e,t,r)<po(o,e,t,r)?i:o)}function sv(n,e){return e.some(t=>n.section_title.includes(t)||n.doc_title.includes(t))}function av(n,e,t,r,o){if(o){let i=n.filter(s=>es(s.doc_title,s.section_title,o));if(i.length>0)return ss(i,t,r,o)}if(e.length>0){let i=n.filter(s=>sv(s,e));if(i.length>0)return ss(i,t,r,o)}return ss(n,t,r,o)}function _d(n,e,t,r,o){let i=kd(e),s=hd(e),c=Qi(e)?.camelCase,l=new Map;for(let I of n){let k=l.get(I.document_id)??[];k.push(I),l.set(I.document_id,k)}let u=[];for(let I of l.values())u.push(av(I,s,i,t,c));let h=u.sort((I,k)=>po(I,i,t,c)-po(k,i,t,c));return(o?Td(h):h).slice(0,r)}function mo(n,e,t,r,o,i){let s=e?qe[e]:void 0,a=Math.max(t,t*Pl,Qy),c=s===void 0?n.all(zy,r,a):n.all(qy,r,s,a);return(s===void 0?_d(c,i,o,t,!0):_d(c,i,o,t,!1)).map(u=>({title:u.doc_title,documentId:u.document_id,sectionTitle:u.section_title||void 0,snippet:Nd(u.lead_text,o,{excerptTruncated:!!u.excerpt_truncated})}))}var fo=`
1306
+ `,Yy=3.5,Jy=1.4,Ky=4,Zy=1.8,Xy=1.35,Qy=3.5,ev=1.8,tv=120,Ld=6;function as(n){return n.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function nv(n){return n.split(/[^\p{L}\p{N}@.]+/u).map(as).filter(e=>e.length>=2)}function rv(n,e){return e.length>1&&e.every(t=>n.includes(t))}function ov(n){return/^[a-z0-9]{1,4}$/.test(n.trim().toLowerCase())}function iv(n,e){return n===e?Qy:n.startsWith(e)||n.includes(`@ohos.${e}`)?ev:1}function sv(n,e){let t=as(e);if(t.length<2)return 1;let r=as(n.doc_title);if(ov(e))return iv(r,t);if(r.includes(t))return Ky;if(t.length>=Ld&&r.includes(t.slice(0,Ld)))return Zy;let o=nv(e);return rv(r,o)?Xy:1}function av(n,e){return e<=1?n:n<0?n*e:n/e}function po(n,e,t,r){let o=n.bm25/(e.get(n.catalog_id)??1);return o=av(o,sv(n,t)),r&&es(n.doc_title,n.section_title,r)&&(o/=Yy,n.catalog_id===qe["harmonyos-references"]&&(o/=Jy)),o}function ss(n,e,t,r){return n.reduce((o,i)=>po(i,e,t,r)<po(o,e,t,r)?i:o)}function cv(n,e){return e.some(t=>n.section_title.includes(t)||n.doc_title.includes(t))}function lv(n,e,t,r,o){if(o){let i=n.filter(s=>es(s.doc_title,s.section_title,o));if(i.length>0)return ss(i,t,r,o)}if(e.length>0){let i=n.filter(s=>cv(s,e));if(i.length>0)return ss(i,t,r,o)}return ss(n,t,r,o)}function _d(n,e,t,r,o){let i=kd(e),s=hd(e),c=Qi(e)?.camelCase,l=new Map;for(let I of n){let k=l.get(I.document_id)??[];k.push(I),l.set(I.document_id,k)}let u=[];for(let I of l.values())u.push(lv(I,s,i,t,c));let h=u.sort((I,k)=>po(I,i,t,c)-po(k,i,t,c));return(o?Td(h):h).slice(0,r)}function mo(n,e,t,r,o,i){let s=e?qe[e]:void 0,a=Math.max(t,t*Pl,tv),c=s===void 0?n.all(Vy,r,a):n.all(Gy,r,s,a);return(s===void 0?_d(c,i,o,t,!0):_d(c,i,o,t,!1)).map(u=>({title:u.doc_title,documentId:u.document_id,sectionTitle:u.section_title||void 0,snippet:Nd(u.lead_text,o,{excerptTruncated:!!u.excerpt_truncated})}))}var fo=`
1307
1307
  CREATE TABLE documents (
1308
1308
  id INTEGER PRIMARY KEY,
1309
1309
  document_id TEXT NOT NULL UNIQUE,
@@ -1341,18 +1341,18 @@ CREATE TRIGGER segments_au AFTER UPDATE ON segments BEGIN
1341
1341
  END;
1342
1342
 
1343
1343
  CREATE INDEX segments_doc_id_idx ON segments(doc_id);
1344
- `;var $t=null,cs=null;function cv(){$t?.close(),$t=null,cs=null}function lv(n,e){if($t&&cs===e)return $t;$t?.close();let t=new n(e,{readonly:!0,fileMustExist:!0});return $t=t,cs=e,t.pragma("mmap_size = 268435456"),t.pragma("cache_size = -8000"),t.pragma("query_only = ON"),t}function dv(n,e){let t=new n(e);return t.pragma("journal_mode = OFF"),t.pragma("synchronous = OFF"),t.pragma("temp_store = MEMORY"),t.exec(fo),t}function uv(n,e,t){let r=e.get(t.documentId);if(r!==void 0)return r;let i=n.prepare("SELECT id FROM documents WHERE document_id = ?").get(t.documentId);if(i)return e.set(t.documentId,i.id),i.id;let a=n.prepare(`
1344
+ `;var $t=null,cs=null;function dv(){$t?.close(),$t=null,cs=null}function uv(n,e){if($t&&cs===e)return $t;$t?.close();let t=new n(e,{readonly:!0,fileMustExist:!0});return $t=t,cs=e,t.pragma("mmap_size = 268435456"),t.pragma("cache_size = -8000"),t.pragma("query_only = ON"),t}function pv(n,e){let t=new n(e);return t.pragma("journal_mode = OFF"),t.pragma("synchronous = OFF"),t.pragma("temp_store = MEMORY"),t.exec(fo),t}function mv(n,e,t){let r=e.get(t.documentId);if(r!==void 0)return r;let i=n.prepare("SELECT id FROM documents WHERE document_id = ?").get(t.documentId);if(i)return e.set(t.documentId,i.id),i.id;let a=n.prepare(`
1345
1345
  INSERT INTO documents(document_id, catalog_id, doc_title)
1346
1346
  VALUES (?, ?, ?)
1347
- `).run(t.documentId,t.catalogId,t.docTitle),c=Number(a.lastInsertRowid);return e.set(t.documentId,c),c}async function pv(n,e,t,r){await Je();let o=dv(n,e),i=new Map,s=o.prepare(`
1347
+ `).run(t.documentId,t.catalogId,t.docTitle),c=Number(a.lastInsertRowid);return e.set(t.documentId,c),c}async function fv(n,e,t,r){await Je();let o=pv(n,e),i=new Map,s=o.prepare(`
1348
1348
  INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated)
1349
1349
  VALUES (?, ?, ?, ?, ?)
1350
- `),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 v=>({source:v,searchText:await uo(v)})));o.transaction(v=>{for(let I of v){let k=uv(o,i,I.source);s.run(k,I.source.sectionTitle,I.source.leadText,I.searchText,I.source.excerptTruncated?1:0)}})(u),await r?.(Math.min(c+l.length,a),a)}o.exec("ANALYZE"),o.exec("VACUUM"),o.close()}function mv(n,e,t,r,o,i,s){let a=lv(n,e);return mo({all(c,...l){return a.prepare(c).all(...l)}},t,r,o,i,s)}async function Hd(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:cv,buildSearchIndex:(t,r,o)=>pv(e,t,r,o),searchIndex:(t,r,o,i,s,a,c)=>Promise.resolve(mv(e,i,r,o,s,a,c))}}import{readFile as fv,stat as hv,writeFile as gv}from"fs/promises";var ls=null,Ke=null;async function ds(){return ls||(ls=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),ls}function yv(n){return{all(e,...t){let r=n.prepare(e);t.length>0&&r.bind(t);let o=[];for(;r.step();)o.push(r.get({}));return r.finalize(),o}}}async function vv(n){let e=await hv(n);if(Ke&&Ke.dbPath===n&&Ke.mtimeMs===e.mtimeMs)return Ke.db;Ke?.db.close();let t=await ds(),r=t.capi,o=t.wasm,i=new Uint8Array(await fv(n)),s=o.allocFromTypedArray(i),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,i.byteLength,i.byteLength,c),Ke={dbPath:n,mtimeMs:e.mtimeMs,db:a},a}function jd(){Ke?.db.close(),Ke=null}async function wv(n,e,t,r){n.exec("BEGIN");for(let o of r){let i=t(o.source);e.bind([i,o.source.sectionTitle,o.source.leadText,o.searchText,o.source.excerptTruncated?1:0]),e.step(),e.reset()}n.exec("COMMIT")}function bv(n,e,t){return r=>{let o=e.get(r.documentId);if(o!==void 0)return o;let i=n.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(i!=null){let a=Number(i);return e.set(r.documentId,a),a}t.bind([r.documentId,r.catalogId,r.docTitle]),t.step(),t.reset();let s=Number(n.selectValue("SELECT last_insert_rowid()"));return e.set(r.documentId,s),s}}async function Sv(n,e,t){await Je();let r=await ds(),o=new r.oo1.DB(":memory:","c");o.exec(fo);let i=new Map,s=o.prepare("INSERT INTO documents(document_id, catalog_id, doc_title) VALUES (?, ?, ?)"),a=o.prepare("INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated) VALUES (?, ?, ?, ?, ?)"),c=bv(o,i,s),l=e.length;for(let h=0;h<l;h+=_t){let v=e.slice(h,h+_t),I=await Promise.all(v.map(async k=>({source:k,searchText:await uo(k)})));await wv(o,a,c,I),await t?.(Math.min(h+v.length,l),l)}o.exec("ANALYZE");let u=r.capi.sqlite3_js_db_export(o);await gv(n,u),o.close(),jd()}async function Pv(n,e,t,r,o,i){let s=await vv(n);return mo(yv(s),e,t,r,o,i)}async function Fd(){return await ds(),{kind:"sqlite-wasm",resetCache:jd,buildSearchIndex:Sv,searchIndex:(n,e,t,r,o,i,s)=>Pv(r,e,t,o,i,s)}}var ho=null,us=null;async function Ev(){try{let e=await Hd();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 Fd();return g("doc-index: using @sqlite.org/sqlite-wasm SQLite backend"),n}async function Rn(){return ho||(ho=Ev().then(n=>(us=n,n))),ho}function $d(){us?.resetCache(),ho=null,us=null}async function Iv(n,e,t,r,o,i,s){let a=await Rn(),c=s??Pn();return a.searchIndex(n,e,t,c,r,o,i)}function Wd(){$d()}async function Ud(n,e,t){await(await Rn()).buildSearchIndex(n,e,t)}function zd(n,e,t){let r=new Set,o=[];for(let i of[...n,...e])if(!r.has(i.documentId)&&(r.add(i.documentId),o.push(i),o.length>=t))break;return o}function go(n,e,t,r,o,i){return Iv(n,e,t,o,r.expandedQuery,r.rawQuery,i)}async function Dv(n,e,t,r,o){let i=await go(n,e,t,r,An(r.tokens,"AND"),o);if(i.length>=t)return i;let s=await go(n,e,t,r,An(r.tokens,"OR"),o);return zd(i,s,t)}async function ps(n,e,t,r,o){return r.ftsMatch?go(n,e,t,r,r.ftsMatch,o):r.preferAnd?Dv(n,e,t,r,o):go(n,e,t,r,An(r.tokens,"OR"),o)}async function Cv(n,e,t,r){let o=await ps(n,"harmonyos-references",e,t,r);if(o.length>=e)return o;let i=await ps(n,void 0,e,t,r);return zd(o,i,e)}function Bd(n,e){return e!==void 0?n:xd(n)}async function qd(n,e,t=20,r){let o=await Cd(n);if(Sd(o.rawQuery,e)){let a=await Cv(n,t,o,r);return Bd(a,e)}let i=e??Md(o.rawQuery),s=await ps(n,i,t,o,r);return Bd(s,e)}import{unified as Qd}from"unified";import eu from"remark-parse";import tu from"remark-gfm";import{toString as vo}from"mdast-util-to-string";var Av=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,Tv=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,xv=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,kv=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,Mv=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function yo(n){let e=n.trim(),t=e.match(kv);return t?t[1]:e}function Rv(n){let e=n.match(Av);if(!e)return;let t=yo(e[1].trim());return{displayTitle:n,symbolName:t,searchExtras:[t,e[3]]}}function Ov(n){let e=yo(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?Rv(e)??(()=>{let t=e.match(Tv);if(t){let r=t[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let t=e.match(xv);if(!t)return;let r=t[1].trim(),o=t[2].trim();return{displayTitle:e,symbolName:o,searchExtras:[r,o]}})()??Ov(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function Nv(n){if(n.length<2||n.length>36||Mv.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 Vd(n){for(let e of n){let t=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(Nv(t))return t}return""}function Gd(n,e,t){let r=[n,...t.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var Lv=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,Nn=/@[A-Z][a-zA-Z]+/g,_v=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,Hv=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,jv=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,Fv=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),$v=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),Bv=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function nu(n,e){let t=new Set,r=[n,...e];for(let o of r){for(let i of Zi(o)){me(t,i);let s=io(i);s&&me(t,s)}for(let i of Xi(o))me(t,i);for(let i of o.matchAll(Lv)){let s=i[0];Wv(s)&&t.add(s)}for(let i of o.matchAll(Nn))t.add(i[0])}return Ft([...t])}function Wv(n){let e=n.trim();if(!e||Nn.test(e))return!!e;if(e.includes(".")){let t=e.split(".")[0]??"";return Bv.has(t)?!1:/^[A-Z]/.test(t)}return Fv.has(e)?!1:$v.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 Yd(n){let e=n.trim();return!!(!e||jv.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function ru(n,e){let t=e.jsonTitle?.trim(),r=Vv(n,"").trim(),o=e.fileName.trim();return t&&!Yd(t)?t:r&&!Yd(r)?r:t||r||o}function ou(n){return _v.test(n.trim())}function ms(n){let e=n.trim().replace(/\([^)]*\)$/,""),t=yo(e);return Hv.test(t)}function wo(n){let e=n.trim();return e?Nn.test(e)||ou(e)||ms(e)?!0:!!On(e).symbolName:!1}function Uv(n){let e=n.trim();return!(!e||ou(e)||ms(e))}function zv(n){let e=new Set,t=[];for(let r of n){let o=r.trim();!Uv(o)||e.has(o)||(e.add(o),t.push(o))}return t}function Jd(n){if(!n.includes("."))return 0;let e=n.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function qv(n,e){let t=Jd(n)-Jd(e);return t!==0?t:n.localeCompare(e)}function iu(n,e=[]){let t=[...new Set(e.map(i=>i.trim()).filter(Boolean))],r=new Set(t),o=[...new Set(n.map(i=>i.trim()).filter(Boolean))].filter(i=>!r.has(i));return o.sort(qv),[...t,...o].slice(0,Ol)}function bo(n){return n.replace(/\s+/g," ").trim()}function Kd(n){return n.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function Vv(n,e=""){let t=n.split(/\r?\n/),r=0;for(;r<t.length&&!t[r].trim();)r+=1;if(r>=t.length)return e;let o=Kd(t[r].trim()),i=o.match(/^#+\s+(.+)$/);if(i)return Kd(i[1].trim());if(r+1<t.length){let s=t[r+1].trim();if(/^=+$/.test(s)||/^-+$/.test(s))return o}return o||e}function su(n){let e=bo(n.join(" "));if(e.length<=Gr)return e;let t=e.slice(0,Gr);return e.length<=Gr+Ni?t:`${t} ${e.slice(-Ni)}`}function Gv(n){let e=zv(n).join(" ");return e.length<=Li?e:e.slice(0,Li)}function au(n){let e=bo(n),{text:t,excerptTruncated:r}=Od(e,Nl);return{leadText:t,excerptTruncated:r}}function Yv(n,e){let{leadText:t,excerptTruncated:r}=au(n);return{leadText:t,excerptTruncated:r||!!e.trim()}}function cu(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)cu(r,e);return}let t=bo(vo(n));t&&e.bodyParts.push(t)}function Jv(n){let e=Qd().use(eu).use(tu).parse(n),t=[],r=null,o=()=>{r&&((r.sectionTitle||r.bodyParts.length||r.codeBlocks.length)&&t.push(r),r=null)},i=()=>{r||(r={sectionTitle:"",bodyParts:[],codeBlocks:[]})};for(let s of e.children){if(s.type==="heading"){let a=s,c=vo(a).trim();if(a.depth>=4&&c&&wo(c)){o(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}i(),c&&r.bodyParts.push(c);continue}i(),cu(s,r)}return o(),t.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:t}function Kv(n){return wl.test(n)}function Zv(n){return n.filter(e=>e.sectionTitle&&wo(e.sectionTitle)).length}function Xv(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 Zd(n){let e=n.trim();return!e||Nn.test(e)?Nn.test(e):/对象说明$|枚举说明$/.test(e)?!0:ms(e)}function Qv(n){let e=n.filter(h=>!h.sectionTitle||!wo(h.sectionTitle)),t=n.filter(h=>h.sectionTitle&&wo(h.sectionTitle)),r=t.filter(h=>Zd(h.sectionTitle)),o=t.filter(h=>!Zd(h.sectionTitle)),i=Math.max(0,vl-r.length),s=o.slice(0,i),a=o.slice(i),c=a.filter(h=>Xd(h.sectionTitle)),l=a.filter(h=>!Xd(h.sectionTitle)),u=[];for(let h=0;h<l.length;h+=Ri)u.push(Xv(l.slice(h,h+Ri)));return[...e,...r,...s,...c,...u]}function ew(n,e,t){let r=n.split(/\r?\n/).length,o=Zv(e);return o===0?!1:Kv(t)?r>=gl&&o>=yl:r>=fl&&o>=hl}var tw=/^\[h2\][A-Za-z]/;function Xd(n){return tw.test(n.trim())}function lu(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 nw(n,e,t,r){let o=lu(n),i=nu(t,r);return e.symbolName&&i.push(e.symbolName),iu([...o,...i],o)}function rw(n,e){let t=su(n.bodyParts),r=n.sectionTitle.trim(),o=On(r),i=Vd(n.bodyParts),s=Gd(r,i,o),a=lu(r),c=r?a.length>0?`${e.docTitle} ${a.join(" ")}`:`${e.docTitle} ${o.symbolName??r}`:e.docTitle,l=[e.docTitle,s,...n.bodyParts].join(" "),{leadText:u,excerptTruncated:h}=Yv(t,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:nw(r,o,l,n.codeBlocks),bodySample:t,leadText:u,excerptTruncated:h}}function du(n,e){for(let t of n){if(t.type==="heading"){let o=vo(t).trim();o&&e.headings.push(o);continue}if(t.type==="code"){e.codeBlocks.push(t.value??"");continue}if("children"in t&&Array.isArray(t.children)){du(t.children,e);continue}let r=bo(vo(t));r&&e.bodyParts.push(r)}}function ow(n){let e=Qd().use(eu).use(tu).parse(n),t={headings:[],bodyParts:[],codeBlocks:[]};return du(e.children,t),t}function iw(n,e){let t=ow(n),r=e.docTitle?.trim()||e.documentId,o=su(t.bodyParts),i=[r,...t.headings,o].join(" "),{leadText:s,excerptTruncated:a}=au(o);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:Gv(t.headings),apiSymbols:iu(nu(i,t.codeBlocks)),bodySample:o,leadText:s,excerptTruncated:a}}function uu(n,e){let t=e.docTitle?.trim()||e.documentId,r=Jv(n);return ew(n,r,e.documentId)?Qv(r).filter(o=>o.sectionTitle||o.bodyParts.length>0||o.codeBlocks.length>0).map(o=>rw(o,{...e,docTitle:t})):[iw(n,{...e,docTitle:t})]}async function sw(n){let e=[];async function t(r){let o=await J.promises.readdir(r,{withFileTypes:!0});for(let i of o){if(i.name.startsWith("."))continue;let s=ne.join(r,i.name);i.isDirectory()?await t(s):i.isFile()&&i.name.endsWith(".md")&&e.push(s)}}return await t(n),e}function aw(n,e){let t=ne.relative(e,n).split(ne.sep).join("/").split("/");if(t[0]==="docs"&&(t=t.slice(1)),t.length<2)return null;let r=t[0],o=Hl[r];if(o===void 0)return null;let i=t[t.length-1].replace(/\.md$/,"");return t[t.length-1]=i,{documentId:t.join("/"),catalogId:o,docTitle:i}}async function cw(n){let e=n.replace(/\.md$/,".json");try{let t=await J.promises.readFile(e,"utf-8");return JSON.parse(t).title?.trim()||void 0}catch{return}}async function lw(n,e){let t=aw(n,e);if(!t)return[];let r=await J.promises.readFile(n,"utf-8"),o=ru(r,{jsonTitle:await cw(n),fileName:t.docTitle});return uu(r,{...t,docTitle:o})}async function dw(n,e,t){let r=ne.join(e,"search.db");return await Ud(r,n,async(o,i)=>{await t?.({current:o,total:i,message:`Building search index\u2026 ${o.toLocaleString()} / ${i.toLocaleString()} segments`})}),n.length}async function uw(n){let e=await sw(n),t=[];for(let r of e){let o=await lw(r,n);t.push(...o)}return t}function pw(n,e){return{indexVersion:Vr,docsZipSha256:n.docsZipSha256,termsHash:n.termsHash,synonymsHash:n.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:n.builtBy}}async function mu(n){n.lexiconDir&&Fi(n.lexiconDir);try{let e=await uw(n.docsDir);await n.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await J.promises.mkdir(n.tmpDir,{recursive:!0});let t=await dw(e,n.tmpDir,n.onProgress),r=pw(n,t);return await J.promises.writeFile(ne.join(n.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await Jl(n.tmpDir),r}finally{n.lexiconDir&&Fi(null)}}async function fu(){return J.promises.mkdtemp(ne.join(pu.tmpdir(),"deveco-docs-"))}async function mw(n,e){try{await J.promises.rename(n,e)}catch(t){let r=t.code;if(r!=="EPERM"&&r!=="EXDEV")throw t;await J.promises.cp(n,e,{recursive:!0}),await J.promises.rm(n,{recursive:!0,force:!0})}}async function hu(n){let e=ne.join(n,"docs");try{await J.promises.access(e)}catch{return}let t=new Set(["docs","docs.zip"]);for(let r of await J.promises.readdir(e,{withFileTypes:!0})){if(t.has(r.name))continue;let o=ne.join(e,r.name),i=ne.join(n,r.name);await J.promises.rm(i,{recursive:!0,force:!0}),await mw(o,i)}await J.promises.rm(ne.join(e,"docs"),{recursive:!0,force:!0}),await J.promises.rm(ne.join(e,"docs.zip"),{force:!0}),await J.promises.rm(e,{recursive:!0,force:!0})}var Ln=class extends Error{constructor(e){super(e),this.name="NativeDepsError"}};function fw(){let n=jt(),e=X();return["Documentation search index is not installed yet.","",...Jr(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(`
1351
- `)}function hw(){let n=jt();return[`Chinese tokenizer (${D()?"jieba-wasm":"@node-rs/jieba"}) failed to load.`,"",`Node.js: ${process.version} (required: >=18)`,"",...Jr(n),"","Try:"," 1. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 2. Use Node.js 18 or newer",D()?" 3. Verify jieba-wasm package is installed (WASM backend for OpenHarmony)":" 3. Configure npm registry/proxy if your network blocks optional platform packages"].join(`
1352
- `)}function gw(n){let e=jt();return[n,"",...Jr(e)].join(`
1353
- `)}async function gu(){try{Gl()}catch(n){throw Vl(n)?new Ln(`${fw()}
1350
+ `),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 v=>({source:v,searchText:await uo(v)})));o.transaction(v=>{for(let I of v){let k=mv(o,i,I.source);s.run(k,I.source.sectionTitle,I.source.leadText,I.searchText,I.source.excerptTruncated?1:0)}})(u),await r?.(Math.min(c+l.length,a),a)}o.exec("ANALYZE"),o.exec("VACUUM"),o.close()}function hv(n,e,t,r,o,i,s){let a=uv(n,e);return mo({all(c,...l){return a.prepare(c).all(...l)}},t,r,o,i,s)}async function Hd(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:dv,buildSearchIndex:(t,r,o)=>fv(e,t,r,o),searchIndex:(t,r,o,i,s,a,c)=>Promise.resolve(hv(e,i,r,o,s,a,c))}}import{readFile as gv,stat as yv,writeFile as vv}from"fs/promises";var ls=null,Ke=null;async function ds(){return ls||(ls=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),ls}function wv(n){return{all(e,...t){let r=n.prepare(e);t.length>0&&r.bind(t);let o=[];for(;r.step();)o.push(r.get({}));return r.finalize(),o}}}async function bv(n){let e=await yv(n);if(Ke&&Ke.dbPath===n&&Ke.mtimeMs===e.mtimeMs)return Ke.db;Ke?.db.close();let t=await ds(),r=t.capi,o=t.wasm,i=new Uint8Array(await gv(n)),s=o.allocFromTypedArray(i),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,i.byteLength,i.byteLength,c),Ke={dbPath:n,mtimeMs:e.mtimeMs,db:a},a}function jd(){Ke?.db.close(),Ke=null}async function Sv(n,e,t,r){n.exec("BEGIN");for(let o of r){let i=t(o.source);e.bind([i,o.source.sectionTitle,o.source.leadText,o.searchText,o.source.excerptTruncated?1:0]),e.step(),e.reset()}n.exec("COMMIT")}function Pv(n,e,t){return r=>{let o=e.get(r.documentId);if(o!==void 0)return o;let i=n.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(i!=null){let a=Number(i);return e.set(r.documentId,a),a}t.bind([r.documentId,r.catalogId,r.docTitle]),t.step(),t.reset();let s=Number(n.selectValue("SELECT last_insert_rowid()"));return e.set(r.documentId,s),s}}async function Ev(n,e,t){await Je();let r=await ds(),o=new r.oo1.DB(":memory:","c");o.exec(fo);let i=new Map,s=o.prepare("INSERT INTO documents(document_id, catalog_id, doc_title) VALUES (?, ?, ?)"),a=o.prepare("INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated) VALUES (?, ?, ?, ?, ?)"),c=Pv(o,i,s),l=e.length;for(let h=0;h<l;h+=_t){let v=e.slice(h,h+_t),I=await Promise.all(v.map(async k=>({source:k,searchText:await uo(k)})));await Sv(o,a,c,I),await t?.(Math.min(h+v.length,l),l)}o.exec("ANALYZE");let u=r.capi.sqlite3_js_db_export(o);await vv(n,u),o.close(),jd()}async function Iv(n,e,t,r,o,i){let s=await bv(n);return mo(wv(s),e,t,r,o,i)}async function Fd(){return await ds(),{kind:"sqlite-wasm",resetCache:jd,buildSearchIndex:Ev,searchIndex:(n,e,t,r,o,i,s)=>Iv(r,e,t,o,i,s)}}var ho=null,us=null;async function Dv(){try{let e=await Hd();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 Fd();return g("doc-index: using @sqlite.org/sqlite-wasm SQLite backend"),n}async function Rn(){return ho||(ho=Dv().then(n=>(us=n,n))),ho}function $d(){us?.resetCache(),ho=null,us=null}async function Cv(n,e,t,r,o,i,s){let a=await Rn(),c=s??Pn();return a.searchIndex(n,e,t,c,r,o,i)}function Wd(){$d()}async function Ud(n,e,t){await(await Rn()).buildSearchIndex(n,e,t)}function zd(n,e,t){let r=new Set,o=[];for(let i of[...n,...e])if(!r.has(i.documentId)&&(r.add(i.documentId),o.push(i),o.length>=t))break;return o}function go(n,e,t,r,o,i){return Cv(n,e,t,o,r.expandedQuery,r.rawQuery,i)}async function Av(n,e,t,r,o){let i=await go(n,e,t,r,An(r.tokens,"AND"),o);if(i.length>=t)return i;let s=await go(n,e,t,r,An(r.tokens,"OR"),o);return zd(i,s,t)}async function ps(n,e,t,r,o){return r.ftsMatch?go(n,e,t,r,r.ftsMatch,o):r.preferAnd?Av(n,e,t,r,o):go(n,e,t,r,An(r.tokens,"OR"),o)}async function Tv(n,e,t,r){let o=await ps(n,"harmonyos-references",e,t,r);if(o.length>=e)return o;let i=await ps(n,void 0,e,t,r);return zd(o,i,e)}function Bd(n,e){return e!==void 0?n:xd(n)}async function qd(n,e,t=20,r){let o=await Cd(n);if(Sd(o.rawQuery,e)){let a=await Tv(n,t,o,r);return Bd(a,e)}let i=e??Md(o.rawQuery),s=await ps(n,i,t,o,r);return Bd(s,e)}import{unified as Qd}from"unified";import eu from"remark-parse";import tu from"remark-gfm";import{toString as vo}from"mdast-util-to-string";var xv=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,kv=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,Mv=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,Rv=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,Ov=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function yo(n){let e=n.trim(),t=e.match(Rv);return t?t[1]:e}function Nv(n){let e=n.match(xv);if(!e)return;let t=yo(e[1].trim());return{displayTitle:n,symbolName:t,searchExtras:[t,e[3]]}}function Lv(n){let e=yo(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?Nv(e)??(()=>{let t=e.match(kv);if(t){let r=t[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let t=e.match(Mv);if(!t)return;let r=t[1].trim(),o=t[2].trim();return{displayTitle:e,symbolName:o,searchExtras:[r,o]}})()??Lv(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function _v(n){if(n.length<2||n.length>36||Ov.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 Vd(n){for(let e of n){let t=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(_v(t))return t}return""}function Gd(n,e,t){let r=[n,...t.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var Hv=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,Nn=/@[A-Z][a-zA-Z]+/g,jv=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,Fv=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,$v=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,Bv=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),Wv=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),Uv=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function nu(n,e){let t=new Set,r=[n,...e];for(let o of r){for(let i of Zi(o)){me(t,i);let s=io(i);s&&me(t,s)}for(let i of Xi(o))me(t,i);for(let i of o.matchAll(Hv)){let s=i[0];zv(s)&&t.add(s)}for(let i of o.matchAll(Nn))t.add(i[0])}return Ft([...t])}function zv(n){let e=n.trim();if(!e||Nn.test(e))return!!e;if(e.includes(".")){let t=e.split(".")[0]??"";return Uv.has(t)?!1:/^[A-Z]/.test(t)}return Bv.has(e)?!1:Wv.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 Yd(n){let e=n.trim();return!!(!e||$v.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function ru(n,e){let t=e.jsonTitle?.trim(),r=Yv(n,"").trim(),o=e.fileName.trim();return t&&!Yd(t)?t:r&&!Yd(r)?r:t||r||o}function ou(n){return jv.test(n.trim())}function ms(n){let e=n.trim().replace(/\([^)]*\)$/,""),t=yo(e);return Fv.test(t)}function wo(n){let e=n.trim();return e?Nn.test(e)||ou(e)||ms(e)?!0:!!On(e).symbolName:!1}function qv(n){let e=n.trim();return!(!e||ou(e)||ms(e))}function Vv(n){let e=new Set,t=[];for(let r of n){let o=r.trim();!qv(o)||e.has(o)||(e.add(o),t.push(o))}return t}function Jd(n){if(!n.includes("."))return 0;let e=n.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function Gv(n,e){let t=Jd(n)-Jd(e);return t!==0?t:n.localeCompare(e)}function iu(n,e=[]){let t=[...new Set(e.map(i=>i.trim()).filter(Boolean))],r=new Set(t),o=[...new Set(n.map(i=>i.trim()).filter(Boolean))].filter(i=>!r.has(i));return o.sort(Gv),[...t,...o].slice(0,Ol)}function bo(n){return n.replace(/\s+/g," ").trim()}function Kd(n){return n.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function Yv(n,e=""){let t=n.split(/\r?\n/),r=0;for(;r<t.length&&!t[r].trim();)r+=1;if(r>=t.length)return e;let o=Kd(t[r].trim()),i=o.match(/^#+\s+(.+)$/);if(i)return Kd(i[1].trim());if(r+1<t.length){let s=t[r+1].trim();if(/^=+$/.test(s)||/^-+$/.test(s))return o}return o||e}function su(n){let e=bo(n.join(" "));if(e.length<=Gr)return e;let t=e.slice(0,Gr);return e.length<=Gr+Ni?t:`${t} ${e.slice(-Ni)}`}function Jv(n){let e=Vv(n).join(" ");return e.length<=Li?e:e.slice(0,Li)}function au(n){let e=bo(n),{text:t,excerptTruncated:r}=Od(e,Nl);return{leadText:t,excerptTruncated:r}}function Kv(n,e){let{leadText:t,excerptTruncated:r}=au(n);return{leadText:t,excerptTruncated:r||!!e.trim()}}function cu(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)cu(r,e);return}let t=bo(vo(n));t&&e.bodyParts.push(t)}function Zv(n){let e=Qd().use(eu).use(tu).parse(n),t=[],r=null,o=()=>{r&&((r.sectionTitle||r.bodyParts.length||r.codeBlocks.length)&&t.push(r),r=null)},i=()=>{r||(r={sectionTitle:"",bodyParts:[],codeBlocks:[]})};for(let s of e.children){if(s.type==="heading"){let a=s,c=vo(a).trim();if(a.depth>=4&&c&&wo(c)){o(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}i(),c&&r.bodyParts.push(c);continue}i(),cu(s,r)}return o(),t.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:t}function Xv(n){return wl.test(n)}function Qv(n){return n.filter(e=>e.sectionTitle&&wo(e.sectionTitle)).length}function ew(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 Zd(n){let e=n.trim();return!e||Nn.test(e)?Nn.test(e):/对象说明$|枚举说明$/.test(e)?!0:ms(e)}function tw(n){let e=n.filter(h=>!h.sectionTitle||!wo(h.sectionTitle)),t=n.filter(h=>h.sectionTitle&&wo(h.sectionTitle)),r=t.filter(h=>Zd(h.sectionTitle)),o=t.filter(h=>!Zd(h.sectionTitle)),i=Math.max(0,vl-r.length),s=o.slice(0,i),a=o.slice(i),c=a.filter(h=>Xd(h.sectionTitle)),l=a.filter(h=>!Xd(h.sectionTitle)),u=[];for(let h=0;h<l.length;h+=Ri)u.push(ew(l.slice(h,h+Ri)));return[...e,...r,...s,...c,...u]}function nw(n,e,t){let r=n.split(/\r?\n/).length,o=Qv(e);return o===0?!1:Xv(t)?r>=gl&&o>=yl:r>=fl&&o>=hl}var rw=/^\[h2\][A-Za-z]/;function Xd(n){return rw.test(n.trim())}function lu(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 ow(n,e,t,r){let o=lu(n),i=nu(t,r);return e.symbolName&&i.push(e.symbolName),iu([...o,...i],o)}function iw(n,e){let t=su(n.bodyParts),r=n.sectionTitle.trim(),o=On(r),i=Vd(n.bodyParts),s=Gd(r,i,o),a=lu(r),c=r?a.length>0?`${e.docTitle} ${a.join(" ")}`:`${e.docTitle} ${o.symbolName??r}`:e.docTitle,l=[e.docTitle,s,...n.bodyParts].join(" "),{leadText:u,excerptTruncated:h}=Kv(t,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:ow(r,o,l,n.codeBlocks),bodySample:t,leadText:u,excerptTruncated:h}}function du(n,e){for(let t of n){if(t.type==="heading"){let o=vo(t).trim();o&&e.headings.push(o);continue}if(t.type==="code"){e.codeBlocks.push(t.value??"");continue}if("children"in t&&Array.isArray(t.children)){du(t.children,e);continue}let r=bo(vo(t));r&&e.bodyParts.push(r)}}function sw(n){let e=Qd().use(eu).use(tu).parse(n),t={headings:[],bodyParts:[],codeBlocks:[]};return du(e.children,t),t}function aw(n,e){let t=sw(n),r=e.docTitle?.trim()||e.documentId,o=su(t.bodyParts),i=[r,...t.headings,o].join(" "),{leadText:s,excerptTruncated:a}=au(o);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:Jv(t.headings),apiSymbols:iu(nu(i,t.codeBlocks)),bodySample:o,leadText:s,excerptTruncated:a}}function uu(n,e){let t=e.docTitle?.trim()||e.documentId,r=Zv(n);return nw(n,r,e.documentId)?tw(r).filter(o=>o.sectionTitle||o.bodyParts.length>0||o.codeBlocks.length>0).map(o=>iw(o,{...e,docTitle:t})):[aw(n,{...e,docTitle:t})]}async function cw(n){let e=[];async function t(r){let o=await J.promises.readdir(r,{withFileTypes:!0});for(let i of o){if(i.name.startsWith("."))continue;let s=ne.join(r,i.name);i.isDirectory()?await t(s):i.isFile()&&i.name.endsWith(".md")&&e.push(s)}}return await t(n),e}function lw(n,e){let t=ne.relative(e,n).split(ne.sep).join("/").split("/");if(t[0]==="docs"&&(t=t.slice(1)),t.length<2)return null;let r=t[0],o=Hl[r];if(o===void 0)return null;let i=t[t.length-1].replace(/\.md$/,"");return t[t.length-1]=i,{documentId:t.join("/"),catalogId:o,docTitle:i}}async function dw(n){let e=n.replace(/\.md$/,".json");try{let t=await J.promises.readFile(e,"utf-8");return JSON.parse(t).title?.trim()||void 0}catch{return}}async function uw(n,e){let t=lw(n,e);if(!t)return[];let r=await J.promises.readFile(n,"utf-8"),o=ru(r,{jsonTitle:await dw(n),fileName:t.docTitle});return uu(r,{...t,docTitle:o})}async function pw(n,e,t){let r=ne.join(e,"search.db");return await Ud(r,n,async(o,i)=>{await t?.({current:o,total:i,message:`Building search index\u2026 ${o.toLocaleString()} / ${i.toLocaleString()} segments`})}),n.length}async function mw(n){let e=await cw(n),t=[];for(let r of e){let o=await uw(r,n);t.push(...o)}return t}function fw(n,e){return{indexVersion:Vr,docsZipSha256:n.docsZipSha256,termsHash:n.termsHash,synonymsHash:n.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:n.builtBy}}async function mu(n){n.lexiconDir&&Fi(n.lexiconDir);try{let e=await mw(n.docsDir);await n.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await J.promises.mkdir(n.tmpDir,{recursive:!0});let t=await pw(e,n.tmpDir,n.onProgress),r=fw(n,t);return await J.promises.writeFile(ne.join(n.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await Jl(n.tmpDir),r}finally{n.lexiconDir&&Fi(null)}}async function fu(){return J.promises.mkdtemp(ne.join(pu.tmpdir(),"deveco-docs-"))}async function hw(n,e){try{await J.promises.rename(n,e)}catch(t){let r=t.code;if(r!=="EPERM"&&r!=="EXDEV")throw t;await J.promises.cp(n,e,{recursive:!0}),await J.promises.rm(n,{recursive:!0,force:!0})}}async function hu(n){let e=ne.join(n,"docs");try{await J.promises.access(e)}catch{return}let t=new Set(["docs","docs.zip"]);for(let r of await J.promises.readdir(e,{withFileTypes:!0})){if(t.has(r.name))continue;let o=ne.join(e,r.name),i=ne.join(n,r.name);await J.promises.rm(i,{recursive:!0,force:!0}),await hw(o,i)}await J.promises.rm(ne.join(e,"docs"),{recursive:!0,force:!0}),await J.promises.rm(ne.join(e,"docs.zip"),{force:!0}),await J.promises.rm(e,{recursive:!0,force:!0})}var Ln=class extends Error{constructor(e){super(e),this.name="NativeDepsError"}};function gw(){let n=jt(),e=X();return["Documentation search index is not installed yet.","",...Jr(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(`
1351
+ `)}function yw(){let n=jt();return[`Chinese tokenizer (${D()?"jieba-wasm":"@node-rs/jieba"}) failed to load.`,"",`Node.js: ${process.version} (required: >=18)`,"",...Jr(n),"","Try:"," 1. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 2. Use Node.js 18 or newer",D()?" 3. Verify jieba-wasm package is installed (WASM backend for OpenHarmony)":" 3. Configure npm registry/proxy if your network blocks optional platform packages"].join(`
1352
+ `)}function vw(n){let e=jt();return[n,"",...Jr(e)].join(`
1353
+ `)}async function gu(){try{Gl()}catch(n){throw Vl(n)?new Ln(`${gw()}
1354
1354
 
1355
- Detail: ${n.message}`):n}try{await Je()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Ln(`${hw()}
1355
+ Detail: ${n.message}`):n}try{await Je()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Ln(`${yw()}
1356
1356
 
1357
- Detail: ${e}`)}try{await Rn()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Ln(gw(e))}}var fs=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function ww(n){return new Promise(e=>setTimeout(e,n))}async function bw(n){let e=jt();await z.promises.mkdir(Bt.dirname(e),{recursive:!0}),await z.promises.appendFile(e,`${new Date().toISOString()} ${n}
1358
- `)}async function Sw(n){let e=Ve();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 yw(e).extractAllTo(n,!0),await hu(n)}async function Pw(){let n=X(),e=Ht(),t=await z.promises.readdir(e);for(let r of t){let o=Bt.join(n,r);await z.promises.rm(o,{force:!0}),await z.promises.rename(Bt.join(e,r),o)}await z.promises.rm(e,{recursive:!0,force:!0}),await z.promises.rm(Bt.join(n,"orama.dpack"),{force:!0})}async function Ew(n,e){e?.start("Installing documentation index\u2026"),await Ye({state:"installing",phase:1,phaseLabel:"Installing index",message:"Installing documentation index\u2026"}),await td(n),e&&(e.text="Documentation index installed.")}async function Iw(n,e,t){let r=Ht(),o=await fu();await z.promises.mkdir(X(),{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 Sw(o),await mu({docsDir:o,tmpDir:r,docsZipSha256:e,termsHash:ro(),synonymsHash:no(),builtBy:n.builtBy??"doc-init",onProgress:async i=>{t&&(t.text=i.message),await Ye({state:"indexing",current:i.current,total:i.total,message:i.message})}})}finally{await z.promises.rm(o,{recursive:!0,force:!0})}await Ye({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await Pw(),Wd()}async function yu(n){await Ye({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function Dw(n){let e=await Gi(),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 Cw(n,e){let t=n instanceof Error?n.message:String(n);throw await Ye({state:"error",error:t}),await bw(`ERROR: ${t}`),e?.fail(t),n}async function Aw(){let n=X();await z.promises.mkdir(n,{recursive:!0});let e=Wl();return z.existsSync(e)||await z.promises.writeFile(e,"","utf-8"),e}async function Tw(){let n=await Aw();return vw.lock(n,{stale:1800*1e3})}async function xw(){let n=Ve(),e=(n?await to(n):null)??await Vi();if(!e)throw new Error("docs.zip not found");return e}async function kw(n,e){let t=await xw(),r=n.force||await Ji(n.force),o=await Yi(n.force);if(!r&&!o&&Dn()){await Dw(e);return}if(Wi()&&!n.force){await Ew(t,e),await yu(e);return}await Iw(n,t,e),await yu(e)}var hs=class{static async run(e={}){let t=e.background??!1,o=e.quiet??t?void 0:wu({text:"Checking documentation\u2026",color:"cyan"}),i;try{i=await Tw(),await qi(sd("Starting documentation setup\u2026")),await kw(e,o)}catch(s){return Cw(s,o)}finally{i&&await i()}}};async function Mw(n){for(;;){let e=await oo();if(e.state==="done"&&Dn())return;if(e.state==="error")throw new fs("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 ww(500)}}async function vu(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await hs.run({builtBy:"doc-init",force:e,quiet:!0})}async function Rw(){if(Dn())return;let n=wu({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await ad()){await Mw(n),n.succeed("Documentation ready.");return}if(await Ji()){await vu(n),n.succeed("Documentation ready.");return}await vu(n,!0),n.succeed("Documentation ready.")}catch(e){throw n.fail(e.message),e}}async function _n(){await Rw(),await gu()}var gs=class{async search(e,t,r=20){return await _n(),qd(e,t,r)}async readDocument(e){return await _n(),Xl(e)}},ys=new gs;function bu(...n){return e=>{if(!n.includes(e))throw new vs(`Allowed values: ${n.join(", ")}`);return e}}function Lw(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new vs("Must be a positive integer.");return e}var _w=bu("json","default"),Hw=bu("json","default"),Po=new Ow("docs").description("Search and read HarmonyOS documentation from local docs directory");Po.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",Fw,"all").option("--format <fmt>","Output format (default, json)",_w,"default").option("--limit <n>","Max number of results",Lw,20).action(async(n,e)=>{try{let t=jw(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await ys.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):$w(o)}catch(t){console.error(So(t.message)),process.exit(1)}});Po.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error(So("Document ID cannot be empty.")),process.exit(1));let t=await ys.readDocument(e);console.log(t)}catch(e){console.error(So(e.message)),process.exit(1)}});Po.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",Hw,"default").action(async n=>{try{if(await _n(),n.format==="json"){let e=ze.map(t=>({name:t,title:at[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of ze)console.log(` ${e.padEnd(20)} ${Nw(at[e])}`)}catch(e){console.error(So(e.message)),process.exit(1)}});function jw(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 Fw(n){if(n==="all")return"all";if(!ze.includes(n))throw new vs(`Invalid catalog "${n}". Allowed: all, ${ze.join(", ")}`);return n}function $w(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 Su=Po;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";Bw();Q.name("devecocli").description("HarmonyOS application development command line tool").version("0.1.0-TD.4.2");Q.addCommand(_s);Q.addCommand(Js);Q.addCommand(Qs);Q.addCommand(ua);D()||Q.addCommand(Ra);Q.addCommand(rc);Q.addCommand(cc);Q.addCommand(yc);Q.addCommand(Dc);Q.addCommand(ml);Q.addCommand(Su);var ws=process.argv.slice(2);ws.length>=2&&ws[ws.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var Uw=new Set(["update"]);Q.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==Q;)t=t.parent;Uw.has(t.name())||await _.checkVersion()});Q.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(Ww(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
1357
+ Detail: ${e}`)}try{await Rn()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Ln(vw(e))}}var fs=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function Sw(n){return new Promise(e=>setTimeout(e,n))}async function Pw(n){let e=jt();await z.promises.mkdir(Bt.dirname(e),{recursive:!0}),await z.promises.appendFile(e,`${new Date().toISOString()} ${n}
1358
+ `)}async function Ew(n){let e=Ve();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 ww(e).extractAllTo(n,!0),await hu(n)}async function Iw(){let n=X(),e=Ht(),t=await z.promises.readdir(e);for(let r of t){let o=Bt.join(n,r);await z.promises.rm(o,{force:!0}),await z.promises.rename(Bt.join(e,r),o)}await z.promises.rm(e,{recursive:!0,force:!0}),await z.promises.rm(Bt.join(n,"orama.dpack"),{force:!0})}async function Dw(n,e){e?.start("Installing documentation index\u2026"),await Ye({state:"installing",phase:1,phaseLabel:"Installing index",message:"Installing documentation index\u2026"}),await td(n),e&&(e.text="Documentation index installed.")}async function Cw(n,e,t){let r=Ht(),o=await fu();await z.promises.mkdir(X(),{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 Ew(o),await mu({docsDir:o,tmpDir:r,docsZipSha256:e,termsHash:ro(),synonymsHash:no(),builtBy:n.builtBy??"doc-init",onProgress:async i=>{t&&(t.text=i.message),await Ye({state:"indexing",current:i.current,total:i.total,message:i.message})}})}finally{await z.promises.rm(o,{recursive:!0,force:!0})}await Ye({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await Iw(),Wd()}async function yu(n){await Ye({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function Aw(n){let e=await Gi(),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 Tw(n,e){let t=n instanceof Error?n.message:String(n);throw await Ye({state:"error",error:t}),await Pw(`ERROR: ${t}`),e?.fail(t),n}async function xw(){let n=X();await z.promises.mkdir(n,{recursive:!0});let e=Wl();return z.existsSync(e)||await z.promises.writeFile(e,"","utf-8"),e}async function kw(){let n=await xw();return bw.lock(n,{stale:1800*1e3})}async function Mw(){let n=Ve(),e=(n?await to(n):null)??await Vi();if(!e)throw new Error("docs.zip not found");return e}async function Rw(n,e){let t=await Mw(),r=n.force||await Ji(n.force),o=await Yi(n.force);if(!r&&!o&&Dn()){await Aw(e);return}if(Wi()&&!n.force){await Dw(t,e),await yu(e);return}await Cw(n,t,e),await yu(e)}var hs=class{static async run(e={}){let t=e.background??!1,o=e.quiet??t?void 0:wu({text:"Checking documentation\u2026",color:"cyan"}),i;try{i=await kw(),await qi(sd("Starting documentation setup\u2026")),await Rw(e,o)}catch(s){return Tw(s,o)}finally{i&&await i()}}};async function Ow(n){for(;;){let e=await oo();if(e.state==="done"&&Dn())return;if(e.state==="error")throw new fs("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 Sw(500)}}async function vu(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await hs.run({builtBy:"doc-init",force:e,quiet:!0})}async function Nw(){if(Dn())return;let n=wu({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await ad()){await Ow(n),n.succeed("Documentation ready.");return}if(await Ji()){await vu(n),n.succeed("Documentation ready.");return}await vu(n,!0),n.succeed("Documentation ready.")}catch(e){throw n.fail(e.message),e}}async function _n(){await Nw(),await gu()}var gs=class{async search(e,t,r=20){return await _n(),qd(e,t,r)}async readDocument(e){return await _n(),Xl(e)}},ys=new gs;function bu(...n){return e=>{if(!n.includes(e))throw new vs(`Allowed values: ${n.join(", ")}`);return e}}function Hw(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new vs("Must be a positive integer.");return e}var jw=bu("json","default"),Fw=bu("json","default"),Po=new Lw("docs").description("Search and read HarmonyOS documentation from local docs directory");Po.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",Bw,"all").option("--format <fmt>","Output format (default, json)",jw,"default").option("--limit <n>","Max number of results",Hw,20).action(async(n,e)=>{try{let t=$w(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await ys.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):Ww(o)}catch(t){console.error(So(t.message)),process.exit(1)}});Po.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error(So("Document ID cannot be empty.")),process.exit(1));let t=await ys.readDocument(e);console.log(t)}catch(e){console.error(So(e.message)),process.exit(1)}});Po.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",Fw,"default").action(async n=>{try{if(await _n(),n.format==="json"){let e=ze.map(t=>({name:t,title:at[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of ze)console.log(` ${e.padEnd(20)} ${_w(at[e])}`)}catch(e){console.error(So(e.message)),process.exit(1)}});function $w(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 Bw(n){if(n==="all")return"all";if(!ze.includes(n))throw new vs(`Invalid catalog "${n}". Allowed: all, ${ze.join(", ")}`);return n}function Ww(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 Su=Po;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";Uw();Q.name("devecocli").description("HarmonyOS application development command line tool").version("0.1.0-TD.5");Q.addCommand(_s);Q.addCommand(Js);Q.addCommand(Qs);Q.addCommand(ua);D()||Q.addCommand(Ra);Q.addCommand(rc);Q.addCommand(cc);Q.addCommand(yc);Q.addCommand(Dc);Q.addCommand(ml);Q.addCommand(Su);var ws=process.argv.slice(2);ws.length>=2&&ws[ws.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var qw=new Set(["update"]);Q.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==Q;)t=t.parent;qw.has(t.name())||await _.checkVersion()});Q.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(zw(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});