@deveco-test/hmos-deveco-cli 0.1.0-TD.3.3 → 0.1.0-TD.4
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 +47 -46
- package/index.zip +0 -0
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{bootstrap as
|
|
2
|
+
import{bootstrap as rw}from"global-agent";import{program as X}from"commander";import{red as ow}from"colorette";import{Command as Cu}from"commander";import{green as Is,red as So,yellow as Cs}from"colorette";import z from"fs";import*as J from"path";import Je from"json5";import*as ho from"fs";import*as F from"path";function g(n){process.env.DEVECO_CLI_DEBUG&&console.log(`[DEBUG] ${n}`)}var S=class n{static ASCII_CONTROL_MAX=31;static ASCII_DELETE=127;static parsePositiveInteger(e,t="value"){let r=e.trim();if(!/^\d+$/.test(r))throw new Error(`${t} must be a positive integer`);let o=Number.parseInt(r,10);if(!Number.isInteger(o)||o<=0)throw new Error(`${t} must be a positive integer`);return o}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
|
|
3
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),E=new Date(o,i,s,a,c,l,h);return E.getTime()>t.getTime()+1440*60*1e3&&E.setFullYear(o-1),E}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(r=>{let 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(F.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=F.resolve(F.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=F.normalize(e),o=F.relative(r,t);if(o.split(F.sep)[0]===".."||F.isAbsolute(o))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||F.isAbsolute(e)}static isPathContained(e,t){let r=F.resolve(t,e),o=F.relative(t,r);return n.isPathEscaping(o)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){if(F.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=ho.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let i=F.resolve(o,e),s;try{s=ho.realpathSync(i)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${i}`}}return n.isPathContained(s,o)}};var Ke=class n{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let r=n.tryLoadProjectProfile(t);if(r)return new n(t,r);let o=J.dirname(t);if(o===t)break;t=o}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=J.join(e,"build-profile.json5");if(!z.existsSync(t))return null;try{let r=z.readFileSync(t,"utf-8"),o=Je.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=S.resolvePathWithinRoot(this.rootDir,t.srcPath),o=J.join(r,"src","main","module.json5");if(!z.existsSync(o))return"entry";try{let i=z.readFileSync(o,"utf-8");return Je.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=S.resolvePathWithinRoot(this.rootDir,t.srcPath),o=J.join(r,"build-profile.json5");if(!z.existsSync(o))throw new Error(`Build profile for module '${e}' not found at ${o}.`);let i=z.readFileSync(o,"utf-8");return Je.parse(i)}getBundleName(){let e=J.join(this.rootDir,"AppScope","app.json5");if(z.existsSync(e))try{let t=z.readFileSync(e,"utf-8"),r=Je.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=S.resolvePathWithinRoot(this.rootDir,r.srcPath),i=J.join(o,"src","main","module.json5");if(!z.existsSync(i))return"EntryAbility";try{let s=z.readFileSync(i,"utf-8"),c=Je.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=S.resolvePathWithinRoot(this.rootDir,t.srcPath),o=J.join(r,"oh-package.json5");if(!z.existsSync(o))return[];let i=[];try{let s=z.readFileSync(o,"utf-8"),c=Je.parse(s)?.dependencies||{};for(let l of Object.values(c)){if(typeof l!="string")continue;let u=l;if(!(u.startsWith("file:")||u.startsWith(".")||u.startsWith("..")))continue;u.startsWith("file:")&&(u=u.substring(5));let E=J.join(t.srcPath,u),C=S.resolvePathWithinRoot(this.rootDir,E),M=this.profile.modules.find(Q=>J.resolve(this.rootDir,Q.srcPath)===C);M&&i.push(M.name)}}catch{}return i}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(Q=>Q.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(!z.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),E=u;if(!h){let Q=this.getSignedHapName(u,i.srcPath,o,t);Q&&(E=Q)}let C=a?"-signed.hsp":"-signed.hap";if(!r&&!E.endsWith(C))throw new Error(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`);let M=this.buildOutputPath(i.srcPath,o,["outputs",t,E]);if(!z.existsSync(M))throw new Error(`Generated package file not found in ${M}.`);return M}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 z.existsSync(s)?i:null}buildOutputPath(e,t,r){let o=S.resolvePathWithinRoot(this.rootDir,e),i=J.resolve(o,"build",t,...r);return S.ensurePathWithinRoot(this.rootDir,i)}parseOutputMetadata(e,t){let r=z.readFileSync(e,"utf-8"),o=Je.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=J.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 go}from"child_process";import k,{existsSync as ps}from"fs";import*as P from"path";import*as $ from"os";import du from"regedit";import{join as ms}from"path";import{red as uu}from"colorette";import*as us from"os";function I(){return lu()==="openharmony"}function lu(){return us.platform()}var fs="https://developer.huawei.com/consumer/cn/download/",hs="6.1.0",pu=["sdk","default","openharmony","native","llvm","bin","clangd"],Rn=n=>new Promise((e,t)=>{du.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===""||I()||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(I())return;let e=await n.findDevEcoStudio();n.enforceStudioMinVersion(e)}static async new(e){if(I())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),E=n.getEmulatorExe(t);return new n(t,r,o,i,s,a,c,l,E??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=P.join(e,"node","bin","node"),r=P.join(e,"ohpm","bin","pm-cli.js"),o=P.join(e,"hvigor","bin","hvigorw.js");n.verifyTools(t,r,o);let i=P.join(e,"sdk"),s=P.join(e,"clangd","clangd"),a=P.join(e,"ace-server","out","index.js");if(!k.existsSync(s))throw new Error(`clangd not found at: ${s}`);if(!k.existsSync(a))throw new Error(`ace-server not found at: ${a}`);let c=n.resolveHdcPath(i,$.platform());return new n("",t,r,o,"",i,c,"",void 0,s,a)}static resolveLspServerPath(e){let t=$.platform();if(t==="linux")throw new Error("LSP server (ace-server) is not supported on Linux.");let r;if(t==="win32")r=P.join(e,"plugins","openharmony");else if(t==="darwin")r=P.join(e,"Contents","plugins","openharmony");else throw new Error(`LSP server (ace-server) is not supported on platform: ${t}`);let o=P.join(r,"ace-server","out","index.js");if(k.existsSync(o))return o;throw new Error(`LSP server (ace-server) not found at: ${o}`)}static devecoContentRootForClangd(e){return $.platform()==="darwin"&&e.endsWith(".app")?P.join(e,"Contents"):e}static clangdCandidatesFromDevecoHome(e){let t=new Set,r=[e,n.devecoContentRootForClangd(e)];for(let o of r){let i=P.join(o,...pu);t.add($.platform()==="win32"?i+".exe":i)}return[...t]}static resolveClangdPath(e){let t=n.clangdCandidatesFromDevecoHome(e);for(let r of t)if(k.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
|
`+fs)}return t.reduce((r,o)=>n.compareVersion(o.version,r.version)>0?o:r)}static assertMinVersion(e,t){n.compareVersion(t,hs)>=0||(g(`[ToolProvider] Selected DevEco Studio ${t} at ${e} \u2014 below minimum`),console.error(uu(`Error: The detected DevEco Studio version is ${t}, which is below the minimum required version ${hs}. Upgrade to the latest version before using deveco-cli:`)+`
|
|
12
12
|
`+fs),process.exit(1))}static isExistingDirectory(e){return!!e&&k.existsSync(e)&&k.statSync(e).isDirectory()}static resolveWindowsTools(e){let t=P.join(e,"tools");return{nodePath:P.join(t,"node","node.exe"),ohpmJsPath:P.join(t,"ohpm","bin","pm-cli.js"),hvigorJsPath:P.join(t,"hvigor","bin","hvigorw.js"),javaPath:P.join(e,"jbr","bin","java.exe"),sdkPath:P.join(e,"sdk")}}static resolveMacTools(e){let t=P.join(e,"Contents","tools");return{nodePath:P.join(t,"node","bin","node"),ohpmJsPath:P.join(t,"ohpm","bin","pm-cli.js"),hvigorJsPath:P.join(t,"hvigor","bin","hvigorw.js"),javaPath:P.join(e,"Contents","jbr","Contents","Home","bin","java"),sdkPath:P.join(e,"Contents","sdk")}}static resolveTools(e){let t=$.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=[P.join(e,"default","openharmony","toolchains",`hdc${r}`),P.join(e,"toolchains",`hdc${r}`)];for(let i of o)if(k.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=P.join(e,"tools","emulator","Emulator.exe");else if(t==="darwin")r=P.join(e,"Contents","tools","emulator","Emulator");else throw new Error("Linux is not fully supported yet");if(!k.existsSync(r))throw new Error(`Emulator executable not found at: ${r}`);return r}static verifyTools(e,t,r,o){if(!k.existsSync(e))throw new Error(`Node executable not found at: ${e}`);if(!k.existsSync(t))throw new Error(`ohpm js file not found at: ${t}`);if(!k.existsSync(r))throw new Error(`hvigor js file not found at: ${r}`);if(o&&!k.existsSync(o))throw new Error(`java executable not found at: ${o}`)}static getEmulatorExe(e){let t=$.platform(),r;if(t==="win32")r=ms(e,"tools","emulator","Emulator.exe");else if(t==="darwin")r=ms(e,"Contents","tools","emulator","Emulator");else return;return ps(r)?r:void 0}static isValidApiLevel(e,t){let r=t??23;return Number.isInteger(e)&&e>=17&&e<=r}static parseApiLevelFromFile(e){if(k.existsSync(e))try{let t=k.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=P.join(e,"default","sdk-pkg.json");return n.parseApiLevelFromFile(t)}static detectFromOhUniPackage(e){let t=[P.join(e,"default","openharmony","toolchains","oh-uni-package.json"),P.join(e,"default","openharmony","native","oh-uni-package.json"),P.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($.platform()!=="win32")return n._powerShellPath="",n._powerShellPath;let e=P.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return ps(e)?(g(`[ToolProvider] Found PowerShell at: ${e}`),n._powerShellPath=e,e):(n._powerShellPath="",n._powerShellPath)}static verifySignature(e){if(!k.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=$.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 P.extname(e).toLowerCase()===".exe";if(t==="darwin")try{return k.accessSync(e,k.constants.X_OK),!0}catch{return!1}return!1}static createSignatureScript(){let e=k.mkdtempSync(P.join($.tmpdir(),"deveco-verify-")),t=P.join(e,"Verify-Signature.ps1");return k.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=go(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{k.rmSync(r,{recursive:!0,force:!0})}catch{}}}static verifyMacSignature(e){try{return go("codesign",["-v",e],{encoding:"utf-8",timeout:5e3}),{signed:!0}}catch{return{signed:!1}}}};import{execa as mu}from"execa";import*as dt from"path";import*as gs from"os";var Ze=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=dt.dirname(e.javaPath);r.PATH=`${o}${dt.delimiter}${process.env.PATH||""}`}I()&&(r.HVIGOR_USER_HOME=dt.join(gs.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(){I()||await this.runHvigor(["--stop-daemon"])}async runHvigor(e){I()&&(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 mu(t,r,{cwd:this.projectRoot,env:this.env,stdout:"inherit",stderr:"inherit"})}};import{execa as fu}from"execa";var ut=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 fu(e,t,{cwd:this.projectRoot,stdout:"inherit",stderr:"inherit"})}};import{mkdir as hu}from"fs/promises";import{dirname as gu,resolve as yu}from"path";import{execa as vu}from"execa";import{lock as yo,check as Fw}from"proper-lockfile";function vo(n){return yu(n,".hvigor",".build-lock")}function wu(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function ys(n){let e=gu(vo(n));if(await hu(e,{recursive:!0}),process.platform==="win32")try{await vu("attrib",["+h",e])}catch{}}async function bu(n,e){let t=new AbortController,r=wu(e);await ys(n);let o={lockfilePath:vo(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await yo(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 yo(n,{...o,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function $t(n,e,t){let{release:r,signal:o}=await bu(n,t);try{return await e(o)}finally{await r()}}async function vs(n,e){let t=new AbortController;await ys(n);let r={lockfilePath:vo(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},o;try{o=await yo(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 Ne from"fs";import*as Xe from"path";import Pu from"json5";var wo={HTTP_TIMEOUT_MS:2e4},Mn={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 Re}from"os";import Se from"path";import{xdgConfig as Su}from"xdg-basedir";var B={"trae-cn":Se.join(Re(),".trae-cn"),opencode:Se.join(Su,"opencode"),cursor:Se.join(Re(),".cursor"),codebuddy:Se.join(Re(),".codebuddy"),qoder:Se.join(Re(),".qoder"),"claude-code":Se.join(Re(),".claude"),codex:Se.join(Re(),".codex"),bitfun:Se.join(Re(),".bitfun"),opendesk:Se.join(Re(),".opendesk")};import Me from"path";var bo="https://matrix.openharmony.cn",le={TAGS_API_URL:`${bo}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${bo}/api/registry/skill/skills`,SKILL_API_BASE:`${bo}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},ws={"trae-cn":{path:Me.join(B["trae-cn"],"skills"),displayName:"trae-cn"},opencode:{path:Me.join(B.opencode,"skills"),displayName:"opencode"},cursor:{path:Me.join(B.cursor,"skills"),displayName:"cursor"},codebuddy:{path:Me.join(B.codebuddy,"skills"),displayName:"codebuddy"},qoder:{path:Me.join(B.qoder,"skills"),displayName:"qoder"},"claude-code":{path:Me.join(B["claude-code"],"skills"),projectPath:".claude/skills",displayName:"claude-code"},codex:{path:Me.join(B.codex,"skills"),displayName:"codex"}},bs={opencode:{path:Me.join(B.opencode,"skills"),displayName:"opencode"}};function Pe(){return I()?bs:ws}import{homedir as Bt}from"os";import re from"path";var he="deveco-mcp";var Oe={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:re.join(B.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(Bt(),"AppData","Roaming"),"Trae CN","User"):re.join(Bt(),"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(B.cursor,"mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:re.join(B.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(Bt(),"AppData","Roaming"),"Qoder","SharedClientCache"):re.join(Bt(),"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(Bt(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:re.join(B.codex,"config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function Ps(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function Ss(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Es(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function On(n,e){return n.format==="opencode"?Ps(e):n.format==="claude-code"||n.format==="codex"?Ss(e):Es(e)}var de={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var Eu=1e3;function Ln(n){g(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=Xe.join(n,de.SYNC_OUTPUT_PATH);if(!Ne.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return g(`[ProjectCheck] ${l.reason}`),l}let t=Ne.statSync(e).mtimeMs;g(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Iu(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return g(`[ProjectCheck] ${l.reason}`),l}let o=Xe.join(n,de.OH_PACKAGE_JSON5),i=Nn(o,t,"root");if(i.required)return g(`[ProjectCheck] Root check: ${i.reason}`),i;let s=Xe.join(n,de.BUILD_PROFILE_JSON5),a=Nn(s,t,"build-profile");if(a.required)return g(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let u=Xe.join(n,l.srcPath,de.OH_PACKAGE_JSON5),h=Nn(u,t,l.name);if(h.required)return g(`[ProjectCheck] Module '${l.name}' check: ${h.reason}`),h;let E=Xe.join(n,l.srcPath,de.BUILD_PROFILE_JSON5),C=Nn(E,t,l.name);if(C.required)return g(`[ProjectCheck] Module '${l.name}' build-profile check: ${C.reason}`),C}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return g(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function Nn(n,e,t){if(!Ne.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=Ne.statSync(n).mtimeMs;return r-e>Eu?{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 Iu(n){let e=Xe.join(n,de.BUILD_PROFILE_JSON5);try{let t=Ne.readFileSync(e,"utf-8");if(!t.trim())return null;let r=Pu.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 Du(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 Au(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 Po(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 Wt(n,e){let t=e,r=`${n} failed`;console.error(So(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 Eo(n,e,t,r,o,i){if(Ln(i).required){console.log(`
|
|
14
|
+
`)}`)}static resolveEmulatorPath(e,t){let r;if(t==="win32")r=P.join(e,"tools","emulator","Emulator.exe");else if(t==="darwin")r=P.join(e,"Contents","tools","emulator","Emulator");else throw new Error("Linux is not fully supported yet");if(!k.existsSync(r))throw new Error(`Emulator executable not found at: ${r}`);return r}static verifyTools(e,t,r,o){if(!k.existsSync(e))throw new Error(`Node executable not found at: ${e}`);if(!k.existsSync(t))throw new Error(`ohpm js file not found at: ${t}`);if(!k.existsSync(r))throw new Error(`hvigor js file not found at: ${r}`);if(o&&!k.existsSync(o))throw new Error(`java executable not found at: ${o}`)}static getEmulatorExe(e){let t=$.platform(),r;if(t==="win32")r=ms(e,"tools","emulator","Emulator.exe");else if(t==="darwin")r=ms(e,"Contents","tools","emulator","Emulator");else return;return ps(r)?r:void 0}static isValidApiLevel(e,t){let r=t??23;return Number.isInteger(e)&&e>=17&&e<=r}static parseApiLevelFromFile(e){if(k.existsSync(e))try{let t=k.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=P.join(e,"default","sdk-pkg.json");return n.parseApiLevelFromFile(t)}static detectFromOhUniPackage(e){let t=[P.join(e,"default","openharmony","toolchains","oh-uni-package.json"),P.join(e,"default","openharmony","native","oh-uni-package.json"),P.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($.platform()!=="win32")return n._powerShellPath="",n._powerShellPath;let e=P.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return ps(e)?(g(`[ToolProvider] Found PowerShell at: ${e}`),n._powerShellPath=e,e):(n._powerShellPath="",n._powerShellPath)}static verifySignature(e){if(!k.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=$.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 P.extname(e).toLowerCase()===".exe";if(t==="darwin")try{return k.accessSync(e,k.constants.X_OK),!0}catch{return!1}return!1}static createSignatureScript(){let e=k.mkdtempSync(P.join($.tmpdir(),"deveco-verify-")),t=P.join(e,"Verify-Signature.ps1");return k.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=go(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{k.rmSync(r,{recursive:!0,force:!0})}catch{}}}static verifyMacSignature(e){try{return go("codesign",["-v",e],{encoding:"utf-8",timeout:5e3}),{signed:!0}}catch{return{signed:!1}}}};import{execa as mu}from"execa";import*as dt from"path";import*as gs from"os";var Ze=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=dt.dirname(e.javaPath);r.PATH=`${o}${dt.delimiter}${process.env.PATH||""}`}I()&&(r.HVIGOR_USER_HOME=dt.join(gs.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(){I()||await this.runHvigor(["--stop-daemon"])}async runHvigor(e){I()&&(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 mu(t,r,{cwd:this.projectRoot,env:this.env,stdout:"inherit",stderr:"inherit"})}};import{execa as fu}from"execa";var ut=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 fu(e,t,{cwd:this.projectRoot,stdout:"inherit",stderr:"inherit"})}};import{mkdir as hu}from"fs/promises";import{dirname as gu,resolve as yu}from"path";import{execa as vu}from"execa";import{lock as yo,check as $w}from"proper-lockfile";function vo(n){return yu(n,".hvigor",".build-lock")}function wu(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function ys(n){let e=gu(vo(n));if(await hu(e,{recursive:!0}),process.platform==="win32")try{await vu("attrib",["+h",e])}catch{}}async function bu(n,e){let t=new AbortController,r=wu(e);await ys(n);let o={lockfilePath:vo(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await yo(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 yo(n,{...o,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function $t(n,e,t){let{release:r,signal:o}=await bu(n,t);try{return await e(o)}finally{await r()}}async function vs(n,e){let t=new AbortController;await ys(n);let r={lockfilePath:vo(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},o;try{o=await yo(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 Ne from"fs";import*as Xe from"path";import Pu from"json5";var wo={HTTP_TIMEOUT_MS:2e4},Mn={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 Re}from"os";import Se from"path";import{xdgConfig as Su}from"xdg-basedir";var B={"trae-cn":Se.join(Re(),".trae-cn"),opencode:Se.join(Su,"opencode"),cursor:Se.join(Re(),".cursor"),codebuddy:Se.join(Re(),".codebuddy"),qoder:Se.join(Re(),".qoder"),"claude-code":Se.join(Re(),".claude"),codex:Se.join(Re(),".codex"),bitfun:Se.join(Re(),".bitfun"),opendesk:Se.join(Re(),".opendesk")};import Me from"path";var bo="https://matrix.openharmony.cn",le={TAGS_API_URL:`${bo}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${bo}/api/registry/skill/skills`,SKILL_API_BASE:`${bo}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},ws={"trae-cn":{path:Me.join(B["trae-cn"],"skills"),displayName:"trae-cn"},opencode:{path:Me.join(B.opencode,"skills"),displayName:"opencode"},cursor:{path:Me.join(B.cursor,"skills"),displayName:"cursor"},codebuddy:{path:Me.join(B.codebuddy,"skills"),displayName:"codebuddy"},qoder:{path:Me.join(B.qoder,"skills"),displayName:"qoder"},"claude-code":{path:Me.join(B["claude-code"],"skills"),projectPath:".claude/skills",displayName:"claude-code"},codex:{path:Me.join(B.codex,"skills"),displayName:"codex"}},bs={opencode:{path:Me.join(B.opencode,"skills"),displayName:"opencode"}};function Pe(){return I()?bs:ws}import{homedir as Bt}from"os";import re from"path";var he="deveco-mcp";var Oe={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:re.join(B.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(Bt(),"AppData","Roaming"),"Trae CN","User"):re.join(Bt(),"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(B.cursor,"mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:re.join(B.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(Bt(),"AppData","Roaming"),"Qoder","SharedClientCache"):re.join(Bt(),"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(Bt(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:re.join(B.codex,"config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function Ps(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function Ss(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Es(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function On(n,e){return n.format==="opencode"?Ps(e):n.format==="claude-code"||n.format==="codex"?Ss(e):Es(e)}var de={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var Eu=1e3;function Ln(n){g(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=Xe.join(n,de.SYNC_OUTPUT_PATH);if(!Ne.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return g(`[ProjectCheck] ${l.reason}`),l}let t=Ne.statSync(e).mtimeMs;g(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Iu(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return g(`[ProjectCheck] ${l.reason}`),l}let o=Xe.join(n,de.OH_PACKAGE_JSON5),i=Nn(o,t,"root");if(i.required)return g(`[ProjectCheck] Root check: ${i.reason}`),i;let s=Xe.join(n,de.BUILD_PROFILE_JSON5),a=Nn(s,t,"build-profile");if(a.required)return g(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let u=Xe.join(n,l.srcPath,de.OH_PACKAGE_JSON5),h=Nn(u,t,l.name);if(h.required)return g(`[ProjectCheck] Module '${l.name}' check: ${h.reason}`),h;let E=Xe.join(n,l.srcPath,de.BUILD_PROFILE_JSON5),C=Nn(E,t,l.name);if(C.required)return g(`[ProjectCheck] Module '${l.name}' build-profile check: ${C.reason}`),C}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return g(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function Nn(n,e,t){if(!Ne.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=Ne.statSync(n).mtimeMs;return r-e>Eu?{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 Iu(n){let e=Xe.join(n,de.BUILD_PROFILE_JSON5);try{let t=Ne.readFileSync(e,"utf-8");if(!t.trim())return null;let r=Pu.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 Du(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 Au(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 Po(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 Wt(n,e){let t=e,r=`${n} failed`;console.error(So(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 Eo(n,e,t,r,o,i){if(Ln(i).required){console.log(`
|
|
15
15
|
[1/3] Running ohpm install...`);try{await n.installAll()}catch(a){Wt("ohpm install",a)}console.log(`
|
|
16
16
|
[2/3] Running hvigor sync...`);try{await e.sync(t,r)}catch(a){Wt("hvigor sync",a)}console.log(`
|
|
17
17
|
[3/3] Running hvigor build...`)}else console.log(`
|
|
@@ -29,19 +29,20 @@ ${o.join(`
|
|
|
29
29
|
`))}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 Gu(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>...].
|
|
30
30
|
Available runnable modules:
|
|
31
31
|
`+t.map(r=>` - ${r.name}`).join(`
|
|
32
|
-
`))}async function
|
|
33
|
-
Installing artifacts to device ${e}...`),await n.installApp(e,r),console.log(`Launching ${t}/${o}...`);let s=await n.launchApp(e,t,o);console.log(Ns(`
|
|
34
|
-
Application '${t}': ${s}`))}
|
|
35
|
-
|
|
32
|
+
`))}function Yu(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 Ju(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(`
|
|
33
|
+
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(Ns(`
|
|
34
|
+
Application '${t}': ${s}`))}else console.log(`
|
|
35
|
+
Application '${t}' installed successfully (no ability to launch).`)}var Ku=new Wu("run").description("Build and run the project on a connected device").option("--module <modules...>","Module(s) to run (format: module or module@target)").option("--device <device>","Target device name or serial").option("--product <product>","Product name (default: default)").option("--build-mode <mode>","Build mode (options: debug, release; default: debug)").option("--ability <ability>","Ability name to launch").option("--uninstall","Uninstall existing app before installation").option("--skip-build","Skip build step and deploy existing artifacts").action(async n=>{try{await Xu(n)}catch(e){console.error(Uu(e.message)),process.exit(1)}});async function Zu(n,e,t,r,o){let i=new ut(e,n.rootDir),s=new Ze(e,n.rootDir),a=new Set;for(let{moduleName:h,targetName:E}of t)for(let C of n.collectNonHarDependentModuleList(h))a.add(`${C}@${E}`);let c=[...a],l=Po(n,c),u={type:"modules",modulesToBuild:c,moduleTasks:l};await $t(n.rootDir,()=>Eo(i,s,r,o,u,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion...")),console.log(`
|
|
36
|
+
`+Ns("Build completed successfully."))}async function Xu(n){let e=Ke.discover(process.cwd());console.warn(zu("Ensure the project source is trusted before proceeding."));let t=await _.new(),o=Gu(e,n.module).map(qu);for(let{moduleName:Q}of o){let ce=e.getModuleType(Q);if(ce!=="entry"&&ce!=="feature"&&ce!=="shared")throw new Error(`Module '${Q}' '${ce}' is not runnable. Specify an entry or feature module.`)}let i=new Hn(t),s=ee.from(t),a=await Vu(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 Zu(e,t,o,l,u);let h=new Set;for(let{moduleName:Q,targetName:ce}of o){let kn=e.collectNonHarDependentModuleList(Q);for(let cu of kn)h.add(e.findArtifactPath(cu,ce,c,l));h.add(e.findArtifactPath(Q,ce,c,l))}let E=[...h],C=e.getBundleName(),M=Yu(e,o,n.ability);await Ju(i,a,C,E,M,!!n.uninstall)}var Ls=Ku;import{Command as Qu}from"commander";import{green as _s,red as Hs,cyan as Do}from"colorette";import{execa as js}from"execa";function ep(){return"@deveco-test/hmos-deveco-cli"}function tp(){return"0.1.0-TD.4"}var np=new Qu("update").description("Update deveco-cli to latest").action(async()=>{let n=ep(),e=tp();console.log(Do("Checking for updates..."));try{let{stdout:t}=await js("npm",["view",n,"version"]),r=t.trim();if(r===e){console.log(_s(`
|
|
36
37
|
${n} is already up to date (version ${e}.)`));return}console.log(Do(`
|
|
37
38
|
New version found: ${r} (current: ${e})`)),console.log(Do(`Updating ${n}...`)),await js("npm",["install","-g",`${n}@latest`],{stdio:"inherit"}),console.log(`
|
|
38
|
-
`+_s(`${n} updated successfully to version ${r}.`))}catch(t){let r=t;console.error(Hs(`Failed to update ${n}`)),r.message&&console.error(Hs(r.message)),process.exit(1)}}),Fs=
|
|
39
|
-
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:Us(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=q(e),o=t.find(a=>q(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 ko(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(!
|
|
39
|
+
`+_s(`${n} updated successfully to version ${r}.`))}catch(t){let r=t;console.error(Hs(`Failed to update ${n}`)),r.message&&console.error(Hs(r.message)),process.exit(1)}}),Fs=np;import{Command as Ip}from"commander";import{execa as ko}from"execa";function q(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as rp}from"child_process";var op=2500;function ip(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 sp(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,op);n.once("error",u=>c(u.message)),ip(n,l,s,a,c,i)}function $s(n,e,t){return g(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,o)=>{let i=[],s=rp(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)),sp(s,i,r,o)})}import*as ft from"path";function ap(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 cp(n){let e=n.instancePath?.trim();if(e)return ft.dirname(ft.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?ft.dirname(ft.normalize(t)).replace(/\\/g,"/"):""}function lp(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function Bs(n,e){return e?[...n,"-bootmode",e]:n}function dp(n,e,t){let r=[Bs(["-start",n],t)],o=cp(e);if(o)for(let i of lp(e.imageRoot))r.push(Bs(["-hvd",n,"-path",o,...i],t));return ap(r)}async function Ws(n,e,t,r){let o=new Error("No start strategy ran"),i=dp(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 Ao(n){return(await ee.withHdcPath(n).listDevices()).map(t=>t.serial).filter(Ut)}async function To(n){let e=await Ao(n);return e.length===0?[]:(await Promise.all(e.map(r=>_n(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function Us(n,e){return(await To(n)).includes(e)}import*as gt from"path";import{existsSync as up,statSync as pp}from"fs";function ht(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function mp(n){let e=ht(n,["instancePath","instance_path","InstancePath","instancepath","instanceDir","instance_dir","InstanceDir","deployPath","deploy_path","deployedPath","deployed_path","workPath","work_path","dataPath","data_path"]);if(e)return e;for(let[t,r]of Object.entries(n)){if(typeof r!="string"||!r.trim())continue;let o=t.toLowerCase();if(o.includes("instance")&&(o.includes("path")||o.includes("dir"))||o==="deployedpath")return r.trim()}return""}function fp(n){return ht(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function hp(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=gt.dirname(gt.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let o=gt.join(t,r.name);up(o)&&pp(o).isDirectory()&&(r.instancePath=o.replace(/\\/g,"/"))}}function gp(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=fp(t),o=ht(t,["deviceType","DeviceType","devicetype"]),i=ht(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:mp(t),path:ht(t,["path","Path","hvdPath","hvd_path"]),imageRoot:ht(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 yp(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 zs(n){let t=gp(n)??yp(n);return hp(t),t}function xo(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function vp(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function wp(n){if(!vp(n))return null;let e=xo(n,["osVersion","OsVersion","OSVersion"]),t=xo(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=xo(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function jn(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=wp(o);i&&r.push(i)}return r}catch{return[]}}function qs(n){let t=jn(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var Vs=/no images are available/i;function ge(n){return n.normalize("NFKC").trim().toLowerCase()}function bp(n){let e=n.message||"";return Vs.test(e)}var yt=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 ko(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return $s(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return zs(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let r of t)r.name&&r.deviceType&&e.set(q(r.name),r.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),r=q(e),o=t.find(a=>q(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 Ws(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.
|
|
40
|
+
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:Us(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=q(e),o=t.find(a=>q(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 ko(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(!bp(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 qs(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}
|
|
40
41
|
`:"";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=jn(t),o=ge(e.deviceType),i=ge(e.osVersion);return r.filter(s=>ge(s.deviceType)===o&&(ge(s.osVersion)===i||ge(s.softwareVersion)===i))}async hasDownloadedSystemImage(e,t){let r=await this.listEmulatorImages({downloaded:!0}),o=jn(r),i=ge(t),s=e?.trim()?ge(e):void 0;return o.some(a=>ge(a.osVersion)===i||ge(a.softwareVersion)===i?s===void 0?!0:ge(a.deviceType)===s:!1)}async assertSystemImageAvailable(e){let t=e.osVersion?.trim();if(!t)throw new Error("The system image file cannot be found, download it again.");if(!await this.hasDownloadedSystemImage(e.deviceType,t))throw new Error(`The system image file ${t} cannot be found, download it again.`)}async runUninstallImageChecked(e,t){await this.runEmulatorChecked(["-uninstall","-deviceType",e,"-osVersion",t,"-force"],{printOutputOnSuccess:!0,extraReject:[Vs]})}async runEmulatorChecked(e,t){let{stdout:r,stderr:o,exitCode:i}=await ko(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(`
|
|
41
42
|
`).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=q(e),i=r.find(s=>q(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(`
|
|
42
43
|
`)}),!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=>q(a.name)===e))return!0;await new Promise(a=>setTimeout(a,r))}return!1}async deleteVirtualDevice(e){let t=await this.listEmulators(),r=q(e),o=t.find(s=>q(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}
|
|
43
|
-
The device may be running.`);return await this.runEmulatorChecked(["-delete",i,"-force"],{printOutputOnSuccess:!1}),i}};import{red as Ro,yellow as Ys,gray as Js}from"colorette";import
|
|
44
|
-
`)}function
|
|
44
|
+
The device may be running.`);return await this.runEmulatorChecked(["-delete",i,"-force"],{printOutputOnSuccess:!1}),i}};import{red as Ro,yellow as Ys,gray as Js}from"colorette";import Cp from"ora";import{red as Sp}from"colorette";function Fn(n,e){n?n.fail(e):console.error(Sp(e)),process.exit(1)}import{green as Pp}from"colorette";function Gs(n,e){return n+" ".repeat(Math.max(0,e-n.length))}function Ep(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=Ep(n,e),r=[];r.push(n.map((o,i)=>Gs(o,t[i])).join(" ")),r.push(t.map(o=>"-".repeat(o)).join(" "));for(let o of e){let i=o.cells.map((s,a)=>Gs(s??"",t[a])).join(" ").trimEnd();r.push(o.highlight?Pp(i):i)}return r.join(`
|
|
45
|
+
`)}function Dp(n,e){if(e.size!==0)for(let t of n){if(!t.isEmulator||!t.name)continue;let r=e.get(q(t.name));r&&(t.deviceType=r)}}var Ap=["Name","Serial","Kind","Device Type"];function Tp(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function xp(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function kp(){console.log(Ys(" No active devices.")),console.log(Js(I()?" Connect a USB device with debugging enabled.":" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function Rp(n){let t=[...n].sort(xp).map(Tp);console.log(zt(Ap,t))}async function Mp(n,e){if(I()||!n.some(o=>o.isEmulator)||!e.emulatorPath)return;let r=await yt.from(e).getDeviceTypeByName();Dp(n,r)}async function Op(n,e,t){try{let r=await n.getConnectedEntries();await Mp(r,e),t?.stop(),r.length===0?kp():Rp(r)}catch(r){Fn(t,`Failed to list devices: ${r.message}`)}}async function Np(n,e){let t=await n.listDevices();if(!(t.length<2)){console.error(Ro("Multiple devices connected. Specify a device with:"));for(let r of t){let o=await n.getDeviceName(r.serial);console.error(Js(` ${e} -t ${r.serial} # ${o}`))}process.exit(1)}}async function Lp(n,e){try{e||await Np(n,"devecocli device view");let t=await n.listDevices(),r=await n.getDeviceInfo(t,e);r||(console.log(Ys("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(Ro(`Failed to show device details: ${t.message}`)),process.exit(1)}}async function Ks(){try{let n=await _.new();return{manager:ee.from(n),toolProvider:n}}catch(n){console.error(Ro(`Failed to initialize device manager: ${n.message}`)),process.exit(1);return}}var Mo=new Ip("device").description("Manage connected devices");Mo.command("list").description("List all connected devices").action(async()=>{let{manager:n,toolProvider:e}=await Ks(),t=Cp({text:"Querying connected devices\u2026",color:"cyan"}).start();await Op(n,e,t)});Mo.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").action(async n=>{let{manager:e}=await Ks();await Lp(e,n.target)});var Zs=Mo;import{Command as Ho,Option as pa}from"commander";import{green as Bn,cyan as wt,red as te,yellow as ye,gray as Vt}from"colorette";import em from"ora";import _p from"readline/promises";import{execa as Qs}from"execa";import*as _e from"fs/promises";import*as No from"os";import*as Qe from"path";var Oo=`1/4:\r
|
|
45
46
|
---------------------------------------\r
|
|
46
47
|
Statement About HarmonyOS and Privacy\r
|
|
47
48
|
\r
|
|
@@ -1211,61 +1212,61 @@ Part I: Chinese mainland.\r
|
|
|
1211
1212
|
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
|
|
1212
1213
|
\r
|
|
1213
1214
|
Part III: Other countries and regions.\r
|
|
1214
|
-
---------------------------------------\r`;var
|
|
1215
|
-
`),ta=ea,_o="HarmonyOS_SDK_Agreement";function na(n,e){return`${n}\0${e}`}function
|
|
1216
|
-
`)}function oa(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
|
|
1217
|
-
${t}.`);return ia(r)}function Xs(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function
|
|
1218
|
-
`,"utf8"),!0}catch{}return!1}async function
|
|
1215
|
+
---------------------------------------\r`;var Hp=new Set,$n=new Map,Lo="HarmonyOS_Software_Service_Agreement",ea=["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(`
|
|
1216
|
+
`),ta=ea,_o="HarmonyOS_SDK_Agreement";function na(n,e){return`${n}\0${e}`}function jp(){Hp.clear(),$n.clear()}var Fp=ea,ue=class extends Error{constructor(e=Fp){super(e),this.name="EmulatorLicenseBlockedError"}};function ra(n,e){return[n??"",e??""].join(`
|
|
1217
|
+
`)}function oa(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 $p(n){return`Emulator${n.trim()}`}function ia(n){let e=$p(n);if(process.platform==="win32"){let r=process.env.LOCALAPPDATA;if(!r)throw new Error("LOCALAPPDATA is not set; cannot resolve .emu_config path.");return Qe.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return Qe.join(No.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||Qe.join(No.homedir(),".cache");return Qe.join(t,"Huawei",e,".emu_config")}async function Bp(n,e,t){let r=na(n,e),o=$n.get(r);if(o!==void 0)return o;let i=await Qs(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=ra(i.stdout,i.stderr).trim();if(i.exitCode!==0||!s)throw new ue(t);return $n.set(r,s),s}function Wp(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function Up(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 zp(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=Wp(e.slice(r+1).trim());return{key:o,entry:{value:i,delimiter:t}}}}function qp(n){let e={};for(let t of n.split(/\r?\n/)){let r=zp(t);r&&(e[r.key]=r.entry)}return e}function Vp(n){let e=n.trim();if(!e)return{};let t=Up(e);return t||qp(n)}function Gp(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function sa(n,e,t,r){let o=await Bp(n,e,r),i=oa(o);if(!i)throw new ue(r);let s=ia(i),a;try{a=await _e.readFile(s,"utf8")}catch(u){throw u.code==="ENOENT"?new ue(r):u}let l=Vp(a)[t];if(!l)throw new ue(r);if(l.delimiter==="=")throw new ue(r);if(!Gp(l.value))throw new ue(r)}async function aa(n,e){await sa(n,e,Lo,ta)}async function ca(n,e){await sa(n,e,_o,ta)}async function Yp(n,e){let t=await Qs(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),r=ra(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=na(n,e);return $n.set(o,r),r}async function Jp(n,e){let t=await Yp(n,e),r=oa(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
|
|
1218
|
+
${t}.`);return ia(r)}function Xs(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function Kp(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[Lo]="agree",r[_o]="agree",await _e.writeFile(n,`${JSON.stringify(r,null,2)}
|
|
1219
|
+
`,"utf8"),!0}catch{}return!1}async function Zp(n,e){let t=Lo,r=_o,o=[{k:t,re:new RegExp(`^\\s*${Xs(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${Xs(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 _e.writeFile(n,s.join(`
|
|
1219
1220
|
`)+(s.length>0?`
|
|
1220
|
-
`:""),"utf8")}async function Zp(n){await _e.mkdir(Qe.dirname(n),{recursive:!0});let e="";try{e=await _e.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await Jp(n,e,t)||await Kp(n,e)}async function la(n,e){return console.log(Oo),0}var Xp="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function da(n,e){if(console.log(Oo),!process.stdin.isTTY||!process.stdout.isTTY)return console.error("`devecocli emulator license accept` requires an interactive terminal."),1;let r=Lp.createInterface({input:process.stdin,output:process.stdout}),o;try{o=await r.question(Xp)}finally{r.close()}let i=o.trim().toLowerCase();if(i!=="y"&&i!=="yes")return 1;try{let s=await Yp(n,e);await Zp(s),Hp()}catch(s){return console.error(s.message),1}return 0}var em=["ohos.qemu.hvd.name","const.product.name","const.product.model"];function tm(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 nm(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 rm(n,e){let t=o=>o.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(ye("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(ye("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(ye("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 om=["Name","Status","Serial","Device Type","OS Version"];function im(n,e,t){return{cells:[n.name,t?"running":"stopped",e??"-",n.deviceType??"-",n.osVersion??"-"],highlight:t}}async function sm(n,e){let t=await Promise.all(e.map(async r=>{let o=await mt(n,r,em);return[r,o]}));return new Map(t)}async function am(n){let e=await Ao(n),t=await sm(n,e);return{serials:e,params:t}}function cm(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 lm(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&&cm(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 dm(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=>im(o.emu,o.serial,o.effectiveRunning))}async function um(n,e,t){try{let[r,o]=await Promise.all([n.listEmulators(),am(e)]);if(r.length===0){t?.stop(),console.log(ye(" No emulator instances found."));return}let i=r.filter(l=>l.isRunning).map(l=>l.name),{productSerialMap:s,hvdSerialMap:a}=lm(o.serials,o.params,i);t?.stop();let c=dm(r,s,a);console.log(zt(om,c))}catch(r){Fn(t,`Failed to list emulators: ${r.message}`)}}function ma(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(Vt(s.stdout)),s.stderr&&console.error(Vt(s.stderr))}return r}var pm=2e3,mm=6e4;async function fm(n,e){let t=q(e);return(await To(n)).some(o=>q(o)===t)}async function fa(n,e,t,r=mm,o=pm){let i=Date.now()+r;for(;Date.now()<i;){if(await fm(n,e)===t)return!0;await new Promise(a=>setTimeout(a,o))}return!1}async function hm(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(ye(`Emulator "${t}" is already running.`));return}console.log(wt(`Starting emulator "${t}"...`));let o=await fa(e,t,!0);console.log(o?Bn(`Emulator "${t}" started successfully.`):ye(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function gm(n,e,t){let r=await Promise.allSettled(t.map(i=>hm(n,e,i)));ma(r,t,"start")&&process.exit(1)}async function ym(n,e){let t=e.trim();if(!Ut(t))return t;let r=await ee.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 vm(n,e,t){let r=await ym(e,t);if(console.log(wt(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(ye(`Emulator "${r}" is already stopped.`));return}let i=await fa(e,r,!1);console.log(i?Bn(`Emulator "${r}" stopped successfully.`):ye(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function wm(n,e,t){let r=await Promise.allSettled(t.map(i=>vm(n,e,i)));ma(r,t,"stop")&&process.exit(1)}async function ve(){try{let n=await _.new();return{manager:yt.from(n),toolProvider:n}}catch(n){console.error(te(`Failed to initialize emulator: ${n.message}`)),process.exit(1);return}}var He=new Ho("emulator").description("Manage emulator instances"),bm=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Wn(n){let e=new pa("--device-type <type>","Emulator device type").choices([...bm]);return n?e.makeOptionMandatory():e}function vt(n,e){for(let t of e)if(t in n)return n[t]}function qt(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function ua(n){let e=qt(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var Sm=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],Pm="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function ha(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function ga(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let o=r,i=qt(vt(o,["osVersion","OsVersion","OSVersion","os_version"])),s=qt(vt(o,["deviceType","DeviceType","device_type"])),a=ua(vt(o,["downloaded","Downloaded","isDownloaded"])),c=qt(vt(o,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=qt(vt(o,["releaseType","ReleaseType","release_type"])),u=ua(vt(o,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[i,s,c,l,u,a],highlight:e&&a==="true"})}return t}function Em(n){let e=n.trim();if(!e)return!0;let t=ha(e);return t===null?!1:t.length===0?!0:ga(t,!0).length===0}function Im(n,e){let t=n.trim();if(!t)return"";let r=ha(t);if(!r)return n.trimEnd();let o=ga(r,e);return zt(Sm,o)}var Un=new Ho("image").description("HarmonyOS emulator system images (download, list, remove)");Un.command("download").description("Download system image").addOption(Wn(!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 ve();try{await ca(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof ue&&(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)}});Un.command("remove").description("Remove a downloaded system image").addOption(Wn(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let{manager:e}=await ve();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)}});Un.command("list").description("List system images").addOption(Wn(!1)).option("--all","List all images (local and remote)").addOption(new pa("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await ve();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if(Em(r)){console.log(ye(Pm));return}if(n.format==="json"){console.log(r.trimEnd());return}let o=Im(r,n.all===!0);console.log(o)}catch(t){console.error(te(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});He.addCommand(Un);var jo=new Ho("license").description("local emulator license");jo.command("view").description("Review agreement text(read-only)").action(async()=>{let{toolProvider:n}=await ve(),e=await la(n.emulatorPath,n.sdkPath);process.exit(e)});jo.command("accept").description("Review and accept agreements").action(async()=>{let{toolProvider:n}=await ve(),e=await da(n.emulatorPath,n.sdkPath);process.exit(e)});He.addCommand(jo);He.command("list").description("List all emulator instances").action(async()=>{let{manager:n,toolProvider:e}=await ve(),t=Qp({text:"Listing emulators\u2026",color:"cyan"}).start();await um(n,e.hdcPath,t)});He.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await ve();try{await aa(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof ue&&(console.error(te(r.message)),process.exit(1)),r}n?.length||(console.error(te("Error: missing required argument 'names'")),process.exit(1)),await gm(e,t.hdcPath,n)});He.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 ve();n?.length||(console.error(te("Error: missing required argument 'names'")),process.exit(1)),await wm(e,t.hdcPath,n)});var ya=He.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(Wn(!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");ya.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
|
|
1221
|
+
`:""),"utf8")}async function Xp(n){await _e.mkdir(Qe.dirname(n),{recursive:!0});let e="";try{e=await _e.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await Kp(n,e,t)||await Zp(n,e)}async function la(n,e){return console.log(Oo),0}var Qp="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function da(n,e){if(console.log(Oo),!process.stdin.isTTY||!process.stdout.isTTY)return console.error("`devecocli emulator license accept` requires an interactive terminal."),1;let r=_p.createInterface({input:process.stdin,output:process.stdout}),o;try{o=await r.question(Qp)}finally{r.close()}let i=o.trim().toLowerCase();if(i!=="y"&&i!=="yes")return 1;try{let s=await Jp(n,e);await Xp(s),jp()}catch(s){return console.error(s.message),1}return 0}var tm=["ohos.qemu.hvd.name","const.product.name","const.product.model"];function nm(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 rm(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 om(n,e){let t=o=>o.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(ye("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(ye("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(ye("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 im=["Name","Status","Serial","Device Type","OS Version"];function sm(n,e,t){return{cells:[n.name,t?"running":"stopped",e??"-",n.deviceType??"-",n.osVersion??"-"],highlight:t}}async function am(n,e){let t=await Promise.all(e.map(async r=>{let o=await mt(n,r,tm);return[r,o]}));return new Map(t)}async function cm(n){let e=await Ao(n),t=await am(n,e);return{serials:e,params:t}}function lm(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 dm(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&&lm(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 um(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=>sm(o.emu,o.serial,o.effectiveRunning))}async function pm(n,e,t){try{let[r,o]=await Promise.all([n.listEmulators(),cm(e)]);if(r.length===0){t?.stop(),console.log(ye(" No emulator instances found."));return}let i=r.filter(l=>l.isRunning).map(l=>l.name),{productSerialMap:s,hvdSerialMap:a}=dm(o.serials,o.params,i);t?.stop();let c=um(r,s,a);console.log(zt(im,c))}catch(r){Fn(t,`Failed to list emulators: ${r.message}`)}}function ma(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(Vt(s.stdout)),s.stderr&&console.error(Vt(s.stderr))}return r}var mm=2e3,fm=6e4;async function hm(n,e){let t=q(e);return(await To(n)).some(o=>q(o)===t)}async function fa(n,e,t,r=fm,o=mm){let i=Date.now()+r;for(;Date.now()<i;){if(await hm(n,e)===t)return!0;await new Promise(a=>setTimeout(a,o))}return!1}async function gm(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(ye(`Emulator "${t}" is already running.`));return}console.log(wt(`Starting emulator "${t}"...`));let o=await fa(e,t,!0);console.log(o?Bn(`Emulator "${t}" started successfully.`):ye(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function ym(n,e,t){let r=await Promise.allSettled(t.map(i=>gm(n,e,i)));ma(r,t,"start")&&process.exit(1)}async function vm(n,e){let t=e.trim();if(!Ut(t))return t;let r=await ee.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 wm(n,e,t){let r=await vm(e,t);if(console.log(wt(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(ye(`Emulator "${r}" is already stopped.`));return}let i=await fa(e,r,!1);console.log(i?Bn(`Emulator "${r}" stopped successfully.`):ye(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function bm(n,e,t){let r=await Promise.allSettled(t.map(i=>wm(n,e,i)));ma(r,t,"stop")&&process.exit(1)}async function ve(){try{let n=await _.new();return{manager:yt.from(n),toolProvider:n}}catch(n){console.error(te(`Failed to initialize emulator: ${n.message}`)),process.exit(1);return}}var He=new Ho("emulator").description("Manage emulator instances"),Sm=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Wn(n){let e=new pa("--device-type <type>","Emulator device type").choices([...Sm]);return n?e.makeOptionMandatory():e}function vt(n,e){for(let t of e)if(t in n)return n[t]}function qt(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function ua(n){let e=qt(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var Pm=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],Em="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function ha(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function ga(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let o=r,i=qt(vt(o,["osVersion","OsVersion","OSVersion","os_version"])),s=qt(vt(o,["deviceType","DeviceType","device_type"])),a=ua(vt(o,["downloaded","Downloaded","isDownloaded"])),c=qt(vt(o,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=qt(vt(o,["releaseType","ReleaseType","release_type"])),u=ua(vt(o,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[i,s,c,l,u,a],highlight:e&&a==="true"})}return t}function Im(n){let e=n.trim();if(!e)return!0;let t=ha(e);return t===null?!1:t.length===0?!0:ga(t,!0).length===0}function Cm(n,e){let t=n.trim();if(!t)return"";let r=ha(t);if(!r)return n.trimEnd();let o=ga(r,e);return zt(Pm,o)}var Un=new Ho("image").description("HarmonyOS emulator system images (download, list, remove)");Un.command("download").description("Download system image").addOption(Wn(!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 ve();try{await ca(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof ue&&(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)}});Un.command("remove").description("Remove a downloaded system image").addOption(Wn(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let{manager:e}=await ve();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)}});Un.command("list").description("List system images").addOption(Wn(!1)).option("--all","List all images (local and remote)").addOption(new pa("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await ve();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if(Im(r)){console.log(ye(Em));return}if(n.format==="json"){console.log(r.trimEnd());return}let o=Cm(r,n.all===!0);console.log(o)}catch(t){console.error(te(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});He.addCommand(Un);var jo=new Ho("license").description("local emulator license");jo.command("view").description("Review agreement text(read-only)").action(async()=>{let{toolProvider:n}=await ve(),e=await la(n.emulatorPath,n.sdkPath);process.exit(e)});jo.command("accept").description("Review and accept agreements").action(async()=>{let{toolProvider:n}=await ve(),e=await da(n.emulatorPath,n.sdkPath);process.exit(e)});He.addCommand(jo);He.command("list").description("List all emulator instances").action(async()=>{let{manager:n,toolProvider:e}=await ve(),t=em({text:"Listing emulators\u2026",color:"cyan"}).start();await pm(n,e.hdcPath,t)});He.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await ve();try{await aa(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof ue&&(console.error(te(r.message)),process.exit(1)),r}n?.length||(console.error(te("Error: missing required argument 'names'")),process.exit(1)),await ym(e,t.hdcPath,n)});He.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 ve();n?.length||(console.error(te("Error: missing required argument 'names'")),process.exit(1)),await bm(e,t.hdcPath,n)});var ya=He.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(Wn(!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");ya.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
|
|
1221
1222
|
${ye("Tip: ")}${Vt("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
|
|
1222
1223
|
${wt('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
|
|
1223
1224
|
${wt('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
|
|
1224
|
-
`)}});ya.action(async(n,e)=>{try{
|
|
1225
|
-
${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)}},je=new Fo;var Sa=["DevEco"];async function zn(){let n=await je.get(le.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 Am(n){let e=[],t=le.DEFAULT_PAGE_SIZE,r=1;for(;;){let o=await je.post(le.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 $o(n){let e=new Map,t=n.map(o=>Am(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=>!Sa.includes(i.name)))}async function Tm(n,e){let t=await je.post(le.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:le.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return qn(t,"Skills API").data.list}async function Bo(n,e){let t=new Map,r=e.map(i=>Tm(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=>!Sa.includes(s.name)))}function Pa(n){let e=[],t=Pe();for(let[,r]of Object.entries(t)){let o=ba.join(r.path,n);wa.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=je.parseJson(n);if(t.code!==le.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Ea(n){let e=`${le.SKILL_API_BASE}/${n}/checksum`,t=await je.get(e);return qn(t,"Checksum API").data}import xm from"adm-zip";import km from"crypto";import Ca from"fs";import H from"path";import{fileURLToPath as Rm}from"url";import{red as Mm}from"colorette";var Ee=Ca.promises;function Wo(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function Ia(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 Uo(n){return H.isAbsolute(n)?n:H.resolve(process.cwd(),n)}function Om(n){return km.createHash("sha256").update(n).digest("hex")}async function Nm(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=Om(n),o=e.sha256.toLowerCase();if(r!==o)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function Da(n){let e=`${le.SKILL_API_BASE}/${n}/install?format=zip`,t=await je.getBinary(e),r=await Ea(n);return await Nm(t,r),t}async function Lm(n,e,t){Wo(t);let r=new xm(n),o=r.getEntries();try{await Ee.stat(e)}catch{await Ee.mkdir(e,{recursive:!0})}let i=H.join(e,t);Ia(e,i);for(let s of o){let a=H.join(i,s.entryName);Ia(i,a)}r.extractAllTo(i,!0)}async function zo(n){let e=Pe();if(!e[n])throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(e).join(", ")}`);let r=B[n];try{return await Ee.access(r),!0}catch{return!1}}function qo(n){return Pe()[n].path}function Vo(n,e){let r=Pe()[e],o="projectPath"in r?r.projectPath:H.join("."+e,"skills");return H.join(n,o)}async function _m(n,e,t){Wo(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 Go(n,e,t){await Lm(n,e,t),console.log(`Skill ${t} installed to ${H.join(e,t)}.`)}async function Yo(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 Aa(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(Mm(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function bt(n,e,t,r){try{let o=await e(),{shouldSkip:i}=await _m(o,n,r);return i?{success:!0,skipped:!0}:(await t(o),{success:!0})}catch(o){return Aa(n,o,"Installation failed")}}async function Jo(n,e){try{Wo(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 Aa(n,t,"Removal failed")}}async function Ta(n,e,t,r=!1){return bt(n,()=>qo(e),o=>Go(t,o,n),r)}async function xa(n,e,t,r=!1){return bt(n,()=>t,o=>Go(e,o,n),r)}async function ka(n,e,t,r,o=!1){return bt(n,()=>Vo(t,r),i=>Go(e,i,n),o)}async function Ra(n,e,t,r=!1){return bt(n,()=>qo(t),o=>Yo(e,o,n),r)}async function Ma(n,e,t,r,o=!1){return bt(n,()=>Vo(t,r),i=>Yo(e,i,n),o)}async function Oa(n,e,t,r=!1){return bt(n,()=>t,o=>Yo(e,o,n),r)}async function Na(n,e){return Jo(n,()=>qo(e))}async function La(n,e){return Jo(n,()=>e)}async function _a(n,e,t){return Jo(n,()=>Vo(e,t))}function Ha(){let e=H.dirname(Rm(import.meta.url));for(;;){let t=H.join(e,"SKILL.md");if(Ca.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 ja from"fs";import{cyan as Hm}from"colorette";async function Gt(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await zo(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function Yt(){let n=[],e=Pe();for(let t of Object.keys(e))await zo(t)&&n.push(t);return n}function Jt(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(Hm("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function Fe(n,e,t){if(!ja.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!ja.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function Kt(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?Uo(n):void 0,resolvedProject:e?Uo(e):void 0}}async function Vn(n,e,t){let r=[],o=[],i;if(e?i=e:t&&n.agent?o=(await Gt(n.agent)).map(a=>({project:t,agent:a})):t?o=(await Yt()).map(a=>({project:t,agent:a})):n.agent?r=await Gt(n.agent):r=await Yt(),!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 Bm(n){let e=await zn();if(n.all)return(await $o(e)).map(r=>r.enName);{let r=(await Bo(n.skill,e)).find(o=>o.enName===n.skill);if(!r)throw new Error(`Skill "${n.skill}" not found`);return[r.enName]}}async function Wm(n,e,t,r){let o=[];if(t.customPath){let i=await xa(n,e,t.customPath,r);return o.push(i),o}for(let i of t.agents){let s=await Ta(n,i,e,r);o.push(s)}for(let{project:i,agent:s}of t.projectAgents){let a=await ka(n,e,i,s,r);o.push(a)}return o}function Um(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}=Kt(n.path,n.project,n.agent);return t&&Fe(t,"Project directory",n.force),e&&Fe(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}async function zm(n,e,t){let r=await Vn(n,e,t);return{skillNames:await Bm(n),targets:r}}async function qm(n,e,t,r){let o=[],i=n.length,s=$m(5),a=n.map(async c=>s(async()=>{try{let l=await Da(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(Zt(`${l}: Download failed - ${h.error}`)),o.push({success:!1});continue}r.stop();let E=await Wm(l,h.buffer,e,t);o.push(...E)}return o}async function Vm(n){let e=new et;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=Um(n),{skillNames:o,targets:i}=await zm(n,t,r),s=await qm(o,i,n.force||!1,e);e.stop(),Jt(s)}catch(t){throw e.stop(),t}}function Gm(n){let{resolvedPath:e,resolvedProject:t}=Kt(n.path,n.project,n.agent);return t&&Fe(t,"Project directory"),e&&Fe(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function Ym(n,e){let t=new et;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:o}=Gm(e);t.stop();let i=await Jm(e,n,r,o);t.stop(),Jt(i)}catch(r){throw t.stop(),r}}function Fa(n,e=""){if(n.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function Gn(n,e){let t=[];for(let r of e){let o=r.type==="agent"?await Na(n,r.agent):await _a(n,r.project,r.agent);t.push(o)}return t}async function Jm(n,e,t,r){if(t)return[await La(e,t)];if(r&&n.agent){let a=(await Gt(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return Gn(e,a)}if(r){let s=await Yt();Fa(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return Gn(e,a)}if(n.agent){let a=(await Gt(n.agent)).map(c=>({type:"agent",agent:c}));return Gn(e,a)}let o=await Yt();Fa(o,"or use --path for a custom location.");let i=o.map(s=>({type:"agent",agent:s}));return Gn(e,i)}var Xt=new jm("skills").description("Manage HarmonyOS skills");Xt.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async n=>{let e=new et;try{e.start("Fetching skills...");let t=await zn(),r=await $o(t);if(r.length===0){e.stop(),console.log(Ba("No skills available."));return}e.succeed(`Fetched ${r.length} skills`);for(let o of r)if(n.long){console.log($a(o.enName)),console.log(Wa(o.description));let i=Pa(o.enName);i.length>0&&console.log(Fm(`Installed for: ${i.join(", ")}`)),console.log()}else console.log(o.enName)}catch(t){e.stop(),console.error(Zt(t.message)),process.exit(1)}});Xt.command("find <keyword>").description("Search skills by keyword").action(async n=>{let e=new et;try{e.start("Searching skills...");let t=await zn(),r=await Bo(n,t);if(r.length===0){console.log(Ba(`No skills found matching '${n}'.`)),e.stop();return}e.succeed(`Found ${r.length} skills.`);for(let o of r)console.log($a(o.enName)),console.log(Wa(o.description)),console.log()}catch(t){e.stop(),console.error(Zt(t.message)),process.exit(1)}});Xt.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 Vm(n)}catch(e){console.error(Zt(e.message)),process.exit(1)}});Xt.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 Ym(n.skill,n)}catch(e){console.error(Zt(e.message)),process.exit(1)}});var Ua=Xt;import{Command as Zm,InvalidArgumentError as Va}from"commander";import{cyan as Yn}from"colorette";function tt(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=pt(t);return r==="transient"?new Error(`${e}: Device communication channel unavailabel. Retry in a few seconds.`):r==="fatal"?new Error(`${e}: ${t.trim()}`):null}var Ko=[800,1500,2500];function Km(n){return new Promise(e=>setTimeout(e,n))}function za(){return I()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device."}var Jn=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=ee.from(e)}createFollowLineHandler(e){return(t,r)=>{let o=e.keyword?t.filter(i=>i.includes(e.keyword)):t;if(r!=="stderr")for(let i of o)console.log(i)}}findDeviceByArg(e,t){return e.find(r=>r.serial===t||r.name===t)}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
|
|
1225
|
+
`)}});ya.action(async(n,e)=>{try{nm(n),rm(e.osVersion);let{manager:t}=await ve(),r=await t.listDownloadedImageOsVersions();om(e.osVersion,r),console.log(wt(`Creating emulator "${n}"...`)),await t.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(Bn(`Emulator "${n}" created successfully.`))}catch(t){console.error(te(`${t.message}`)),process.exit(1)}});He.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let{manager:e}=await ve();console.log(wt(`Deleting emulator "${n}"...`));try{let t=await e.deleteVirtualDevice(n);console.log(Bn(`Emulator "${t}" deleted successfully.`))}catch(t){let r=t;console.error(te(r.message)),r.stdout&&console.error(Vt(r.stdout)),r.stderr&&console.error(Vt(r.stderr)),process.exit(1)}});var va=He;import{Command as Fm}from"commander";import{green as $m,red as Zt,cyan as $a,yellow as Ba,dim as Wa}from"colorette";import Bm from"p-limit";import Dm from"ora";var et=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=Dm(e),this.spinner.start(),this.isRunning=!0}stop(){this.spinner&&this.isRunning&&(this.spinner.stop(),this.isRunning=!1)}succeed(e){this.spinner&&(this.spinner.succeed(e),this.isRunning=!1)}fail(e){this.spinner&&(this.spinner.fail(e),this.isRunning=!1)}};import*as wa from"fs";import*as ba from"path";import Am from"axios";var Fo=class{client;constructor(){let e={timeout:wo.HTTP_TIMEOUT_MS,headers:{"User-Agent":Mn.USER_AGENT,"accept-language":Mn.ACCEPT_LANGUAGE},transformResponse:[t=>t],proxy:!1};this.client=Am.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}
|
|
1226
|
+
${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)}},je=new Fo;var Sa=["DevEco"];async function zn(){let n=await je.get(le.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 Tm(n){let e=[],t=le.DEFAULT_PAGE_SIZE,r=1;for(;;){let o=await je.post(le.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 $o(n){let e=new Map,t=n.map(o=>Tm(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=>!Sa.includes(i.name)))}async function xm(n,e){let t=await je.post(le.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:le.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return qn(t,"Skills API").data.list}async function Bo(n,e){let t=new Map,r=e.map(i=>xm(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=>!Sa.includes(s.name)))}function Pa(n){let e=[],t=Pe();for(let[,r]of Object.entries(t)){let o=ba.join(r.path,n);wa.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=je.parseJson(n);if(t.code!==le.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Ea(n){let e=`${le.SKILL_API_BASE}/${n}/checksum`,t=await je.get(e);return qn(t,"Checksum API").data}import km from"adm-zip";import Rm from"crypto";import Ca from"fs";import H from"path";import{fileURLToPath as Mm}from"url";import{red as Om}from"colorette";var Ee=Ca.promises;function Wo(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function Ia(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 Uo(n){return H.isAbsolute(n)?n:H.resolve(process.cwd(),n)}function Nm(n){return Rm.createHash("sha256").update(n).digest("hex")}async function Lm(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=Nm(n),o=e.sha256.toLowerCase();if(r!==o)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function Da(n){let e=`${le.SKILL_API_BASE}/${n}/install?format=zip`,t=await je.getBinary(e),r=await Ea(n);return await Lm(t,r),t}async function _m(n,e,t){Wo(t);let r=new km(n),o=r.getEntries();try{await Ee.stat(e)}catch{await Ee.mkdir(e,{recursive:!0})}let i=H.join(e,t);Ia(e,i);for(let s of o){let a=H.join(i,s.entryName);Ia(i,a)}r.extractAllTo(i,!0)}async function zo(n){let e=Pe();if(!e[n])throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(e).join(", ")}`);let r=B[n];try{return await Ee.access(r),!0}catch{return!1}}function qo(n){return Pe()[n].path}function Vo(n,e){let r=Pe()[e],o="projectPath"in r?r.projectPath:H.join("."+e,"skills");return H.join(n,o)}async function Hm(n,e,t){Wo(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 Go(n,e,t){await _m(n,e,t),console.log(`Skill ${t} installed to ${H.join(e,t)}.`)}async function Yo(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 Aa(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(Om(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function bt(n,e,t,r){try{let o=await e(),{shouldSkip:i}=await Hm(o,n,r);return i?{success:!0,skipped:!0}:(await t(o),{success:!0})}catch(o){return Aa(n,o,"Installation failed")}}async function Jo(n,e){try{Wo(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 Aa(n,t,"Removal failed")}}async function Ta(n,e,t,r=!1){return bt(n,()=>qo(e),o=>Go(t,o,n),r)}async function xa(n,e,t,r=!1){return bt(n,()=>t,o=>Go(e,o,n),r)}async function ka(n,e,t,r,o=!1){return bt(n,()=>Vo(t,r),i=>Go(e,i,n),o)}async function Ra(n,e,t,r=!1){return bt(n,()=>qo(t),o=>Yo(e,o,n),r)}async function Ma(n,e,t,r,o=!1){return bt(n,()=>Vo(t,r),i=>Yo(e,i,n),o)}async function Oa(n,e,t,r=!1){return bt(n,()=>t,o=>Yo(e,o,n),r)}async function Na(n,e){return Jo(n,()=>qo(e))}async function La(n,e){return Jo(n,()=>e)}async function _a(n,e,t){return Jo(n,()=>Vo(e,t))}function Ha(){let e=H.dirname(Mm(import.meta.url));for(;;){let t=H.join(e,"SKILL.md");if(Ca.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 ja from"fs";import{cyan as jm}from"colorette";async function Gt(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await zo(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function Yt(){let n=[],e=Pe();for(let t of Object.keys(e))await zo(t)&&n.push(t);return n}function Jt(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(jm("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function Fe(n,e,t){if(!ja.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!ja.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function Kt(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?Uo(n):void 0,resolvedProject:e?Uo(e):void 0}}async function Vn(n,e,t){let r=[],o=[],i;if(e?i=e:t&&n.agent?o=(await Gt(n.agent)).map(a=>({project:t,agent:a})):t?o=(await Yt()).map(a=>({project:t,agent:a})):n.agent?r=await Gt(n.agent):r=await Yt(),!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 Wm(n){let e=await zn();if(n.all)return(await $o(e)).map(r=>r.enName);{let r=(await Bo(n.skill,e)).find(o=>o.enName===n.skill);if(!r)throw new Error(`Skill "${n.skill}" not found`);return[r.enName]}}async function Um(n,e,t,r){let o=[];if(t.customPath){let i=await xa(n,e,t.customPath,r);return o.push(i),o}for(let i of t.agents){let s=await Ta(n,i,e,r);o.push(s)}for(let{project:i,agent:s}of t.projectAgents){let a=await ka(n,e,i,s,r);o.push(a)}return o}function zm(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}=Kt(n.path,n.project,n.agent);return t&&Fe(t,"Project directory",n.force),e&&Fe(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}async function qm(n,e,t){let r=await Vn(n,e,t);return{skillNames:await Wm(n),targets:r}}async function Vm(n,e,t,r){let o=[],i=n.length,s=Bm(5),a=n.map(async c=>s(async()=>{try{let l=await Da(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(Zt(`${l}: Download failed - ${h.error}`)),o.push({success:!1});continue}r.stop();let E=await Um(l,h.buffer,e,t);o.push(...E)}return o}async function Gm(n){let e=new et;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=zm(n),{skillNames:o,targets:i}=await qm(n,t,r),s=await Vm(o,i,n.force||!1,e);e.stop(),Jt(s)}catch(t){throw e.stop(),t}}function Ym(n){let{resolvedPath:e,resolvedProject:t}=Kt(n.path,n.project,n.agent);return t&&Fe(t,"Project directory"),e&&Fe(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function Jm(n,e){let t=new et;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:o}=Ym(e);t.stop();let i=await Km(e,n,r,o);t.stop(),Jt(i)}catch(r){throw t.stop(),r}}function Fa(n,e=""){if(n.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function Gn(n,e){let t=[];for(let r of e){let o=r.type==="agent"?await Na(n,r.agent):await _a(n,r.project,r.agent);t.push(o)}return t}async function Km(n,e,t,r){if(t)return[await La(e,t)];if(r&&n.agent){let a=(await Gt(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return Gn(e,a)}if(r){let s=await Yt();Fa(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return Gn(e,a)}if(n.agent){let a=(await Gt(n.agent)).map(c=>({type:"agent",agent:c}));return Gn(e,a)}let o=await Yt();Fa(o,"or use --path for a custom location.");let i=o.map(s=>({type:"agent",agent:s}));return Gn(e,i)}var Xt=new Fm("skills").description("Manage HarmonyOS skills");Xt.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async n=>{let e=new et;try{e.start("Fetching skills...");let t=await zn(),r=await $o(t);if(r.length===0){e.stop(),console.log(Ba("No skills available."));return}e.succeed(`Fetched ${r.length} skills`);for(let o of r)if(n.long){console.log($a(o.enName)),console.log(Wa(o.description));let i=Pa(o.enName);i.length>0&&console.log($m(`Installed for: ${i.join(", ")}`)),console.log()}else console.log(o.enName)}catch(t){e.stop(),console.error(Zt(t.message)),process.exit(1)}});Xt.command("find <keyword>").description("Search skills by keyword").action(async n=>{let e=new et;try{e.start("Searching skills...");let t=await zn(),r=await Bo(n,t);if(r.length===0){console.log(Ba(`No skills found matching '${n}'.`)),e.stop();return}e.succeed(`Found ${r.length} skills.`);for(let o of r)console.log($a(o.enName)),console.log(Wa(o.description)),console.log()}catch(t){e.stop(),console.error(Zt(t.message)),process.exit(1)}});Xt.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 Gm(n)}catch(e){console.error(Zt(e.message)),process.exit(1)}});Xt.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 Jm(n.skill,n)}catch(e){console.error(Zt(e.message)),process.exit(1)}});var Ua=Xt;import{Command as Xm,InvalidArgumentError as Va}from"commander";import{cyan as Yn}from"colorette";function tt(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=pt(t);return r==="transient"?new Error(`${e}: Device communication channel unavailabel. Retry in a few seconds.`):r==="fatal"?new Error(`${e}: ${t.trim()}`):null}var Ko=[800,1500,2500];function Zm(n){return new Promise(e=>setTimeout(e,n))}function za(){return I()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device."}var Jn=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=ee.from(e)}createFollowLineHandler(e){return(t,r)=>{let o=e.keyword?t.filter(i=>i.includes(e.keyword)):t;if(r!=="stderr")for(let i of o)console.log(i)}}findDeviceByArg(e,t){return e.find(r=>r.serial===t||r.name===t)}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
|
|
1226
1227
|
`)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let o=t[0];return g(Yn(`Using device serial: ${o}`)),o}if(e&&t.includes(e))return g(Yn(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let o=this.findDeviceByArg(r,e);if(o)return g(Yn(`Using device: ${o.name} (${o.serial})`)),o.serial;let i=this.formatConnectedDeviceList(r);throw new Error(`Device '${e}' not found.
|
|
1227
1228
|
Available devices:
|
|
1228
|
-
${i}`)}if(r.length===1){let o=r[0];return g(Yn(`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(za());return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error(za());return e}async getPidForBundle(e,t,r){g(`Retrieving PID for bundle ${r}`),S.assertBundleName(r);let o=await Le(e,["-t",t,"shell","pidof",r]),i=tt(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 Le(e,["-t",t,"shell","hilog","-G",r]),i=tt(o,"Failed to resize hilog buffer");if(i)throw i;o.exitCode!==0&&console.error(`Failed to resize hilog buffer: ${o.stderr||o.stdout}`)}buildHilogCommand(e,t,r,o){let i=this.buildHilogShellCommand(r,o);return[e,["-t",t,"shell",i]]}buildHilogShellCommand(e,t){let r=["hilog"];return e.isFollow||r.push("-x"),e.tag&&(S.assertHilogToken(e.tag,"tag"),r.push("-T",e.tag)),e.level&&(S.assertHilogLevel(e.level),r.push("-L",e.level)),e.domain&&(S.assertHilogToken(e.domain,"domain"),r.push("-D",e.domain)),t&&r.push("-P",t),e.keyword&&(S.assertHilogKeyword(e.keyword),r.push("-e",S.quotePosixShellArg(e.keyword))),r.join(" ")}async followHilog(e,t,r,o,i){let a=await Rs(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+Ko.length,a={stdout:"",stderr:"",exitCode:-1};for(let c=0;c<s;c++){a=await this.followHilog(e,t,r,o,i);let l=a.exitCode===0?a.stdout:a.stderr||a.stdout;if(pt(l)!=="transient"||c>=s-1)return a;g(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${Ko[c]}ms`),await
|
|
1229
|
+
${i}`)}if(r.length===1){let o=r[0];return g(Yn(`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(za());return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error(za());return e}async getPidForBundle(e,t,r){g(`Retrieving PID for bundle ${r}`),S.assertBundleName(r);let o=await Le(e,["-t",t,"shell","pidof",r]),i=tt(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 Le(e,["-t",t,"shell","hilog","-G",r]),i=tt(o,"Failed to resize hilog buffer");if(i)throw i;o.exitCode!==0&&console.error(`Failed to resize hilog buffer: ${o.stderr||o.stdout}`)}buildHilogCommand(e,t,r,o){let i=this.buildHilogShellCommand(r,o);return[e,["-t",t,"shell",i]]}buildHilogShellCommand(e,t){let r=["hilog"];return e.isFollow||r.push("-x"),e.tag&&(S.assertHilogToken(e.tag,"tag"),r.push("-T",e.tag)),e.level&&(S.assertHilogLevel(e.level),r.push("-L",e.level)),e.domain&&(S.assertHilogToken(e.domain,"domain"),r.push("-D",e.domain)),t&&r.push("-P",t),e.keyword&&(S.assertHilogKeyword(e.keyword),r.push("-e",S.quotePosixShellArg(e.keyword))),r.join(" ")}async followHilog(e,t,r,o,i){let a=await Rs(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+Ko.length,a={stdout:"",stderr:"",exitCode:-1};for(let c=0;c<s;c++){a=await this.followHilog(e,t,r,o,i);let l=a.exitCode===0?a.stdout:a.stderr||a.stdout;if(pt(l)!=="transient"||c>=s-1)return a;g(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${Ko[c]}ms`),await Zm(Ko[c])}return a}async printTailSnapshotIfNeeded(e,t,r,o){if(!r.tail&&!r.fromSeconds&&!r.toSeconds)return;let i={...r,isFollow:!1},[,s]=this.buildHilogCommand(e,t,i,o),a=await Le(e,s),c=tt(a,"Failed to get hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to get hilog: ${a.stderr}`);let l=S.filterLogsByRelativeWindow(a.stdout||a.stderr,r.fromSeconds,r.toSeconds);l=S.getLastLines(l,r.tail),l.trim()&&console.log(l)}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.runHilogWithSpawnRetry(i,s,()=>{},h=>{g(`Callback triggered when an error occurs during a single hilog streaming read: ${h.message}`)},()=>{}),c=tt(a,"Failed to get hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to get hilog: ${a.stderr}`);let l=a.stdout||a.stderr,u=S.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return u=S.getLastLines(u,r.tail),u}async runHilogFollow(e,t,r,o){await this.printTailSnapshotIfNeeded(e,t,r,o);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(r),l=>{console.error(l.message)},()=>{}),c=tt(a,"Failed to follow hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to follow hilog: ${a.stderr}`);return""}async getHilog(e,t){let r=this.toolProvider.hdcPath,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 Le(e,o),s=tt(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:
|
|
1229
1230
|
${i.stdout}`),i.stdout.split(`
|
|
1230
|
-
`).map(c=>c.trim()).filter(c=>c.length>0).filter(c=>{try{return S.assertCrashFilename(c),!0}catch{return!1}}).filter(c=>r?c.toLowerCase().includes(r.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){g(`Fetching latest crash log file: ${r}`);let o=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];g(`Executing command: ${e} ${o.join(" ")}`);let i=await Le(e,o),s=tt(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 Zo,red as Ga}from"colorette";import Xm from"ora";function Qm(n){try{return S.parsePositiveInteger(n,"tail")}catch{throw new Va("`tail` must be a positive integer.")}}function qa(n,e){try{return S.parseDurationToSeconds(n,e)}catch{throw new Va(`${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 ef(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.");S.assertRelativeTimeRange(n.from,n.to)}async function tf(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 nf(n,e,t,r){let o=S.filterLogsByRelativeWindow(n,t,r);return e.tail?S.getLastLines(o,e.tail):o}var rf=new Zm("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(Ga(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",Qm).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>qa(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>qa(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await of(n)});async function of(n){let e=Xm({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),ef(n);let r=n.from,o=n.to,i=await _.new(),s=new Jn(i),a=await s.selectDevice(n.device);a||(t(),process.exit(1)),g(Zo(`deviceId: ${a}`)),g(Zo(`type: ${n.crash?"Crash logs":"Common logs"}`)),g(Zo("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await tf(s,a,n,r,o);t(),n.crash&&c&&(c=nf(c,n,r,o)),c&&console.log(c)}catch(r){t(),console.error(Ga(r.message)),process.exit(1)}}var Ya=rf;import en from"path";import Ie from"fs";import ei from"process";import tc from"os";import{Command as vf}from"commander";import{green as Xa,red as Xo,cyan as wf,yellow as Qo}from"colorette";import j from"fs-extra";import R from"path";import*as Ja from"os";import{fileURLToPath as sf}from"url";var af={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"}},cf=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function lf(){let n=import.meta.url,e=sf(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 Ka(n,e){j.mkdirSync(e,{recursive:!0});for(let t of j.readdirSync(n,{withFileTypes:!0})){let r=R.join(n,t.name),o=R.join(e,t.name);if(t.isDirectory()){Ka(r,o);continue}j.existsSync(o)||(j.mkdirSync(R.dirname(o),{recursive:!0}),j.copyFileSync(r,o))}}function Qt(n,e){let t=j.readFileSync(n,"utf-8"),r=t;for(let[o,i]of e)r=r.replaceAll(o,i);r!==t&&j.writeFileSync(n,r,"utf-8")}function df(n,e){if(e===22)return;let t=af[e];t&&(Qt(R.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),Qt(R.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),Qt(R.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function uf(n){return cf.filter(t=>!j.existsSync(R.join(n,t))).length===0}function pf(){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 mf(n){return Ja.platform()==="darwin"?R.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):R.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function ff(n,e){let t=mf(e);if(!j.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);j.existsSync(s)&&(j.mkdirSync(R.dirname(a),{recursive:!0}),j.copyFileSync(s,a))}return!0}function hf(n){let e=pf(),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);j.mkdirSync(R.dirname(o),{recursive:!0}),j.writeFileSync(o,e)}}function gf(n,e){e&&ff(n,e)||hf(n)}function yf(n){let e=[R.join(n,"gitignore.txt"),R.join(n,"entry","gitignore.txt")];for(let t of e)j.existsSync(t)&&j.renameSync(t,t.replace(/\/gitignore\.txt$/,"/.gitignore"))}function Za(n,e,t,r,o){let i=lf();if(!j.existsSync(i))throw new Error(`Template directory not found: ${i}`);j.mkdirSync(n,{recursive:!0}),Ka(i,n),yf(n),gf(n,o),Qt(R.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),Qt(R.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),df(n,r);let s=uf(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function bf(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 Sf(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 nc(n){if(tc.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function Qa(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=tc.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=nc(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 Pf(n){let e=n,t=en.parse(n).root;for(;e!==t;){if(Ie.existsSync(e))return e;e=en.dirname(e)}return Ie.existsSync(t)?t:null}function ec(n){let e=Pf(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=en.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 Ef(n){return`com.example.${n.toLowerCase()}`}function If(n,e){if(e){let o=nc(e),i=en.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 ec(i);return i}let t=ei.cwd(),r=en.join(t,n);if(Ie.existsSync(r))throw new Error(`Directory '${r}' already exists. Cannot create project here.`);return ec(r),r}function Cf(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=I()?"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 Df(){try{return await _.new()}catch(n){let e=n,t=I()?"Toolchain not found":"DevEco Studio not found";console.error(Qo(`${t}: ${e.message}`)),I()?console.log(Qo("Please install commandLineTools. Use placeholder API level instead.")):console.log(Qo("Use placeholder API level instead."));return}}var Af=new vf("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(Xo("Error: --app-name is required")),ei.exit(1));let e=n.appName;bf(e);let t=n.bundleName||Ef(e);Sf(t),n.projectPath&&Qa(n.projectPath);let r=If(e,n.projectPath);Qa(r),console.log(wf("Initializing project...")),console.log(`Project path: ${r}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let o=await Df(),i=Cf(n,o);console.log(`API level: ${i}`);let s=o?.devecoStudioPath,a=Za(r,e,t,i,s);console.log(`
|
|
1231
|
+
`).map(c=>c.trim()).filter(c=>c.length>0).filter(c=>{try{return S.assertCrashFilename(c),!0}catch{return!1}}).filter(c=>r?c.toLowerCase().includes(r.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){g(`Fetching latest crash log file: ${r}`);let o=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];g(`Executing command: ${e} ${o.join(" ")}`);let i=await Le(e,o),s=tt(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 Zo,red as Ga}from"colorette";import Qm from"ora";function ef(n){try{return S.parsePositiveInteger(n,"tail")}catch{throw new Va("`tail` must be a positive integer.")}}function qa(n,e){try{return S.parseDurationToSeconds(n,e)}catch{throw new Va(`${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 tf(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.");S.assertRelativeTimeRange(n.from,n.to)}async function nf(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 rf(n,e,t,r){let o=S.filterLogsByRelativeWindow(n,t,r);return e.tail?S.getLastLines(o,e.tail):o}var of=new Xm("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(Ga(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",ef).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>qa(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>qa(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await sf(n)});async function sf(n){let e=Qm({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),tf(n);let r=n.from,o=n.to,i=await _.new(),s=new Jn(i),a=await s.selectDevice(n.device);a||(t(),process.exit(1)),g(Zo(`deviceId: ${a}`)),g(Zo(`type: ${n.crash?"Crash logs":"Common logs"}`)),g(Zo("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await nf(s,a,n,r,o);t(),n.crash&&c&&(c=rf(c,n,r,o)),c&&console.log(c)}catch(r){t(),console.error(Ga(r.message)),process.exit(1)}}var Ya=of;import en from"path";import Ie from"fs";import ei from"process";import tc from"os";import{Command as wf}from"commander";import{green as Xa,red as Xo,cyan as bf,yellow as Qo}from"colorette";import j from"fs-extra";import R from"path";import*as Ja from"os";import{fileURLToPath as af}from"url";var cf={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"}},lf=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function df(){let n=import.meta.url,e=af(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 Ka(n,e){j.mkdirSync(e,{recursive:!0});for(let t of j.readdirSync(n,{withFileTypes:!0})){let r=R.join(n,t.name),o=R.join(e,t.name);if(t.isDirectory()){Ka(r,o);continue}j.existsSync(o)||(j.mkdirSync(R.dirname(o),{recursive:!0}),j.copyFileSync(r,o))}}function Qt(n,e){let t=j.readFileSync(n,"utf-8"),r=t;for(let[o,i]of e)r=r.replaceAll(o,i);r!==t&&j.writeFileSync(n,r,"utf-8")}function uf(n,e){if(e===22)return;let t=cf[e];t&&(Qt(R.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),Qt(R.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),Qt(R.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function pf(n){return lf.filter(t=>!j.existsSync(R.join(n,t))).length===0}function mf(){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 ff(n){return Ja.platform()==="darwin"?R.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):R.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function hf(n,e){let t=ff(e);if(!j.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);j.existsSync(s)&&(j.mkdirSync(R.dirname(a),{recursive:!0}),j.copyFileSync(s,a))}return!0}function gf(n){let e=mf(),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);j.mkdirSync(R.dirname(o),{recursive:!0}),j.writeFileSync(o,e)}}function yf(n,e){e&&hf(n,e)||gf(n)}function vf(n){let e=[R.join(n,"gitignore.txt"),R.join(n,"entry","gitignore.txt")];for(let t of e)j.existsSync(t)&&j.renameSync(t,t.replace(/\/gitignore\.txt$/,"/.gitignore"))}function Za(n,e,t,r,o){let i=df();if(!j.existsSync(i))throw new Error(`Template directory not found: ${i}`);j.mkdirSync(n,{recursive:!0}),Ka(i,n),vf(n),yf(n,o),Qt(R.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),Qt(R.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),uf(n,r);let s=pf(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function Sf(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 Pf(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 nc(n){if(tc.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function Qa(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=tc.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=nc(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 Ef(n){let e=n,t=en.parse(n).root;for(;e!==t;){if(Ie.existsSync(e))return e;e=en.dirname(e)}return Ie.existsSync(t)?t:null}function ec(n){let e=Ef(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=en.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 If(n){return`com.example.${n.toLowerCase()}`}function Cf(n,e){if(e){let o=nc(e),i=en.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 ec(i);return i}let t=ei.cwd(),r=en.join(t,n);if(Ie.existsSync(r))throw new Error(`Directory '${r}' already exists. Cannot create project here.`);return ec(r),r}function Df(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=I()?"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 Af(){try{return await _.new()}catch(n){let e=n,t=I()?"Toolchain not found":"DevEco Studio not found";console.error(Qo(`${t}: ${e.message}`)),I()?console.log(Qo("Please install commandLineTools. Use placeholder API level instead.")):console.log(Qo("Use placeholder API level instead."));return}}var Tf=new wf("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(Xo("Error: --app-name is required")),ei.exit(1));let e=n.appName;Sf(e);let t=n.bundleName||If(e);Pf(t),n.projectPath&&Qa(n.projectPath);let r=Cf(e,n.projectPath);Qa(r),console.log(bf("Initializing project...")),console.log(`Project path: ${r}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let o=await Af(),i=Df(n,o);console.log(`API level: ${i}`);let s=o?.devecoStudioPath,a=Za(r,e,t,i,s);console.log(`
|
|
1231
1232
|
`+Xa("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(Xa("Template integrity check passed."))}catch(e){let t=e;console.error(Xo(`
|
|
1232
|
-
Failed to create project.`)),console.error(Xo(t.message)),ei.exit(1)}}),rc=
|
|
1233
|
+
Failed to create project.`)),console.error(Xo(t.message)),ei.exit(1)}}),rc=Tf;import{Command as Lf}from"commander";import{red as _f,cyan as dc}from"colorette";import xf from"fs";import Kn from"path";import{cyan as kf}from"colorette";import*as Zn from"smol-toml";var St=xf.promises;async function Rf(n){try{let e=await St.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 Mf(n){try{let e=await St.readFile(n,"utf8");return e.trim()===""?{}:Zn.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 Of(n,e){let t=Kn.dirname(n);await St.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await St.writeFile(n,r,"utf8")}async function Nf(n,e){let t=Kn.dirname(n);await St.mkdir(t,{recursive:!0});let r=Zn.stringify(e);await St.writeFile(n,r,"utf8")}function oc(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function ic(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 sc(n,e){return n.format==="codex"?Mf(e):Rf(e)}async function ac(n,e,t){return n.format==="codex"?Nf(e,t):Of(e,t)}async function cc(n,e,t=!1){let r=Oe[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Oe).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 sc(r,r.globalConfigPath);if(oc(o,r.mcpServersKey,he)&&!t)return console.log(`MCP server ${he} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let i=On(r,void 0);return ic(o,r.mcpServersKey,he,i,t),await ac(r,r.globalConfigPath,o),console.log(`MCP server ${he} 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 ti(n,e,t=!1){let r=Oe[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Oe).join(", ")}`};let o=Kn.isAbsolute(r.projectConfigPath)?r.projectConfigPath:Kn.join(e,r.projectConfigPath);try{let i=await sc(r,o);if(oc(i,r.mcpServersKey,he)&&!t)return console.log(`MCP server ${he} already configured in ${o}.`),{success:!0,skipped:!0,configPath:o,agentName:n,installType:"project"};let s=On(r,e);return ic(i,r.mcpServersKey,he,s,t),await ac(r,o,i),console.log(`MCP server ${he} 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 lc(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(kf("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 ni="deveco-cli";async function Hf(n,e,t){if(n.customPath)return[await Oa(ni,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>Ma(ni,e,s,a,t.force)),...n.agents.map(s=>()=>Ra(ni,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 jf(n,e,t){let r=[];for(let{project:o,agent:i}of n.projectAgents){let s=await ti(i,o,t);r.push(s)}for(let o of n.agents){let i=await ti(o,e,t);r.push(i)}return r}async function Ff(n,e){let t=[];for(let r of n){if(!Oe[r])continue;let i=await cc(r,process.cwd(),e);t.push(i)}return t}async function $f(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 jf(s,e,r):await Ff(s.agents,r);a.length>0&&(console.log(dc("MCP Configuration:")),lc(a))}async function Bf(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}=Kt(n.path,n.project,n.agent);t&&Fe(t,"Project directory",n.force),e&&Fe(e,"Directory",n.force);let r=await Vn(n,e,t);if(n.mcp){await $f(r,t,n);return}let o=Ha(),i=await Hf(r,o,n);console.log(),i.length>0&&(console.log(dc("Skill Installation:")),Jt(i))}var Wf=new Lf("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 Bf(n)}catch(e){console.error(_f(e.message)),process.exit(1)}}),uc=Wf;import{Command as Kh}from"commander";import{McpServer as Gh}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Yh}from"@modelcontextprotocol/sdk/server/stdio.js";import*as Hr from"path";import{z as bi}from"zod";var Xn=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 ri(){return new Xn}import*as xe from"fs";import*as be from"path";import{z as gi}from"zod";import W from"fs";import*as Qn from"os";import*as L from"path";import Uf from"json5";var zf=3;function oi(n){if(!W.existsSync(n)||!W.statSync(n).isDirectory())return!1;let e=W.existsSync(L.join(n,"build-profile.json5")),t=W.existsSync(L.join(n,"hvigorfile.js"))||W.existsSync(L.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=W.readFileSync(L.join(n,"build-profile.json5"),"utf-8");return Uf.parse(r).app!==void 0}catch{return!1}}function pc(n,e,t){if(e>=t)return null;let r=qf(n),o=Vf(r);if(o)return o;for(let i of r){let s=pc(i,e+1,t);if(s)return s}return null}function qf(n){try{let e=W.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(L.join(n,r.name));return t}catch{return[]}}function Vf(n){for(let e of n)if(oi(e))return e;return null}function Ce(n){if(!n||n.trim()==="")return null;let e=L.resolve(n),t;try{t=W.realpathSync(e)}catch{t=e}if(!W.existsSync(t))return null;if(oi(t))return t;let r=t;for(let o=1;o<=3;o++){let i=L.dirname(r);if(i===r)break;if(oi(i))return i;r=i}if(W.statSync(t).isDirectory()){let o=pc(t,0,zf);if(o)return o}return null}var ii=[I()?".bitfun":".idea",".deveco",I()?".cxx":"cxx","compile_commands.json"];function nn(n){return L.join(n,...ii)}function mc(n){return new Promise(e=>setTimeout(e,n))}var Gf=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function er(n){let e=L.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&Gf.has(e)}function fc(n){return L.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function we(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function si(n){return we(n)}function nt(n){let e=si(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function tn(n){try{let e=new URL(n);if(e.protocol==="file:"){let t=decodeURIComponent(e.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(t)&&(t=t.slice(1)),nt(t)}}catch{}return n}function hc(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=tn(o);i!==n&&i!==tn(n)&&e.push(i)}}return e}function tr(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??L.join(Qn.homedir(),"AppData","Local");return L.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?L.join(Qn.homedir(),"Library","Logs","devecocli-mcp-server"):L.join(Qn.homedir(),".local","share","devecocli-mcp-server","logs")}function gc(n,e){let t=Yf(e),r=Jf(t,n);if(r!==null)return r;let o=Date.now(),s=`${n.replace(/:/g,"\\:")}=${o}`,a=Kf(t,n,s);return Zf(e,a),o}function Yf(n){let e;try{e=W.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function Jf(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 Kf(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 Zf(n,e){try{W.mkdirSync(L.dirname(n),{recursive:!0})}catch{}try{W.writeFileSync(n,e.join(`
|
|
1233
1234
|
`)+`
|
|
1234
|
-
`,"utf8")}catch{}}function ai(n,e,t="[Cleanup]"){try{let r=L.dirname(n);if(!W.existsSync(r))return;let o=Date.now();for(let i of W.readdirSync(r,{withFileTypes:!0}))i.isDirectory()&&
|
|
1235
|
-
`;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 li(n=!1){ie&&ie.dispose(),ie=new ci(n)}function vc(){ie&&(ie.dispose(),ie=null)}function wc(){ie&&ie.flush()}function bc(){return ie?.getLogFilePath()??null}function Sc(){return ie?.getLogDirectory()??null}function nr(){return ie||li(!1),ie}var f={debug:(n,...e)=>nr().debug(n,...e),info:(n,...e)=>nr().info(n,...e),warn:(n,...e)=>nr().warn(n,...e),error:(n,...e)=>nr().error(n,...e)};function Pc(n){return"method"in n&&!("id"in n)}import{spawn as
|
|
1235
|
+
`,"utf8")}catch{}}function ai(n,e,t="[Cleanup]"){try{let r=L.dirname(n);if(!W.existsSync(r))return;let o=Date.now();for(let i of W.readdirSync(r,{withFileTypes:!0}))i.isDirectory()&&Xf(L.join(r,i.name),o,e,t)}catch{}}function Xf(n,e,t,r){try{let{mtimeMs:o}=W.statSync(n);if(e-o<=t)return;W.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 rr from"path";var yc="mcp-server.log",Qf="mcp-server",eh={maxSize:10*1024*1024,maxFiles:4},ci=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={...eh,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=tr(),this.currentLogFile=rr.join(this.logDir,yc),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 rr.join(this.logDir,`${Qf}-${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===yc||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(o)){let i=rr.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}
|
|
1236
|
+
`;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 li(n=!1){ie&&ie.dispose(),ie=new ci(n)}function vc(){ie&&(ie.dispose(),ie=null)}function wc(){ie&&ie.flush()}function bc(){return ie?.getLogFilePath()??null}function Sc(){return ie?.getLogDirectory()??null}function nr(){return ie||li(!1),ie}var f={debug:(n,...e)=>nr().debug(n,...e),info:(n,...e)=>nr().info(n,...e),warn:(n,...e)=>nr().warn(n,...e),error:(n,...e)=>nr().error(n,...e)};function Pc(n){return"method"in n&&!("id"in n)}import{spawn as rh}from"child_process";import{EventEmitter as oh}from"events";import*as Et from"fs";import*as Rc from"path";import*as Ec from"util";var di="";function Ic(n){if(!n||n==="auto"||n==="stdout"||n==="none"){di="";return}di=n}function Cc(){return di||(Sc()??"")}function or(n,...e){if(e.length===0)return n;try{return Ec.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] ${or(n,...e)}`)},warn(n,...e){f.warn(`[lsp] ${or(n,...e)}`)},error(n,...e){f.error(`[lsp] ${or(n,...e)}`)},debug(n,...e){f.debug(`[lsp] ${or(n,...e)}`)}};import*as on from"fs";import*as sn from"os";import*as Pt from"path";import nh from"json5";var th={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"},ir={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"},w={...th,...ir},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 Dc=8192,ui=100,Ac=.03,Tc=.7,rn=900*1e3;function oe(n){if(!on.existsSync(n))return null;try{let e=on.readFileSync(n,"utf-8");return e.trim()?nh.parse(e):null}catch{return null}}function xc(n,e){let t=Math.floor(sn.totalmem()/1048576),r=Math.floor(t*Tc),o,i;e!==void 0&&Number.isFinite(e)&&e>0?(o=e,i=`override(${e})`):(o=Dc,n>ui&&(o+=(n-ui)*Ac*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 De(n){try{let e=Pt.resolve(n),t=new URL(`file://${e}`).toString();if(sn.platform()==="win32"){let r=t.match(/^file:\/\/\/([A-Za-z]):/);if(r){let o=r[1].toUpperCase(),i=t.substring(`file:///${r[1]}:`.length);t=`file:///${o}%3A${i}`}}return t}catch{return n}}function sr(n){return n&&n.replace(/\\/g,"/")}function V(n){let e=Pt.normalize(n).replace(/\\/g,"/");if(sn.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function kc(n){return Pt.join(n,"build-profile.json5")}var ar=class extends oh{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;ensureDirectories(){let t=Rc.join(this.config.logPath,"lspLog");return Et.existsSync(t)||Et.mkdirSync(t,{recursive:!0}),Et.existsSync(this.config.indexingDataLocation)||Et.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let r=this.ensureDirectories();d.info(`[LspClient] serverMaxSize=${t}MB`);let o=V(r),i=["--expose-gc",`--max-old-space-size=${t}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${o}`,this.config.serverPath,"--stdio",`--logger-path=${o}`,"--logger-level=TRACE"];d.info(`[LspClient] Starting process: node ${i.join(" ")}`);let s=this.config.nodePath;d.info(`[LspClient] nodePath: ${s}`),this.process=rh(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
|
|
1236
1237
|
\r
|
|
1237
1238
|
${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this.buffer.indexOf(`\r
|
|
1238
1239
|
\r
|
|
1239
|
-
`);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 cr=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 lr=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 pi(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)}},pi=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var dr=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 mi(n){return Array.isArray(n)&&n.every(e=>typeof e=="string")}function oh(n){if(!y(n))return!1;let e=n.textDocument;return y(e)&&typeof e.uri=="string"}function ih(n){return y(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function sh(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 ur=class n{client;isInitialized=!1;stopOnce=null;callbacks=new dr;requestCallbacks=new cr;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;static EXPECTED_DIAGNOSTIC_TYPES=new Set([1e3,2e3,3e3,3001]);constructor(e){this.client=new ar(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:w.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(w.BROADCAST),this.callbacks.register(w.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(w.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(w.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(w.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:w.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(!oh(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=De(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(!ih(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:w.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),w.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:w.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=De(t);e.textDocument.uri=o,d.info(`[LSP] onAsyncOpenFile, uri: ${o}`);let i=this.diagnosticMap.get(o);i||(i=new lr(o),this.diagnosticMap.set(o,i),this.registerDiagnosticTimeout(o,ir.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(i.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:w.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),se.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=De(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,ir.PUBLISH_DIAGNOSTICS)),d.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:w.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=De(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:w.DID_CLOSE,params:{textDocument:{uri:r}}}),se.DID_CLOSE)}getDiagnosticMessage(e){let t=De(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,w.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:O,method:w.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 w.MODULE_INIT_FINISH:return d.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(w.MODULE_INIT_FINISH),this.callbacks.unregister(w.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case w.INDEXING_PROGRESS_UPDATE:return d.info(`[LSP] onIndexingProgressUpdate: ${sh(t.params)}`),this.callbacks.invoke(w.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case w.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case w.ON_PACKAGE_CHANGE_FINISH:d.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case w.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case w.ON_ASYNC_HOVER:this.handleAsyncResponse(t,w.HOVER);return;case w.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,w.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case w.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,w.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:w.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,w.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,w.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 fi from"path";import*as vr from"path";var pr=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var mr=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var fr=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var hr=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var gr=class{typeSetting=new fr;parameterNames=new hr};var yr=class{constructor(e,t,r,o){this.rootUri=e;this.lspServerWorkspacePath=V(vr.dirname(t)),this.indexingDataLocation=V(o),this.loggerPath=V(vr.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new pr;gutterIconsSetting=new mr;inlayHintsSetting=new gr;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Mc from"path";var an=class{productName="default";buildModeName="debug";targetName="default";arkTSVersion="1.1";resourceDirectories=[];targetESVersion="ES2021";maxFlowDepth=2e3;caseSensitiveCheck=!0;tsImportSendable=!1;compatibleSdkVersionStage="";useNormalizedOHMUrl=!0;reExportCheckMode="noCheck";skipOhModulesLint=!1;byteCodeHar=!0;obfuscationRuleOptionsEnable=!1;enableStrictCheckOHModules=!1;sourceRoots=[];constructor(e){e&&this.resourceDirectories.push(V(Mc.join(e,"src","main","resources")))}};var ah="OS",It=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${ah}`;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 an(e)):this.buildProfileParam=new an}toString(){return JSON.stringify(this)}};var Ct=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as ae from"path";import*as Tt from"fs";var wr=class{modulePath;dependencies={};dynamicDependencies={}};var rt=class{registryType;resolved;name;version;type;constructor(e){let t=typeof e=="object"&&e!==null?e:{};this.name=typeof t.name=="string"?t.name:"",this.version=typeof t.version=="string"?t.version:"",typeof t.registryType=="string"?this.registryType=t.registryType:this.registryType=typeof t.path=="string"?"local":"ohpm",typeof t.resolved=="string"?this.resolved=t.resolved:typeof t.storePath=="string"?this.resolved=t.storePath:this.resolved="",this.type=typeof t.type=="string"?t.type:void 0}};var Dt=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 br from"fs";var At=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:de.OH_PACKAGE_JSON5},cn=`${A.HVIGOR_CACHE}/${A.DEPENDENCY}`,ot=`${A.DEPENDENCY}${A.JSON5}`,$C=de.SYNC_OUTPUT_PATH;var ln=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 At;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=S.ensurePathWithinRoot(this.projectPath,a)}br.existsSync(i)&&br.statSync(i).isDirectory()&&(r.dependencyPath=i)}catch(i){d.error("parser dependency path is invalid",i)}}};import*as dn from"fs";import*as un from"path";import ch from"json5";var Sr=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 un.join(this.projectPath,A.OH_MODULES_PATH,A.OHPM_PATH,A.LOCK_JSON5_FILE)}readLockFile(e){if(!dn.existsSync(e))return d.error("lock file does not exist"),this.clearDependencies(),null;try{let t=dn.readFileSync(e,"utf8"),r=ch.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 At;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 E=`${a}@${u}`;this.storePathMap.has(E)&&(h.storePath=this.storePathMap.get(E)||""),i.push(h)}return i}parseDependencyPath(e,t,r,o,i){let s=S.resolvePathWithinRoot(this.projectPath,un.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=un.isAbsolute(a)?S.ensurePathWithinRoot(this.projectPath,a):S.resolvePathWithinRoot(this.projectPath,a);dn.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 it=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=kc(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 Oc(n){return y(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var pn=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new it(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=ae.join(t,cn),o=ae.join(r,ot);if(!Tt.existsSync(r)||!Tt.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 Dt(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];Oc(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,cn),i=ae.join(o,ot);if(!Tt.existsSync(o)||!Tt.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 Dt(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(!Oc(l))continue;let u=l.name;if(s&&!s.has(u))continue;let h=S.resolvePathWithinRoot(this.projectPath,l.srcPath),E=ae.join(o,u),C=V(h),M=this.buildModuleDependencies(u,C,E,a);M.moduleName=u,t.push(M)}return t}parseSingleModule(e,t,r,o){let i=e.name,s=S.resolvePathWithinRoot(this.projectPath,e.srcPath),a=ae.join(t,i),c=V(s),l=new It(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 Ct(h),o.push(l)}buildModuleDependencies(e,t,r,o){let i=new Dt(this.projectPath,e,t);ln.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 wr;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 rt(i);for(let i of e.finalDynamicDependencies)o[i.name]=new rt(i);t.dependencies=r,t.dynamicDependencies=o}parseProjectDependencies(e,t){let r=ae.join(e,A.OH_PACKAGE_JSON5);if(!Tt.existsSync(r))return;ln.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 Sr(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 Pr=class{constructor(e=[]){this.valueSet=e}valueSet};var xt=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Nc=(v=>(v[v.File=1]="File",v[v.Module=2]="Module",v[v.Namespace=3]="Namespace",v[v.Package=4]="Package",v[v.Class=5]="Class",v[v.Method=6]="Method",v[v.Property=7]="Property",v[v.Field=8]="Field",v[v.Constructor=9]="Constructor",v[v.Enum=10]="Enum",v[v.Interface=11]="Interface",v[v.Function=12]="Function",v[v.Variable=13]="Variable",v[v.Constant=14]="Constant",v[v.String=15]="String",v[v.Number=16]="Number",v[v.Boolean=17]="Boolean",v[v.Array=18]="Array",v[v.Object=19]="Object",v[v.Key=20]="Key",v[v.Null=21]="Null",v[v.EnumMember=22]="EnumMember",v[v.Struct=23]="Struct",v[v.Event=24]="Event",v[v.Operator=25]="Operator",v[v.TypeParameter=26]="TypeParameter",v))(Nc||{}),Lc=()=>Object.values(Nc).filter(n=>typeof n=="number");var Er=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Ir=class{applyEdit=!0;workspaceEdit=new Er;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Pr(Lc());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new xt;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Cr=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Dr=class{constructor(e=[]){this.valueSet=e}valueSet};var Ar=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var _c=(b=>(b[b.Text=1]="Text",b[b.Method=2]="Method",b[b.Function=3]="Function",b[b.Constructor=4]="Constructor",b[b.Field=5]="Field",b[b.Variable=6]="Variable",b[b.Class=7]="Class",b[b.Interface=8]="Interface",b[b.Module=9]="Module",b[b.Property=10]="Property",b[b.Unit=11]="Unit",b[b.Value=12]="Value",b[b.Enum=13]="Enum",b[b.Keyword=14]="Keyword",b[b.Snippet=15]="Snippet",b[b.Color=16]="Color",b[b.File=17]="File",b[b.Reference=18]="Reference",b[b.Folder=19]="Folder",b[b.EnumMember=20]="EnumMember",b[b.Constant=21]="Constant",b[b.Struct=22]="Struct",b[b.Event=23]="Event",b[b.Operator=24]="Operator",b[b.TypeParameter=25]="TypeParameter",b))(_c||{}),Hc=()=>Object.values(_c).filter(n=>typeof n=="number");var Tr=class{completionItemKind=new Dr(Hc());completionItem=new Ar;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var xr=class{synchronization=new Cr;completion=new Tr;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 xt;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var kr=class{workspace=new Ir;textDocument=new xr;notebookDocument=null;window=null;general=null;experimental=null};var Rr=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};function kt(n){return y(n)?typeof n.line=="number"&&typeof n.character=="number":!1}function jc(n){return y(n)?typeof n.uri=="string"&&typeof n.text=="string"&&typeof n.languageId=="string"&&typeof n.version=="number":!1}function Fc(n){if(!y(n)||typeof n.text!="string")return!1;let e=n.range;return y(e)?kt(e.start)&&kt(e.end):!1}var Mr=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=Cc(),this.indexLogPath=e.indexLogPath||this.logPath,this.messageHandle=new ur({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=De(this.rootUri),i=new yr(o,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new pn(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),i.modules=s;let l=xc(s.length,this.nodeMaxOldSpaceSize);await this.messageHandle.start(l),this.currentParams=new Rr(o,i,new kr),this.messageHandle.sendInitialize(this.currentParams,1),this.messageHandle.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:O,method:w.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((u,h)=>{this.messageHandle.onIndexingProgressUpdate(h),this.messageHandle.onInitializationCompleted(u)},"LSP initialization",rn),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=De(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 pn(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 rt({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new It(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new Ct([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let o of e){let i=o.moduleName??"",s=t.get(i);s?(s.modulePath=o.modulePath,s.moduleDependencies=o):s=this.createMinimalModelFromDepsItem(o),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let o=new Map(r.map(s=>[s.moduleName??"",s])),i=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=o.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,o.delete(a)),i.push(s)}for(let[,s]of o)i.push(this.createMinimalModelFromDepsItem(s));return i}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=sr(fi.join(t,"default/openharmony/ets/build-tools/ets-loader")),o=sr(fi.join(t,"default/openharmony/ets/api")),i=sr(fi.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=o,s.hosSdkPath=i}sendRequest(e){switch(e.method){case w.HOVER:this.handleHoverRequest(e);break;case w.DEFINITION:this.handleDefinitionRequest(e);break;case w.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"||!kt(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(w.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"||!kt(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(w.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"||!kt(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(w.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(!Pc(e)){d.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case w.DID_OPEN:this.handleDidOpenNotification(e);break;case w.DID_CHANGE:this.handleDidChangeNotification(e);break;case w.DID_CLOSE:this.handleDidCloseNotification(e);break;case w.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:this.handleDidChangePackageDependencies(e);break;case w.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(!jc(r)||!mi(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(Fc)){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 $e from"path";import{createHash as lh}from"crypto";import{EventEmitter as dh}from"events";var Or=class extends dh{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=S.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=S.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=S.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=S.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=$e.join(this.projectRoot,A.OH_PACKAGE_JSON5);Te.existsSync(r)&&t.push(r);let o=this.parseModulesFromBuildProfile();for(let i of o){let s=S.resolvePathWithinRoot(this.projectRoot,i.srcPath),a=$e.join(s,A.OH_PACKAGE_JSON5);Te.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return $e.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Te.readFileSync(t,"utf-8");return lh("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:$e.basename(t),relativePath:$e.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 Be from"fs";import*as pe from"path";import{createHash as uh}from"crypto";import{EventEmitter as ph}from"events";var Nr=class extends ph{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=pe.join(t,cn)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!Be.existsSync(this.depMapDir)){d.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=Be.watch(this.depMapDir,{recursive:!0},(t,r)=>this.onDirEvent(t,r)),this.dirWatcher.on("error",t=>{d.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){d.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),d.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return V(pe.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===ot)i="dep-map-json";else{let a=o.match(/^([^/]+)\/oh-package\.json5$/);i=a?`module:${a[1]}`:""}if(!i)return;let s=pe.join(this.depMapDir,r);Be.existsSync(s)&&this.scheduleDebouncedFullScan()}stop(){this.dirWatcher&&(this.dirWatcher.close(),this.dirWatcher=null),this.fullScanTimer&&(clearTimeout(this.fullScanTimer),this.fullScanTimer=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.coalesceTimer&&(clearTimeout(this.coalesceTimer),this.coalesceTimer=null),this.pendingTags=[],this.pendingRenames=[],this.contentHashes.clear(),this.initialScanDone=!1,d.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=pe.join(this.depMapDir,A.OH_PACKAGE_JSON5),r=pe.join(this.depMapDir,ot),o=this.parseModulesFromDepMap(),i=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...o.map(s=>({path:pe.join(this.depMapDir,s.name,A.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of i){if(!Be.existsSync(s))continue;let c=this.canonicalPath(s),l=this.computeFileHash(s);if(!l)continue;let u=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,l);continue}u!==l&&(this.contentHashes.set(c,l),d.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=pe.join(this.depMapDir,ot);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 V(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(i=>[i.name,i])),o=new Map(t.map(i=>[this.normalizeSrcPath(i.srcPath),i]));return{byName:r,bySrcPath:o}}detectModuleRenames(t,r,o,i){for(let[s,a]of t){let c=r.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),o.add(a.name),i.add(c.name);let l=pe.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=pe.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=Be.readFileSync(t,"utf-8");return uh("sha256").update(r).digest("hex")}catch{return null}}};import*as $c from"os";import*as Bc from"path";import{spawn as mh}from"child_process";var fh=600*1e3;function hh(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 Lr(n){return n.join("")}function gh(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
1240
|
+
`);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 cr=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 lr=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 pi(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)}},pi=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var dr=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 mi(n){return Array.isArray(n)&&n.every(e=>typeof e=="string")}function ih(n){if(!y(n))return!1;let e=n.textDocument;return y(e)&&typeof e.uri=="string"}function sh(n){return y(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function ah(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 ur=class n{client;isInitialized=!1;stopOnce=null;callbacks=new dr;requestCallbacks=new cr;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;static EXPECTED_DIAGNOSTIC_TYPES=new Set([1e3,2e3,3e3,3001]);constructor(e){this.client=new ar(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:w.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(w.BROADCAST),this.callbacks.register(w.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(w.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(w.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(w.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:w.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(!ih(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=De(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(!sh(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:w.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),w.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:w.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=De(t);e.textDocument.uri=o,d.info(`[LSP] onAsyncOpenFile, uri: ${o}`);let i=this.diagnosticMap.get(o);i||(i=new lr(o),this.diagnosticMap.set(o,i),this.registerDiagnosticTimeout(o,ir.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(i.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:w.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),se.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=De(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,ir.PUBLISH_DIAGNOSTICS)),d.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:w.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=De(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:w.DID_CLOSE,params:{textDocument:{uri:r}}}),se.DID_CLOSE)}getDiagnosticMessage(e){let t=De(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,w.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:O,method:w.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 w.MODULE_INIT_FINISH:return d.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(w.MODULE_INIT_FINISH),this.callbacks.unregister(w.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case w.INDEXING_PROGRESS_UPDATE:return d.info(`[LSP] onIndexingProgressUpdate: ${ah(t.params)}`),this.callbacks.invoke(w.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case w.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case w.ON_PACKAGE_CHANGE_FINISH:d.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case w.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case w.ON_ASYNC_HOVER:this.handleAsyncResponse(t,w.HOVER);return;case w.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,w.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case w.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,w.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:w.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,w.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,w.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 fi from"path";import*as vr from"path";var pr=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var mr=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var fr=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var hr=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var gr=class{typeSetting=new fr;parameterNames=new hr};var yr=class{constructor(e,t,r,o){this.rootUri=e;this.lspServerWorkspacePath=V(vr.dirname(t)),this.indexingDataLocation=V(o),this.loggerPath=V(vr.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new pr;gutterIconsSetting=new mr;inlayHintsSetting=new gr;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Mc from"path";var an=class{productName="default";buildModeName="debug";targetName="default";arkTSVersion="1.1";resourceDirectories=[];targetESVersion="ES2021";maxFlowDepth=2e3;caseSensitiveCheck=!0;tsImportSendable=!1;compatibleSdkVersionStage="";useNormalizedOHMUrl=!0;reExportCheckMode="noCheck";skipOhModulesLint=!1;byteCodeHar=!0;obfuscationRuleOptionsEnable=!1;enableStrictCheckOHModules=!1;sourceRoots=[];constructor(e){e&&this.resourceDirectories.push(V(Mc.join(e,"src","main","resources")))}};var ch="OS",It=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${ch}`;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 an(e)):this.buildProfileParam=new an}toString(){return JSON.stringify(this)}};var Ct=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as ae from"path";import*as Tt from"fs";var wr=class{modulePath;dependencies={};dynamicDependencies={}};var rt=class{registryType;resolved;name;version;type;constructor(e){let t=typeof e=="object"&&e!==null?e:{};this.name=typeof t.name=="string"?t.name:"",this.version=typeof t.version=="string"?t.version:"",typeof t.registryType=="string"?this.registryType=t.registryType:this.registryType=typeof t.path=="string"?"local":"ohpm",typeof t.resolved=="string"?this.resolved=t.resolved:typeof t.storePath=="string"?this.resolved=t.storePath:this.resolved="",this.type=typeof t.type=="string"?t.type:void 0}};var Dt=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 br from"fs";var At=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:de.OH_PACKAGE_JSON5},cn=`${A.HVIGOR_CACHE}/${A.DEPENDENCY}`,ot=`${A.DEPENDENCY}${A.JSON5}`,BC=de.SYNC_OUTPUT_PATH;var ln=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 At;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=S.ensurePathWithinRoot(this.projectPath,a)}br.existsSync(i)&&br.statSync(i).isDirectory()&&(r.dependencyPath=i)}catch(i){d.error("parser dependency path is invalid",i)}}};import*as dn from"fs";import*as un from"path";import lh from"json5";var Sr=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 un.join(this.projectPath,A.OH_MODULES_PATH,A.OHPM_PATH,A.LOCK_JSON5_FILE)}readLockFile(e){if(!dn.existsSync(e))return d.error("lock file does not exist"),this.clearDependencies(),null;try{let t=dn.readFileSync(e,"utf8"),r=lh.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 At;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 E=`${a}@${u}`;this.storePathMap.has(E)&&(h.storePath=this.storePathMap.get(E)||""),i.push(h)}return i}parseDependencyPath(e,t,r,o,i){let s=S.resolvePathWithinRoot(this.projectPath,un.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=un.isAbsolute(a)?S.ensurePathWithinRoot(this.projectPath,a):S.resolvePathWithinRoot(this.projectPath,a);dn.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 it=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=kc(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 Oc(n){return y(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var pn=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new it(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=ae.join(t,cn),o=ae.join(r,ot);if(!Tt.existsSync(r)||!Tt.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 Dt(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];Oc(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,cn),i=ae.join(o,ot);if(!Tt.existsSync(o)||!Tt.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 Dt(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(!Oc(l))continue;let u=l.name;if(s&&!s.has(u))continue;let h=S.resolvePathWithinRoot(this.projectPath,l.srcPath),E=ae.join(o,u),C=V(h),M=this.buildModuleDependencies(u,C,E,a);M.moduleName=u,t.push(M)}return t}parseSingleModule(e,t,r,o){let i=e.name,s=S.resolvePathWithinRoot(this.projectPath,e.srcPath),a=ae.join(t,i),c=V(s),l=new It(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 Ct(h),o.push(l)}buildModuleDependencies(e,t,r,o){let i=new Dt(this.projectPath,e,t);ln.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 wr;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 rt(i);for(let i of e.finalDynamicDependencies)o[i.name]=new rt(i);t.dependencies=r,t.dynamicDependencies=o}parseProjectDependencies(e,t){let r=ae.join(e,A.OH_PACKAGE_JSON5);if(!Tt.existsSync(r))return;ln.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 Sr(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 Pr=class{constructor(e=[]){this.valueSet=e}valueSet};var xt=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Nc=(v=>(v[v.File=1]="File",v[v.Module=2]="Module",v[v.Namespace=3]="Namespace",v[v.Package=4]="Package",v[v.Class=5]="Class",v[v.Method=6]="Method",v[v.Property=7]="Property",v[v.Field=8]="Field",v[v.Constructor=9]="Constructor",v[v.Enum=10]="Enum",v[v.Interface=11]="Interface",v[v.Function=12]="Function",v[v.Variable=13]="Variable",v[v.Constant=14]="Constant",v[v.String=15]="String",v[v.Number=16]="Number",v[v.Boolean=17]="Boolean",v[v.Array=18]="Array",v[v.Object=19]="Object",v[v.Key=20]="Key",v[v.Null=21]="Null",v[v.EnumMember=22]="EnumMember",v[v.Struct=23]="Struct",v[v.Event=24]="Event",v[v.Operator=25]="Operator",v[v.TypeParameter=26]="TypeParameter",v))(Nc||{}),Lc=()=>Object.values(Nc).filter(n=>typeof n=="number");var Er=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Ir=class{applyEdit=!0;workspaceEdit=new Er;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Pr(Lc());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new xt;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Cr=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Dr=class{constructor(e=[]){this.valueSet=e}valueSet};var Ar=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var _c=(b=>(b[b.Text=1]="Text",b[b.Method=2]="Method",b[b.Function=3]="Function",b[b.Constructor=4]="Constructor",b[b.Field=5]="Field",b[b.Variable=6]="Variable",b[b.Class=7]="Class",b[b.Interface=8]="Interface",b[b.Module=9]="Module",b[b.Property=10]="Property",b[b.Unit=11]="Unit",b[b.Value=12]="Value",b[b.Enum=13]="Enum",b[b.Keyword=14]="Keyword",b[b.Snippet=15]="Snippet",b[b.Color=16]="Color",b[b.File=17]="File",b[b.Reference=18]="Reference",b[b.Folder=19]="Folder",b[b.EnumMember=20]="EnumMember",b[b.Constant=21]="Constant",b[b.Struct=22]="Struct",b[b.Event=23]="Event",b[b.Operator=24]="Operator",b[b.TypeParameter=25]="TypeParameter",b))(_c||{}),Hc=()=>Object.values(_c).filter(n=>typeof n=="number");var Tr=class{completionItemKind=new Dr(Hc());completionItem=new Ar;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var xr=class{synchronization=new Cr;completion=new Tr;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 xt;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var kr=class{workspace=new Ir;textDocument=new xr;notebookDocument=null;window=null;general=null;experimental=null};var Rr=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};function kt(n){return y(n)?typeof n.line=="number"&&typeof n.character=="number":!1}function jc(n){return y(n)?typeof n.uri=="string"&&typeof n.text=="string"&&typeof n.languageId=="string"&&typeof n.version=="number":!1}function Fc(n){if(!y(n)||typeof n.text!="string")return!1;let e=n.range;return y(e)?kt(e.start)&&kt(e.end):!1}var Mr=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=Cc(),this.indexLogPath=e.indexLogPath||this.logPath,this.messageHandle=new ur({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=De(this.rootUri),i=new yr(o,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new pn(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),i.modules=s;let l=xc(s.length,this.nodeMaxOldSpaceSize);await this.messageHandle.start(l),this.currentParams=new Rr(o,i,new kr),this.messageHandle.sendInitialize(this.currentParams,1),this.messageHandle.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:O,method:w.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((u,h)=>{this.messageHandle.onIndexingProgressUpdate(h),this.messageHandle.onInitializationCompleted(u)},"LSP initialization",rn),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=De(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 pn(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 rt({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new It(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new Ct([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let o of e){let i=o.moduleName??"",s=t.get(i);s?(s.modulePath=o.modulePath,s.moduleDependencies=o):s=this.createMinimalModelFromDepsItem(o),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let o=new Map(r.map(s=>[s.moduleName??"",s])),i=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=o.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,o.delete(a)),i.push(s)}for(let[,s]of o)i.push(this.createMinimalModelFromDepsItem(s));return i}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=sr(fi.join(t,"default/openharmony/ets/build-tools/ets-loader")),o=sr(fi.join(t,"default/openharmony/ets/api")),i=sr(fi.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=o,s.hosSdkPath=i}sendRequest(e){switch(e.method){case w.HOVER:this.handleHoverRequest(e);break;case w.DEFINITION:this.handleDefinitionRequest(e);break;case w.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"||!kt(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(w.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"||!kt(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(w.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"||!kt(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(w.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(!Pc(e)){d.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case w.DID_OPEN:this.handleDidOpenNotification(e);break;case w.DID_CHANGE:this.handleDidChangeNotification(e);break;case w.DID_CLOSE:this.handleDidCloseNotification(e);break;case w.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:this.handleDidChangePackageDependencies(e);break;case w.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(!jc(r)||!mi(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(Fc)){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 $e from"path";import{createHash as dh}from"crypto";import{EventEmitter as uh}from"events";var Or=class extends uh{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=S.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=S.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=S.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=S.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=$e.join(this.projectRoot,A.OH_PACKAGE_JSON5);Te.existsSync(r)&&t.push(r);let o=this.parseModulesFromBuildProfile();for(let i of o){let s=S.resolvePathWithinRoot(this.projectRoot,i.srcPath),a=$e.join(s,A.OH_PACKAGE_JSON5);Te.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return $e.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Te.readFileSync(t,"utf-8");return dh("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:$e.basename(t),relativePath:$e.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 Be from"fs";import*as pe from"path";import{createHash as ph}from"crypto";import{EventEmitter as mh}from"events";var Nr=class extends mh{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=pe.join(t,cn)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!Be.existsSync(this.depMapDir)){d.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=Be.watch(this.depMapDir,{recursive:!0},(t,r)=>this.onDirEvent(t,r)),this.dirWatcher.on("error",t=>{d.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){d.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),d.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return V(pe.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===ot)i="dep-map-json";else{let a=o.match(/^([^/]+)\/oh-package\.json5$/);i=a?`module:${a[1]}`:""}if(!i)return;let s=pe.join(this.depMapDir,r);Be.existsSync(s)&&this.scheduleDebouncedFullScan()}stop(){this.dirWatcher&&(this.dirWatcher.close(),this.dirWatcher=null),this.fullScanTimer&&(clearTimeout(this.fullScanTimer),this.fullScanTimer=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.coalesceTimer&&(clearTimeout(this.coalesceTimer),this.coalesceTimer=null),this.pendingTags=[],this.pendingRenames=[],this.contentHashes.clear(),this.initialScanDone=!1,d.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=pe.join(this.depMapDir,A.OH_PACKAGE_JSON5),r=pe.join(this.depMapDir,ot),o=this.parseModulesFromDepMap(),i=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...o.map(s=>({path:pe.join(this.depMapDir,s.name,A.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of i){if(!Be.existsSync(s))continue;let c=this.canonicalPath(s),l=this.computeFileHash(s);if(!l)continue;let u=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,l);continue}u!==l&&(this.contentHashes.set(c,l),d.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=pe.join(this.depMapDir,ot);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 V(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(i=>[i.name,i])),o=new Map(t.map(i=>[this.normalizeSrcPath(i.srcPath),i]));return{byName:r,bySrcPath:o}}detectModuleRenames(t,r,o,i){for(let[s,a]of t){let c=r.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),o.add(a.name),i.add(c.name);let l=pe.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=pe.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=Be.readFileSync(t,"utf-8");return ph("sha256").update(r).digest("hex")}catch{return null}}};import*as $c from"os";import*as Bc from"path";import{spawn as fh}from"child_process";var hh=600*1e3;function gh(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 Lr(n){return n.join("")}function yh(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
1240
1241
|
Output so far:
|
|
1241
|
-
`+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function
|
|
1242
|
+
`+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function vh(n,e,t){return new Promise(r=>{let o=fh(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:i,stderr:s}=gh(o),a=setTimeout(()=>{o.kill();let c=[Lr(i),Lr(s)].filter(Boolean).join(`
|
|
1242
1243
|
`).trim();r({success:!1,output:`Build process timeout after 10 minutes.
|
|
1243
1244
|
Output so far:
|
|
1244
|
-
`+c,exitCode:-1})},
|
|
1245
|
-
`).trim()||"";r(
|
|
1245
|
+
`+c,exitCode:-1})},hh);o.on("close",(c,l)=>{clearTimeout(a);let u=[Lr(i),Lr(s)].filter(Boolean).join(`
|
|
1246
|
+
`).trim()||"";r(yh(c,l,u))}),o.on("error",c=>{clearTimeout(a),r({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function hi(n,e,t,r,o){let i={...process.env,DEVECO_SDK_HOME:r};return I()&&(i.HVIGOR_USER_HOME=Bc.join($c.homedir(),".hvigor")),await vh([e,[t,...o]],n,i)}var wh=["--sync","-p","product=default","--analyze=normal","--parallel","--incremental","--no-daemon"];async function Wc(n,e){try{return(await hi(n,e.nodePath,e.hvigorJsPath,e.sdkPath,wh)).success}catch(t){return d.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}import{spawn as bh}from"child_process";var Sh=["install","--all"];async function Ph(n,e,t,r){return new Promise(o=>{let i=bh(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(`
|
|
1246
1247
|
`);o({exitCode:c??-1,output:l})}),i.on("error",c=>{let l=[s,a].filter(Boolean).join(`
|
|
1247
1248
|
`);o({exitCode:-1,output:l+`
|
|
1248
|
-
`+c.message})})})}function
|
|
1249
|
-
`):"\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=be.isAbsolute(i)?i:be.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 mc(500);try{let i=await this.checkFile(o);r.push(
|
|
1249
|
+
`+c.message})})})}function Eh(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>d.info("[ohpm] %s",e))}async function Uc(n,e){try{let{exitCode:t,output:r}=await Ph(e.nodePath,[e.ohpmJsPath,...Sh],n,e.sdkPath);return Eh(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 zc={UNINITIALIZED:-32099,UNKNOWN:-32e3},mn=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,zc.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,zc.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var Rt=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 vs(e,async()=>await Uc(e,t)?await Wc(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 Mr(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:w.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();d.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?mn.uninitialized(t):mn.unknown();this.onMessage({jsonrpc:O,method:w.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:w.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Or(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Nr(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:w.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT,params:{moduleSet:r}}),this.onMessage({jsonrpc:O,method:w.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 Ih=120*1e3,Ch=10080*60*1e3,Dh=7200*60*1e3,Mt=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:gi.object({files:gi.array(gi.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=we(e),{logPath:i,indexPath:s}=this.getLogAndIndexPath(o);setImmediate(()=>{ai(s,Ch,"[ArkTS-Check]"),ai(i,Dh,"[ArkTS-Check]")}),Ic(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 Rt({sdkPath:l,arktsLangServerPath:r,workspaceRoot:V(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(rn),this.manager.start([]).catch(E=>{let C=E instanceof Error?E:new Error(String(E));this.failInit(C)})})}resolveProjectAndDeveco(){let e=Ce(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=tn(nt(e)),r=si(e),o=await xe.promises.readFile(e,"utf8"),s=`deveco.apptool.${be.extname(e).replace(/^\./,"")||"plaintext"}`,a=new Promise((l,u)=>{let h=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&u(new Error("Wait for diagnostics timeout"))},Ih);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(`
|
|
1250
|
+
`):"\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=be.isAbsolute(i)?i:be.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 mc(500);try{let i=await this.checkFile(o);r.push(Ah(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(`
|
|
1250
1251
|
`)),t.length>0&&r.push(t.join(`
|
|
1251
1252
|
`));let o=r.join(`
|
|
1252
|
-
`).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(rn),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=tn(e),r=this.popDiagnosticWaiter(t);if(r)return r;for(let o of hc(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=be.join(tr(),"ArkTSCheck"),r=be.join(t,"mapping-config.properties"),o=gc(e,r),i=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=be.join(t,"lsp-log",String(o),i),a=be.join(t,"lsp-index",String(o));return xe.mkdirSync(s,{recursive:!0}),xe.mkdirSync(a,{recursive:!0}),{logPath:we(s),indexPath:we(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function
|
|
1253
|
+
`).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(rn),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=tn(e),r=this.popDiagnosticWaiter(t);if(r)return r;for(let o of hc(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=be.join(tr(),"ArkTSCheck"),r=be.join(t,"mapping-config.properties"),o=gc(e,r),i=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=be.join(t,"lsp-log",String(o),i),a=be.join(t,"lsp-index",String(o));return xe.mkdirSync(s,{recursive:!0}),xe.mkdirSync(a,{recursive:!0}),{logPath:we(s),indexPath:we(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function Ah(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 Th}from"child_process";import*as D from"fs";import*as K from"path";import{z as yi}from"zod";var qc=60*1e3,xh=30*1e3,kh=new Set(["textDocument/didOpen","textDocument/didChange","textDocument/didClose","textDocument/didSave"]),Rh=1e3,wi=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=we(this.projectPath),o=nt(r),i=K.basename(r)||"workspace",s={processId:null,clientInfo:{name:"devecocli-mcp-server",version:"0.1.0-TD.4"},rootPath:r,rootUri:o,workspaceFolders:[{uri:o,name:i}],capabilities:{}};await this.sendRequestToClangd("initialize",s,qc),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=qc,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=D.realpathSync(e)}catch{t=e}let r=nt(t),o=fc(t),i=await D.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}`))},xh);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}kh.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
|
|
1253
1254
|
\r
|
|
1254
1255
|
`,"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
|
|
1255
1256
|
\r
|
|
1256
|
-
`);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=
|
|
1257
|
+
`);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=Mh(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 Mh(n){try{let e=new URL(n);if(e.protocol==="file:"){let t=decodeURIComponent(e.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(t)&&(t=t.slice(1)),nt(t)}}catch{}return n}function Oh(n){let e=K.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function Nh(n,e){let t=K.join(n,e.name);return e.isDirectory()?e.name===".cxx"||Vc(t):Oh(t)}function Vc(n){if(!D.existsSync(n))return!1;try{return D.readdirSync(n,{withFileTypes:!0}).some(t=>Nh(n,t))}catch{}return!1}function Gc(n){let t=new it(n).getAllModuleInfo(),r=[];for(let o of t){let i=S.resolvePathWithinRoot(n,o.srcPath);Vc(i)&&r.push(o)}return r}function Lh(n){let e=[],r=new it(n).getAllModuleInfo();for(let o of r){let i=S.resolvePathWithinRoot(n,o.srcPath),s=K.join(i,".cxx");D.existsSync(s)&&Yc(s,e)}return e}function Yc(n,e){try{let t=D.readdirSync(n,{withFileTypes:!0});for(let r of t){let o=K.join(n,r.name);r.isDirectory()?Yc(o,e):r.name==="compile_commands.json"&&e.push(o)}}catch{}}function _h(n){let e=[];for(let t of n)try{let r=D.readFileSync(t,"utf8"),o=JSON.parse(r);e.push(...o)}catch{}return e}function Hh(n,e){let t=K.join(n,...ii.slice(0,-1));D.mkdirSync(t,{recursive:!0});let r=K.join(t,"compile_commands.json");D.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function jh(n){let e=Lh(n);if(e.length>0){let t=_h(e);Hh(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 vi="/data/app/sdk.org/sdk_1.0.0";function Fh(n,e){if(!I())return;let t=nn(n);if(!D.existsSync(t))return;let r=D.readFileSync(t,"utf8");if(!r.includes(vi))return;let o=r.replaceAll(vi,e);D.writeFileSync(t,o,"utf8"),f.info(`[CppCheck] Patched SDK path in compile_commands.json: ${vi} -> ${e}`)}function $h(n){let e=new Set;for(let t of n)if(t.file)try{e.add(D.realpathSync(t.file))}catch{e.add(t.file)}return e}function Bh(n,e){try{let t=D.realpathSync(n);if(!e.has(t))return f.info(`[CppCheck] File not covered by compile_commands.json: ${n}`),!1}catch{}return!0}function Wh(n,e){if(!D.existsSync(n))return!1;try{let t=D.readFileSync(n,"utf8"),r=JSON.parse(t),o=$h(r);for(let i of e)if(!Bh(i,o))return!1;return!0}catch(t){return f.warn(`[CppCheck] Failed to read/parse compile_commands.json: ${t}`),!1}}async function Uh(n,e,t=""){let r=qh(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 zh(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=>hi(n,o,i,r,a);for(let a of e)await Uh(a,s)}function qh(n){return["--mode","module","-p",`module=${n.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"]}async function Vh(n,e){let t=Gc(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 zh(n,t,e),jh(n)}var Ot=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:yi.object({files:yi.array(yi.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(`
|
|
1257
1258
|
`):"\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(`
|
|
1258
1259
|
`)}],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(`
|
|
1259
1260
|
`),e.join(`
|
|
1260
1261
|
`)].filter(i=>i.trim().length>0).join(`
|
|
1261
|
-
`).trim()}],isError:r}}async ensureInitializedWithFiles(e){let t=we(this.projectPath),r=this.prepareCppCheck(t,e);if(
|
|
1262
|
+
`).trim()}],isError:r}}async ensureInitializedWithFiles(e){let t=we(this.projectPath),r=this.prepareCppCheck(t,e);if(Fh(t,this.toolProvider.sdkPath),r)this.client&&this.initializedProjectPath&&(f.info("[CppCheck] Re-initializing C++ project due to file changes"),await this.shutdown()),await Vh(t,this.toolProvider);else if(this.client&&this.initializedProjectPath){let o=we(this.projectPath);if(this.initializedProjectPath===o)return this.client;await this.shutdown()}return this.doEnsureInitialized()}prepareCppCheck(e,t){let r=nn(e);return D.existsSync(r)?Gc(e).length===0?(f.info("[CppCheck] No cpp modules found, no initialization needed"),!1):Wh(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 wi,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=Ce(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);return this.projectPath=e,we(e)}startPollingForClangd(e){let t=nn(e);if(D.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}D.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}`)}))},Rh)}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=nn(e),o=K.dirname(r);return{clangdPath:t,compileCommandsDir:o}}spawnClangd(e,t,r){let o=Th(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=K.isAbsolute(i)?i:K.join(r,i);if(!D.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${i}`);continue}if(!D.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${i}`);continue}if(!er(s)){t.push(`\u4E0D\u662F\u53D7\u652F\u6301\u7684 C/C++ \u6587\u4EF6: ${i}`);continue}try{o.push(D.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 Jc(n){let e=Ln(n);return d.info(`[SyncGuard] ${e.reason}`),e}var Zc=(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))(Zc||{}),Si=3,Kc=600*1e3,_r=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,li(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=Ce(t);f.info(`Constructor: findHarmonyProject('${t}') => ${o??"null"}`),this.config.projectPath=o??void 0,this.server=new Gh({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=ri(),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:bi.object({files:bi.array(bi.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=S.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(`
|
|
1262
1263
|
`)}],isError:!0}:null}let r=e.filter(o=>Hr.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(`
|
|
1263
|
-
`)}],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}=
|
|
1264
|
+
`)}],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}=Jh(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(`
|
|
1264
1265
|
`),a.join(`
|
|
1265
1266
|
`)].filter(h=>h.trim().length>0).join(`
|
|
1266
1267
|
`).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 ${Zc[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>=Si?(f.error(`Init retry limit reached (${this.initRetryCount}/${Si}), 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}/${Si})`),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(`
|
|
1267
|
-
`);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 Gh;if(await this.server.connect(e),f.info("devecocli-mcp-server started"),!this.config.debug){let t=bc();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=Ce(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 Ot(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?Ce(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=Ce(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 Mt(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=Jc(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 Rt.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>=Kc?(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 / ${Kc/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"),wc(),vc()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function Yh(n){let e=[],t=[],r=[];for(let o of n)Hr.extname(o).toLowerCase()===".ets"?e.push(o):er(o)?t.push(o):r.push(o);return{etsFiles:e,cppFiles:t,unsupported:r}}function Pi(n){return new _r(n)}async function Kh(){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=Pi({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 Xc=new Jh("serve").description("Host bundled auxiliary protocol servers");Xc.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await Kh()});var Qc=Xc;import{Command as Yv,InvalidArgumentError as ls}from"commander";import{red as mo,dim as Jv}from"colorette";import*as U from"fs";import*as Ft from"path";import Mv from"adm-zip";import Ov from"proper-lockfile";import iu from"ora";import*as me from"fs";import*as yn from"path";var We=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],st={"harmonyos-guides":"\u5F00\u53D1\u6307\u5357","harmonyos-references":"API\u53C2\u8003","best-practices":"\u6700\u4F73\u5B9E\u8DF5","harmonyos-faqs":"FAQ","harmonyos-releases":"\u7248\u672C\u8BF4\u660E","harmonyos-roadmap":"\u53D8\u66F4\u9884\u544A"};var jr="1.9.1",Ix=48*1024*1024,el=280,tl=6,nl=100,rl=3,ol=28,Ei=10,il=/API参考|APIReference/i,fn=200,sl=12,al=4,Ii=8,cl=6,Fr=700,Ci=250,Di=400,ll=1320,dl=120,ul=450,pl=250,ml=500,fl=480,hl=80,gl=200,yl=60,vl=200,wl=40,bl=200,Sl=200,Pl=40,Nt=500,El=Object.fromEntries(We.map((n,e)=>[st[n],e])),Ue=Object.fromEntries(We.map((n,e)=>[n,e]));import*as Dl from"fs";import*as x from"path";import{fileURLToPath as Al}from"url";import*as $r from"path";import{homedir as Zh}from"os";var Xh="deveco-cli";function Cl(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function Qh(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&Cl(n)!==""}function Il(){return $r.join(Zh(),".local","share",Xh)}function Br(n){let e=Wr();return Qh()?[`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 Wr(){let n=process.env.DEVECO_CLI_DATA_DIR;if(n===void 0||n==="")return Il();let e=Cl(n);return e?$r.resolve(e):Il()}var eg="docs";function Ur(){return x.join(Wr(),eg)}function Z(){return x.join(Ur(),".index")}function Tl(){return x.join(Z(),"build.lock")}function Ai(){return x.join(Z(),"build-status.json")}function zr(){return x.join(Z(),"build-meta.json")}function hn(){return x.join(Z(),"search.db")}function Lt(){return x.join(Z(),".tmp")}function tg(){return x.join(Wr(),"logs")}function _t(){return x.join(tg(),"doc-init.log")}function ng(n,e){let t=e;for(;!t.endsWith(`${x.sep}dist`)&&t!==x.dirname(t);)t=x.dirname(t);return t}function xl(n,e){return x.dirname(ng(n,e))}function rg(){let n=Al(import.meta.url),e=x.dirname(n);return n.includes(`${x.sep}dist${x.sep}`)?xl(n,e):x.join(e,"..","..","..")}function og(...n){let e=Al(import.meta.url),t=x.dirname(e);return e.includes(`${x.sep}dist${x.sep}`)?[x.join(xl(e,t),...n)]:[x.join(t,"..","..","..",...n)]}function kl(...n){for(let e of og(...n))if(Dl.existsSync(e))return e;return null}function ze(){return kl("docs.zip")}function Ti(){return kl("index.zip")}function Rl(){return x.join(rg(),"index","data")}import*as ke from"fs";import*as at from"path";var ct=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],qr=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function Ml(n){return n instanceof qr}var xi=null;function ki(n){xi=n}function Ri(){if(xi)return xi;let n=Z();if(ct.every(o=>ke.existsSync(at.join(n,o))))return n;let t=Rl();if(ct.every(o=>ke.existsSync(at.join(t,o))))return t;throw new qr("Lexicon files not found. Install the documentation index first (index.zip).")}function Ol(){Ri()}function lt(n){let e=at.join(Ri(),n);return ke.readFileSync(e,"utf-8")}function Nl(n,e){return ke.readFileSync(at.join(e,n),"utf-8")}async function Ll(n,e=Ri()){await ke.promises.mkdir(n,{recursive:!0});for(let t of ct){let r=at.join(e,t),o=at.join(n,t);await ke.promises.copyFile(r,o)}}import*as Vr from"fs";import*as _l from"path";import*as Hl from"yauzl";var gn=null;function ig(n){return new Promise((e,t)=>{Hl.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 sg(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function ag(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",o=>{let i=sg(o);i.endsWith("/")||e.set(i,o),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function cg(){gn?.zipfile.close(),gn=null}async function lg(n){let e=_l.resolve(n),t=await Vr.promises.stat(e),r=gn;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;cg();let o=await ig(e),i=await ag(o);return gn={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:o,entries:i,readChain:Promise.resolve()},gn}function dg(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 ug(n,e){let t=n.readChain,r;n.readChain=new Promise(o=>{r=o}),await t;try{return await dg(n.zipfile,e)}finally{r()}}function pg(n){let e=n.replace(/\\/g,"/").replace(/\.md$/,"");return[`docs/${e}.md`,`${e}.md`,`docs/${e}`,e]}function mg(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function jl(n){let e=ze();if(!e)throw new Error("docs.zip not found");let t=await lg(e),r=mg(t.entries,pg(n));if(!r)throw new Error(`Document not found: ${n}`);return(await ug(t,r)).toString("utf-8")}function Mi(){let n=ze();return n!==null&&Vr.existsSync(n)}import*as G from"fs";import*as qe from"path";import Fl from"adm-zip";var $l=["search.db","build-meta.json",...ct],fg=["corpus.json","corpus-offsets.json","orama.dpack"];async function hg(n){for(let e of fg)await G.promises.rm(qe.join(n,e),{force:!0})}async function gg(n){let e=await G.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await G.promises.rm(qe.join(n,t.name),{recursive:!0,force:!0})}function yg(n){let t=new Fl(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 vg(n){let e=Z();await G.promises.mkdir(e,{recursive:!0});for(let t of $l){let r=qe.join(e,t);await G.promises.rm(r,{force:!0}),await G.promises.rename(qe.join(n,t),r)}await hg(e),await G.promises.rm(Lt(),{recursive:!0,force:!0})}function Oi(){let n=Ti();return n!==null&&G.existsSync(n)}async function Bl(n){let e=Ti();if(!e)throw new Error("index.zip not found");let t=yg(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=Lt();await G.promises.rm(r,{recursive:!0,force:!0}),await G.promises.mkdir(r,{recursive:!0});let o=new Fl(e);for(let s of $l){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await G.promises.writeFile(qe.join(r,s),a.getData())}let i=JSON.parse(await G.promises.readFile(qe.join(r,"build-meta.json"),"utf-8"));if(!G.existsSync(qe.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await vg(r),await G.promises.mkdir(Ur(),{recursive:!0}),await gg(Ur()),i}import{createHash as Wl}from"crypto";import*as Ul from"fs";async function Gr(n){return new Promise((e,t)=>{let r=Wl("sha256"),o=Ul.createReadStream(n);o.on("data",i=>r.update(i)),o.on("error",t),o.on("end",()=>e(r.digest("hex")))})}function zl(n){return Wl("sha256").update(n,"utf8").digest("hex")}var Ni=null;function wg(){let n=lt("harmonyos-synonyms.json");return JSON.parse(n)}function bg(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 Sg(){let n=bg(wg()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function Pg(){return Ni||(Ni=Sg()),Ni}function Li(n,e){let t=Pg(),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 ql(n,e){let t=e?Nl(n,e):lt(n);return zl(t)}function Yr(n){return ql("harmonyos-synonyms.json",n)}function Jr(n){return ql("harmonyos-terms.txt",n)}var Eg={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function Kr(){try{let n=await me.promises.readFile(Ai(),"utf-8");return JSON.parse(n)}catch{return{...Eg}}}async function _i(n){let e=Ai();await me.promises.mkdir(yn.dirname(e),{recursive:!0}),await me.promises.writeFile(e,JSON.stringify(n,null,2))}function Vl(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 Ve(n){let t={...await Kr(),...n,updatedAt:Date.now()};return await _i(t),t}async function Hi(){let n=ze();return n?Gr(n):null}async function ji(){try{let n=await me.promises.readFile(zr(),"utf-8");return JSON.parse(n)}catch{return null}}async function Fi(n=!1){if(n)return"no-index";let e=await ji();if(!e||e.segmentCount===0)return"no-index";let t=await Hi();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==jr?"engine-upgraded":e.termsHash!==Jr()?"terms-changed":e.synonymsHash!==Yr()?"synonyms-changed":null}function vn(){if(!Mi()||!me.existsSync(hn())||!me.existsSync(zr()))return!1;let n=yn.dirname(hn());if(!ct.every(e=>me.existsSync(yn.join(n,e))))return!1;try{let e=me.readFileSync(zr(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function $i(n=!1){return n?!0:Mi()?vn()?await Fi()!==null:!0:!1}async function Gl(){let n=await Kr();return["installing","indexing","persisting"].includes(n.state)}import*as Y from"fs";import*as Xd from"os";import*as ne from"path";var Yl=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),Bi=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),Jl=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"]),Kl=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 Ig=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,Cg=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,Dg=/[A-Z][a-zA-Z0-9]{2,}/g,Ag=/@[A-Z][a-zA-Z0-9]*/g,Tg=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,Zl=6,xg=/^[a-z][a-z0-9]{2,}$/,kg=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,Rg=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,Mg=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,Og=/^[A-Z][a-zA-Z0-9]+$/;function Ng(n){return`"${n.replace(/"/g,'""')}"`}function bn(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(Ng).join(` ${e} `)}function wn(n){return bn(n,"OR")}function Xl(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?wn([...t,...r]):`(${wn(t)}) AND (${wn(r)})`}function Sn(n){return Rg.test(n)}function Ql(n){return Mg.test(n)&&n.length>=Zl}function Lg(n){return Og.test(n)}function Pn(n){return Sn(n)||Ql(n)||Lg(n)}function _g(n){let e=n.trim().toLowerCase();return Kl.has(e)?!1:Yl.has(e)}function Hg(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function Zr(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function Wi(n){return[...n.matchAll(Ig)].map(e=>e[0])}function Ui(n,e=Zl){let t=[];for(let r of n.matchAll(Cg))r[0].length>=e&&t.push(r[0]);return t}function Ht(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 fe(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function jg(n){let e=new Set;fe(e,n);let t=Zr(n);return t&&fe(e,t),Ht([...e])}function Xr(n){if(Sn(n))return jg(n);let e=new Set;return fe(e,n),Ht([...e])}function Qr(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(kg);if(!t)return null;let r=t[1].toLowerCase(),o=t[2].toLowerCase();if(!xg.test(r)||Jl.has(r)||!_g(o))return null;let i=Hg(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function zi(n){let e=Qr(n.trim());return!e||e.second!=="manager"?null:e}function Fg(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function ed(n){let e=n.trim(),t=zi(e);if(t&&Bi.has(t.first))return!0;if(Ql(e)){let r=Fg(e);return r!==null&&Bi.has(r)}return!1}function qi(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 Vi(n){let e=n.trim();if(Pn(e))return Xr(e);let t=new Set;for(let r of Wi(n)){fe(t,r);let o=Zr(r);o&&fe(t,o)}for(let r of Ui(n))fe(t,r);for(let r of n.matchAll(Ag))t.add(r[0]);for(let r of n.matchAll(Tg))t.add(r[0]);for(let r of n.matchAll(Dg))r[0].length>=4&&t.add(r[0]);return Ht([...t])}function td(n){let e=n.trim();if(Pn(e))return Xr(e);let t=new Set,r=Qr(e);r&&fe(t,r.camelCase);for(let o of Vi(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 Ht([...t])}function nd(n){return Pn(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 rd(n){return N.pureApiSymbol.test(n.trim())}function En(n){let e=n.trim();return N.stageModelExact.test(e)||N.stageModelEnglishExact.test(e)}function od(n){let e=[];return En(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 id(n){return En(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var $g=[{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=>En(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!En(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 Bg(n,e){for(let{catalog:t,multiplier:r}of e){let o=Ue[t];n.set(o,(n.get(o)??1)*r)}}function sd(n,e){for(let t of $g)t.matches(n)&&Bg(e,t.weights)}function ad(n,e){if(e!==void 0)return!1;let t=n.trim();return Sn(t)||N.pureApiSymbol.test(t)||ed(t)}function cd(n){let e=n.trim();if(Sn(e)||N.pureApiSymbol.test(e))return"harmonyos-references";if(En(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 eo=null,Yi=null,Ji=null,ld=!1,Gi=null;function Wg(){if(eo)return eo;let n=lt("harmonyos-stopwords.txt");return eo=new Set(n.split(`
|
|
1268
|
-
`).map(e=>e.trim()).filter(Boolean)),eo}function
|
|
1268
|
+
`);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 Yh;if(await this.server.connect(e),f.info("devecocli-mcp-server started"),!this.config.debug){let t=bc();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=Ce(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 Ot(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?Ce(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=Ce(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 Mt(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=Jc(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 Rt.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>=Kc?(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 / ${Kc/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"),wc(),vc()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function Jh(n){let e=[],t=[],r=[];for(let o of n)Hr.extname(o).toLowerCase()===".ets"?e.push(o):er(o)?t.push(o):r.push(o);return{etsFiles:e,cppFiles:t,unsupported:r}}function Pi(n){return new _r(n)}async function Zh(){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=Pi({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 Xc=new Kh("serve").description("Host bundled auxiliary protocol servers");Xc.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await Zh()});var Qc=Xc;import{Command as Jv,InvalidArgumentError as ls}from"commander";import{red as mo,dim as Kv}from"colorette";import*as U from"fs";import*as Ft from"path";import Ov from"adm-zip";import Nv from"proper-lockfile";import iu from"ora";import*as me from"fs";import*as yn from"path";var We=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],st={"harmonyos-guides":"\u5F00\u53D1\u6307\u5357","harmonyos-references":"API\u53C2\u8003","best-practices":"\u6700\u4F73\u5B9E\u8DF5","harmonyos-faqs":"FAQ","harmonyos-releases":"\u7248\u672C\u8BF4\u660E","harmonyos-roadmap":"\u53D8\u66F4\u9884\u544A"};var jr="1.9.1",Cx=48*1024*1024,el=280,tl=6,nl=100,rl=3,ol=28,Ei=10,il=/API参考|APIReference/i,fn=200,sl=12,al=4,Ii=8,cl=6,Fr=700,Ci=250,Di=400,ll=1320,dl=120,ul=450,pl=250,ml=500,fl=480,hl=80,gl=200,yl=60,vl=200,wl=40,bl=200,Sl=200,Pl=40,Nt=500,El=Object.fromEntries(We.map((n,e)=>[st[n],e])),Ue=Object.fromEntries(We.map((n,e)=>[n,e]));import*as Dl from"fs";import*as x from"path";import{fileURLToPath as Al}from"url";import*as $r from"path";import{homedir as Xh}from"os";var Qh="deveco-cli";function Cl(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function eg(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&Cl(n)!==""}function Il(){return $r.join(Xh(),".local","share",Qh)}function Br(n){let e=Wr();return eg()?[`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 Wr(){let n=process.env.DEVECO_CLI_DATA_DIR;if(n===void 0||n==="")return Il();let e=Cl(n);return e?$r.resolve(e):Il()}var tg="docs";function Ur(){return x.join(Wr(),tg)}function Z(){return x.join(Ur(),".index")}function Tl(){return x.join(Z(),"build.lock")}function Ai(){return x.join(Z(),"build-status.json")}function zr(){return x.join(Z(),"build-meta.json")}function hn(){return x.join(Z(),"search.db")}function Lt(){return x.join(Z(),".tmp")}function ng(){return x.join(Wr(),"logs")}function _t(){return x.join(ng(),"doc-init.log")}function rg(n,e){let t=e;for(;!t.endsWith(`${x.sep}dist`)&&t!==x.dirname(t);)t=x.dirname(t);return t}function xl(n,e){return x.dirname(rg(n,e))}function og(){let n=Al(import.meta.url),e=x.dirname(n);return n.includes(`${x.sep}dist${x.sep}`)?xl(n,e):x.join(e,"..","..","..")}function ig(...n){let e=Al(import.meta.url),t=x.dirname(e);return e.includes(`${x.sep}dist${x.sep}`)?[x.join(xl(e,t),...n)]:[x.join(t,"..","..","..",...n)]}function kl(...n){for(let e of ig(...n))if(Dl.existsSync(e))return e;return null}function ze(){return kl("docs.zip")}function Ti(){return kl("index.zip")}function Rl(){return x.join(og(),"index","data")}import*as ke from"fs";import*as at from"path";var ct=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],qr=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function Ml(n){return n instanceof qr}var xi=null;function ki(n){xi=n}function Ri(){if(xi)return xi;let n=Z();if(ct.every(o=>ke.existsSync(at.join(n,o))))return n;let t=Rl();if(ct.every(o=>ke.existsSync(at.join(t,o))))return t;throw new qr("Lexicon files not found. Install the documentation index first (index.zip).")}function Ol(){Ri()}function lt(n){let e=at.join(Ri(),n);return ke.readFileSync(e,"utf-8")}function Nl(n,e){return ke.readFileSync(at.join(e,n),"utf-8")}async function Ll(n,e=Ri()){await ke.promises.mkdir(n,{recursive:!0});for(let t of ct){let r=at.join(e,t),o=at.join(n,t);await ke.promises.copyFile(r,o)}}import*as Vr from"fs";import*as _l from"path";import*as Hl from"yauzl";var gn=null;function sg(n){return new Promise((e,t)=>{Hl.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 ag(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function cg(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",o=>{let i=ag(o);i.endsWith("/")||e.set(i,o),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function lg(){gn?.zipfile.close(),gn=null}async function dg(n){let e=_l.resolve(n),t=await Vr.promises.stat(e),r=gn;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;lg();let o=await sg(e),i=await cg(o);return gn={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:o,entries:i,readChain:Promise.resolve()},gn}function ug(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 pg(n,e){let t=n.readChain,r;n.readChain=new Promise(o=>{r=o}),await t;try{return await ug(n.zipfile,e)}finally{r()}}function mg(n){let e=n.replace(/\\/g,"/").replace(/\.md$/,"");return[`docs/${e}.md`,`${e}.md`,`docs/${e}`,e]}function fg(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function jl(n){let e=ze();if(!e)throw new Error("docs.zip not found");let t=await dg(e),r=fg(t.entries,mg(n));if(!r)throw new Error(`Document not found: ${n}`);return(await pg(t,r)).toString("utf-8")}function Mi(){let n=ze();return n!==null&&Vr.existsSync(n)}import*as G from"fs";import*as qe from"path";import Fl from"adm-zip";var $l=["search.db","build-meta.json",...ct],hg=["corpus.json","corpus-offsets.json","orama.dpack"];async function gg(n){for(let e of hg)await G.promises.rm(qe.join(n,e),{force:!0})}async function yg(n){let e=await G.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await G.promises.rm(qe.join(n,t.name),{recursive:!0,force:!0})}function vg(n){let t=new Fl(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 wg(n){let e=Z();await G.promises.mkdir(e,{recursive:!0});for(let t of $l){let r=qe.join(e,t);await G.promises.rm(r,{force:!0}),await G.promises.rename(qe.join(n,t),r)}await gg(e),await G.promises.rm(Lt(),{recursive:!0,force:!0})}function Oi(){let n=Ti();return n!==null&&G.existsSync(n)}async function Bl(n){let e=Ti();if(!e)throw new Error("index.zip not found");let t=vg(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=Lt();await G.promises.rm(r,{recursive:!0,force:!0}),await G.promises.mkdir(r,{recursive:!0});let o=new Fl(e);for(let s of $l){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await G.promises.writeFile(qe.join(r,s),a.getData())}let i=JSON.parse(await G.promises.readFile(qe.join(r,"build-meta.json"),"utf-8"));if(!G.existsSync(qe.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await wg(r),await G.promises.mkdir(Ur(),{recursive:!0}),await yg(Ur()),i}import{createHash as Wl}from"crypto";import*as Ul from"fs";async function Gr(n){return new Promise((e,t)=>{let r=Wl("sha256"),o=Ul.createReadStream(n);o.on("data",i=>r.update(i)),o.on("error",t),o.on("end",()=>e(r.digest("hex")))})}function zl(n){return Wl("sha256").update(n,"utf8").digest("hex")}var Ni=null;function bg(){let n=lt("harmonyos-synonyms.json");return JSON.parse(n)}function Sg(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 Pg(){let n=Sg(bg()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function Eg(){return Ni||(Ni=Pg()),Ni}function Li(n,e){let t=Eg(),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 ql(n,e){let t=e?Nl(n,e):lt(n);return zl(t)}function Yr(n){return ql("harmonyos-synonyms.json",n)}function Jr(n){return ql("harmonyos-terms.txt",n)}var Ig={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function Kr(){try{let n=await me.promises.readFile(Ai(),"utf-8");return JSON.parse(n)}catch{return{...Ig}}}async function _i(n){let e=Ai();await me.promises.mkdir(yn.dirname(e),{recursive:!0}),await me.promises.writeFile(e,JSON.stringify(n,null,2))}function Vl(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 Ve(n){let t={...await Kr(),...n,updatedAt:Date.now()};return await _i(t),t}async function Hi(){let n=ze();return n?Gr(n):null}async function ji(){try{let n=await me.promises.readFile(zr(),"utf-8");return JSON.parse(n)}catch{return null}}async function Fi(n=!1){if(n)return"no-index";let e=await ji();if(!e||e.segmentCount===0)return"no-index";let t=await Hi();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==jr?"engine-upgraded":e.termsHash!==Jr()?"terms-changed":e.synonymsHash!==Yr()?"synonyms-changed":null}function vn(){if(!Mi()||!me.existsSync(hn())||!me.existsSync(zr()))return!1;let n=yn.dirname(hn());if(!ct.every(e=>me.existsSync(yn.join(n,e))))return!1;try{let e=me.readFileSync(zr(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function $i(n=!1){return n?!0:Mi()?vn()?await Fi()!==null:!0:!1}async function Gl(){let n=await Kr();return["installing","indexing","persisting"].includes(n.state)}import*as Y from"fs";import*as Xd from"os";import*as ne from"path";var Yl=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),Bi=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),Jl=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"]),Kl=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 Cg=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,Dg=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,Ag=/[A-Z][a-zA-Z0-9]{2,}/g,Tg=/@[A-Z][a-zA-Z0-9]*/g,xg=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,Zl=6,kg=/^[a-z][a-z0-9]{2,}$/,Rg=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,Mg=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,Og=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,Ng=/^[A-Z][a-zA-Z0-9]+$/;function Lg(n){return`"${n.replace(/"/g,'""')}"`}function bn(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(Lg).join(` ${e} `)}function wn(n){return bn(n,"OR")}function Xl(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?wn([...t,...r]):`(${wn(t)}) AND (${wn(r)})`}function Sn(n){return Mg.test(n)}function Ql(n){return Og.test(n)&&n.length>=Zl}function _g(n){return Ng.test(n)}function Pn(n){return Sn(n)||Ql(n)||_g(n)}function Hg(n){let e=n.trim().toLowerCase();return Kl.has(e)?!1:Yl.has(e)}function jg(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function Zr(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function Wi(n){return[...n.matchAll(Cg)].map(e=>e[0])}function Ui(n,e=Zl){let t=[];for(let r of n.matchAll(Dg))r[0].length>=e&&t.push(r[0]);return t}function Ht(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 fe(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function Fg(n){let e=new Set;fe(e,n);let t=Zr(n);return t&&fe(e,t),Ht([...e])}function Xr(n){if(Sn(n))return Fg(n);let e=new Set;return fe(e,n),Ht([...e])}function Qr(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(Rg);if(!t)return null;let r=t[1].toLowerCase(),o=t[2].toLowerCase();if(!kg.test(r)||Jl.has(r)||!Hg(o))return null;let i=jg(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function zi(n){let e=Qr(n.trim());return!e||e.second!=="manager"?null:e}function $g(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function ed(n){let e=n.trim(),t=zi(e);if(t&&Bi.has(t.first))return!0;if(Ql(e)){let r=$g(e);return r!==null&&Bi.has(r)}return!1}function qi(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 Vi(n){let e=n.trim();if(Pn(e))return Xr(e);let t=new Set;for(let r of Wi(n)){fe(t,r);let o=Zr(r);o&&fe(t,o)}for(let r of Ui(n))fe(t,r);for(let r of n.matchAll(Tg))t.add(r[0]);for(let r of n.matchAll(xg))t.add(r[0]);for(let r of n.matchAll(Ag))r[0].length>=4&&t.add(r[0]);return Ht([...t])}function td(n){let e=n.trim();if(Pn(e))return Xr(e);let t=new Set,r=Qr(e);r&&fe(t,r.camelCase);for(let o of Vi(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 Ht([...t])}function nd(n){return Pn(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 rd(n){return N.pureApiSymbol.test(n.trim())}function En(n){let e=n.trim();return N.stageModelExact.test(e)||N.stageModelEnglishExact.test(e)}function od(n){let e=[];return En(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 id(n){return En(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var Bg=[{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=>En(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!En(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 Wg(n,e){for(let{catalog:t,multiplier:r}of e){let o=Ue[t];n.set(o,(n.get(o)??1)*r)}}function sd(n,e){for(let t of Bg)t.matches(n)&&Wg(e,t.weights)}function ad(n,e){if(e!==void 0)return!1;let t=n.trim();return Sn(t)||N.pureApiSymbol.test(t)||ed(t)}function cd(n){let e=n.trim();if(Sn(e)||N.pureApiSymbol.test(e))return"harmonyos-references";if(En(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 eo=null,Yi=null,Ji=null,ld=!1,Gi=null;function Ug(){if(eo)return eo;let n=lt("harmonyos-stopwords.txt");return eo=new Set(n.split(`
|
|
1269
|
+
`).map(e=>e.trim()).filter(Boolean)),eo}function zg(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 dd(n){let e=Ug(),t=[];for(let r of zg(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 qg(){let n=await import("jieba-wasm");Yi=n.cut,Ji=n.cut_for_search;let e=lt("harmonyos-terms.txt");n.with_dict(e)}async function Vg(){let{Jieba:n}=await import("@node-rs/jieba"),e=lt("harmonyos-terms.txt"),t=n.withDict(Buffer.from(e,"utf-8"));Yi=t.cut.bind(t),Ji=t.cutForSearch.bind(t)}async function Ge(){if(!ld)return Gi||(Gi=(I()?qg():Vg()).then(()=>{ld=!0})),Gi}async function Gg(n){return await Ge(),dd(Ji(n,!0))}async function ud(n){return await Ge(),dd(Yi(n,!0))}async function to(n,e){let t=n.trim();if(!t||e<=0)return"";let r=(await Gg(t)).join(" ");return r.length<=e?r:r.slice(0,e)}async function Yg(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 no(n){let e=!!n.sectionTitle.trim(),t=n.titleTokens.trim(),r=e?fl:ll,o=e?gl:ul,i=e?await Yg(n.apiSymbols,o):await to(n.apiSymbols.join(" "),o),a=(await Promise.all([to(t,e?hl:dl),Promise.resolve(i),to(n.headingsText,e?yl:pl),to(n.bodySample,e?vl:ml)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}function Jg(n){return n.join(" ").replace(/\s+/g," ").trim().slice(0,fn)}function Ki(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>=sl))break}return r}function Kg(n){return n.length>=2&&n.length<=al}function Zg(n,e){let t=Li(n,Ii),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=Ki(o,i);return{rawQuery:n,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:Xl(o,i)}}function Xg(n,e){let t=Ki(Xr(e),[]);return{rawQuery:n,expandedQuery:n,tokens:t,preferAnd:!1,ftsMatch:wn(t)}}async function pd(n){let e=Jg(n),t=e.trim(),r=id(t);if(r)return{rawQuery:e,expandedQuery:r.expandedQuery,tokens:r.tokens,preferAnd:!1};let o=Qr(t);if(o)return Zg(e,o);if(Pn(t))return Xg(e,t);let i=od(e),s=[...Vi(e),...i],c=nd(t)?e:Li(e,Ii),l=await ud(c),u=Ki(s,l);return{rawQuery:e,expandedQuery:c,tokens:u,preferAnd:i.length===0&&Kg(u)}}var md=["harmonyos-releases","harmonyos-roadmap"],Qg=new Set(md.map(n=>Ue[n])),ey=md.map(n=>`${st[n]}/`);function ty(n){return Qg.has(n)}function ny(n){return ey.some(e=>n.startsWith(e))}function fd(n){let e=[],t=[];for(let r of n)ty(r.catalog_id)?t.push(r):e.push(r);return[...e,...t]}function hd(n){let e=[],t=[];for(let r of n)ny(r.documentId)?t.push(r):e.push(r);return[...e,...t]}var ry=[{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 In(n,e,t){let r=Ue[e];n.set(r,(n.get(r)??1)*t)}function oy(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)){In(e,"harmonyos-guides",1.45),In(e,"harmonyos-references",1.35);return}(o||i)&&In(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&In(e,"harmonyos-references",1.75)}function gd(n){let e=new Map,t=n.trim();if(!t)return e;let r=rd(t);oy(t,e),sd(t,e);for(let o of ry)o.pattern.test(t)&&(o.skipForPureApiSymbol&&r||In(e,o.catalog,o.multiplier));return e}function yd(n){return cd(n)}var iy=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function vd(n,e){let t=-1;for(let r of iy){let o=n.lastIndexOf(r);o>t&&(t=o)}return t>=e?t:-1}function wd(n,e){let t=n.trim();if(t.length<=e)return{text:t,excerptTruncated:!1};let r=t.slice(0,e),o=vd(r,e-20),i=o>=0?o:e;return{text:t.slice(0,i).trimEnd(),excerptTruncated:!0}}function bd(n,e,t={}){let{maxLen:r=Sl,contextChars:o=Pl,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(ce=>ce.trim()).filter(Boolean),c=0;for(let ce of a){let kn=s.toLowerCase().indexOf(ce.toLowerCase());if(kn>=0){c=kn;break}}let l=Math.max(0,c-o),u=Math.min(s.length,l+r),h=s.slice(l,u),E=vd(h,r-25);E>=0&&(u=l+E);let C=s.slice(l,u).trim(),M=l>0?"...":"",Q=u<s.length||i?"...":"";return`${M}${C}${Q}`}var sy=`
|
|
1269
1270
|
SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
|
|
1270
1271
|
d.catalog_id, bm25(segments_fts) AS bm25
|
|
1271
1272
|
FROM segments_fts
|
|
@@ -1274,7 +1275,7 @@ Output so far:
|
|
|
1274
1275
|
WHERE segments_fts MATCH ?
|
|
1275
1276
|
ORDER BY bm25(segments_fts)
|
|
1276
1277
|
LIMIT ?
|
|
1277
|
-
`,
|
|
1278
|
+
`,ay=`
|
|
1278
1279
|
SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
|
|
1279
1280
|
d.catalog_id, bm25(segments_fts) AS bm25
|
|
1280
1281
|
FROM segments_fts
|
|
@@ -1283,7 +1284,7 @@ Output so far:
|
|
|
1283
1284
|
WHERE segments_fts MATCH ? AND d.catalog_id = ?
|
|
1284
1285
|
ORDER BY bm25(segments_fts)
|
|
1285
1286
|
LIMIT ?
|
|
1286
|
-
`,
|
|
1287
|
+
`,cy=3.5,ly=1.4,dy=4,uy=1.8,py=1.35,my=3.5,fy=1.8,hy=120,Sd=6;function Xi(n){return n.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function gy(n){return n.split(/[^\p{L}\p{N}@.]+/u).map(Xi).filter(e=>e.length>=2)}function yy(n,e){return e.length>1&&e.every(t=>n.includes(t))}function vy(n){return/^[a-z0-9]{1,4}$/.test(n.trim().toLowerCase())}function wy(n,e){return n===e?my:n.startsWith(e)||n.includes(`@ohos.${e}`)?fy:1}function by(n,e){let t=Xi(e);if(t.length<2)return 1;let r=Xi(n.doc_title);if(vy(e))return wy(r,t);if(r.includes(t))return dy;if(t.length>=Sd&&r.includes(t.slice(0,Sd)))return uy;let o=gy(e);return yy(r,o)?py:1}function Sy(n,e){return e<=1?n:n<0?n*e:n/e}function ro(n,e,t,r){let o=n.bm25/(e.get(n.catalog_id)??1);return o=Sy(o,by(n,t)),r&&qi(n.doc_title,n.section_title,r)&&(o/=cy,n.catalog_id===Ue["harmonyos-references"]&&(o/=ly)),o}function Zi(n,e,t,r){return n.reduce((o,i)=>ro(i,e,t,r)<ro(o,e,t,r)?i:o)}function Py(n,e){return e.some(t=>n.section_title.includes(t)||n.doc_title.includes(t))}function Ey(n,e,t,r,o){if(o){let i=n.filter(s=>qi(s.doc_title,s.section_title,o));if(i.length>0)return Zi(i,t,r,o)}if(e.length>0){let i=n.filter(s=>Py(s,e));if(i.length>0)return Zi(i,t,r,o)}return Zi(n,t,r,o)}function Pd(n,e,t,r,o){let i=gd(e),s=td(e),c=zi(e)?.camelCase,l=new Map;for(let C of n){let M=l.get(C.document_id)??[];M.push(C),l.set(C.document_id,M)}let u=[];for(let C of l.values())u.push(Ey(C,s,i,t,c));let h=u.sort((C,M)=>ro(C,i,t,c)-ro(M,i,t,c));return(o?fd(h):h).slice(0,r)}function oo(n,e,t,r,o,i){let s=e?Ue[e]:void 0,a=Math.max(t,t*cl,hy),c=s===void 0?n.all(sy,r,a):n.all(ay,r,s,a);return(s===void 0?Pd(c,i,o,t,!0):Pd(c,i,o,t,!1)).map(u=>({title:u.doc_title,documentId:u.document_id,sectionTitle:u.section_title||void 0,snippet:bd(u.lead_text,o,{excerptTruncated:!!u.excerpt_truncated})}))}var io=`
|
|
1287
1288
|
CREATE TABLE documents (
|
|
1288
1289
|
id INTEGER PRIMARY KEY,
|
|
1289
1290
|
document_id TEXT NOT NULL UNIQUE,
|
|
@@ -1321,18 +1322,18 @@ CREATE TRIGGER segments_au AFTER UPDATE ON segments BEGIN
|
|
|
1321
1322
|
END;
|
|
1322
1323
|
|
|
1323
1324
|
CREATE INDEX segments_doc_id_idx ON segments(doc_id);
|
|
1324
|
-
`;var jt=null,Qi=null;function
|
|
1325
|
+
`;var jt=null,Qi=null;function Iy(){jt?.close(),jt=null,Qi=null}function Cy(n,e){if(jt&&Qi===e)return jt;jt?.close();let t=new n(e,{readonly:!0,fileMustExist:!0});return jt=t,Qi=e,t.pragma("mmap_size = 268435456"),t.pragma("cache_size = -8000"),t.pragma("query_only = ON"),t}function Dy(n,e){let t=new n(e);return t.pragma("journal_mode = OFF"),t.pragma("synchronous = OFF"),t.pragma("temp_store = MEMORY"),t.exec(io),t}function Ay(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(`
|
|
1325
1326
|
INSERT INTO documents(document_id, catalog_id, doc_title)
|
|
1326
1327
|
VALUES (?, ?, ?)
|
|
1327
|
-
`).run(t.documentId,t.catalogId,t.docTitle),c=Number(a.lastInsertRowid);return e.set(t.documentId,c),c}async function
|
|
1328
|
+
`).run(t.documentId,t.catalogId,t.docTitle),c=Number(a.lastInsertRowid);return e.set(t.documentId,c),c}async function Ty(n,e,t,r){await Ge();let o=Dy(n,e),i=new Map,s=o.prepare(`
|
|
1328
1329
|
INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated)
|
|
1329
1330
|
VALUES (?, ?, ?, ?, ?)
|
|
1330
|
-
`),a=t.length;for(let c=0;c<a;c+=Nt){let l=t.slice(c,c+Nt),u=await Promise.all(l.map(async E=>({source:E,searchText:await no(E)})));o.transaction(E=>{for(let C of E){let M=Dy(o,i,C.source);s.run(M,C.source.sectionTitle,C.source.leadText,C.searchText,C.source.excerptTruncated?1:0)}})(u),await r?.(Math.min(c+l.length,a),a)}o.exec("ANALYZE"),o.exec("VACUUM"),o.close()}function Ty(n,e,t,r,o,i,s){let a=Iy(n,e);return oo({all(c,...l){return a.prepare(c).all(...l)}},t,r,o,i,s)}async function Ed(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:Ey,buildSearchIndex:(t,r,o)=>Ay(e,t,r,o),searchIndex:(t,r,o,i,s,a,c)=>Promise.resolve(Ty(e,i,r,o,s,a,c))}}import{readFile as xy,stat as ky,writeFile as Ry}from"fs/promises";var es=null,Ye=null;async function ts(){return es||(es=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),es}function My(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 Oy(n){let e=await ky(n);if(Ye&&Ye.dbPath===n&&Ye.mtimeMs===e.mtimeMs)return Ye.db;Ye?.db.close();let t=await ts(),r=t.capi,o=t.wasm,i=new Uint8Array(await xy(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),Ye={dbPath:n,mtimeMs:e.mtimeMs,db:a},a}function Id(){Ye?.db.close(),Ye=null}async function Ny(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 Ly(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 _y(n,e,t){await Ge();let r=await ts(),o=new r.oo1.DB(":memory:","c");o.exec(io);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=Ly(o,i,s),l=e.length;for(let h=0;h<l;h+=Nt){let E=e.slice(h,h+Nt),C=await Promise.all(E.map(async M=>({source:M,searchText:await no(M)})));await Ny(o,a,c,C),await t?.(Math.min(h+E.length,l),l)}o.exec("ANALYZE");let u=r.capi.sqlite3_js_db_export(o);await Ry(n,u),o.close(),Id()}async function Hy(n,e,t,r,o,i){let s=await Oy(n);return oo(My(s),e,t,r,o,i)}async function Cd(){return await ts(),{kind:"sqlite-wasm",resetCache:Id,buildSearchIndex:_y,searchIndex:(n,e,t,r,o,i,s)=>Hy(r,e,t,o,i,s)}}var so=null,ns=null;async function jy(){try{let e=await Ed();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 Cd();return g("doc-index: using @sqlite.org/sqlite-wasm SQLite backend"),n}async function Cn(){return so||(so=jy().then(n=>(ns=n,n))),so}function Dd(){ns?.resetCache(),so=null,ns=null}async function Fy(n,e,t,r,o,i,s){let a=await Cn(),c=s??hn();return a.searchIndex(n,e,t,c,r,o,i)}function Td(){Dd()}async function xd(n,e,t){await(await Cn()).buildSearchIndex(n,e,t)}function kd(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 ao(n,e,t,r,o,i){return Fy(n,e,t,o,r.expandedQuery,r.rawQuery,i)}async function $y(n,e,t,r,o){let i=await ao(n,e,t,r,bn(r.tokens,"AND"),o);if(i.length>=t)return i;let s=await ao(n,e,t,r,bn(r.tokens,"OR"),o);return kd(i,s,t)}async function rs(n,e,t,r,o){return r.ftsMatch?ao(n,e,t,r,r.ftsMatch,o):r.preferAnd?$y(n,e,t,r,o):ao(n,e,t,r,bn(r.tokens,"OR"),o)}async function By(n,e,t,r){let o=await rs(n,"harmonyos-references",e,t,r);if(o.length>=e)return o;let i=await rs(n,void 0,e,t,r);return kd(o,i,e)}function Ad(n,e){return e!==void 0?n:hd(n)}async function Rd(n,e,t=20,r){let o=await pd(n);if(ad(o.rawQuery,e)){let a=await By(n,t,o,r);return Ad(a,e)}let i=e??yd(o.rawQuery),s=await rs(n,i,t,o,r);return Ad(s,e)}import{unified as Fd}from"unified";import $d from"remark-parse";import Bd from"remark-gfm";import{toString as lo}from"mdast-util-to-string";var Wy=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,Uy=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,zy=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,qy=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,Vy=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function co(n){let e=n.trim(),t=e.match(qy);return t?t[1]:e}function Gy(n){let e=n.match(Wy);if(!e)return;let t=co(e[1].trim());return{displayTitle:n,symbolName:t,searchExtras:[t,e[3]]}}function Yy(n){let e=co(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 Dn(n){let e=n.trim();return e?Gy(e)??(()=>{let t=e.match(Uy);if(t){let r=t[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let t=e.match(zy);if(!t)return;let r=t[1].trim(),o=t[2].trim();return{displayTitle:e,symbolName:o,searchExtras:[r,o]}})()??Yy(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function Jy(n){if(n.length<2||n.length>36||Vy.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 Md(n){for(let e of n){let t=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(Jy(t))return t}return""}function Od(n,e,t){let r=[n,...t.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var Ky=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,An=/@[A-Z][a-zA-Z]+/g,Zy=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,Xy=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,Qy=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,ev=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),tv=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),nv=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function Wd(n,e){let t=new Set,r=[n,...e];for(let o of r){for(let i of Wi(o)){fe(t,i);let s=Zr(i);s&&fe(t,s)}for(let i of Ui(o))fe(t,i);for(let i of o.matchAll(Ky)){let s=i[0];rv(s)&&t.add(s)}for(let i of o.matchAll(An))t.add(i[0])}return Ht([...t])}function rv(n){let e=n.trim();if(!e||An.test(e))return!!e;if(e.includes(".")){let t=e.split(".")[0]??"";return nv.has(t)?!1:/^[A-Z]/.test(t)}return ev.has(e)?!1:tv.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 Nd(n){let e=n.trim();return!!(!e||Qy.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function Ud(n,e){let t=e.jsonTitle?.trim(),r=av(n,"").trim(),o=e.fileName.trim();return t&&!Nd(t)?t:r&&!Nd(r)?r:t||r||o}function zd(n){return Zy.test(n.trim())}function os(n){let e=n.trim().replace(/\([^)]*\)$/,""),t=co(e);return Xy.test(t)}function uo(n){let e=n.trim();return e?An.test(e)||zd(e)||os(e)?!0:!!Dn(e).symbolName:!1}function ov(n){let e=n.trim();return!(!e||zd(e)||os(e))}function iv(n){let e=new Set,t=[];for(let r of n){let o=r.trim();!ov(o)||e.has(o)||(e.add(o),t.push(o))}return t}function Ld(n){if(!n.includes("."))return 0;let e=n.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function sv(n,e){let t=Ld(n)-Ld(e);return t!==0?t:n.localeCompare(e)}function qd(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(sv),[...t,...o].slice(0,wl)}function po(n){return n.replace(/\s+/g," ").trim()}function _d(n){return n.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function av(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=_d(t[r].trim()),i=o.match(/^#+\s+(.+)$/);if(i)return _d(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 Vd(n){let e=po(n.join(" "));if(e.length<=Fr)return e;let t=e.slice(0,Fr);return e.length<=Fr+Ci?t:`${t} ${e.slice(-Ci)}`}function cv(n){let e=iv(n).join(" ");return e.length<=Di?e:e.slice(0,Di)}function Gd(n){let e=po(n),{text:t,excerptTruncated:r}=wd(e,bl);return{leadText:t,excerptTruncated:r}}function lv(n,e){let{leadText:t,excerptTruncated:r}=Gd(n);return{leadText:t,excerptTruncated:r||!!e.trim()}}function Yd(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)Yd(r,e);return}let t=po(lo(n));t&&e.bodyParts.push(t)}function dv(n){let e=Fd().use($d).use(Bd).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=lo(a).trim();if(a.depth>=4&&c&&uo(c)){o(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}i(),c&&r.bodyParts.push(c);continue}i(),Yd(s,r)}return o(),t.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:t}function uv(n){return il.test(n)}function pv(n){return n.filter(e=>e.sectionTitle&&uo(e.sectionTitle)).length}function mv(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 Hd(n){let e=n.trim();return!e||An.test(e)?An.test(e):/对象说明$|枚举说明$/.test(e)?!0:os(e)}function fv(n){let e=n.filter(h=>!h.sectionTitle||!uo(h.sectionTitle)),t=n.filter(h=>h.sectionTitle&&uo(h.sectionTitle)),r=t.filter(h=>Hd(h.sectionTitle)),o=t.filter(h=>!Hd(h.sectionTitle)),i=Math.max(0,ol-r.length),s=o.slice(0,i),a=o.slice(i),c=a.filter(h=>jd(h.sectionTitle)),l=a.filter(h=>!jd(h.sectionTitle)),u=[];for(let h=0;h<l.length;h+=Ei)u.push(mv(l.slice(h,h+Ei)));return[...e,...r,...s,...c,...u]}function hv(n,e,t){let r=n.split(/\r?\n/).length,o=pv(e);return o===0?!1:uv(t)?r>=nl&&o>=rl:r>=el&&o>=tl}var gv=/^\[h2\][A-Za-z]/;function jd(n){return gv.test(n.trim())}function Jd(n){if(!n.includes(" | ")){let t=Dn(n);return t.symbolName?[t.symbolName]:[]}let e=[];for(let t of n.split(" | ")){let r=Dn(t.trim()).symbolName;r&&e.push(r)}return e}function yv(n,e,t,r){let o=Jd(n),i=Wd(t,r);return e.symbolName&&i.push(e.symbolName),qd([...o,...i],o)}function vv(n,e){let t=Vd(n.bodyParts),r=n.sectionTitle.trim(),o=Dn(r),i=Md(n.bodyParts),s=Od(r,i,o),a=Jd(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}=lv(t,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:yv(r,o,l,n.codeBlocks),bodySample:t,leadText:u,excerptTruncated:h}}function Kd(n,e){for(let t of n){if(t.type==="heading"){let o=lo(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)){Kd(t.children,e);continue}let r=po(lo(t));r&&e.bodyParts.push(r)}}function wv(n){let e=Fd().use($d).use(Bd).parse(n),t={headings:[],bodyParts:[],codeBlocks:[]};return Kd(e.children,t),t}function bv(n,e){let t=wv(n),r=e.docTitle?.trim()||e.documentId,o=Vd(t.bodyParts),i=[r,...t.headings,o].join(" "),{leadText:s,excerptTruncated:a}=Gd(o);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:cv(t.headings),apiSymbols:qd(Wd(i,t.codeBlocks)),bodySample:o,leadText:s,excerptTruncated:a}}function Zd(n,e){let t=e.docTitle?.trim()||e.documentId,r=dv(n);return hv(n,r,e.documentId)?fv(r).filter(o=>o.sectionTitle||o.bodyParts.length>0||o.codeBlocks.length>0).map(o=>vv(o,{...e,docTitle:t})):[bv(n,{...e,docTitle:t})]}async function Sv(n){let e=[];async function t(r){let o=await Y.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 Pv(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=El[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 Ev(n){let e=n.replace(/\.md$/,".json");try{let t=await Y.promises.readFile(e,"utf-8");return JSON.parse(t).title?.trim()||void 0}catch{return}}async function Iv(n,e){let t=Pv(n,e);if(!t)return[];let r=await Y.promises.readFile(n,"utf-8"),o=Ud(r,{jsonTitle:await Ev(n),fileName:t.docTitle});return Zd(r,{...t,docTitle:o})}async function Cv(n,e,t){let r=ne.join(e,"search.db");return await xd(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 Dv(n){let e=await Sv(n),t=[];for(let r of e){let o=await Iv(r,n);t.push(...o)}return t}function Av(n,e){return{indexVersion:jr,docsZipSha256:n.docsZipSha256,termsHash:n.termsHash,synonymsHash:n.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:n.builtBy}}async function Qd(n){n.lexiconDir&&ki(n.lexiconDir);try{let e=await Dv(n.docsDir);await n.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await Y.promises.mkdir(n.tmpDir,{recursive:!0});let t=await Cv(e,n.tmpDir,n.onProgress),r=Av(n,t);return await Y.promises.writeFile(ne.join(n.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await Ll(n.tmpDir),r}finally{n.lexiconDir&&ki(null)}}async function eu(){return Y.promises.mkdtemp(ne.join(Xd.tmpdir(),"deveco-docs-"))}async function Tv(n,e){try{await Y.promises.rename(n,e)}catch(t){let r=t.code;if(r!=="EPERM"&&r!=="EXDEV")throw t;await Y.promises.cp(n,e,{recursive:!0}),await Y.promises.rm(n,{recursive:!0,force:!0})}}async function tu(n){let e=ne.join(n,"docs");try{await Y.promises.access(e)}catch{return}let t=new Set(["docs","docs.zip"]);for(let r of await Y.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 Y.promises.rm(i,{recursive:!0,force:!0}),await Tv(o,i)}await Y.promises.rm(ne.join(e,"docs"),{recursive:!0,force:!0}),await Y.promises.rm(ne.join(e,"docs.zip"),{force:!0}),await Y.promises.rm(e,{recursive:!0,force:!0})}var Tn=class extends Error{constructor(e){super(e),this.name="NativeDepsError"}};function xv(){let n=_t(),e=Z();return["Documentation search index is not installed yet.","",...Br(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(`
|
|
1331
|
-
`)}function
|
|
1332
|
-
`)}function
|
|
1333
|
-
`)}async function nu(){try{Ol()}catch(n){throw Ml(n)?new Tn(`${
|
|
1331
|
+
`),a=t.length;for(let c=0;c<a;c+=Nt){let l=t.slice(c,c+Nt),u=await Promise.all(l.map(async E=>({source:E,searchText:await no(E)})));o.transaction(E=>{for(let C of E){let M=Ay(o,i,C.source);s.run(M,C.source.sectionTitle,C.source.leadText,C.searchText,C.source.excerptTruncated?1:0)}})(u),await r?.(Math.min(c+l.length,a),a)}o.exec("ANALYZE"),o.exec("VACUUM"),o.close()}function xy(n,e,t,r,o,i,s){let a=Cy(n,e);return oo({all(c,...l){return a.prepare(c).all(...l)}},t,r,o,i,s)}async function Ed(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:Iy,buildSearchIndex:(t,r,o)=>Ty(e,t,r,o),searchIndex:(t,r,o,i,s,a,c)=>Promise.resolve(xy(e,i,r,o,s,a,c))}}import{readFile as ky,stat as Ry,writeFile as My}from"fs/promises";var es=null,Ye=null;async function ts(){return es||(es=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),es}function Oy(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 Ny(n){let e=await Ry(n);if(Ye&&Ye.dbPath===n&&Ye.mtimeMs===e.mtimeMs)return Ye.db;Ye?.db.close();let t=await ts(),r=t.capi,o=t.wasm,i=new Uint8Array(await ky(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),Ye={dbPath:n,mtimeMs:e.mtimeMs,db:a},a}function Id(){Ye?.db.close(),Ye=null}async function Ly(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 _y(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 Hy(n,e,t){await Ge();let r=await ts(),o=new r.oo1.DB(":memory:","c");o.exec(io);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=_y(o,i,s),l=e.length;for(let h=0;h<l;h+=Nt){let E=e.slice(h,h+Nt),C=await Promise.all(E.map(async M=>({source:M,searchText:await no(M)})));await Ly(o,a,c,C),await t?.(Math.min(h+E.length,l),l)}o.exec("ANALYZE");let u=r.capi.sqlite3_js_db_export(o);await My(n,u),o.close(),Id()}async function jy(n,e,t,r,o,i){let s=await Ny(n);return oo(Oy(s),e,t,r,o,i)}async function Cd(){return await ts(),{kind:"sqlite-wasm",resetCache:Id,buildSearchIndex:Hy,searchIndex:(n,e,t,r,o,i,s)=>jy(r,e,t,o,i,s)}}var so=null,ns=null;async function Fy(){try{let e=await Ed();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 Cd();return g("doc-index: using @sqlite.org/sqlite-wasm SQLite backend"),n}async function Cn(){return so||(so=Fy().then(n=>(ns=n,n))),so}function Dd(){ns?.resetCache(),so=null,ns=null}async function $y(n,e,t,r,o,i,s){let a=await Cn(),c=s??hn();return a.searchIndex(n,e,t,c,r,o,i)}function Td(){Dd()}async function xd(n,e,t){await(await Cn()).buildSearchIndex(n,e,t)}function kd(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 ao(n,e,t,r,o,i){return $y(n,e,t,o,r.expandedQuery,r.rawQuery,i)}async function By(n,e,t,r,o){let i=await ao(n,e,t,r,bn(r.tokens,"AND"),o);if(i.length>=t)return i;let s=await ao(n,e,t,r,bn(r.tokens,"OR"),o);return kd(i,s,t)}async function rs(n,e,t,r,o){return r.ftsMatch?ao(n,e,t,r,r.ftsMatch,o):r.preferAnd?By(n,e,t,r,o):ao(n,e,t,r,bn(r.tokens,"OR"),o)}async function Wy(n,e,t,r){let o=await rs(n,"harmonyos-references",e,t,r);if(o.length>=e)return o;let i=await rs(n,void 0,e,t,r);return kd(o,i,e)}function Ad(n,e){return e!==void 0?n:hd(n)}async function Rd(n,e,t=20,r){let o=await pd(n);if(ad(o.rawQuery,e)){let a=await Wy(n,t,o,r);return Ad(a,e)}let i=e??yd(o.rawQuery),s=await rs(n,i,t,o,r);return Ad(s,e)}import{unified as Fd}from"unified";import $d from"remark-parse";import Bd from"remark-gfm";import{toString as lo}from"mdast-util-to-string";var Uy=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,zy=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,qy=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,Vy=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,Gy=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function co(n){let e=n.trim(),t=e.match(Vy);return t?t[1]:e}function Yy(n){let e=n.match(Uy);if(!e)return;let t=co(e[1].trim());return{displayTitle:n,symbolName:t,searchExtras:[t,e[3]]}}function Jy(n){let e=co(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 Dn(n){let e=n.trim();return e?Yy(e)??(()=>{let t=e.match(zy);if(t){let r=t[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let t=e.match(qy);if(!t)return;let r=t[1].trim(),o=t[2].trim();return{displayTitle:e,symbolName:o,searchExtras:[r,o]}})()??Jy(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function Ky(n){if(n.length<2||n.length>36||Gy.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 Md(n){for(let e of n){let t=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(Ky(t))return t}return""}function Od(n,e,t){let r=[n,...t.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var Zy=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,An=/@[A-Z][a-zA-Z]+/g,Xy=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,Qy=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,ev=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,tv=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),nv=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),rv=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function Wd(n,e){let t=new Set,r=[n,...e];for(let o of r){for(let i of Wi(o)){fe(t,i);let s=Zr(i);s&&fe(t,s)}for(let i of Ui(o))fe(t,i);for(let i of o.matchAll(Zy)){let s=i[0];ov(s)&&t.add(s)}for(let i of o.matchAll(An))t.add(i[0])}return Ht([...t])}function ov(n){let e=n.trim();if(!e||An.test(e))return!!e;if(e.includes(".")){let t=e.split(".")[0]??"";return rv.has(t)?!1:/^[A-Z]/.test(t)}return tv.has(e)?!1:nv.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 Nd(n){let e=n.trim();return!!(!e||ev.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function Ud(n,e){let t=e.jsonTitle?.trim(),r=cv(n,"").trim(),o=e.fileName.trim();return t&&!Nd(t)?t:r&&!Nd(r)?r:t||r||o}function zd(n){return Xy.test(n.trim())}function os(n){let e=n.trim().replace(/\([^)]*\)$/,""),t=co(e);return Qy.test(t)}function uo(n){let e=n.trim();return e?An.test(e)||zd(e)||os(e)?!0:!!Dn(e).symbolName:!1}function iv(n){let e=n.trim();return!(!e||zd(e)||os(e))}function sv(n){let e=new Set,t=[];for(let r of n){let o=r.trim();!iv(o)||e.has(o)||(e.add(o),t.push(o))}return t}function Ld(n){if(!n.includes("."))return 0;let e=n.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function av(n,e){let t=Ld(n)-Ld(e);return t!==0?t:n.localeCompare(e)}function qd(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(av),[...t,...o].slice(0,wl)}function po(n){return n.replace(/\s+/g," ").trim()}function _d(n){return n.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function cv(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=_d(t[r].trim()),i=o.match(/^#+\s+(.+)$/);if(i)return _d(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 Vd(n){let e=po(n.join(" "));if(e.length<=Fr)return e;let t=e.slice(0,Fr);return e.length<=Fr+Ci?t:`${t} ${e.slice(-Ci)}`}function lv(n){let e=sv(n).join(" ");return e.length<=Di?e:e.slice(0,Di)}function Gd(n){let e=po(n),{text:t,excerptTruncated:r}=wd(e,bl);return{leadText:t,excerptTruncated:r}}function dv(n,e){let{leadText:t,excerptTruncated:r}=Gd(n);return{leadText:t,excerptTruncated:r||!!e.trim()}}function Yd(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)Yd(r,e);return}let t=po(lo(n));t&&e.bodyParts.push(t)}function uv(n){let e=Fd().use($d).use(Bd).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=lo(a).trim();if(a.depth>=4&&c&&uo(c)){o(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}i(),c&&r.bodyParts.push(c);continue}i(),Yd(s,r)}return o(),t.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:t}function pv(n){return il.test(n)}function mv(n){return n.filter(e=>e.sectionTitle&&uo(e.sectionTitle)).length}function fv(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 Hd(n){let e=n.trim();return!e||An.test(e)?An.test(e):/对象说明$|枚举说明$/.test(e)?!0:os(e)}function hv(n){let e=n.filter(h=>!h.sectionTitle||!uo(h.sectionTitle)),t=n.filter(h=>h.sectionTitle&&uo(h.sectionTitle)),r=t.filter(h=>Hd(h.sectionTitle)),o=t.filter(h=>!Hd(h.sectionTitle)),i=Math.max(0,ol-r.length),s=o.slice(0,i),a=o.slice(i),c=a.filter(h=>jd(h.sectionTitle)),l=a.filter(h=>!jd(h.sectionTitle)),u=[];for(let h=0;h<l.length;h+=Ei)u.push(fv(l.slice(h,h+Ei)));return[...e,...r,...s,...c,...u]}function gv(n,e,t){let r=n.split(/\r?\n/).length,o=mv(e);return o===0?!1:pv(t)?r>=nl&&o>=rl:r>=el&&o>=tl}var yv=/^\[h2\][A-Za-z]/;function jd(n){return yv.test(n.trim())}function Jd(n){if(!n.includes(" | ")){let t=Dn(n);return t.symbolName?[t.symbolName]:[]}let e=[];for(let t of n.split(" | ")){let r=Dn(t.trim()).symbolName;r&&e.push(r)}return e}function vv(n,e,t,r){let o=Jd(n),i=Wd(t,r);return e.symbolName&&i.push(e.symbolName),qd([...o,...i],o)}function wv(n,e){let t=Vd(n.bodyParts),r=n.sectionTitle.trim(),o=Dn(r),i=Md(n.bodyParts),s=Od(r,i,o),a=Jd(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}=dv(t,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:vv(r,o,l,n.codeBlocks),bodySample:t,leadText:u,excerptTruncated:h}}function Kd(n,e){for(let t of n){if(t.type==="heading"){let o=lo(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)){Kd(t.children,e);continue}let r=po(lo(t));r&&e.bodyParts.push(r)}}function bv(n){let e=Fd().use($d).use(Bd).parse(n),t={headings:[],bodyParts:[],codeBlocks:[]};return Kd(e.children,t),t}function Sv(n,e){let t=bv(n),r=e.docTitle?.trim()||e.documentId,o=Vd(t.bodyParts),i=[r,...t.headings,o].join(" "),{leadText:s,excerptTruncated:a}=Gd(o);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:lv(t.headings),apiSymbols:qd(Wd(i,t.codeBlocks)),bodySample:o,leadText:s,excerptTruncated:a}}function Zd(n,e){let t=e.docTitle?.trim()||e.documentId,r=uv(n);return gv(n,r,e.documentId)?hv(r).filter(o=>o.sectionTitle||o.bodyParts.length>0||o.codeBlocks.length>0).map(o=>wv(o,{...e,docTitle:t})):[Sv(n,{...e,docTitle:t})]}async function Pv(n){let e=[];async function t(r){let o=await Y.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 Ev(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=El[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 Iv(n){let e=n.replace(/\.md$/,".json");try{let t=await Y.promises.readFile(e,"utf-8");return JSON.parse(t).title?.trim()||void 0}catch{return}}async function Cv(n,e){let t=Ev(n,e);if(!t)return[];let r=await Y.promises.readFile(n,"utf-8"),o=Ud(r,{jsonTitle:await Iv(n),fileName:t.docTitle});return Zd(r,{...t,docTitle:o})}async function Dv(n,e,t){let r=ne.join(e,"search.db");return await xd(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 Av(n){let e=await Pv(n),t=[];for(let r of e){let o=await Cv(r,n);t.push(...o)}return t}function Tv(n,e){return{indexVersion:jr,docsZipSha256:n.docsZipSha256,termsHash:n.termsHash,synonymsHash:n.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:n.builtBy}}async function Qd(n){n.lexiconDir&&ki(n.lexiconDir);try{let e=await Av(n.docsDir);await n.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await Y.promises.mkdir(n.tmpDir,{recursive:!0});let t=await Dv(e,n.tmpDir,n.onProgress),r=Tv(n,t);return await Y.promises.writeFile(ne.join(n.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await Ll(n.tmpDir),r}finally{n.lexiconDir&&ki(null)}}async function eu(){return Y.promises.mkdtemp(ne.join(Xd.tmpdir(),"deveco-docs-"))}async function xv(n,e){try{await Y.promises.rename(n,e)}catch(t){let r=t.code;if(r!=="EPERM"&&r!=="EXDEV")throw t;await Y.promises.cp(n,e,{recursive:!0}),await Y.promises.rm(n,{recursive:!0,force:!0})}}async function tu(n){let e=ne.join(n,"docs");try{await Y.promises.access(e)}catch{return}let t=new Set(["docs","docs.zip"]);for(let r of await Y.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 Y.promises.rm(i,{recursive:!0,force:!0}),await xv(o,i)}await Y.promises.rm(ne.join(e,"docs"),{recursive:!0,force:!0}),await Y.promises.rm(ne.join(e,"docs.zip"),{force:!0}),await Y.promises.rm(e,{recursive:!0,force:!0})}var Tn=class extends Error{constructor(e){super(e),this.name="NativeDepsError"}};function kv(){let n=_t(),e=Z();return["Documentation search index is not installed yet.","",...Br(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(`
|
|
1332
|
+
`)}function Rv(){let n=_t();return[`Chinese tokenizer (${I()?"jieba-wasm":"@node-rs/jieba"}) failed to load.`,"",`Node.js: ${process.version} (required: >=18)`,"",...Br(n),"","Try:"," 1. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 2. Use Node.js 18 or newer",I()?" 3. Verify jieba-wasm package is installed (WASM backend for OpenHarmony)":" 3. Configure npm registry/proxy if your network blocks optional platform packages"].join(`
|
|
1333
|
+
`)}function Mv(n){let e=_t();return[n,"",...Br(e)].join(`
|
|
1334
|
+
`)}async function nu(){try{Ol()}catch(n){throw Ml(n)?new Tn(`${kv()}
|
|
1334
1335
|
|
|
1335
|
-
Detail: ${n.message}`):n}try{await Ge()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Tn(`${
|
|
1336
|
+
Detail: ${n.message}`):n}try{await Ge()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Tn(`${Rv()}
|
|
1336
1337
|
|
|
1337
|
-
Detail: ${e}`)}try{await Cn()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Tn(
|
|
1338
|
-
`)}async function
|
|
1338
|
+
Detail: ${e}`)}try{await Cn()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Tn(Mv(e))}}var is=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function Lv(n){return new Promise(e=>setTimeout(e,n))}async function _v(n){let e=_t();await U.promises.mkdir(Ft.dirname(e),{recursive:!0}),await U.promises.appendFile(e,`${new Date().toISOString()} ${n}
|
|
1339
|
+
`)}async function Hv(n){let e=ze();if(!e)throw new Error("docs.zip not found");await U.promises.rm(n,{recursive:!0,force:!0}),await U.promises.mkdir(n,{recursive:!0}),new Ov(e).extractAllTo(n,!0),await tu(n)}async function jv(){let n=Z(),e=Lt(),t=await U.promises.readdir(e);for(let r of t){let o=Ft.join(n,r);await U.promises.rm(o,{force:!0}),await U.promises.rename(Ft.join(e,r),o)}await U.promises.rm(e,{recursive:!0,force:!0}),await U.promises.rm(Ft.join(n,"orama.dpack"),{force:!0})}async function Fv(n,e){e?.start("Installing documentation index\u2026"),await Ve({state:"installing",phase:1,phaseLabel:"Installing index",message:"Installing documentation index\u2026"}),await Bl(n),e&&(e.text="Documentation index installed.")}async function $v(n,e,t){let r=Lt(),o=await eu();await U.promises.mkdir(Z(),{recursive:!0}),await U.promises.rm(r,{recursive:!0,force:!0}),t?.start("Building search index\u2026"),await Ve({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"});try{await Hv(o),await Qd({docsDir:o,tmpDir:r,docsZipSha256:e,termsHash:Jr(),synonymsHash:Yr(),builtBy:n.builtBy??"doc-init",onProgress:async i=>{t&&(t.text=i.message),await Ve({state:"indexing",current:i.current,total:i.total,message:i.message})}})}finally{await U.promises.rm(o,{recursive:!0,force:!0})}await Ve({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await jv(),Td()}async function ru(n){await Ve({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function Bv(n){let e=await ji(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await Ve({state:"done",message:t,error:null})}async function Wv(n,e){let t=n instanceof Error?n.message:String(n);throw await Ve({state:"error",error:t}),await _v(`ERROR: ${t}`),e?.fail(t),n}async function Uv(){let n=Z();await U.promises.mkdir(n,{recursive:!0});let e=Tl();return U.existsSync(e)||await U.promises.writeFile(e,"","utf-8"),e}async function zv(){let n=await Uv();return Nv.lock(n,{stale:1800*1e3})}async function qv(){let n=ze(),e=(n?await Gr(n):null)??await Hi();if(!e)throw new Error("docs.zip not found");return e}async function Vv(n,e){let t=await qv(),r=n.force||await $i(n.force),o=await Fi(n.force);if(!r&&!o&&vn()){await Bv(e);return}if(Oi()&&!n.force){await Fv(t,e),await ru(e);return}await $v(n,t,e),await ru(e)}var ss=class{static async run(e={}){let t=e.background??!1,o=e.quiet??t?void 0:iu({text:"Checking documentation\u2026",color:"cyan"}),i;try{i=await zv(),await _i(Vl("Starting documentation setup\u2026")),await Vv(e,o)}catch(s){return Wv(s,o)}finally{i&&await i()}}};async function Gv(n){for(;;){let e=await Kr();if(e.state==="done"&&vn())return;if(e.state==="error")throw new is("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 Lv(500)}}async function ou(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await ss.run({builtBy:"doc-init",force:e,quiet:!0})}async function Yv(){if(vn())return;let n=iu({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await Gl()){await Gv(n),n.succeed("Documentation ready.");return}if(await $i()){await ou(n),n.succeed("Documentation ready.");return}await ou(n,!0),n.succeed("Documentation ready.")}catch(e){throw n.fail(e.message),e}}async function xn(){await Yv(),await nu()}var as=class{async search(e,t,r=20){return await xn(),Rd(e,t,r)}async readDocument(e){return await xn(),jl(e)}},cs=new as;function su(...n){return e=>{if(!n.includes(e))throw new ls(`Allowed values: ${n.join(", ")}`);return e}}function Zv(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new ls("Must be a positive integer.");return e}var Xv=su("json","default"),Qv=su("json","default"),fo=new Jv("docs").description("Search and read HarmonyOS documentation from local docs directory");fo.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",tw,"all").option("--format <fmt>","Output format (default, json)",Xv,"default").option("--limit <n>","Max number of results",Zv,20).action(async(n,e)=>{try{let t=ew(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await cs.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):nw(o)}catch(t){console.error(mo(t.message)),process.exit(1)}});fo.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error(mo("Document ID cannot be empty.")),process.exit(1));let t=await cs.readDocument(e);console.log(t)}catch(e){console.error(mo(e.message)),process.exit(1)}});fo.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",Qv,"default").action(async n=>{try{if(await xn(),n.format==="json"){let e=We.map(t=>({name:t,title:st[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of We)console.log(` ${e.padEnd(20)} ${Kv(st[e])}`)}catch(e){console.error(mo(e.message)),process.exit(1)}});function ew(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>fn)throw new Error(`Query exceeds ${fn} characters.`);return e}function tw(n){if(n==="all")return"all";if(!We.includes(n))throw new ls(`Invalid catalog "${n}". Allowed: all, ${We.join(", ")}`);return n}function nw(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 au=fo;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";rw();X.name("devecocli").description("HarmonyOS application development command line tool").version("0.1.0-TD.4");X.addCommand(As);X.addCommand(Ls);X.addCommand(Fs);X.addCommand(Zs);I()||X.addCommand(va);X.addCommand(Ua);X.addCommand(Ya);X.addCommand(rc);X.addCommand(uc);X.addCommand(Qc);X.addCommand(au);var ds=process.argv.slice(2);ds.length>=2&&ds[ds.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var iw=new Set(["update"]);X.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==X;)t=t.parent;iw.has(t.name())||await _.checkVersion()});X.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(ow(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
|