@deveco-test/deveco-cli 1.3.0-Test.5 → 1.3.0-Test.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +157 -16
- package/SKILL.md +86 -6
- package/THIRD-PARTY-LICENSES +344 -5
- package/dist/cli.js +126 -101
- package/dist/internal/doc-init-background.js +8 -8
- package/docs.zip +0 -0
- package/index.zip +0 -0
- package/package.json +9 -3
- package/scripts/install-jieba-wasm.mjs +47 -0
- package/scripts/lib/jieba-wasm-vendor.mjs +102 -0
- package/scripts/postinstall.mjs +9 -0
- package/src/resources/aclPermission/aclPermissionsInfo.json +311 -0
package/dist/cli.js
CHANGED
|
@@ -1,46 +1,53 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{bootstrap as
|
|
3
|
-
`)}static parseDurationToSeconds(e,t="value"){let i=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!i)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported).`);let o=i[1];if((i[2]??"s")==="s")return n.parsePositiveInteger(o,t);if(!/^\d+(?:\.\d)?$/.test(o))throw new Error(`${t} supports a maximum of 1 decimal place for minutes (e.g. 2.5m).`);let a=Number.parseFloat(o);if(!Number.isFinite(a)||a<=0)throw new Error(`${t} must be a positive duration.`);return Math.round(a*60)}static assertRelativeTimeRange(e,t){if(e!==void 0&&t!==void 0&&e<t)throw new Error("--from must be greater than or equal to --to when both are provided (e.g. --from 30s --to 10s)")}static filterLogsByRelativeWindow(e,t,r,i=new Date){if(!t&&!r)return e;let[o,s]=n.resolveTimeBounds(t,r,i),a=e.split(/\r?\n/),c=[],l=!1;for(let
|
|
4
|
-
`)}static resolveTimeBounds(e,t,r){let i=e?new Date(r.getTime()-e*1e3):null,o=t?new Date(r.getTime()-t*1e3):null;return i&&o?i<o?[i,o]:[o,i]:i?[i,r]:o?[null,o]:[null,null]}static isWithinBounds(e,t,r){let i=e.getTime(),o=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(o!==null&&i<o||s!==null&&i>s)}static extractTimestampFromLogLine(e,t){let r=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!r)return null;let i=t.getFullYear(),o=Number.parseInt(r[1],10)-1,s=Number.parseInt(r[2],10),a=Number.parseInt(r[3],10),c=Number.parseInt(r[4],10),l=Number.parseInt(r[5],10),u=r[6]??"0",f=Number.parseInt(u.padEnd(3,"0").slice(0,3),10),P=new Date(i,o,s,a,c,l,f);return P.getTime()>t.getTime()+1440*60*1e3&&P.setFullYear(i-1),P}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(r=>{let i=r.charCodeAt(0);return i<=n.ASCII_CONTROL_MAX||i===n.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let r=`'${e.replace(/'/g,"'\\''")}'`;return g(`quotePosixShellArg: ${e} -> ${r}`),r}static assertCrashFilename(e){if(!/^\w+-.+\d+-\d+$/.test(e))throw new Error(`Invalid crash log filename: ${JSON.stringify(e)}`)}static assertHilogLevel(e){if(!/^[DIWEF]$/.test(e))throw new Error(`Invalid log level: ${e}`)}static resolvePathWithinRoot(e,t){if(W.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=W.resolve(W.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=W.normalize(e),i=W.relative(r,t);if(i.split(W.sep)[0]===".."||W.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||W.isAbsolute(e)}static isPathContained(e,t){let r=W.resolve(t,e),i=W.relative(t,r);return n.isPathEscaping(i)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){if(W.isAbsolute(e))return{contained:!1,reason:`Absolute path is not allowed: ${e}`};let r=n.isPathContained(e,t);if(!r.contained)return r;let i;try{i=ki.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=W.resolve(i,e),s;try{s=ki.realpathSync(o)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${o}`}}return n.isPathContained(s,i)}};var tt=class n{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let r=n.tryLoadProjectProfile(t);if(r)return new n(t,r);let i=Q.dirname(t);if(i===t)break;t=i}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=Q.join(e,"build-profile.json5");if(!q.existsSync(t))return null;try{let r=q.readFileSync(t,"utf-8"),i=et.parse(r);return i.app?i:null}catch(r){return console.error(`Error parsing ${t}:`,r),null}}getModuleType(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=b.resolvePathWithinRoot(this.rootDir,t.srcPath),i=Q.join(r,"src","main","module.json5");if(!q.existsSync(i))return"entry";try{let o=q.readFileSync(i,"utf-8");return et.parse(o)?.module?.type||"entry"}catch(o){return console.warn(`Warning: Failed to parse ${i}:`,o),"entry"}}getModuleProfile(e){let t=this.profile.modules.find(a=>a.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=b.resolvePathWithinRoot(this.rootDir,t.srcPath),i=Q.join(r,"build-profile.json5");if(!q.existsSync(i))throw new Error(`Build profile for module '${e}' not found at ${i}.`);let o=q.readFileSync(i,"utf-8");return et.parse(o)}getBundleName(){let e=Q.join(this.rootDir,"AppScope","app.json5");if(q.existsSync(e))try{let t=q.readFileSync(e,"utf-8"),r=et.parse(t);if(r?.app?.bundleName)return r.app.bundleName}catch(t){console.warn(`Warning: Failed to parse ${e}:`,t)}throw new Error("Could not find bundleName in AppScope/app.json5.")}getMainAbility(e,t){if(t)return t;let r=this.profile.modules.find(s=>s.name===e);if(!r)return"EntryAbility";let i=b.resolvePathWithinRoot(this.rootDir,r.srcPath),o=Q.join(i,"src","main","module.json5");if(!q.existsSync(o))return"EntryAbility";try{let s=q.readFileSync(o,"utf-8"),c=et.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let l=c.find(u=>u.name==="EntryAbility");return l?l.name:c[0].name}catch(s){return console.warn(`Warning: Failed to parse ${o}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new Error(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`);if(!this.profile.app.products?.some(r=>r.name===e)){let r=this.profile.app.products?.map(i=>i.name).join(", ")||"none";throw new Error(`Product '${e}' not found in project configuration. Available products: ${r}`)}}getModuleDependencies(e){let t=this.profile.modules.find(s=>s.name===e);if(!t)return[];let r=b.resolvePathWithinRoot(this.rootDir,t.srcPath),i=Q.join(r,"oh-package.json5");if(!q.existsSync(i))return[];let o=[];try{let s=q.readFileSync(i,"utf-8"),c=et.parse(s)?.dependencies||{};for(let l of Object.values(c)){if(typeof l!="string")continue;let u=l;if(!(u.startsWith("file:")||u.startsWith(".")||u.startsWith("..")))continue;u.startsWith("file:")&&(u=u.substring(5));let P=Q.join(t.srcPath,u),C=b.resolvePathWithinRoot(this.rootDir,P),L=this.profile.modules.find(ne=>Q.resolve(this.rootDir,ne.srcPath)===C);L&&o.push(L.name)}}catch{}return o}collectNonHarDependentModuleList(e){let t=[],r=[],i=new Set;for(r.push(e),i.add(e);r.length>0;){let o=r.shift();this.getModuleType(o)!=="har"&&t.push(o);let a=this.getModuleDependencies(o);for(let c of a)i.has(c)||(r.push(c),i.add(c))}return t}findArtifactPath(e,t,r,i="default"){this.validateProduct(i);let o=this.profile.modules.find(ne=>ne.name===e);if(!o)throw new Error(`Module '${e}' not found`);let a=this.getModuleType(e)==="shared",c=a?"hspName":"hapName",l=this.buildOutputPath(o.srcPath,i,["intermediates",a?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!q.existsSync(l))throw new Error(`Build metadata not found for module '${e}' at ${l}. Build the project first.`);let{packageName:u,isSigned:f}=this.parseOutputMetadata(l,c),P=u;if(!f){let ne=this.getSignedHapName(u,o.srcPath,i,t);ne&&(P=ne)}let C=a?"-signed.hsp":"-signed.hap";if(!r&&!P.endsWith(C))throw new Error(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`);let L=this.buildOutputPath(o.srcPath,i,["outputs",t,P]);if(!q.existsSync(L))throw new Error(`Generated package file not found in ${L}.`);return L}getSignedHapName(e,t,r,i){let o=null;if(e.endsWith("-unsigned.hap")?o=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(o=e.replace("-unsigned.hsp","-signed.hsp")),!o)return null;let s=this.buildOutputPath(t,r,["outputs",i,o]);return q.existsSync(s)?o:null}buildOutputPath(e,t,r){let i=b.resolvePathWithinRoot(this.rootDir,e),o=Q.resolve(i,"build",t,...r);return b.ensurePathWithinRoot(this.rootDir,o)}parseOutputMetadata(e,t){let r=q.readFileSync(e,"utf-8"),i=et.parse(r),o,s=!1;if(Array.isArray(i)){let a=i[0];a&&(o=a[t],s=a.isSigned===!0)}else i&&typeof i=="object"&&(o=i[t],s=i.isSigned===!0);if(!o)throw new Error(`Could not find ${t} in output_metadata.json at ${e}`);return this.validatePackageName(o),{packageName:o,isSigned:s}}validatePackageName(e){let t=Q.basename(e);if(t!==e)throw new Error(`Invalid traversal name: '${e}'. It must contain path characters.`);if(!t.endsWith(".hap")&&!t.endsWith(".hsp"))throw new Error(`Invalid package name '${t}'.It must be a .hap or .hsp file.`)}};import{execFileSync as Ri}from"child_process";import H,{existsSync as Ts}from"fs";import*as I from"path";import*as ce from"os";import Nu from"regedit";import{join as ks}from"path";import{red as _u}from"colorette";var Rs="https://developer.huawei.com/consumer/cn/download/",Ms="6.1.0",Un=n=>new Promise((e,t)=>{Nu.list(n,(r,i)=>{r?t(r):e(i)})}),N=class n{_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;_emulatorLauncherPath;static _verifiedPaths=new Set;static _powerShellPath;static verifyAndCache(e){n._verifiedPaths.has(e)||(n.verifySignature(e),n._verifiedPaths.add(e))}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return n.verifyAndCache(this._nodePath),this._nodePath}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get javaPath(){return n.verifyAndCache(this._javaPath),this._javaPath}get sdkPath(){return this._sdkPath}get hdcPath(){return n.verifyAndCache(this._hdcPath),this._hdcPath}get emulatorPath(){return n.verifyAndCache(this._emulatorPath),this._emulatorPath}get emulatorLauncherPath(){return this._emulatorLauncherPath&&n.verifyAndCache(this._emulatorLauncherPath),this._emulatorLauncherPath}constructor(e,t,r,i,o,s,a,c,l){this._devecoStudioPath=e,this._nodePath=t,this._ohpmJsPath=r,this._hvigorJsPath=i,this._javaPath=o,this._sdkPath=s,this._hdcPath=a,this._emulatorPath=c,this._emulatorLauncherPath=l}static enforceStudioMinVersion(e){let t=n.parseProductInfoVersion(e);if(t===void 0)throw new Error(`Failed to determine DevEco Studio version at ${e}`);n.assertMinVersion(e,t)}static async checkVersion(){let e=await n.findDevEcoStudio();n.enforceStudioMinVersion(e)}static async new(){let e=await n.findDevEcoStudio(),{nodePath:t,ohpmJsPath:r,hvigorJsPath:i,javaPath:o,sdkPath:s,hdcPath:a,emulatorPath:c}=n.resolveTools(e),l=n.getEmulatorExe(e);return new n(e,t,r,i,o,s,a,c,l??void 0)}static _cachedInstallRoot;static async findDevEcoStudio(){if(n._cachedInstallRoot!==void 0)return g(`[ToolProvider] findDevEcoStudio: cache hit -> ${n._cachedInstallRoot}`),n._cachedInstallRoot;let e=ce.platform(),t=e==="win32"?await n.collectCandidatesWindows():e==="darwin"?n.collectCandidatesMac():(()=>{throw new Error("Linux is not fully supported yet for automatic DevEco Studio detection.")})();return n._cachedInstallRoot=n.pickLatestByProductInfo(t),n._cachedInstallRoot}static async collectCandidatesWindows(){let e=new Set,t=[],r=(i,o)=>{if(!n.isExistingDirectory(i))return;let s=I.normalize(i).toLowerCase();e.has(s)||(e.add(s),t.push(i),g(`[ToolProvider] Found via ${o}: ${i}`))};if(await n.addFromUninstallKey(r),await n.addFromHuaweiStudioKeys(r),n.addFromDefaultWindowsPath(r),t.length===0)throw new Error("DevEco Studio installation not found in registry or default locations.");return t}static UNINSTALL_REGISTRY_PARENTS=["HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall","HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"];static HUAWEI_STUDIO_REGISTRY_KEYS=["HKLM\\SOFTWARE\\Huawei\\DevEco Studio","HKLM\\SOFTWARE\\WOW6432Node\\Huawei\\DevEco Studio"];static isDevEcoStudioUninstallSubkey(e){return e.normalize("NFKC").trim().toLowerCase().startsWith("deveco studio")}static async addFromUninstallKey(e){for(let t of n.UNINSTALL_REGISTRY_PARENTS)try{let o=((await Un([t]))[t]?.keys??[]).filter(n.isDevEcoStudioUninstallSubkey);if(o.length===0)continue;let s=o.map(c=>`${t}\\${c}`),a=await Un(s);for(let c of s){let l=a[c]?.values?.InstallLocation?.value;e(l,`Uninstall registry key (${c})`)}}catch{}}static async addFromHuaweiStudioRegistryKey(e,t,r){try{let o=(await Un([t]))[t]?.keys??[];if(o.length===0)return;let s=o.map(c=>`${t}\\${c}`),a=await Un(s);for(let c of s){let l=a[c]?.values?.[""]?.value;e(l,`${r} subkey ${c}`)}}catch{}}static async addFromHuaweiStudioKeys(e){for(let t of n.HUAWEI_STUDIO_REGISTRY_KEYS){let r=t.includes("WOW6432Node")?"Huawei DevEco Studio (WOW6432Node)":"Huawei DevEco Studio";await n.addFromHuaweiStudioRegistryKey(e,t,r)}}static addFromDefaultWindowsPath(e){let t=I.join("C:","Program Files","Huawei","DevEco Studio");e(t,"default installation path")}static collectCandidatesMac(){let e=ce.homedir(),t=[I.join(e,"Applications"),"/Applications"],r=[],i=new Set;for(let o of t){if(!H.existsSync(o))continue;let s;try{s=H.readdirSync(o)}catch{continue}for(let a of s){if(!a.endsWith(".app")||!a.toLowerCase().includes("deveco"))continue;let l=I.join(o,a);n.isExistingDirectory(l)&&(i.has(l)||(i.add(l),r.push(l),g(`[ToolProvider] Found macOS candidate: ${l}`)))}}if(r.length===0)throw new Error("DevEco Studio not found in /Applications or ~/Applications.");return r}static productInfoPath(e){return I.join(e,"product-info.json")}static macInfoPlistPath(e){return I.join(e,"Contents","Info.plist")}static readMacInfoPlistKey(e,t){if(!H.existsSync(e)){g(`[ToolProvider] Info.plist not found at: ${e}`);return}let r=[{command:"/usr/libexec/PlistBuddy",args:["-c",`Print :${t}`,e],label:`PlistBuddy Print :${t}`},{command:"plutil",args:["-extract",t,"raw","-o","-",e],label:`plutil -extract ${t}`}];for(let{command:i,args:o,label:s}of r)try{let a=Ri(i,o,{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:5e3}).trim();if(a.length>0&&!a.includes("Does Not Exist"))return a}catch(a){let c=a,l=c.stderr?String(c.stderr).trim():"",u=c.status??c.code??"?";g(`[ToolProvider] ${s} failed for ${e} (exit ${u})${l?`: ${l}`:""}`)}}static extractCompactBuildCode(e){let t=e.split(".").at(-1);if(t!==void 0&&/^\d+$/.test(t))return t}static compactPrefixFromShortVersion(e){let t=e.split(".").slice(0,3);if(!(t.length<3||!t.every(r=>/^\d+$/.test(r))))return t.join("")}static extractFourthSegmentMatchingShortVersion(e,t){let r=n.compactPrefixFromShortVersion(e),i=n.extractCompactBuildCode(t);if(r===void 0||i===void 0)return;if(!i.startsWith(r)){g(`[ToolProvider] CFBundleVersion suffix ${i} does not match short-version prefix ${r} (${e})`);return}let o=i.slice(r.length);if(!(o.length===0||!/^\d+$/.test(o)))return o}static readMacFourthSegmentFromPlist(e,t){let r=n.readMacInfoPlistKey(e,"CFBundleVersion");if(r!==void 0){let s=n.extractFourthSegmentMatchingShortVersion(t,r);if(s!==void 0)return s}let i=n.readMacInfoPlistKey(e,"CFBundleGetInfoString");if(i===void 0)return;let o=i.match(/DS-[\d.]+/);if(o!==null)return n.extractFourthSegmentMatchingShortVersion(t,o[0])}static parseMacInfoPlistVersion(e){let t=n.macInfoPlistPath(e),r=n.readMacInfoPlistKey(t,"CFBundleShortVersionString");if(r!==void 0){let i=n.readMacFourthSegmentFromPlist(t,r);return i!==void 0?`${r}.${i}`:r}return n.readMacInfoPlistKey(t,"CFBundleVersion")}static parseProductInfoVersion(e){if(ce.platform()==="darwin")return n.parseMacInfoPlistVersion(e);let t=n.productInfoPath(e);if(!H.existsSync(t)){g(`[ToolProvider] product-info.json not found at: ${t}`);return}try{let i=JSON.parse(H.readFileSync(t,"utf-8"))?.version;if(typeof i!="string"||i.trim()===""){g(`[ToolProvider] product-info.json at ${t} has no valid "version" field`);return}return i.trim()}catch(r){g(`[ToolProvider] Failed to parse product-info.json at ${t}: ${r instanceof Error?r.message:String(r)}`);return}}static compareVersion(e,t){let r=e.split(".").map(s=>parseInt(s,10)||0),i=t.split(".").map(s=>parseInt(s,10)||0),o=Math.max(r.length,i.length);for(let s=0;s<o;s++){let a=(r[s]??0)-(i[s]??0);if(a!==0)return a}return 0}static pickLatestByProductInfo(e){let t=n.selectHighestVersion(e);return g(`[ToolProvider] Selected DevEco Studio ${t.version} at ${t.installRoot}`),t.installRoot}static selectHighestVersion(e){let t=[];for(let r of e){let i=n.parseProductInfoVersion(r);i!==void 0?(t.push({installRoot:r,version:i}),g(`[ToolProvider] ${r} => version ${i}`)):g(`[ToolProvider] Skipping ${r}: could not read version from Info.plist.`)}if(t.length===0){let r=e.join(`
|
|
5
|
-
|
|
6
|
-
Searched
|
|
7
|
-
${r
|
|
8
|
-
Please reinstall DevEco Studio or download the latest version from:
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
${i.join(`
|
|
12
|
-
`)}`)}static resolveEmulatorPath(e,t){let r;if(t==="win32")r=I.join(e,"tools","emulator","Emulator.exe");else if(t==="darwin")r=I.join(e,"Contents","tools","emulator","Emulator");else throw new Error("Linux is not fully supported yet");if(!H.existsSync(r))throw new Error(`Emulator executable not found at: ${r}`);return r}static verifyTools(e,t,r,i){if(!H.existsSync(e))throw new Error(`Node executable not found at: ${e}`);if(!H.existsSync(t))throw new Error(`ohpm js file not found at: ${t}`);if(!H.existsSync(r))throw new Error(`hvigor js file not found at: ${r}`);if(!H.existsSync(i))throw new Error(`java executable not found at: ${i}`)}static getEmulatorExe(e){let t=ce.platform(),r;if(t==="win32")r=ks(e,"tools","emulator","Emulator.exe");else if(t==="darwin")r=ks(e,"Contents","tools","emulator","Emulator");else return;return Ts(r)?r:void 0}static isValidApiLevel(e,t){let r=t??23;return Number.isInteger(e)&&e>=17&&e<=r}static parseApiLevelFromFile(e){if(H.existsSync(e))try{let t=H.readFileSync(e,"utf-8"),r=JSON.parse(t),i=r?.apiVersion??r?.data?.apiVersion;if(typeof i!="string"&&typeof i!="number")return;let o=Number(i);return Number.isInteger(o)&&o>=17?o:void 0}catch{return}}static detectFromSdkPkg(e){let t=I.join(e,"default","sdk-pkg.json");return n.parseApiLevelFromFile(t)}static detectFromOhUniPackage(e){let t=[I.join(e,"default","openharmony","toolchains","oh-uni-package.json"),I.join(e,"default","openharmony","native","oh-uni-package.json"),I.join(e,"default","openharmony","previewer","oh-uni-package.json")];for(let r of t){let i=n.parseApiLevelFromFile(r);if(i!==void 0)return i}}getMaxApiLevel(){let e=n.detectFromSdkPkg(this.sdkPath);if(e!==void 0)return e;let t=n.detectFromOhUniPackage(this.sdkPath);return t!==void 0?t:23}detectApiLevel(){return this.getMaxApiLevel()}static findPowerShellPath(){if(n._powerShellPath)return n._powerShellPath;if(ce.platform()!=="win32")return n._powerShellPath="",n._powerShellPath;let e=I.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return Ts(e)?(g(`[ToolProvider] Found PowerShell at: ${e}`),n._powerShellPath=e,e):(n._powerShellPath="",n._powerShellPath)}static verifySignature(e){if(!H.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=ce.platform();if(n.isExecutableFile(e,t)){if(t==="win32"){if(!n.verifyWindowsSignature(e).signed)throw new Error(`The executable is not digitally signed: ${e}`)}else if(t==="darwin"&&!n.verifyMacSignature(e).signed)throw new Error(`The executable is not digitally signed: ${e}`)}}static isExecutableFile(e,t){if(t==="win32")return I.extname(e).toLowerCase()===".exe";if(t==="darwin")try{return H.accessSync(e,H.constants.X_OK),!0}catch{return!1}return!1}static createSignatureScript(){let e=H.mkdtempSync(I.join(ce.tmpdir(),"deveco-verify-")),t=I.join(e,"Verify-Signature.ps1");return H.writeFileSync(t,"$env:PSModulePath = ($env:PSModulePath -split ';' | Where-Object { $_ -notmatch 'windowsapps' }) -join ';'; Get-AuthenticodeSignature -FilePath $args[0] | ConvertTo-Json -Depth 3 -Compress","utf-8"),{tmpDir:e,scriptPath:t}}static verifyWindowsSignature(e){let t=n.findPowerShellPath();if(!t)throw new Error("PowerShell application not found");let{tmpDir:r,scriptPath:i}=n.createSignatureScript();try{let o=Ri(t,["-NoProfile","-ExecutionPolicy","Bypass","-File",i,e],{encoding:"utf-8",timeout:5e3,stdio:["pipe","pipe","ignore"]}),s=JSON.parse(o);return{signed:s?.Status===0,signer:s?.SignerCertificate?.Subject??void 0}}catch(o){return g(`[ToolProvider] verify Windows Signature, error msg: ${o}`),{signed:!0}}finally{try{H.rmSync(r,{recursive:!0,force:!0})}catch{}}}static verifyMacSignature(e){try{return Ri("codesign",["-v",e],{encoding:"utf-8",timeout:5e3}),{signed:!0}}catch{return{signed:!1}}}};import{execa as Hu}from"execa";import*as zn from"path";var nt=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let i=`${zn.dirname(e.javaPath)}${zn.delimiter}${process.env.PATH||""}`;this.env={...process.env,PATH:i,DEVECO_SDK_HOME:e.sdkPath}}async sync(e,t){let r=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(r)}async buildProduct(e,t){let r=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(r)}async buildModules(e,t,r,i){let o=[...Array.from(i),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(o)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];await this.runHvigor(e)}async stopDaemon(){await this.runHvigor(["--stop-daemon"])}async runHvigor(e){let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];g(`Executing: ${t} ${r.join(" ")}`),await Hu(t,r,{cwd:this.projectRoot,env:this.env,stdout:"inherit",stderr:"inherit"})}};import{execa as Fu}from"execa";var ft=class{toolProvider;projectRoot;constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=[this.toolProvider.ohpmJsPath,"install","--all"];g(`Executing: ${e} ${t.join(" ")}`),await Fu(e,t,{cwd:this.projectRoot,stdout:"inherit",stderr:"inherit"})}};import{mkdir as ju}from"fs/promises";import{dirname as $u,resolve as Bu}from"path";import{execa as Wu}from"execa";import{lock as Mi,check as sS}from"proper-lockfile";function Oi(n){return Bu(n,".hvigor",".build-lock")}function Uu(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function Os(n){let e=$u(Oi(n));if(await ju(e,{recursive:!0}),process.platform==="win32")try{await Wu("attrib",["+h",e])}catch{}}async function zu(n,e){let t=new AbortController,r=Uu(e);await Os(n);let i={lockfilePath:Oi(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await Mi(n,{...i,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return r(),{release:await Mi(n,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Kt(n,e,t){let{release:r,signal:i}=await zu(n,t);try{return await e(i)}finally{await r()}}async function Ls(n,e){let t=new AbortController;await Os(n);let r={lockfilePath:Oi(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await Mi(n,{...r,retries:0})}catch(o){if(o&&typeof o=="object"&&"code"in o&&o.code==="ELOCKED")return{acquired:!1};throw o}try{return{acquired:!0,result:await e(t.signal)}}finally{await i()}}import*as He from"fs";import*as rt from"path";import qu from"json5";var Li={HTTP_TIMEOUT_MS:2e4},qn={USER_AGENT:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",ACCEPT_LANGUAGE:"zh-CN"};var Ni="https://matrix.openharmony.cn",fe={TAGS_API_URL:`${Ni}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${Ni}/api/registry/skill/skills`,SKILL_API_BASE:`${Ni}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},ge={"trae-cn":{path:".trae-cn/skills",displayName:"trae-cn"},opencode:{path:".config/opencode/skills",displayName:"opencode"},cursor:{path:".cursor/skills",displayName:"cursor"},codebuddy:{path:".codebuddy/skills",displayName:"codebuddy"},qoder:{path:".qoder/skills",displayName:"qoder"},"claude-code":{path:".claude/skills",projectPath:".claude/skills",displayName:"claude-code"},codex:{path:".codex/skills",displayName:"codex"}};import{homedir as Ae}from"os";import oe from"path";var Ce="deveco-mcp";var _e={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:oe.join(Ae(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:oe.join(process.platform==="win32"?oe.join(process.env.APPDATA??oe.join(Ae(),"AppData","Roaming"),"Trae CN","User"):oe.join(Ae(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:oe.join(Ae(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:oe.join(Ae(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:oe.join(process.platform==="win32"?oe.join(process.env.APPDATA??oe.join(Ae(),"AppData","Roaming"),"Qoder","SharedClientCache"):oe.join(Ae(),"Library","Application Support","Qoder","SharedClientCache"),"mcp.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"standard"},"claude-code":{name:"claude-code",displayName:"Claude Code",supportsGlobal:!0,globalConfigPath:oe.join(Ae(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:oe.join(Ae(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function _s(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function Ns(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Hs(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function Gn(n,e){return n.format==="opencode"?_s(e):n.format==="claude-code"||n.format==="codex"?Ns(e):Hs(e)}var ye={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var Gu=1e3;function Yn(n){g(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=rt.join(n,ye.SYNC_OUTPUT_PATH);if(!He.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return g(`[ProjectCheck] ${l.reason}`),l}let t=He.statSync(e).mtimeMs;g(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Vu(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return g(`[ProjectCheck] ${l.reason}`),l}let i=rt.join(n,ye.OH_PACKAGE_JSON5),o=Vn(i,t,"root");if(o.required)return g(`[ProjectCheck] Root check: ${o.reason}`),o;let s=rt.join(n,ye.BUILD_PROFILE_JSON5),a=Vn(s,t,"build-profile");if(a.required)return g(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let u=rt.join(n,l.srcPath,ye.OH_PACKAGE_JSON5),f=Vn(u,t,l.name);if(f.required)return g(`[ProjectCheck] Module '${l.name}' check: ${f.reason}`),f;let P=rt.join(n,l.srcPath,ye.BUILD_PROFILE_JSON5),C=Vn(P,t,l.name);if(C.required)return g(`[ProjectCheck] Module '${l.name}' build-profile check: ${C.reason}`),C}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return g(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function Vn(n,e,t){if(!He.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=He.statSync(n).mtimeMs;return r-e>Gu?{required:!0,reason:`${t}: source mtime (${new Date(r).toISOString()}) is newer than sync baseline (${new Date(e).toISOString()})`}:{required:!1,reason:`${t}: up-to-date`}}function Vu(n){let e=rt.join(n,ye.BUILD_PROFILE_JSON5);try{let t=He.readFileSync(e,"utf-8");if(!t.trim())return null;let r=qu.parse(t);if(typeof r!="object"||r===null)return null;let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}function Ju(n,e){if(e.product&&n.validateProduct(e.product),e.buildMode&&!n.profile.app.buildModeSet.some(r=>r.name===e.buildMode))throw new Error(`Build mode '${e.buildMode}' not found in project build-profile.json5.`)}function Ku(n,e){let t;if(e.modules&&e.modules.length>0)t=e.modules;else{let i=n.profile.modules,o=i.filter(s=>n.getModuleType(s.name)==="entry");if(i.length===1)t=[i[0].name];else if(o.length===1)t=[o[0].name];else throw o.length>1?new Error(`Multiple entry modules found (${o.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`):new Error(`No entry module found and multiple modules available (${i.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`)}let r=new Set;for(let i of t){let o=i.indexOf("@"),s=o!==-1?i.substring(0,o):i,a=o!==-1?i.substring(o+1):"default";r.add(`${s}@${a}`)}return Array.from(r)}function Hi(n,e){let t=new Set;for(let r of e){let i=r.indexOf("@"),o=i!==-1?r.substring(0,i):r,s=n.getModuleType(o);s==="shared"?t.add("assembleHsp"):s==="har"?t.add("assembleHar"):t.add("assembleHap")}return t}function Zt(n,e){let t=e,r=`${n} failed`;console.error(_i(r));let i=t.stdout||t.message;throw i&&console.error(i),t.stderr&&console.error(t.stderr),new Error(r,{cause:e})}async function Fi(n,e,t,r,i,o){if(Yn(o).required){console.log(`
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
[
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
[
|
|
20
|
-
[
|
|
21
|
-
|
|
2
|
+
var cw=Object.defineProperty;var lw=(n,e)=>{for(var t in e)cw(n,t,{get:e[t],enumerable:!0})};import{bootstrap as sN}from"global-agent";import{program as ee}from"commander";import{red as aN}from"colorette";import{Command as fv}from"commander";import{green as Za,red as Qa,yellow as ec}from"colorette";import Z from"fs";import*as te from"path";import Nt from"json5";import*as ja from"fs";import*as ie from"path";function m(n){process.env.DEVECO_CLI_DEBUG&&console.log(`[DEBUG] ${n}`)}var P=class n{static ASCII_CONTROL_MAX=31;static ASCII_DELETE=127;static parsePositiveInteger(e,t="value"){let r=e.trim();if(!/^\d+$/.test(r))throw new Error(`${t} must be a positive integer`);let i=Number.parseInt(r,10);if(!Number.isInteger(i)||i<=0)throw new Error(`${t} must be a positive integer`);return i}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
|
|
3
|
+
`)}static parseDurationToSeconds(e,t="value"){let i=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!i)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported).`);let o=i[1];if((i[2]??"s")==="s")return n.parsePositiveInteger(o,t);if(!/^\d+(?:\.\d)?$/.test(o))throw new Error(`${t} supports a maximum of 1 decimal place for minutes (e.g. 2.5m).`);let a=Number.parseFloat(o);if(!Number.isFinite(a)||a<=0)throw new Error(`${t} must be a positive duration.`);return Math.round(a*60)}static assertRelativeTimeRange(e,t){if(e!==void 0&&t!==void 0&&e<t)throw new Error("--from must be greater than or equal to --to when both are provided (e.g. --from 30s --to 10s)")}static filterLogsByRelativeWindow(e,t,r,i=new Date){if(!t&&!r)return e;let[o,s]=n.resolveTimeBounds(t,r,i),a=e.split(/\r?\n/),c=[],l=!1;for(let d of a){let h=n.extractTimestampFromLogLine(d,i);h&&(l=n.isWithinBounds(h,o,s)),l&&c.push(d)}return c.join(`
|
|
4
|
+
`)}static resolveTimeBounds(e,t,r){let i=e?new Date(r.getTime()-e*1e3):null,o=t?new Date(r.getTime()-t*1e3):null;return i&&o?i<o?[i,o]:[o,i]:i?[i,r]:o?[null,o]:[null,null]}static isWithinBounds(e,t,r){let i=e.getTime(),o=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(o!==null&&i<o||s!==null&&i>s)}static extractTimestampFromLogLine(e,t){let r=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!r)return null;let i=t.getFullYear(),o=Number.parseInt(r[1],10)-1,s=Number.parseInt(r[2],10),a=Number.parseInt(r[3],10),c=Number.parseInt(r[4],10),l=Number.parseInt(r[5],10),d=r[6]??"0",h=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),w=new Date(i,o,s,a,c,l,h);return w.getTime()>t.getTime()+1440*60*1e3&&w.setFullYear(i-1),w}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(r=>{let i=r.charCodeAt(0);return i<=n.ASCII_CONTROL_MAX||i===n.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let r=`'${e.replace(/'/g,"'\\''")}'`;return m(`quotePosixShellArg: ${e} -> ${r}`),r}static assertCrashFilename(e){if(!/^\w+-[\w.]+-\d+-\d+$/.test(e))throw new Error(`Invalid crash log filename: ${JSON.stringify(e)}`)}static assertHilogLevel(e){if(!/^[DIWEF]$/.test(e))throw new Error(`Invalid log level: ${e}`)}static resolvePathWithinRoot(e,t){if(ie.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=ie.resolve(ie.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=ie.normalize(e),i=ie.relative(r,t);if(i.split(ie.sep)[0]===".."||ie.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||ie.isAbsolute(e)}static isPathContained(e,t){let r=ie.resolve(t,e),i=ie.relative(t,r);return n.isPathEscaping(i)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){if(ie.isAbsolute(e))return{contained:!1,reason:`Absolute path is not allowed: ${e}`};let r=n.isPathContained(e,t);if(!r.contained)return r;let i;try{i=ja.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=ie.resolve(i,e),s;try{s=ja.realpathSync(o)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${o}`}}return n.isPathContained(s,i)}};var U=class n{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let r=n.tryLoadProjectProfile(t);if(r)return new n(t,r);let i=te.dirname(t);if(i===t)break;t=i}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=te.join(e,"build-profile.json5");if(!Z.existsSync(t))return null;try{let r=Z.readFileSync(t,"utf-8"),i=Nt.parse(r);return i.app?i:null}catch(r){return console.error(`Error parsing ${t}:`,r),null}}getRunnableModuleNames(){return this.profile.modules.map(e=>e.name).filter(e=>this.getModuleType(e)!=="har").join(", ")}getModuleType(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=P.resolvePathWithinRoot(this.rootDir,t.srcPath),i=te.join(r,"src","main","module.json5");if(!Z.existsSync(i))return"entry";try{let o=Z.readFileSync(i,"utf-8");return Nt.parse(o)?.module?.type||"entry"}catch(o){return console.warn(`Warning: Failed to parse ${i}:`,o),"entry"}}getModuleProfile(e){let t=this.profile.modules.find(a=>a.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=P.resolvePathWithinRoot(this.rootDir,t.srcPath),i=te.join(r,"build-profile.json5");if(!Z.existsSync(i))throw new Error(`Build profile for module '${e}' not found at ${i}.`);let o=Z.readFileSync(i,"utf-8");return Nt.parse(o)}getBundleName(){let e=te.join(this.rootDir,"AppScope","app.json5");if(Z.existsSync(e))try{let t=Z.readFileSync(e,"utf-8"),r=Nt.parse(t);if(r?.app?.bundleName)return r.app.bundleName}catch(t){console.warn(`Warning: Failed to parse ${e}:`,t)}throw new Error("Could not find bundleName in AppScope/app.json5.")}isAtomicService(){let e=te.join(this.rootDir,"AppScope","app.json5");if(!Z.existsSync(e))return!1;try{let t=Z.readFileSync(e,"utf-8");return Nt.parse(t)?.app?.bundleType==="atomicService"}catch{return!1}}getMainAbility(e,t){if(t)return t;let r=this.profile.modules.find(s=>s.name===e);if(!r)return"EntryAbility";let i=P.resolvePathWithinRoot(this.rootDir,r.srcPath),o=te.join(i,"src","main","module.json5");if(!Z.existsSync(o))return"EntryAbility";try{let s=Z.readFileSync(o,"utf-8"),c=Nt.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let l=c.find(d=>d.name==="EntryAbility");return l?l.name:c[0].name}catch(s){return console.warn(`Warning: Failed to parse ${o}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new Error(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`);if(!this.profile.app.products?.some(r=>r.name===e)){let r=this.profile.app.products?.map(i=>i.name).join(", ")||"none";throw new Error(`Product '${e}' not found in project configuration. Available products: ${r}`)}}getModuleDependencies(e){let t=this.profile.modules.find(s=>s.name===e);if(!t)return[];let r=P.resolvePathWithinRoot(this.rootDir,t.srcPath),i=te.join(r,"oh-package.json5");if(!Z.existsSync(i))return[];let o=[];try{let s=Z.readFileSync(i,"utf-8"),c=Nt.parse(s)?.dependencies||{};for(let l of Object.values(c)){if(typeof l!="string")continue;let d=l;if(!(d.startsWith("file:")||d.startsWith(".")||d.startsWith("..")))continue;d.startsWith("file:")&&(d=d.substring(5));let w=te.join(t.srcPath,d),b=P.resolvePathWithinRoot(this.rootDir,w),L=this.profile.modules.find(he=>te.resolve(this.rootDir,he.srcPath)===b);L&&o.push(L.name)}}catch{}return o}collectNonHarDependentModuleList(e){let t=[],r=[],i=new Set;for(r.push(e),i.add(e);r.length>0;){let o=r.shift();this.getModuleType(o)!=="har"&&t.push(o);let a=this.getModuleDependencies(o);for(let c of a)i.has(c)||(r.push(c),i.add(c))}return t}resolveModuleMetadata(e,t,r){this.validateProduct(r);let i=this.profile.modules.find(l=>l.name===e);if(!i){let l=this.getRunnableModuleNames();throw new Error(`Module '${e}' not found. Available modules: ${l}`)}let o=this.getModuleType(e)==="shared",s=o?"hspName":"hapName",a=this.buildOutputPath(i.srcPath,r,["intermediates",o?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!Z.existsSync(a))throw new Error(`Build metadata not found for module '${e}' at ${a}. Build the project first.`);let c=this.parseOutputMetadata(a,s);return{moduleNode:i,isShared:o,metadataPath:a,metadata:c}}findArtifactPath(e,t,r,i="default"){let{moduleNode:o,isShared:s,metadata:a}=this.resolveModuleMetadata(e,t,i),{packageName:c,isSigned:l}=a,d=c;if(!l){let b=this.getSignedHapName(c,o.srcPath,i,t);b&&(d=b)}let h=s?"-signed.hsp":"-signed.hap";if(!r&&!d.endsWith(h))throw new Error(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`);let w=this.buildOutputPath(o.srcPath,i,["outputs",t,d]);if(!Z.existsSync(w))throw new Error(`Generated package file not found in ${w}.`);return w}findRemoteHspPaths(e,t,r="default"){let{moduleNode:i,metadata:o}=this.resolveModuleMetadata(e,t,r),s=[],a=new Set;for(let{hspPath:c}of o.dependRemoteHsps){if(a.has(c))continue;a.add(c);let l=te.isAbsolute(c)?c:this.buildOutputPath(i.srcPath,r,["outputs",t,c]);if(!Z.existsSync(l))throw new Error(`Remote HSP dependency not found: ${l}`);s.push(l)}return s}getSignedHapName(e,t,r,i){let o=null;if(e.endsWith("-unsigned.hap")?o=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(o=e.replace("-unsigned.hsp","-signed.hsp")),!o)return null;let s=this.buildOutputPath(t,r,["outputs",i,o]);return Z.existsSync(s)?o:null}buildOutputPath(e,t,r){let i=P.resolvePathWithinRoot(this.rootDir,e),o=te.resolve(i,"build",t,...r);return P.ensurePathWithinRoot(this.rootDir,o)}collectRemoteHsps(e){return e.flatMap(t=>{let r=t.dependRemoteHsps;return Array.isArray(r)?r.filter(i=>!!(i.hspName&&i.hspPath)).map(i=>({hspName:i.hspName,hspPath:i.hspPath})):[]})}parseOutputMetadata(e,t){let r=Z.readFileSync(e,"utf-8"),i=Nt.parse(r),o,s=!1,a=Array.isArray(i)?i:[i];for(let l of a)o||(o=l[t]),s||(s=l.isSigned===!0);if(!o)throw new Error(`Could not find ${t} in output_metadata.json at ${e}`);this.validatePackageName(o);let c=this.collectRemoteHsps(a);return{packageName:o,isSigned:s,dependRemoteHsps:c}}validatePackageName(e){let t=te.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 Yd}from"child_process";import J from"fs";import*as De from"os";import*as S from"path";import Ud from"fs";import*as no from"os";import*as to from"path";import pw from"regedit";import{execFileSync as dw}from"child_process";import Fd from"fs";import*as jd from"os";import*as Ha from"path";function eo(n,e){let t=Ha.join(n,"Contents","Info.plist");if(!Fd.existsSync(t)){m(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[r,i]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let o=dw(r,i,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(o&&!o.includes("Does Not Exist"))return o}catch{}}function uw(n){let e=eo(n,"CFBundleShortVersionString");if(!e)return eo(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[eo(n,"CFBundleVersion"),eo(n,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let i of r){let o=i?.split(".").at(-1)?.replace(new RegExp(`^${t}`),"");if(o&&/^\d+$/.test(o))return`${e}.${o}`}return e}function Lr(n){if(jd.platform()==="darwin")return uw(n);let e=Ha.join(n,"product-info.json");try{let t=JSON.parse(Fd.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}function Or(n,e){let t=Math.max(n.split(".").length,e.split(".").length);for(let r=0;r<t;r++){let i=Number(n.split(".")[r]??0)-Number(e.split(".")[r]??0);if(i)return i}return 0}function fw(n){return n.filter(e=>{try{return Ud.statSync(e).isDirectory()}catch{return!1}})}function mw(){let n=[];for(let e of[to.join(no.homedir(),"Applications"),"/Applications"])try{n.push(...Ud.readdirSync(e).filter(t=>t.endsWith(".app")&&t.toLowerCase().includes("deveco")).map(t=>to.join(e,t)))}catch{}return n}function Hd(n){return new Promise((e,t)=>pw.list(n,(r,i)=>r?t(r):e(i)))}async function $d(n,e,t){let i=((await Hd([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(i.length===0)return[];let o=await Hd(i);return i.flatMap(s=>{let a=o[s]?.values?.[t]?.value;return a?[a]:[]})}async function hw(){let n=[to.join("C:","Program Files","Huawei","DevEco Studio")];for(let e of["HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall","HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"])try{n.push(...await $d(e,t=>t.normalize("NFKC").trim().toLowerCase().startsWith("deveco studio"),"InstallLocation"))}catch{}for(let e of["HKLM\\SOFTWARE\\Huawei\\DevEco Studio","HKLM\\SOFTWARE\\WOW6432Node\\Huawei\\DevEco Studio"])try{n.push(...await $d(e,()=>!0,""))}catch{}return n}async function Bd(){let n=no.platform();if(n==="linux")throw new Error("DevEco Studio is not available on Linux. Set DEVECO_CLI_CLT_PATH to a Command Line Tools installation.");let e=n==="darwin"?mw():await hw(),t=fw(e).flatMap(r=>{let i=Lr(r);return i?(m(`[ToolProvider] ${r} => version ${i}`),[{root:r,version:i}]):(m(`[ToolProvider] Skipping ${r}: could not read version`),[])});if(!t.length)throw new Error("DevEco Studio installation not found in default locations.");return t.reduce((r,i)=>Or(i.version,r.version)>0?i:r)}import*as Wd from"fs";import*as ve from"path";function Mr(n,e){let t=ve.relative(e,n);return t===""||!ve.isAbsolute(t)&&!t.startsWith(`..${ve.sep}`)&&t!==".."}function st(n){let e=ve.resolve(n),t=[],r=e;for(;;)try{let i=Wd.realpathSync(r);return t.length===0?i:ve.join(i,...t.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=ve.dirname(r);if(o===r)return e;t.push(ve.basename(r)),r=o}}function ro(n,e){let t=st(e),r=st(n);return Mr(r,t)?r:null}function io(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function oo(n){let e=io(n);if(!e)throw new Error("Path must not be empty.");return st(e)}var _r={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},so={USER_AGENT:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",ACCEPT_LANGUAGE:"zh-CN"};var Ie={APP_ID:"1009",CONFIG_DIR_NAME:".config",APP_NAME:"deveco-cli",TOKEN_FILE_NAME:"token.enc",KEY_FILE_NAME:"token.dek",API_VERSION:"1.0.0"},ze={LOGIN_URL:"https://devecostudio.huawei.com",CN_LOGIN_URL:"https://cn.devecostudio.huawei.com",AUTH_APPLY_PATH:"console/DevEcoIDE/apply",TEMP_TOKEN_CHECK_PATH:"authrouter/auth/api/temptoken/check",JWT_TOKEN_CHECK_PATH:"authrouter/auth/api/jwToken/check",LOGIN_SUCCESS_PATH:"console/DevEcoCLI/loginSuccess",LOGIN_FAILED_PATH:"console/DevEcoCLI/loginFailed",LOGOUT_PATH:"authrouter/auth/api/logout",AGC_TEAM_LIST_URL:"https://connect-api.cloud.huawei.com/api/ups/user-permission-service/v1/user-team-list"},cn={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},Fr={baseUrl:ze.LOGIN_URL,authUrl:ze.AUTH_APPLY_PATH,tempTokenCheckUrl:ze.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:ze.JWT_TOKEN_CHECK_PATH,successRedirectUrl:ze.LOGIN_SUCCESS_PATH,failedRedirectUrl:ze.LOGIN_FAILED_PATH,logoutUrl:ze.LOGOUT_PATH,agcTeamListUrl:ze.AGC_TEAM_LIST_URL,appId:Ie.APP_ID,timeout:_r.LOGIN_TIMEOUT_MS,countryCode:"CN"};var $a="https://matrix.openharmony.cn",Ve={TAGS_API_URL:`${$a}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${$a}/api/registry/skill/skills`,SKILL_API_BASE:`${$a}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},qe={"trae-cn":{path:".trae-cn/skills",displayName:"trae-cn"},opencode:{path:".config/opencode/skills",displayName:"opencode"},cursor:{path:".cursor/skills",displayName:"cursor"},codebuddy:{path:".codebuddy/skills",displayName:"codebuddy"},qoder:{path:".qoder/skills",displayName:"qoder"},"claude-code":{path:".claude/skills",projectPath:".claude/skills",displayName:"claude-code"},codex:{path:".codex/skills",displayName:"codex"}};import{homedir as ft}from"os";import Ae from"path";var at="deveco-mcp";var Lt={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:Ae.join(ft(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:Ae.join(process.platform==="win32"?Ae.join(process.env.APPDATA??Ae.join(ft(),"AppData","Roaming"),"Trae CN","User"):Ae.join(ft(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:Ae.join(ft(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:Ae.join(ft(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:Ae.join(process.platform==="win32"?Ae.join(process.env.APPDATA??Ae.join(ft(),"AppData","Roaming"),"Qoder","SharedClientCache"):Ae.join(ft(),"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:Ae.join(ft(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:Ae.join(ft(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function zd(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function Gd(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Vd(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function ao(n,e){return n.format==="opencode"?zd(e):n.format==="claude-code"||n.format==="codex"?Gd(e):Vd(e)}var Ye={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var qd="https://developer.huawei.com/consumer/cn/download/";var gw=/^#\s*Version:\s*(\S+)/,yw="26.0.0.810";function ww(n){try{let e=JSON.parse(J.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch{return}}function vw(n){let e=S.join(n,"default","openharmony");return[S.join(n,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>S.join(e,t,"oh-uni-package.json"))]}var I=class n{constructor(e,t,r,i,o,s,a,c,l,d){this._sourceType=e;this._toolchainRoot=t;this._devecoStudioPath=r;this._nodePath=i;this._ohpmJsPath=o;this._hvigorJsPath=s;this._javaPath=a;this._sdkPath=c;this._hdcPath=l;this._emulatorPath=d}_sourceType;_toolchainRoot;_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;static verifiedPaths=new Set;static powerShellPath;static powerShellModulesPath;static installSourcePromise;get sourceType(){return this._sourceType}get toolchainRoot(){return this._toolchainRoot}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return this.verify(this._nodePath)}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get codelinterPath(){return n.resolveCodelinterPath(this._toolchainRoot,this._sourceType)}get javaPath(){return this._javaPath?this.verify(this._javaPath):""}get sdkPath(){return this._sdkPath}get hdcPath(){return this.verify(this._hdcPath)}get emulatorPath(){return this.verify(this._emulatorPath)}get emulatorLauncherPath(){return this.emulatorPath}verify(e){return n.verifiedPaths.has(e)||(n.verifySignature(e),n.verifiedPaths.add(e)),e}assertJava(){if(this._sourceType==="clt"&&!this._javaPath&&(this._javaPath=n.resolveCltJava(!0)),!this._javaPath)throw new Error("Java runtime is required to run hvigor. Set JAVA_HOME or add Java to PATH.");this.verify(this._javaPath)}assertEmulator(){this.verify(this._emulatorPath)}assertStudio(){if(this._sourceType==="clt")throw new Error("This operation requires DevEco Studio. Set DEVECO_CLI_STUDIO_PATH to a DevEco Studio installation.")}assertLsp(){this.assertStudio()}static compareVersion(e,t){return Or(e,t)}static async checkVersion(){let e=await n.resolveInstallSource();(e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)).assertVersion()}static async new(){let e=await n.resolveInstallSource();return e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)}static fromCLT(e){let t=n.buildToolPaths(e,"clt");return n.assertBuiltPathsInsideRoot(e,t,!1),new n("clt",e,void 0,t.nodePath,t.ohpmJsPath,t.hvigorJsPath,n.resolveCltJava(!1),t.sdkPath,t.hdcPath,t.emulatorPath)}static fromIDE(e,t="studio"){let r=n.buildToolPaths(e,"studio");return n.assertBuiltPathsInsideRoot(e,r,!0),new n(t,e,e,r.nodePath,r.ohpmJsPath,r.hvigorJsPath,r.javaPath,r.sdkPath,r.hdcPath,r.emulatorPath)}assertVersion(){if(this._sourceType==="clt"){this.assertCltVersion();return}this.assertIdeVersion()}assertCltVersion(e="26.0.0"){if(this._sourceType!=="clt")throw new Error("This operation requires Command Line Tools.");n.assertMinimumVersion(n.readCltVersion(this._toolchainRoot),"Command Line Tools","version.txt",e,this._toolchainRoot)}assertIdeVersion(e="6.1.0"){this.assertStudio(),n.assertMinimumVersion(Lr(this._toolchainRoot),"DevEco Studio","product-info.json / Info.plist",e,this._toolchainRoot)}require(e){if(this._sourceType==="clt"){this.requireClt(e.clt);return}this.requireIde(e.studio)}requireClt(e){if(e===!1)throw new Error("This operation is not supported in Command Line Tools mode.");typeof e=="string"&&this.assertCltVersion(e)}requireIde(e){if(e===!1)throw new Error("This operation is not supported in DevEco Studio mode.");typeof e=="string"&&this.assertIdeVersion(e)}static assertMinimumVersion(e,t,r,i,o){if(!e)throw new Error(`Failed to determine ${t} version from ${r} at ${o}`);if(!/^\d+(?:\.\d+){1,3}$/.test(e))throw new Error(`Invalid ${t} version "${e}" from ${r} at ${o}`);if(Or(e,i)<0)throw new Error(`The detected ${t} version is ${e}, which is below the minimum required version ${i}. Upgrade before using deveco-cli:
|
|
5
|
+
${qd}`)}static resolveCodelinterPath(e,t){let r=n.getCodelinterCandidates(e,t),i=r.find(n.isFile);if(!i){let a=t==="studio"?"Code Linter not found in DevEco Studio.":"Code Linter not found in DevEco Command Line Tools.";throw new Error(`${a}
|
|
6
|
+
Searched paths:
|
|
7
|
+
${r.join(`
|
|
8
|
+
`)}`)}let o=st(e),s=st(i);return n.assertInsideRoot(s,o,"codelinter"),s}static getCodelinterCandidates(e,t){if(t==="studio"){let r=De.platform()==="darwin"?["Contents"]:[];return[S.join(e,...r,"plugins","codelinter","run","index.js"),S.join(e,...r,"plugins","codelinter","index.js"),S.join(e,...r,"tools","codelinter","bin","codelinter.js"),S.join(e,...r,"tools","codelinter","codelinter.js")]}return[S.join(e,"codelinter","index.js"),S.join(e,"codelinter","run","index.js"),S.join(e,"tool","codelinter","bin","codelinter.js"),S.join(e,"tool","codelinter","codelinter.js")]}static isValidRoot(e,t){if(!n.isDirectory(e))return!1;if(t==="clt")return J.existsSync(S.join(e,"version.txt"));let r=De.platform()==="darwin"?S.join(e,"Contents"):e,i=De.platform()==="darwin"?S.join(r,"Info.plist"):S.join(r,"product-info.json");if(!J.existsSync(i))return!1;let o=n.buildToolPaths(e,"studio");return[o.nodePath,o.ohpmJsPath,o.hvigorJsPath].every(J.existsSync)}static buildToolPaths(e,t){return t==="clt"?n.buildCltToolPaths(e):n.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=S.join(e,"sdk"),r=De.platform()==="win32",i=r?".exe":"";return{nodePath:r?S.join(e,"tool","node","node.exe"):S.join(e,"tool","node","bin","node"),ohpmJsPath:S.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:S.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:t,hdcPath:S.join(t,"default","openharmony","toolchains",`hdc${i}`),emulatorPath:S.join(e,"emulator",r?"Emulator.exe":"Emulator")}}static buildStudioToolPaths(e){let t=De.platform()==="darwin",r=De.platform()==="win32",i=t?S.join(e,"Contents"):e,o=S.join(i,"tools"),s=S.join(i,"sdk"),a=r?".exe":"";return{nodePath:r?S.join(o,"node","node.exe"):S.join(o,"node","bin","node"),ohpmJsPath:S.join(o,"ohpm","bin","pm-cli.js"),hvigorJsPath:S.join(o,"hvigor","bin","hvigorw.js"),javaPath:r?S.join(e,"jbr","bin","java.exe"):t?S.join(i,"jbr","Contents","Home","bin","java"):S.join(i,"jbr","bin","java"),sdkPath:s,hdcPath:S.join(s,"default","openharmony","toolchains",`hdc${a}`),emulatorPath:S.join(o,"emulator",r?"Emulator.exe":"Emulator")}}static isFile(e){try{return J.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return J.existsSync(e)&&J.statSync(e).isDirectory()}catch{return!1}}static resolveInstallSource(){return n.installSourcePromise||(n.installSourcePromise=n.resolveInstallSourceUncached()),n.installSourcePromise}static async resolveInstallSourceUncached(){let e=[["DEVECO_CLI_STUDIO_PATH","studio","studio"],["DEVECO_CLI_CLT_PATH","clt","clt"],["DEVECO_HOME","studio","studio"],["DEVECO_PATH","studio","studio"]];for(let[r,i,o]of e){let s=process.env[r]?.trim();if(s){let a=n.resolveExplicitRoot(s,i,r);return m(`[ToolProvider] Using ${r} \u2192 ${a}`),{sourceType:o,toolchainRoot:a}}}let t=await Bd();return m(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,r){let i;try{i=oo(e)}catch(o){throw new Error(`Invalid ${r}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}return t==="studio"&&De.platform()==="darwin"&&(i=n.normalizeMacStudioRoot(i)),n.isValidRoot(i,t)?i:n.throwInvalidSource(i,t,r,e)}static assertBuiltPathsInsideRoot(e,t,r){let i=st(e),o=[["node",t.nodePath],["ohpm",t.ohpmJsPath],["hvigor",t.hvigorJsPath],["sdk",t.sdkPath],["hdc",t.hdcPath],["emulator",t.emulatorPath]];r&&t.javaPath&&o.push(["java",t.javaPath]);for(let[s,a]of o)n.assertInsideRoot(a,i,s)}static assertInsideRoot(e,t,r){if(ro(e,t)===null)throw new Error(`Unsafe toolchain path: ${r} resolves outside the toolchain root`)}static throwInvalidSource(e,t,r,i){throw t==="clt"&&n.isValidRoot(e,"studio")?new Error(`${r} must point to Command Line Tools, not a DevEco Studio installation; use DEVECO_CLI_STUDIO_PATH instead`):t==="studio"&&n.isValidRoot(e,"clt")?new Error(`${r} must point to a DevEco Studio installation, not Command Line Tools; use DEVECO_CLI_CLT_PATH instead`):new Error(`Invalid ${r}: ${i}`)}static normalizeMacStudioRoot(e){let t=`${S.sep}Contents`,r=S.normalize(e);return r.endsWith(t)?r.slice(0,-t.length):r}static readCltVersion(e){try{return J.readFileSync(S.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(gw)?.[1]?.trim()).find(Boolean)}catch{return}}static resolveCltJava(e){let t=process.env.JAVA_HOME?.trim(),r=t&&(n.javaIn(S.join(t,"bin"))??n.javaIn(t)),i=(process.env.Path??process.env.PATH??"").split(S.delimiter).map(s=>n.javaIn(s.trim())).find(Boolean),o=r??i;if(o)return J.realpathSync(o);if(e)throw new Error("No Java runtime found in CLT mode. Set JAVA_HOME to a JDK/JBR installation directory (or point JAVA_HOME at the JDK bin directory), or add the JDK bin directory to PATH.");return""}static javaIn(e){return(De.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(r=>S.join(e,r)).find(J.existsSync)}getMaxApiLevel(){for(let e of vw(this.sdkPath)){let t=ww(e);if(t!==void 0)return t}return 23}detectApiLevel(){return this.getMaxApiLevel()}_apiscanPaths;getApiscanPaths(){if(this._apiscanPaths)return this._apiscanPaths;let e=De.platform();if(e!=="darwin"&&e!=="win32")throw new Error(`Unsupported platform: ${e}. compat only supports macOS and Windows.`);if(!this._devecoStudioPath)throw new Error("DevEco Studio is required for compatibility checking. Set DEVECO_CLI_STUDIO_PATH or install DevEco Studio.");let t=e==="darwin"?"Contents":"",r=S.join(this._devecoStudioPath,t,"plugins","harmony","arkanalyzer-apiscan"),i=S.join(r,"resources","apiChange"),o=S.join(r,"api-change-scan.js");if(!J.existsSync(i)||!J.existsSync(o)){let s=Lr(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${yw}. Upgrade before using 'check compat' at ${DOWNLOAD_URL}`)}return this._apiscanPaths={apiChangeDir:i,scriptPath:o},this._apiscanPaths}static verifySignature(e){if(!J.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=De.platform();if(t==="linux"){n.assertExecutable(e);return}if(t==="win32"&&S.extname(e).toLowerCase()===".exe"){n.assertSigned(n.verifyWindowsSignature(e),e);return}t==="darwin"&&(n.assertExecutable(e),n.assertSigned(n.verifyMacSignature(e),e))}static assertExecutable(e){try{if(!J.statSync(e).isFile())throw new Error;J.accessSync(e,J.constants.X_OK)}catch{throw new Error(`executable is not accessible: ${e}`)}}static assertSigned(e,t){if(!e.signed)throw new Error(`The executable is not digitally signed: ${t}`)}static findPowerShellPath(){if(n.powerShellPath!==void 0)return n.powerShellPath;let e=S.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return n.powerShellPath=J.existsSync(e)?e:"",n.powerShellPath&&(n.powerShellModulesPath=S.join(S.dirname(n.powerShellPath),"Modules")),n.powerShellPath}static verifyWindowsSignature(e){let t=n.findPowerShellPath();if(!t)throw new Error("The PowerShell application was not found");let r=J.mkdtempSync(S.join(De.tmpdir(),"deveco-verify-")),i=S.join(r,"Verify-Signature.ps1");J.writeFileSync(i,"Get-AuthenticodeSignature -FilePath $args[0] | ConvertTo-Json -Depth 3 -Compress","utf8");try{let o=Yd(t,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",i,e],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"],env:{...process.env,PSModulePath:n.powerShellModulesPath}}),s=JSON.parse(o);return{signed:Number(s.Status)===0}}catch(o){return m(`[ToolProvider] verify Windows Signature, error msg: ${o}`),{signed:!1}}finally{J.rmSync(r,{recursive:!0,force:!0})}}static verifyMacSignature(e){try{return Yd("codesign",["-v",e],{encoding:"utf8",timeout:5e3,stdio:["ignore","ignore","ignore"]}),{signed:!0}}catch{return{signed:!1}}}};import{execa as Sw}from"execa";import*as jr from"path";var mt=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let i=jr.dirname(e.javaPath),o=`${i}${jr.delimiter}${process.env.PATH||""}`,s={...process.env,PATH:o,DEVECO_SDK_HOME:e.sdkPath};e.sourceType==="clt"&&e.javaPath&&(s.JAVA_HOME=jr.dirname(i)),this.env=s}async sync(e,t){let r=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(r)}async buildProduct(e,t){let r=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(r)}async buildModules(e,t,r,i){let o=[...Array.from(i),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(o)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];await this.runHvigor(e)}async stopDaemon(){await this.runHvigor(["--stop-daemon"])}async compileNative(e,t){let r=["--mode","module"];t&&r.push("-p",`module=${t}`),r.push("-p",`product=${e}`,"compileNative","--analyze=normal"),await this.runHvigor(r)}async runHvigor(e){let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];m(`Executing: ${t} ${r.join(" ")}`);let i=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit";await Sw(t,r,{cwd:this.projectRoot,env:this.env,stdout:i,stderr:i})}};import{execa as bw}from"execa";var Ln=class{toolProvider;projectRoot;constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=[this.toolProvider.ohpmJsPath,"install","--all"];m(`Executing: ${e} ${t.join(" ")}`),await bw(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"})}};import{mkdir as Ew}from"fs/promises";import{dirname as Pw,resolve as Cw}from"path";import{execa as Iw}from"execa";import{lock as Ua,check as TL}from"proper-lockfile";function Ba(n){return Cw(n,".hvigor",".build-lock")}function Aw(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function Jd(n){let e=Pw(Ba(n));if(await Ew(e,{recursive:!0}),process.platform==="win32")try{await Iw("attrib",["+h",e])}catch{}}async function Dw(n,e){let t=new AbortController,r=Aw(e);await Jd(n);let i={lockfilePath:Ba(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await Ua(n,{...i,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return r(),{release:await Ua(n,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function ln(n,e,t){let{release:r,signal:i}=await Dw(n,t);try{return await e(i)}finally{await r()}}async function co(n,e){let t=new AbortController;await Jd(n);let r={lockfilePath:Ba(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await Ua(n,{...r,retries:0})}catch(o){if(o&&typeof o=="object"&&"code"in o&&o.code==="ELOCKED")return{acquired:!1};throw o}try{return{acquired:!0,result:await e(t.signal)}}finally{await i()}}import*as Ot from"fs";import*as dn from"path";import Rw from"json5";var Tw=1e3;function uo(n){m(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=dn.join(n,Ye.SYNC_OUTPUT_PATH);if(!Ot.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return m(`[ProjectCheck] ${l.reason}`),l}let t=Ot.statSync(e).mtimeMs;m(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=kw(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return m(`[ProjectCheck] ${l.reason}`),l}let i=dn.join(n,Ye.OH_PACKAGE_JSON5),o=lo(i,t,"root");if(o.required)return m(`[ProjectCheck] Root check: ${o.reason}`),o;let s=dn.join(n,Ye.BUILD_PROFILE_JSON5),a=lo(s,t,"build-profile");if(a.required)return m(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let d=dn.join(n,l.srcPath,Ye.OH_PACKAGE_JSON5),h=lo(d,t,l.name);if(h.required)return m(`[ProjectCheck] Module '${l.name}' check: ${h.reason}`),h;let w=dn.join(n,l.srcPath,Ye.BUILD_PROFILE_JSON5),b=lo(w,t,l.name);if(b.required)return m(`[ProjectCheck] Module '${l.name}' build-profile check: ${b.reason}`),b}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return m(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function lo(n,e,t){if(!Ot.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=Ot.statSync(n).mtimeMs;return r-e>Tw?{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 kw(n){let e=dn.join(n,Ye.BUILD_PROFILE_JSON5);try{let t=Ot.readFileSync(e,"utf-8");if(!t.trim())return null;let r=Rw.parse(t);if(typeof r!="object"||r===null)return null;let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}import*as Te from"fs";import*as Xe from"path";import*as uu from"util";import*as _ from"fs";import*as vo from"path";import k from"fs";import*as po from"os";import*as D from"path";import xw from"json5";var Wa="Huawei";var Qd=3,eu=3,Kd="DevEco Studio",tu={DevEcoStudio:"deveco_studio"};function fo(n){if(!k.existsSync(n)||!k.statSync(n).isDirectory())return!1;let e=k.existsSync(D.join(n,"build-profile.json5")),t=k.existsSync(D.join(n,"hvigorfile.js"))||k.existsSync(D.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=k.readFileSync(D.join(n,"build-profile.json5"),"utf-8");return xw.parse(r).app!==void 0}catch{return!1}}function Ga(n,e,t){if(e>=t)return null;let r=Nw(n),i=Lw(r);if(i)return i;for(let o of r){let s=Ga(o,e+1,t);if(s)return s}return null}function Nw(n){try{let e=k.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(D.join(n,r.name));return t}catch{return[]}}function Lw(n){for(let e of n)if(fo(e))return e;return null}function ht(n){if(!n||n.trim()==="")return null;let e=D.resolve(n),t;try{t=k.realpathSync(e)}catch{t=e}if(!k.existsSync(t))return null;if(fo(t))return t;let r=t;for(let i=1;i<=3;i++){let o=D.dirname(r);if(o===r)break;if(fo(o))return o;r=o}if(k.statSync(t).isDirectory()){let i=Ga(t,0,Qd);if(i)return i}return null}function mo(n){if(!n||n.trim()==="")return null;let e=D.resolve(n),t;try{t=k.realpathSync(e)}catch{t=e}return!k.existsSync(t)||!k.statSync(t).isDirectory()?null:fo(t)?t:Ga(t,0,Qd)}function On(n){if(process.platform==="linux")return null;let e=n??Je();if(!e)return null;let t;if(process.platform==="win32")t=D.join(e,"plugins","openharmony");else if(process.platform==="darwin")t=D.join(e,"contents","plugins","openharmony");else return null;let r=D.join(t,"ace-server","out","index.js");return k.existsSync(r)?t:null}var Ow=["sdk","default","openharmony","native","llvm","bin","clangd"],Mw=[".idea",".deveco","cxx","compile_commands.json"];function _w(n){return process.platform==="darwin"&&n.endsWith(".app")?D.join(n,"Contents"):n}function Xd(n){let e=new Set,t=[n,_w(n)];for(let r of t){let i=D.join(r,...Ow);e.add(process.platform==="win32"?i+".exe":i)}return[...e]}function ho(n){let e=[],t=process.env.DEVECO_HOME??process.env.DEVECO_PATH;if(t&&t.trim()){for(let i of Xd(t.trim()))if(e.push(i),k.existsSync(i))return i}let r=n??Je();if(r){for(let i of Xd(r))if(e.push(i),k.existsSync(i))return i}return null}function Hr(n){return D.join(n,...Mw)}function Je(){if(process.platform==="win32"){let n=[D.join("C:\\Program Files",Wa,Kd),D.join("C:\\Program Files (x86)",Wa,Kd)];return Zd(n)}if(process.platform==="darwin"){let n=["/Applications/DevEco Studio.app",D.join(process.env.HOME??"","Applications","DevEco Studio.app")];return Zd(n)}return null}function Zd(n){for(let e of n)if(k.existsSync(e))return e;return null}function ct(n){return process.platform==="darwin"?D.join(n,"Contents"):n}function Fw(n){if(!n||!k.existsSync(n)||!nu(n))return!1;let e=ct(n);return[D.join(e,"plugins","openharmony"),D.join(e,"sdk"),D.join(e,"tools")].some(r=>k.existsSync(r))}function nu(n){try{return k.statSync(n).isDirectory()}catch{return!1}}function za(n,e){return!n||!k.existsSync(n)?!1:e===tu.DevEcoStudio?Fw(n):!1}function ru(n,e=tu.DevEcoStudio){if(!n)return"";if(za(n,e))return n;let t=jw(n,e);if(t)return t;let r=Hw(n,e);return r||n}function jw(n,e){let t=n;for(let r=0;r<eu;r++){let i=D.dirname(t);if(!i||i===t)break;if(za(i,e))return i;t=i}return null}function Hw(n,e){if(!k.existsSync(n)||!nu(n))return null;let t=[{p:n,depth:0}];for(;t.length>0;){let{p:r,depth:i}=t.shift();if(i>=eu)continue;let o=$w(r,i,e,t);if(o)return o}return null}function $w(n,e,t,r){let i;try{i=k.readdirSync(n,{withFileTypes:!0})}catch{return null}for(let o of i){if(!o.isDirectory())continue;let s=D.join(n,o.name);if(za(s,t))return s;r.push({p:s,depth:e+1})}return null}function iu(n){return new Promise(e=>setTimeout(e,n))}var Uw=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function un(n){let e=D.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&Uw.has(e)}function go(n){return D.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function oe(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function Bw(n){return oe(n)}function pn(n){let e=Bw(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function Mt(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??D.join(po.homedir(),"AppData","Local");return D.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?D.join(po.homedir(),"Library","Logs","devecocli-mcp-server"):D.join(po.homedir(),".local","share","devecocli-mcp-server","logs")}function ou(n,e){let t=Ww(e),r=Gw(t,n);if(r!==null)return r;let i=Date.now(),s=`${n.replace(/:/g,"\\:")}=${i}`,a=zw(t,n,s);return Vw(e,a),i}function Ww(n){let e;try{e=k.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function Gw(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let o=parseInt(t.slice(r+1),10);return Number.isFinite(o)&&o>0?o:null}return null}function zw(n,e,t){let r=!1,i=n.map(o=>{if(r)return o;let s=o.indexOf("=");return s<=0?o:o.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):o});return r||i.push(t),i}function Vw(n,e){try{k.mkdirSync(D.dirname(n),{recursive:!0})}catch{}try{k.writeFileSync(n,e.join(`
|
|
9
|
+
`)+`
|
|
10
|
+
`,"utf8")}catch{}}function Va(n,e,t="[Cleanup]"){try{let r=D.dirname(n);if(!k.existsSync(r))return;let i=Date.now();for(let o of k.readdirSync(r,{withFileTypes:!0}))o.isDirectory()&&qw(D.join(r,o.name),i,e,t)}catch{}}function qw(n,e,t,r){try{let{mtimeMs:i}=k.statSync(n);if(e-i<=t)return;k.rmSync(n,{recursive:!0,force:!0});let o=Math.floor((e-i)/1e3);console.error(`${r} Removed expired dir (age ${Math.floor(o/86400)}d ${Math.floor(o%86400/3600)}h): ${n}`)}catch(i){console.error(`${r} Failed to remove expired dir ${n}: ${i}`)}}function yo(n){let e=n.replace(/sdk\/?$/i,"tools"),t=process.platform==="win32"?"node.exe":"node",r=D.join(e,"node",t);return k.existsSync(r)||process.platform!=="win32"&&(r=D.join(e,"node","bin","node"),k.existsSync(r))?r:process.execPath??"node"}var su="mcp-server.log",Yw="mcp-server",Jw={maxSize:10*1024*1024,maxFiles:4},qa=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={...Jw,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Mt(),this.currentLogFile=vo.join(this.logDir,su),_.existsSync(this.logDir)||_.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${i}`}getRotatedFileName(e,t){return vo.join(this.logDir,`${Yw}-${e}.log.${t}`)}fileExists(e){try{return _.accessSync(e,_.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=_.readdirSync(this.logDir),t=[];for(let i of e)if(i===su||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=vo.join(this.logDir,i),s=_.statSync(o);t.push({name:i,mtime:s.mtime,path:o})}t.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let i=r;i<t.length;i++)try{_.unlinkSync(t[i].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&_.unlinkSync(t);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(e,i),s=this.getRotatedFileName(e,i+1);this.fileExists(o)&&_.renameSync(o,s)}let r=this.getRotatedFileName(e,1);_.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=_.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=_.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{_.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...r){if(this.mode==="silent"||n.LEVEL_ORDER[e]<n.LEVEL_ORDER[this.minLevel])return;let i=r.map(c=>typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),o=i?`${t} ${i}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] ${o}
|
|
11
|
+
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);_.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{_.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},Le=null;function fn(n=!1){Le&&Le.dispose(),Le=new qa(n)}function au(){Le&&(Le.dispose(),Le=null)}function cu(){Le&&Le.flush()}function lu(){return Le?.getLogFilePath()??null}function du(){return Le?.getLogDirectory()??null}function wo(){return Le||fn(!1),Le}var g={debug:(n,...e)=>wo().debug(n,...e),info:(n,...e)=>wo().info(n,...e),warn:(n,...e)=>wo().warn(n,...e),error:(n,...e)=>wo().error(n,...e)};var Ya="";function bo(n){if(!n||n==="auto"||n==="stdout"||n==="none"){Ya="";return}Ya=n}function pu(){return Ya||(du()??"")}function So(n,...e){if(e.length===0)return n;try{return uu.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var f={info(n,...e){g.info(`[lsp] ${So(n,...e)}`)},warn(n,...e){g.warn(`[lsp] ${So(n,...e)}`)},error(n,...e){g.error(`[lsp] ${So(n,...e)}`)},debug(n,...e){g.debug(`[lsp] ${So(n,...e)}`)}};import*as $r from"fs";import*as Ur from"os";import*as Mn from"path";import Kw from"json5";var y={INITIALIZE:"initialize",INITIALIZED:"initialized",SHUTDOWN:"shutdown",EXIT:"exit",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",DID_CLOSE:"textDocument/didClose",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",DECLARATION:"textDocument/declaration",REFERENCES:"textDocument/references",IMPLEMENTATION:"textDocument/implementation",COMPLETION:"textDocument/completion",COMPLETION_ITEM_RESOLVE:"completionItem/resolve",SIGNATURE_HELP:"textDocument/signatureHelp",CODE_ACTION:"textDocument/codeAction",PREPARE_RENAME:"textDocument/prepareRename",RENAME:"textDocument/rename",DOCUMENT_HIGHLIGHT:"textDocument/documentHighlight",DOCUMENT_LINK:"textDocument/documentLink",INLAY_HINT:"textDocument/inlayHint",DOCUMENT_SYMBOL:"textDocument/documentSymbol",WORKSPACE_SYMBOL:"workspace/symbol",DIAGNOSTIC:"textDocument/diagnostic",WORKSPACE_DIAGNOSTIC:"workspace/diagnostic",PREPARE_CALL_HIERARCHY:"textDocument/prepareCallHierarchy",INCOMING_CALLS:"callHierarchy/incomingCalls",OUTGOING_CALLS:"callHierarchy/outgoingCalls",PREPARE_TYPE_HIERARCHY:"textDocument/prepareTypeHierarchy",SUPERTYPES:"typeHierarchy/supertypes",SUBTYPES:"typeHierarchy/subtypes",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",DID_CREATE_FILES:"workspace/didCreateFiles",DID_DELETE_FILES:"workspace/didDeleteFiles",PROGRESS:"$/progress",WINDOW_SHOW_MESSAGE:"window/showMessage",WINDOW_LOG_MESSAGE:"window/logMessage",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing",ARKTS_ERROR:"arkts/error",CPP_INITIALIZED:"cpp/initialized",CPP_INITIALIZATION_FAILED:"cpp/initializationFailed",CPP_INDEXING_PROGRESS:"cpp/indexingProgress",CPP_SYNC_PROJECT:"cpp/syncProject",CPP_SYNC_COMPLETED:"cpp/syncCompleted",CPP_REINITIALIZING:"cpp/reinitializing",CPP_ERROR:"cpp/error",BROADCAST:"lsp/broadcast"},R="2.0";var fu=8192,Ja=100,mu=.03,hu=.7,Oe=900*1e3;function Re(n){if(!$r.existsSync(n))return null;try{let e=$r.readFileSync(n,"utf-8");return e.trim()?Kw.parse(e):null}catch{return null}}function Eo(n,e){let t=Math.floor(Ur.totalmem()/1048576),r=Math.floor(t*hu),i,o;e!==void 0&&Number.isFinite(e)&&e>0?(i=e,o=`override(${e})`):(i=fu,n>Ja&&(i+=(n-Ja)*mu*1024),o=`formula(moduleCount=${n})`);let s=r>0&&i>r;s&&(i=r);let a=Math.round(i);return f.info(`[computeLspServerMaxSize] source=${o}, physicalTotal=${t}MB, physicalCap(70%)=${r}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function Ke(n){if(n.startsWith("file:"))return n;try{let e=Mn.resolve(n),t=new URL(`file://${e}`).toString();if(Ur.platform()==="win32"){let r=t.match(/^file:\/\/\/([A-Za-z]):/);if(r){let i=r[1].toUpperCase(),o=t.substring(`file:///${r[1]}:`.length);t=`file:///${i}%3A${o}`}}return t}catch{return n}}function _n(n){return n&&n.replace(/\\/g,"/")}function H(n){let e=Mn.normalize(n).replace(/\\/g,"/");if(Ur.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function gu(n){return Mn.join(n,"build-profile.json5")}var gt=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=gu(this.projectRoot);try{let t=Re(e);if(typeof t!="object"||t===null)return[];let r=t.modules;return Array.isArray(r)?r.filter(i=>{if(typeof i!="object"||i===null)return!1;let o=i;return typeof o.name=="string"&&typeof o.srcPath=="string"}):[]}catch(t){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};import{spawn as Xw}from"child_process";import*as Io from"path";import*as Co from"fs";var Zw=600*1e3;function Qw(n,e,t){let r=t.split(/\s+/).filter(i=>i.length>0);return[n,[e,...r]]}function ev(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 Po(n){return n.join("")}function tv(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
12
|
+
Output so far:
|
|
13
|
+
`+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function nv(n,e,t){return new Promise(r=>{let i=Xw(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:o,stderr:s}=ev(i),a=setTimeout(()=>{i.kill();let c=[Po(o),Po(s)].filter(Boolean).join(`
|
|
14
|
+
`).trim();r({success:!1,output:`Build process timeout after 10 minutes.
|
|
15
|
+
Output so far:
|
|
16
|
+
`+c,exitCode:-1})},Zw);i.on("close",(c,l)=>{clearTimeout(a);let d=[Po(o),Po(s)].filter(Boolean).join(`
|
|
17
|
+
`).trim()||"";r(tv(c,l,d))}),i.on("error",c=>{clearTimeout(a),r({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function Ka(n,e,t,r,i){let o={...process.env,DEVECO_SDK_HOME:r},s=Qw(e,t,i);return await nv(s,n,o)}function rv(n){let e=Io.join(Io.dirname(n),"tools","hvigor","bin","hvigorw.js");return{node_path:yo(n),hvigor_path:e,sdk_path:n}}function iv(n){return!n.node_path||!Co.existsSync(n.node_path)?`Node path not found or invalid: ${n.node_path}`:!n.hvigor_path||!Co.existsSync(n.hvigor_path)?`Hvigor path not found or invalid: ${n.hvigor_path}`:!n.sdk_path||!Co.existsSync(n.sdk_path)?`SDK path not found or invalid: ${n.sdk_path}`:null}var ov="--sync -p product=default --analyze=normal --parallel --incremental --no-daemon";async function yu(n,e){try{let t=rv(e),r=iv(t);return r!=null?(f.info(`Config validation failed: ${r}`),!1):(await Ka(n,t.node_path,t.hvigor_path,e,ov)).success}catch(t){return f.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}function sv(n){let e=Xe.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function av(n,e){let t=Xe.join(n,e.name);return e.isDirectory()?e.name===".cxx"||wu(t):sv(t)}function wu(n){if(!Te.existsSync(n))return!1;try{return Te.readdirSync(n,{withFileTypes:!0}).some(t=>av(n,t))}catch{}return!1}function mn(n){let t=new gt(n).getAllModuleInfo(),r=[];for(let i of t){let o=P.resolvePathWithinRoot(n,i.srcPath);wu(o)&&r.push(i)}return r}function cv(n){let e=[],r=new gt(n).getAllModuleInfo();for(let i of r){let o=P.resolvePathWithinRoot(n,i.srcPath),s=Xe.join(o,".cxx");Te.existsSync(s)&&vu(s,e)}return e}function vu(n,e){try{let t=Te.readdirSync(n,{withFileTypes:!0});for(let r of t){let i=Xe.join(n,r.name);r.isDirectory()?vu(i,e):r.name==="compile_commands.json"&&e.push(i)}}catch{}}function lv(n){let e=[];for(let t of n)try{let r=Te.readFileSync(t,"utf8"),i=JSON.parse(r);e.push(...i)}catch{}return e}function dv(n,e){let t=Xe.join(n,...uv.slice(0,-1));Te.mkdirSync(t,{recursive:!0});let r=Xe.join(t,"compile_commands.json");Te.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function Xa(n){let e=cv(n);if(e.length>0){let t=lv(e);dv(n,t),g.info(`[CppCompile] compile_commands.json generated, ${t.length} compile commands`)}else g.warn("[CppCompile] No compile_commands.json files found")}var uv=[".idea",".deveco","cxx","compile_commands.json"];async function pv(n,e,t){let r=Xe.join(ct(e),"sdk"),i=process.execPath||"node",o=Xe.join(ct(e),"tools");g.info(`[CppCompile] devecoPath: ${e}, contentRoot: ${ct(e)}, sdkPath: ${r}, toolsDir: ${o}`);let s=Xe.join(o,"hvigor","bin","hvigorw.js");for(let a of t){let c=["--mode","module","-p",`module=${a.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"].join(" ");g.info(`[CppCompile] Running compileNative for module: ${a.name}`);let l=await Ka(n,i,s,r,c);l.success?g.info(`[CppCompile] compileNative ${a.name} succeeded`):g.warn(`[CppCompile] compileNative ${a.name} failed: ${l.output}`)}}async function Su(n,e){let t=mn(n);if(t.length===0){g.info("[CppCompile] No C++ modules found, skipping initialization");return}g.info(`[CppCompile] Found ${t.length} C++ module(s): ${t.map(r=>r.name).join(", ")}`),await pv(n,e,t),Xa(n)}function mv(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 hv(n,e){let t;if(e.modules&&e.modules.length>0)t=e.modules;else{let i=n.profile.modules,o=i.filter(s=>n.getModuleType(s.name)==="entry");if(i.length===1)t=[i[0].name];else if(o.length===1)t=[o[0].name];else throw o.length>1?new Error(`Multiple entry modules found (${o.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`):new Error(`No entry module found and multiple modules available (${i.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`)}let r=new Set;for(let i of t){let o=i.indexOf("@"),s=o!==-1?i.substring(0,o):i,a=o!==-1?i.substring(o+1):"default";r.add(`${s}@${a}`)}return Array.from(r)}function tc(n,e){let t=new Set;for(let r of e){let i=r.indexOf("@"),o=i!==-1?r.substring(0,i):r,s=n.getModuleType(o);s==="shared"?t.add("assembleHsp"):s==="har"?t.add("assembleHar"):t.add("assembleHap")}return t}function Br(n,e){let t=e,r=`${n} failed`;console.error(Qa(r));let i=t.stdout||t.message;throw i&&console.error(i),t.stderr&&console.error(t.stderr),new Error(r,{cause:e})}async function nc(n,e,t,r,i,o){let s=uo(o);console.log(`
|
|
18
|
+
[ohpm install] Running...`);try{await n.installAll()}catch(a){Br("ohpm install",a)}if(s.required){console.log(`
|
|
19
|
+
[hvigor sync] Running...`);try{await e.sync(t,r)}catch(a){Br("hvigor sync",a)}}else console.log(`
|
|
20
|
+
[hvigor sync] Skipped (configurations unchanged)`);console.log(`
|
|
21
|
+
[hvigor build] Running...`);try{i.type==="product"?await e.buildProduct(t,r):await e.buildModules(t,r,i.modulesToBuild,i.moduleTasks)}catch(a){Br("hvigor build",a)}gv(o)}function gv(n){try{if(mn(n).length===0)return;Xa(n),console.log(Za(`
|
|
22
|
+
Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(ec(`
|
|
23
|
+
Failed to merge compile_commands.json: ${e.message}`))}}var bu=new fv("build").description("Build HarmonyOS project").option("--product <product>","Product name defined in build-profile.json5 (default: default)").option("--modules <modules...>","Modules to build (format: module or module@target)").option("--build-mode <mode>","Build mode (buildModeSet in build-profile.json5; e.g. debug, release; default: debug)").action(async n=>{try{let e=process.cwd(),t=U.discover(e);console.warn(ec("Ensure the project source is trustworthy before proceeding."));let r=await I.new();r.assertJava(),mv(t,n);let i=n.product||"default",o=n.buildMode||"debug",s;if(n.product&&!n.modules)s={type:"product"};else{let l=hv(t,n),d=tc(t,l);s={type:"modules",modulesToBuild:l,moduleTasks:d}}let a=new Ln(r,t.rootDir),c=new mt(r,t.rootDir);await ln(t.rootDir,async()=>nc(a,c,i,o,s,t.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")}),console.log(`
|
|
24
|
+
`+Za("Build completed successfully"))}catch(e){console.error(Qa(e.message)),process.exit(1)}});bu.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{try{let n=process.cwd(),e=U.discover(n);console.warn(ec("Ensure the project source is trusted before proceeding."));let t=await I.new();t.assertJava();let r=new mt(t,e.rootDir);await ln(e.rootDir,async()=>{console.log(`
|
|
25
|
+
[1/2] Running hvigor clean...`);try{await r.clean()}catch(i){Br("hvigor clean",i)}console.log(`
|
|
26
|
+
[2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(i){Br("hvigor --stop-daemon",i)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
|
|
27
|
+
`+Za("Clean completed successfully."))}catch(n){console.error(Qa(n.message)),process.exit(1)}});var Eu=bu;import{Command as $v}from"commander";import{green as _u,red as Uv,yellow as No}from"colorette";import*as Lo from"path";import{randomUUID as Tv}from"crypto";import{execa as kv}from"execa";import{execa as Rv}from"execa";import{execFile as yv,spawn as wv}from"child_process";import{promisify as vv}from"util";var Sv=vv(yv);function Pu(n,e,t){let i=n.replace(/\r\n/g,`
|
|
22
28
|
`).split(`
|
|
23
|
-
`),o=i.pop()??"",s=i.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),o}function
|
|
24
|
-
`)){let i=r.trim();if(!i||i.startsWith("[Empty]"))continue;let o=i.split(/\s+/),s=o[0];if(!s||s.startsWith("[Empty]"))continue;let a=o.length>=2?o[1]:"device";if(a.toLowerCase()==="unauthorized"){
|
|
29
|
+
`),o=i.pop()??"",s=i.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),o}function Cu(n,e,t){let r=n.endsWith("\r")?n.slice(0,-1):n;r.length>0&&t.onData([r],e)}function bv(n,e){return{stdout:n.stdoutChunks.join(""),stderr:n.stderrChunks.join(""),exitCode:e??-1}}function Ev(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function Pv(n,e,t,r,i){n.stdout?.on("data",o=>{let s=o.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=Pu(e.stdoutLineBuffer+s,"stdout",t)}),n.stderr?.on("data",o=>{let s=o.toString();e.stderrChunks.push(s),e.stderrLineBuffer=Pu(e.stderrLineBuffer+s,"stderr",t)}),n.on("error",o=>{e.settled||(e.settled=!0,t.onError(o),i(o))}),n.on("close",o=>{if(e.settled)return;e.settled=!0,Cu(e.stdoutLineBuffer,"stdout",t),Cu(e.stderrLineBuffer,"stderr",t),t.onClose(o);let s=bv(e,o);r(s)})}async function Wr(n,e=[],t={}){try{let{stdout:r,stderr:i}=await Sv(n,e,t);return{stdout:typeof r=="string"?r.trim():"",stderr:typeof i=="string"?i.trim():"",exitCode:0}}catch(r){let i=r;return{stdout:i.stdout?.trim()||"",stderr:i.stderr?.trim()||i.message,exitCode:typeof i.code=="number"?i.code:1}}}async function Iu(n,e,t){return await new Promise((r,i)=>{let o=wv(n,e,{stdio:["inherit","pipe","pipe"]}),s=Ev();Pv(o,s,t,r,i)})}function Au(n){let e=n.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var Cv=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],Iv=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function Fn(n){return n?Cv.some(e=>e.test(n))?"transient":Iv.some(e=>e.test(n))?"fatal":"ok":"ok"}var rc=[800,1500,2500];function Av(n){return new Promise(e=>setTimeout(e,n))}async function ke(n,e){let t=1+rc.length,r={stdout:"",stderr:"",exitCode:-1};for(let i=0;i<t;i++){if(r=await Wr(n,e),r.exitCode===0||Fn(r.stderr)!=="transient"||i>=t-1)return r;m(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${rc[i]}ms`),await Av(rc[i])}return r}var Du=/^[\w.-]+$/;async function Ao(n,e,t){if(!Du.test(t)){m(`Skipping invalid param key: ${JSON.stringify(t)}`);return}let r=["-t",e,"shell","param","get",t];m(`Executing: ${n} ${r.join(" ")}`);let i=await ke(n,r);if(i.exitCode!==0)return;let o=i.stdout.trim();if(!(!o||Fn(o)!=="ok"))return Au(o)}var ic="__DEVECO_PARAM_DELIM__";function Dv(n,e){let t=new Map,r=n.split(ic);for(let i=0;i<e.length;i++){let o=(r[i]??"").trim();if(!o||Fn(o)!=="ok")continue;let s=Au(o);s&&t.set(e[i],s)}return t}async function jn(n,e,t){let r=t.filter(a=>Du.test(a)?!0:(m(`Skipping invalid param key: ${JSON.stringify(a)}`),!1));if(r.length===0)return new Map;if(r.length===1){let a=new Map,c=await Ao(n,e,r[0]);return c&&a.set(r[0],c),a}let i=r.map(a=>`param get ${a}`).join(`; echo ${ic}; `)+`; echo ${ic}`,o=await ke(n,["-t",e,"shell",i]);if(o.exitCode===0){let a=Dv(o.stdout,r);if(a.size>0)return a}m(`Batched param fetch failed (exit=${o.exitCode}), falling back to individual calls for ${e}`);let s=new Map;for(let a of r){let c=await Ao(n,e,a);c&&s.set(a,c)}return s}function hn(n){return n.startsWith("127.0.0.1:")}var Ru=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],Q=class n{hdcPath;constructor(e){this.hdcPath=e}static from(e){return new n(e.hdcPath)}static withHdcPath(e){return new n(e)}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}stripBrandPrefix(e,t){let r=e.trim(),i=t?.trim();if(!r||!i)return r;let o=new RegExp(`^${this.escapeRegExp(i)}(\\s+|[-_]+)?`,"i");return r.replace(o,"").trim()||r}async executeHdc(e){return m(`Executing: ${this.hdcPath} ${e.join(" ")}`),Rv(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let r of e.split(`
|
|
30
|
+
`)){let i=r.trim();if(!i||i.startsWith("[Empty]"))continue;let o=i.split(/\s+/),s=o[0];if(!s||s.startsWith("[Empty]"))continue;let a=o.length>=2?o[1]:"device";if(a.toLowerCase()==="unauthorized"){m(`[DeviceManager] Skipping unauthorized device: ${s}`);continue}t.push({serial:s,status:a})}return t}extractDisplayName(e){let t=e.get("ohos.qemu.hvd.name");if(t)return t;let r=e.get("const.product.name");if(r&&r!=="emulator")return r;let i=e.get("const.product.model");if(i&&i!=="emulator"){let s=e.get("const.product.brand");return this.stripBrandPrefix(i,s)}let o=e.get("const.build.product");if(o&&o!=="emulator")return o}async getDeviceName(e){let t=await jn(this.hdcPath,e,[...Ru]);return this.extractDisplayName(t)??e}async getDeviceInfo(e,t){if(e.length===0)return null;if(t){let r=e.find(s=>s.serial===t);if(r)return r;let i=t.toLowerCase(),o=[];for(let s of e){let a=await this.getDeviceName(s.serial);a.toLowerCase()===i&&o.push({device:s,name:a})}if(o.length===1)return o[0].device;throw o.length>1?new Error(`Multiple devices match "${t}". Use a serial instead:
|
|
25
31
|
`+o.map(s=>` - ${s.name} (${s.device.serial})`).join(`
|
|
26
|
-
`)):new Error(`Device "${t}" not found. Use \`devecocli device list\` to see available targets.`)}return e[0]}async getDeviceDetail(e){let t={serial:e,status:"device"};try{let r=await yt(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=r.get("const.product.devicetype");let i=r.get("const.ohos.apiversion"),o=r.get("const.ohos.releasetype");i&&(t.osVersion=o?`API ${i} (${o})`:`API ${i}`)}catch{}return t}async listDevicesWithName(){let e=await this.listDevices();return Promise.all(e.map(async t=>({serial:t.serial,name:await this.getDeviceName(t.serial)})))}async getConnectedEntries(){let e=await this.listDevices();return Promise.all(e.map(t=>this.buildConnectedEntry(t.serial)))}async buildConnectedEntry(e){let t=Xt(e),r,i;try{let o=await yt(this.hdcPath,e,[...Vs]);r=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:i}}};var Kn=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=G.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;g(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await dp(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){let r=await this.runHdc(["-t",e,"shell","bm","uninstall","-n",t],!1);if(r.includes("uninstall bundle successfully"))return!0;if(r.includes("uninstall missing installed bundle"))return!1;throw new Error(`Uninstall failed: ${r}`)}async installApp(e,t){if(t.length===0)return;let i=`/data/local/tmp/${lp()}`;try{await this.runHdc(["-t",e,"shell","mkdir",i]);for(let s of t){let a=await this.runHdc(["-t",e,"file","send",s,i+"/"]);if(!a.startsWith("FileTransfer finish"))throw new Error(a)}let o=await this.runHdc(["-t",e,"shell","bm","install","-p",i]);if(!o.includes("install bundle successfully."))throw new Error(o);console.log("App installed successfully")}finally{await this.runHdc(["-t",e,"shell","rm","-rf",i],!1)}}async launchApp(e,t,r){let i=["-t",e,"shell","aa","start","-a",r,"-b",t];return await this.runHdc(i)}};function hp(n){let e=n.indexOf("@"),t=e!==-1?n.substring(0,e):n,r=e!==-1?n.substring(e+1):"default";return{moduleName:t,targetName:r}}async function fp(n,e){let t=await n.listDevices();if(t.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");if(!e&&t.length>1){let i=await n.listDevicesWithName();throw new Error("Multiple devices found. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+i.map(o=>` - ${o.name} (${o.serial})`).join(`
|
|
27
|
-
`))}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let i=await n.getDeviceName(r.serial);console.log(`Auto-selected device: ${i} (${r.serial})`)}return r.serial}function
|
|
32
|
+
`)):new Error(`Device "${t}" not found. Use \`devecocli device list\` to see available targets.`)}return e[0]}async getDeviceDetail(e){let t={serial:e,status:"device"};try{let r=await jn(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=r.get("const.product.devicetype");let i=r.get("const.ohos.apiversion"),o=r.get("const.ohos.releasetype");i&&(t.osVersion=o?`API ${i} (${o})`:`API ${i}`)}catch{}return t}async listDevicesWithName(){let e=await this.listDevices();return Promise.all(e.map(async t=>({serial:t.serial,name:await this.getDeviceName(t.serial)})))}async getConnectedEntries(){let e=await this.listDevices();return Promise.all(e.map(t=>this.buildConnectedEntry(t.serial)))}async buildConnectedEntry(e){let t=hn(e),r,i;try{let o=await jn(this.hdcPath,e,[...Ru]);r=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:i}}};var Hn=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=Q.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;m(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await kv(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){let r=await this.runHdc(["-t",e,"shell","bm","uninstall","-n",t],!1);if(r.includes("uninstall bundle successfully"))return!0;if(r.includes("uninstall missing installed bundle"))return!1;throw new Error(`Uninstall failed: ${r}`)}async installApp(e,t){if(t.length===0)return;let i=`/data/local/tmp/${Tv()}`;try{await this.runHdc(["-t",e,"shell","mkdir",i]);for(let s of t){let a=await this.runHdc(["-t",e,"file","send",s,i+"/"]);if(!a.startsWith("FileTransfer finish"))throw new Error(a)}let o=await this.runHdc(["-t",e,"shell","bm","install","-p",i]);if(!o.includes("install bundle successfully."))throw new Error(o);console.log("App installed successfully")}finally{await this.runHdc(["-t",e,"shell","rm","-rf",i],!1)}}async launchApp(e,t,r){let i=["-t",e,"shell","aa","start","-a",r,"-b",t];return await this.runHdc(i)}async forceStopApp(e,t){let r=["-t",e,"shell","aa","force-stop",t];return await this.runHdc(r,!1)}};import oc from"fs";import*as sc from"path";function Tu(n,e){if(!oc.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=oc.readFileSync(n,"utf-8").split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("#"));if(r.length===0)throw new Error("Apply file list is empty (no valid entries)");let i=sc.resolve(e),o=new Set,s=[];for(let a of r){let c=sc.resolve(i,a),l=P.isPathContainedWithSymlink(a,i);if(!l.contained){if(P.isPathContained(a,i).contained&&!oc.existsSync(c))throw new Error(`File not found: ${a}`);let d=l.reason?`; ${l.reason}`:"";throw new Error(`File path is outside the project directory: ${a}${d}`)}o.has(c)||(o.add(c),s.push(c))}return s}import ac from"fs";import Gr from"path";import{execa as Lv}from"execa";import ku from"fs";import*as xu from"path";import xv from"json5";function Nv(n,e){try{let r=xv.parse(ku.readFileSync(n,"utf-8")).modules?.find(i=>i.name===e);return r?.srcPath?r.srcPath.replace(/^\.\//,""):null}catch(t){return m(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function Do(n,e){let t=xu.join(n,"build-profile.json5");return ku.existsSync(t)?Nv(t,e)??e:e}async function Nu(n,e,t,r){let i=Gr.dirname(n.javaPath),o={...process.env,PATH:`${i}${Gr.delimiter}${process.env.PATH||""}`,DEVECO_SDK_HOME:n.sdkPath},s=[n.hvigorJsPath,"--mode","module","-p",`module=${t.join(",")}@${r}`,"-p",`product=${r}`,"-p","debuggable=true","assembleDevHqf","--analyze=normal","--parallel","--incremental","--no-daemon"];m(`[buildSignedHqf] ${n.nodePath} ${s.join(" ")}`);let a=await Lv(n.nodePath,s,{cwd:e,env:o,stdout:"inherit",stderr:"inherit",reject:!1}),c=(a.exitCode??0)|0;if(c===-1)throw new Error("hvigor hot compile produced invalid abc (exit code -1)");if(c!==0)throw new Error(`hvigor assembleDevHqf failed with exit code ${a.exitCode}`);return t.map(l=>Mv(e,l,r))}function Lu(n,e,t){let r=Do(n,e);return Gr.join(n,r,"build",t,"outputs")}function Ov(n,e,t){return Gr.join(Lu(n,e,t),`${e}-${t}-signed.hqf`)}function Mv(n,e,t){let r=Lu(n,e,t),i=Ov(n,e,t);if(ac.existsSync(i))return i;let o=cc(r,"-signed.hqf")??cc(r,".hqf");if(!o)throw new Error(`Signed hqf not found at ${i} (and no *.hqf under ${r})`);return m(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${o}`),o}function cc(n,e){if(!ac.existsSync(n))return null;for(let t of ac.readdirSync(n,{withFileTypes:!0})){let r=Gr.join(n,t.name);if(t.isDirectory()){let i=cc(r,e);if(i)return i}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import B from"fs";import*as x from"path";import lc from"json5";var Ou="default",Ro=class n{static writeChangedFileLists(e,t,r,i){let o=t||Ou,s=n.loadBuildProfile(e);if(!s)return{writtenModules:[],skippedFiles:r};let a=s.modules,c=n.filterRunnableModules(e,a);if(c.length===0)return{writtenModules:[],skippedFiles:r};let l=n.buildReverseDependencyMap(e,a),d=n.createCollectors(c),h=n.collectChanges(r,e,a,l,d);return{writtenModules:n.flushCollectors(e,o,c,d,i),skippedFiles:h}}static initEmptyChangedFileLists(e,t,r){let i=t||Ou,o=n.loadBuildProfile(e);if(!o)return[];let s=o.modules,a=[];for(let c of s){let l=n.getModuleType(e,c.srcPath);if(l!=="entry"&&l!=="shared")continue;let d=!r||c.name===r;n.initEmptyForModule(e,i,c.srcPath,d),a.push(c.name)}return a}static filterRunnableModules(e,t){return t.filter(r=>{let i=n.getModuleType(e,r.srcPath);return i==="entry"||i==="shared"})}static createCollectors(e){let t=new Map;for(let r of e)t.set(r.name,{hotReloadEntries:[],patchEtsFiles:[],patchRawFiles:[],patchResFiles:[]});return t}static collectChanges(e,t,r,i,o){let s=[];for(let a of e){let c=x.normalize(a),l=n.classifyFile(c,t,r);if(l.fileClass==="unknown"){s.push(c);continue}let d=n.findModuleByFilePath(c,t,r);if(!d){s.push(c);continue}let h=n.resolveTargetModules(d,t,r,i);if(h.length===0){s.push(c);continue}n.dispatchToCollectors(h,o,c,l,d.srcPath,t)}return s}static resolveTargetModules(e,t,r,i){let o=n.getModuleType(t,e.srcPath);return o==="entry"||o==="shared"?[e.name]:Array.from(n.findTopLevelConsumers(e.name,i,t,r))}static dispatchToCollectors(e,t,r,i,o,s){for(let a of e){let c=t.get(a);c&&n.addFileToCollector(c,r,i.fileClass,o,s)}}static flushCollectors(e,t,r,i,o){let s=[];for(let a of r){let c=i.get(a.name);if(!c||!n.hasAnyChange(c))continue;(!o||a.name===o)&&c.hotReloadEntries.length>0&&n.writeApplyFile(e,a.srcPath,t,c.hotReloadEntries),n.writePatchFile(e,a.srcPath,t,c.patchEtsFiles,c.patchRawFiles,c.patchResFiles),s.push(a.name)}return s}static hasAnyChange(e){return e.hotReloadEntries.length>0||e.patchEtsFiles.length>0||e.patchRawFiles.length>0||e.patchResFiles.length>0}static initEmptyForModule(e,t,r,i){let o=x.join(e,r,"build",t,"intermediates","patch","default"),s=x.join(o,"changedFileList.json");if(B.existsSync(s)||(B.mkdirSync(o,{recursive:!0}),B.writeFileSync(s,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!i)return;let a=x.join(e,r,"build",t,"intermediates","hotReload"),c=x.join(a,"changedFileList.json");B.existsSync(c)||(B.mkdirSync(a,{recursive:!0}),B.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=x.join(e,"build-profile.json5");if(!B.existsSync(t))return null;try{let r=B.readFileSync(t,"utf-8");return lc.parse(r)}catch{return null}}static classifyFile(e,t,r){let i=x.extname(e).toLowerCase();if(i===".ets"||i===".ts")return{fileClass:"ets_ts",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};let o=e.replace(/\\/g,"/");return o.includes("/resources/rawfile/")?{fileClass:"raw_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:o.includes("/resources/resfile/")?{fileClass:"res_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:{fileClass:"unknown",moduleSrcPath:""}}static findModuleByFilePath(e,t,r){let i=x.normalize(e);for(let o of r){let s=x.normalize(x.join(t,o.srcPath)),a=s+x.sep;if(i.startsWith(a)||i===s)return o}return null}static getModuleType(e,t){let r=x.join(e,t,"src","main","module.json5");if(!B.existsSync(r))return"entry";try{let i=B.readFileSync(r,"utf-8");return lc.parse(i)?.module?.type||"entry"}catch{return"entry"}}static buildReverseDependencyMap(e,t){let r=new Map;for(let i of t){let o=n.readLocalDependencies(e,i.srcPath);for(let s of o){let a=r.get(s)||[];a.includes(i.name)||a.push(i.name),r.set(s,a)}}return r}static readLocalDependencies(e,t){let r=x.join(e,t,"oh-package.json5");if(!B.existsSync(r))return[];try{let i=B.readFileSync(r,"utf-8"),o=lc.parse(i);return n.resolveDepModuleNames(e,t,o.dependencies||{})}catch{return[]}}static resolveDepModuleNames(e,t,r){let i=n.loadBuildProfile(e);if(!i)return[];let o=i.modules,s=[];for(let a of Object.values(r)){if(typeof a!="string")continue;let c=n.tryResolveDepModule(e,t,a,o);c&&s.push(c)}return s}static tryResolveDepModule(e,t,r,i){let o=r;if(!(o.startsWith("file:")||o.startsWith(".")||o.startsWith("..")))return null;o.startsWith("file:")&&(o=o.substring(5));let a=x.resolve(e,t,o);return i.find(l=>x.resolve(e,l.srcPath)===a)?.name??null}static findTopLevelConsumers(e,t,r,i){let o=new Set,s=new Set,a=[e];for(;a.length>0;){let c=a.shift();s.has(c)||(s.add(c),n.processDependents(c,t,r,i,o,a))}return o}static processDependents(e,t,r,i,o,s){let a=t.get(e)||[];for(let c of a){let l=i.find(h=>h.name===c);if(!l)continue;let d=n.getModuleType(r,l.srcPath);(d==="entry"||d==="shared")&&o.add(c),d==="har"&&s.push(c)}}static addFileToCollector(e,t,r,i,o){let s=x.join(o,i,"src","main","resources");r==="ets_ts"?(e.hotReloadEntries.push({filePath:t,belongProjectPath:o}),e.patchEtsFiles.push(t)):r==="raw_file"?e.patchRawFiles.push({filePath:t,resourcePath:s}):r==="res_file"&&e.patchResFiles.push({filePath:t,resourcePath:s})}static writeApplyFile(e,t,r,i){let o=t.replace(/^\.\//,""),s=x.join(e,o,"build",r,"intermediates","hotReload","changedFileList.json"),a=n.readExistingApply(s),c=n.mergeApplyEntries(a,i),l=x.dirname(s);B.existsSync(l)||B.mkdirSync(l,{recursive:!0}),B.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),m(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!B.existsSync(e))return[];try{let t=B.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,r,i,o,s){let a=t.replace(/^\.\//,""),c=x.join(e,a,"build",r,"intermediates","patch","default","changedFileList.json"),l=n.readExistingPatch(c),d=x.join(e,a,"src","main","ets"),h=i.map(kt=>n.resolveRelativePathForPatch(kt,d)),w=n.mergeStrings(l.modifiedFiles,h),b=n.mergePatchResources(l.rawFile,o),L=n.mergePatchResources(l.resFile,s),he=x.dirname(c);B.existsSync(he)||B.mkdirSync(he,{recursive:!0}),B.writeFileSync(c,JSON.stringify({resources:{resFile:L,rawFile:b},modifiedFiles:w}),"utf-8"),m(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!B.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=B.readFileSync(e,"utf-8"),r=JSON.parse(t);return{modifiedFiles:r?.modifiedFiles||[],rawFile:r?.resources?.rawFile||[],resFile:r?.resources?.resFile||[]}}catch{return{modifiedFiles:[],rawFile:[],resFile:[]}}}static resolveRelativePathForPatch(e,t){return x.relative(x.normalize(t),x.normalize(e)).replace(/\\/g,"/")}static mergeApplyEntries(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o.filePath)||(r.add(o.filePath),i.push(o));return i}static mergeStrings(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o)||(r.add(o),i.push(o));return i}static mergePatchResources(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o.filePath)||(r.add(o.filePath),i.push(o));return i}};import _v from"fs";import{randomUUID as Fv}from"crypto";import{execa as jv}from"execa";var To=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!_v.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}let o=`/data/local/tmp/${Fv()}`,s=[];try{for(let a=0;a<t.length;a++){let c=`${o}/${r}_${a}.hqf`;s.push(c),await this.pushHqf(e,t[a],o,c)}return await this.executeQuickfix(e,s)}catch(a){let c=`hqf install error: ${a.message}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}finally{await this.runHdc(["-t",e,"shell","rm","-rf",o],!1)}}async pushHqf(e,t,r,i){console.log(`[Apply] Pushing hqf to device ${e}: ${t}`),await this.runHdc(["-t",e,"shell","mkdir","-p",r]);let o=await this.runHdc(["-t",e,"file","send",t,i]);if(!o.startsWith("FileTransfer finish"))throw new Error(`Failed to send hqf: ${o}`)}async executeQuickfix(e,t){console.log(`[Apply] Installing ${t.length} hqf patch(es) via quickfix...`);let r=await this.runHdc(["-t",e,"shell","bm","quickfix","-a","-f",...t,"-o"],!1);if(m(`[InstallHqf] quickfix output: ${r}`),/succe(?:ed|ss)/i.test(r))return console.log("[Apply] hqf installed successfully."),{success:!0,message:"hqf quickfix installed successfully."};let i=`hqf quickfix install failed. Device response: ${r||"(empty)"}. Please try reinstalling the application.`;return console.error(`[Apply] ${i}`),{success:!1,message:i}}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;m(`[InstallHqf] Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await jv(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}};var Hv="6.1.1",ko=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}toolProvider;projectRoot;async execute(e){await ln(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(Hv);let t=Tu(e.applyFile,this.projectRoot);console.log(`[Apply] Parsed ${t.length} changed file(s)`);let r=this.writeChangeFileList(e,t),i=await this.buildHqf(e,r);await this.installHqf(e,i),await this.restartApp(e),console.log("[Apply] Apply complete")}writeChangeFileList(e,t){let r=Ro.writeChangedFileLists(this.projectRoot,e.productName,t);if(r.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");return console.log(`[Apply] changeFileList written for: ${r.writtenModules.join(", ")}`),r.writtenModules}async buildHqf(e,t){return m(`[Apply] hvigor assembleDevHqf --no-daemon (modules=${t.join(",")})`),await Nu(this.toolProvider,this.projectRoot,t,e.productName)}async installHqf(e,t){console.log(`[Apply] Installing ${t.length} hqf(s) to ${e.targetDeviceId}`);let i=await new To(this.toolProvider).install(e.targetDeviceId,t,e.bundleName);if(!i.success)throw new Error(`hqf install failed: ${i.message}`);console.log("[Apply] hqf installed")}async restartApp(e){let t=new Hn(this.toolProvider);try{await t.forceStopApp(e.targetDeviceId,e.bundleName),await t.launchApp(e.targetDeviceId,e.bundleName,e.abilityName),console.log("[Apply] app restarted")}catch(r){console.warn(`[Apply] restart failed (hqf already applied): ${r.message}`)}}};import Mu from"fs";import*as j from"path";var xo=class n{static generate(e,t,r,i){let o=Do(e,t),s=j.join(e,o),a=j.join(s,"build","config"),c=n.buildConfig(e,s,r,i);Mu.mkdirSync(a,{recursive:!0}),Mu.writeFileSync(j.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[BuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,i){let o=j.dirname(i.nodePath)+j.sep,s=j.join(t,"build",r),a=j.join(s,"intermediates"),c=j.join(a,"loader_out",r),l=j.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:j.join(e,"build-profile.json5"),localPropertiesPath:j.join(e,"local.properties"),appResource:j.join(l,"ResourceTable.txt"),cachePath:j.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:j.join(a,"loader",r,"loader.json"),aceModuleJsonPath:j.join(l,"module.json"),aceSoPath:j.join(c,"nativeDependencies.txt"),aceModuleRoot:j.join(t,"src","main","ets"),aceModuleBuild:j.join(c,"ets"),aceProfilePath:j.join(l,"resources","base","profile"),aceSuperVisualPath:j.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:j.join(c,"ets"),changedFileList:j.join(a,"patch","default","changedFileList.json"),patchAbcPath:j.join(a,"patch","default","ets"),removeChangedFileListInSdk:"true"}}}};function Bv(n){let e=n.indexOf("@"),t=e!==-1?n.substring(0,e):n,r=e!==-1?n.substring(e+1):"default";return{moduleName:t,targetName:r}}async function Fu(n,e){let t=await n.listDevices();if(t.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");if(!e&&t.length>1){let i=await n.listDevicesWithName();throw new Error("Multiple devices found. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+i.map(o=>` - ${o.name} (${o.serial})`).join(`
|
|
33
|
+
`))}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let i=await n.getDeviceName(r.serial);console.log(`Auto-selected device: ${i} (${r.serial})`)}return r.serial}function Wv(n,e){if(e&&e.length>0)return e;let t=n.profile.modules.filter(r=>{let i=n.getModuleType(r.name);return i==="entry"||i==="feature"||i==="shared"});if(t.length===1){let r=t[0].name;return console.log(`Auto-selected module: ${r}`),[r]}throw new Error(`Specify module(s) using --module <name> [<name>...].
|
|
28
34
|
Available runnable modules:
|
|
29
35
|
`+t.map(r=>` - ${r.name}`).join(`
|
|
30
|
-
`))}async function
|
|
31
|
-
Installing artifacts to device ${e}...`),await n.installApp(e,r),console.log(`Launching ${t}/${i}...`);let s=await n.launchApp(e,t,i);console.log(
|
|
32
|
-
Application '${t}': ${s}`))}
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
`)
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
`)
|
|
42
|
-
|
|
43
|
-
|
|
36
|
+
`))}function Gv(n,e,t){if(t)return t;let r=e.find(({moduleName:o})=>n.getModuleType(o)==="entry");if(r)return n.getMainAbility(r.moduleName);let i=e.find(({moduleName:o})=>n.getModuleType(o)==="feature");if(i)return n.getMainAbility(i.moduleName)}async function zv(n,e,t,r,i,o){if(o&&(console.log(`Uninstalling ${t}...`),await n.uninstallApp(e,t)||console.log(`App ${t} not installed; skipping uninstallation.`)),console.log(`
|
|
37
|
+
Installing artifacts to device ${e}...`),await n.installApp(e,r),i){console.log(`Launching ${t}/${i}...`);let s=await n.launchApp(e,t,i);console.log(_u(`
|
|
38
|
+
Application '${t}': ${s}`))}else console.log(`
|
|
39
|
+
Application '${t}' installed successfully (no ability to launch).`)}var Vv=new $v("run").description("Build and run the project on a connected device").option("--module <modules...>","Module(s) to run (format: module or module@target)").option("--device <device>","Target device name or serial").option("--product <product>","Product name (default: default)").option("--build-mode <mode>","Build mode (options: debug, release; default: debug)").option("--ability <ability>","Ability name to launch").option("--uninstall","Uninstall existing app before installation").option("--skip-build","Skip build step and deploy existing artifacts").option("--apply <fileName>","Quick-apply changed files via quickfix (incremental hqf) and restart. <fileName> under project .hvigor/").action(async n=>{try{await Yv(n)}catch(e){console.error(Uv(e.message)),process.exit(1)}});async function qv(n,e,t,r,i){let o=new Ln(e,n.rootDir),s=new mt(e,n.rootDir),a=new Set,c=new Set;for(let{moduleName:w,targetName:b}of t)for(let L of n.collectNonHarDependentModuleList(w))a.add(`${L}@${b}`),c.add(L);let l=[...a],d=tc(n,l),h={type:"modules",modulesToBuild:l,moduleTasks:d};for(let w of c)xo.generate(n.rootDir,w,r,e);await ln(n.rootDir,()=>nc(o,s,r,i,h,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion...")),console.log(`
|
|
40
|
+
`+_u("Build completed successfully."))}async function Yv(n){let e=U.discover(process.cwd());console.warn(No("Ensure the project source is trusted before proceeding."));let t=await I.new();if(n.skipBuild||t.assertJava(),n.apply){await Kv(n,e,t);return}await ju(n,e,t)}function Jv(n,e,t,r){let i=new Set;for(let{moduleName:o,targetName:s}of e)for(let a of n.collectNonHarDependentModuleList(o)){i.add(n.findArtifactPath(a,s,t,r));for(let c of n.findRemoteHspPaths(a,s,r))i.add(c)}return[...i]}async function ju(n,e,t){let i=Wv(e,n.module).map(Bv);for(let{moduleName:L}of i){let he=e.getModuleType(L);if(he!=="entry"&&he!=="feature"&&he!=="shared")throw new Error(`Module '${L}' '${he}' is not runnable. Specify an entry or feature module.`)}let o=new Hn(t),s=Q.from(t),a=await Fu(s,n.device),c=a.includes("127.0.0.1")||a.includes("localhost"),l=n.product||"default";e.validateProduct(l);let d=n.buildMode||"debug";n.skipBuild||await qv(e,t,i,l,d);let h=Jv(e,i,c,l),w=e.getBundleName(),b=Gv(e,i,n.ability);await zv(o,a,w,h,b,!!n.uninstall)}async function Kv(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(Lo.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let i=Lo.join(e.rootDir,".hvigor",r),o=Q.from(t),s=await Fu(o,n.device),a=n.product||"default";e.validateProduct(a);let c=e.getBundleName(),l=e.profile.modules.find(w=>e.getModuleType(w.name)==="entry")?.name,d=l?e.getMainAbility(l,n.ability):n.ability||"EntryAbility",h=new ko(t,e.rootDir);try{await h.execute({applyFile:i,productName:a,targetDeviceId:s,bundleName:c,abilityName:d}),console.log(No("[Apply] \u5B8C\u6210\u3002\u82E5\u6539\u52A8\u672A\u751F\u6548\uFF0C\u8BF7\u68C0\u67E5 <module>/build/config/buildConfig.json \u662F\u5426\u6709\u5185\u5BB9\uFF0C\u6216\u6267\u884C devecocli run \u5168\u91CF\u6784\u5EFA\u3002"));return}catch(w){console.warn(No(`[Apply] \u5931\u8D25\uFF1A${w.message}`)),console.warn(No("[Apply] \u81EA\u52A8\u56DE\u9000\u5230\u5168\u91CF devecocli run..."))}await ju(n,e,t)}var Hu=Vv;import{Command as Xv}from"commander";import{green as $u,red as Uu,cyan as dc}from"colorette";import{execa as Bu}from"execa";function Zv(){return"latest"}function Qv(){return"@deveco-test/deveco-cli"}function eS(){return"1.3.0-Test.7"}var tS=new Xv("update").description("Update deveco-cli to latest").action(async()=>{let n=Qv(),e=eS(),t=Zv();console.log(dc("Checking for updates..."));try{let{stdout:r}=await Bu("npm",["view",n,`dist-tags.${t}`]),i=r.trim();if(!i||i===e){console.log($u(`
|
|
41
|
+
${n} is already up to date (v${e}, tag: ${t})`));return}console.log(dc(`
|
|
42
|
+
New version found: ${i} (current: ${e})`)),console.log(dc(`Updating ${n}...`)),await Bu("npm",["install","-g",`${n}@${t}`],{stdio:"inherit"}),console.log(`
|
|
43
|
+
`+$u(`${n} updated successfully to version ${i}.`))}catch(r){let i=r;console.error(Uu(`Failed to update ${n}`)),i.message&&console.error(Uu(i.message)),process.exit(1)}}),Wu=tS;import{Command as RS}from"commander";import{execa as Mo}from"execa";function de(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as nS}from"child_process";var rS=2500;function iS(n,e,t,r,i,o){n.once("exit",s=>{if(o())return;clearTimeout(e);let a=t();s===0||s===null?r():i(a||`Emulator process exited with code ${s}`)})}function oS(n,e,t,r){let i=!1,o=()=>i,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{i||(i=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners(),n.stderr?.destroy(),n.unref(),t())},c=d=>{if(!i){i=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners();try{n.kill()}catch{}r(new Error(d))}},l=setTimeout(a,rS);n.once("error",d=>c(d.message)),iS(n,l,s,a,c,o)}function Gu(n,e,t){return m(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,i)=>{let o=[],s=nS(n,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>o.push(a)),oS(s,o,r,i)})}import*as $n from"path";function sS(n){let e=new Set,t=[];for(let r of n){let i=JSON.stringify(r);e.has(i)||(e.add(i),t.push(r))}return t}function aS(n){let e=n.instancePath?.trim();if(e)return $n.dirname($n.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?$n.dirname($n.normalize(t)).replace(/\\/g,"/"):""}function cS(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function zu(n,e){return e?[...n,"-bootmode",e]:n}function lS(n,e,t){let r=[zu(["-start",n],t)],i=aS(e);if(i)for(let o of cS(e.imageRoot))r.push(zu(["-hvd",n,"-path",i,...o],t));return sS(r)}async function Vu(n,e,t,r){let i=new Error("No start strategy ran"),o=lS(n,e,r);for(let s of o)try{return await t(s),{ok:!0}}catch(a){i=a}return{ok:!1,lastError:i}}async function uc(n){return(await Q.withHdcPath(n).listDevices()).map(t=>t.serial).filter(hn)}async function pc(n){let e=await uc(n);return e.length===0?[]:(await Promise.all(e.map(r=>Ao(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function qu(n,e){return(await pc(n)).includes(e)}import*as Bn from"path";import{existsSync as dS,statSync as uS}from"fs";function Un(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function pS(n){let e=Un(n,["instancePath","instance_path","InstancePath","instancepath","instanceDir","instance_dir","InstanceDir","deployPath","deploy_path","deployedPath","deployed_path","workPath","work_path","dataPath","data_path"]);if(e)return e;for(let[t,r]of Object.entries(n)){if(typeof r!="string"||!r.trim())continue;let i=t.toLowerCase();if(i.includes("instance")&&(i.includes("path")||i.includes("dir"))||i==="deployedpath")return r.trim()}return""}function fS(n){return Un(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function mS(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=Bn.dirname(Bn.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let i=Bn.join(t,r.name);dS(i)&&uS(i).isDirectory()&&(r.instancePath=i.replace(/\\/g,"/"))}}function hS(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=fS(t),i=Un(t,["deviceType","DeviceType","devicetype"]),o=Un(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:pS(t),path:Un(t,["path","Path","hvdPath","hvd_path"]),imageRoot:Un(t,["imageRoot","image_root","ImageRoot"]),uuid:r||void 0,deviceType:i||void 0,osVersion:o||void 0}}).filter(t=>t.name):null}catch{return null}}function gS(n){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,r=null,i;for(;(i=t.exec(n))!==null;){let[,o,s]=i;if(o.toLowerCase()==="name")r&&e.push(r),r={name:s.trim()};else if(r){let a=o.toLowerCase();a==="isrunning"?r.isRunning=s.trim().toLowerCase()==="true":a==="instancepath"?r.instancePath=s.trim():a==="path"?r.path=s.trim():a==="imageroot"?r.imageRoot=s.trim():a==="devicetype"?r.deviceType=s.trim():a==="os.osversion"&&(r.osVersion=s.trim())}}return r&&e.push(r),e}function Yu(n){let t=hS(n)??gS(n);return mS(t),t}function fc(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function yS(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function wS(n){if(!yS(n))return null;let e=fc(n,["osVersion","OsVersion","OSVersion"]),t=fc(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=fc(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function Oo(n){let e=n.trim();if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let r=[];for(let i of t){if(!i||typeof i!="object")continue;let o=wS(i);o&&r.push(o)}return r}catch{return[]}}function Ju(n){let t=Oo(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var Ku=/no images are available/i,vS="7.0.0",SS={foldable:["open","half-open","close"],"2in1_foldable":["open","vertical-open","half-open","close"],triplefold:["single","double","triple","left-folded-right-half-folded","left-half-folded-right-expanded","left-expanded-right-folded","left-half-folded-right-folded","left-expanded-right-half-folded","left-half-folded-right-half-folded"]};function Ze(n){return n.normalize("NFKC").trim().toLowerCase()}function bS(n,e){let t=n.deviceType?.trim(),r=t?SS[Ze(t)]:void 0;if(!r)throw new Error(`Fold-state control is not supported for emulator "${n.name}" (device type: ${t||"unknown"}).`);if(!r.includes(e))throw new Error(`Fold state "${e}" is not supported by emulator "${n.name}" (device type: ${t}). Available states: ${r.join(", ")}.`)}function ES(n){let e=n.message||"";return Ku.test(e)}function PS(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function zr(n,e){return`${n} ${e.join(" ")}`.trim()}function CS(n){switch(n.type){case"gps":return`${n.type}:${n.key}=${n.value}`;case"sensor":return`${n.type}:${n.key}=${n.value}`;case"rotation":case"volume":return`${n.type}:${n.direction}`;case"folded-state":return`${n.type}:${n.state}`;case"battery":return`${n.type}:${n.level}`;case"battery-status":return`${n.type}:${n.status}`;default:return n.type}}var Wn=class n{static supportedControlPaths=new Set;emulatorPath;sdkPath;hdcPath;constructor(e,t,r){this.emulatorPath=e,this.sdkPath=t,this.hdcPath=r}static from(e){return new n(e.emulatorPath,e.sdkPath,e.hdcPath)}async executeEmulator(e){return m(`Executing: ${zr(this.emulatorPath,e)}`),Mo(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return Gu(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return Yu(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let r of t)r.name&&r.deviceType&&e.set(de(r.name),r.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),r=de(e),i=t.find(a=>de(a.name)===r);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;if(await this.isAlreadyRunning(o,i))return"already-running";await this.assertSystemImageAvailable(i);let s=await Vu(o,i,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return"started";if(await this.isAlreadyRunning(o))return"already-running";throw new Error(`Unable to start emulator "${e}". All methods failed.
|
|
44
|
+
Last error: ${s.lastError.message||"unknown"}`)}async isAlreadyRunning(e,t){return t?.isRunning===!0||t===void 0&&(await this.listEmulators()).find(i=>i.name===e)?.isRunning===!0?!0:qu(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=de(e),i=t.find(a=>de(a.name)===r);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;return await this.isAlreadyRunning(o,i)?(await this.executeEmulator(["-stop",o]),"stopped"):"already-stopped"}async controlEmulator(e,t){await this.assertControlCommandSupported();let i=(await this.listEmulators()).find(s=>s.name===e);if(!i)throw new Error(`Emulator "${e}" not found.`);if(!await this.isAlreadyRunning(i.name,i))throw new Error(`Emulator "${e}" is not running.`);t.type==="folded-state"&&bS(i,t.state);let o=this.buildControlArgs(i.name,t);m(`[EmulatorManager] control ${CS(t)} -> ${zr(this.emulatorPath,o)}`),await this.runEmulatorChecked(o,{printOutputOnSuccess:!1})}async assertControlCommandSupported(){let e=this.emulatorPath;if(n.supportedControlPaths.has(e))return;let t=["-version"];m(`Executing: ${zr(this.emulatorPath,t)}`);let{stdout:r,stderr:i,exitCode:o}=await Mo(this.emulatorPath,t,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:1024*1024}),s=[r,i].filter(Boolean).join(`
|
|
45
|
+
`).trim(),a=PS(s);if(o!==0||!a)throw new Error("Emulator scene control commands require Emulator 7.0 or later. Unable to determine the current Emulator version.");if(I.compareVersion(a,vS)<0)throw new Error(`Emulator scene control commands require Emulator 7.0 or later. Current Emulator version is ${a}. Please upgrade DevEco Studio or the Emulator SDK.`);n.supportedControlPaths.add(e)}buildControlArgs(e,t){let r=["-instance",e];switch(t.type){case"shake":return[...r,"-shake"];case"power":return[...r,"-power"];case"rotation":return[...r,"-rotation",t.direction];case"volume":return[...r,"-volume",t.direction];case"folded-state":return[...r,"-foldedState",t.state];case"battery":return[...r,"-battery",String(t.level)];case"battery-status":return[...r,"-batteryStatus",String(t.status)];case"gps":return[...r,"-gps",`-${t.key}`,t.value];case"outdoor-running":return[...r,"-outdoorRunning"];case"outdoor-cycling":return[...r,"-outdoorCycling"];case"driving-navigation":return[...r,"-drivingNavigation"];case"sensor":return[...r,"-sensor",`-${t.key}`,String(t.value)]}}async executeEmulatorInherit(e){m(`Executing: ${zr(this.emulatorPath,e)}`);let{exitCode:t}=await Mo(this.emulatorPath,e,{stdio:"inherit",env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1});if(t!==0)throw new Error(`Emulator exited with code ${t===null?"null":t}.`)}async installEmulatorImage(e){let t=["-install","-deviceType",e.deviceType,"-osVersion",e.osVersion];e.force&&t.push("-force"),await this.executeEmulatorInherit(t)}async uninstallEmulatorImage(e){let t=await this.resolveSoftwareVersionsForUninstall(e);if(t.length===0)throw new Error(`No downloaded image matches --os-version "${e.osVersion}" for --device-type "${e.deviceType}".`);let r;try{await this.runUninstallImageChecked(e.deviceType,e.osVersion)}catch(o){if(!ES(o))throw o;r=o}(r!==void 0||await this.hasMatchingDownloadedImage(e))&&await this.runSoftwareVersionFallback(e,t,r)}async listEmulatorImages(e){let t=["-imageList"];e.deviceType&&t.push("-deviceType",e.deviceType),e.downloaded!==void 0&&t.push("-downloaded",e.downloaded?"true":"false");let{stdout:r}=await this.executeEmulator(t);return r}async listDownloadedImageOsVersions(){let e=await this.listEmulatorImages({downloaded:!0});return Ju(e)}async hasMatchingDownloadedImage(e){return(await this.findMatchingDownloadedImages(e)).length>0}async runSoftwareVersionFallback(e,t,r){try{for(let i of t)await this.runUninstallImageChecked(e.deviceType,i)}catch(i){let o=r!==void 0?`Primary uninstall failed: ${r.message}
|
|
46
|
+
`:"";throw new Error(`${o}Fallback uninstall failed: ${i.message}`,{cause:i})}if(await this.hasMatchingDownloadedImage(e))throw new Error(`Image for --device-type "${e.deviceType}" and --os-version "${e.osVersion}" remains listed as downloaded after uninstallation.`)}async resolveSoftwareVersionsForUninstall(e){let t=await this.findMatchingDownloadedImages(e);return[...new Set(t.map(r=>r.softwareVersion).filter(Boolean))]}async findMatchingDownloadedImages(e){let t=await this.listEmulatorImages({deviceType:e.deviceType,downloaded:!0}),r=Oo(t),i=Ze(e.deviceType),o=Ze(e.osVersion);return r.filter(s=>Ze(s.deviceType)===i&&(Ze(s.osVersion)===o||Ze(s.softwareVersion)===o))}async hasDownloadedSystemImage(e,t){let r=await this.listEmulatorImages({downloaded:!0}),i=Oo(r),o=Ze(t),s=e?.trim()?Ze(e):void 0;return i.some(a=>Ze(a.osVersion)===o||Ze(a.softwareVersion)===o?s===void 0?!0:Ze(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:[Ku]})}async runEmulatorChecked(e,t){m(`Executing: ${zr(this.emulatorPath,e)}`);let{stdout:r,stderr:i,exitCode:o}=await Mo(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:20*1024*1024}),s=[r,i].filter(Boolean).join(`
|
|
47
|
+
`).trim(),a=/Invalid command|无效命令|鏃犳晥鍛戒护/i.test(s)||/please attach the correct parameter/i.test(s),c=(t?.extraReject??[]).some(d=>d.test(s));if(o!==0||a||c)throw new Error(s||`emulator exited with code ${o===null?"null":o}`);if(t?.printOutputOnSuccess!==!1&&s){let d=(t?.transformOutput?t.transformOutput(s):s).trim();d&&console.log(d)}}async checkExistingVirtualDevice(e,t){let r=await this.listEmulators(),i=de(e),o=r.find(s=>de(s.name)===i);if(o)if(t)await this.deleteVirtualDevice(o.name);else throw new Error(`Emulator "${e}" already exists. Use \`--force\` to overwrite.`);return i}async createVirtualDevice(e){let t=await this.checkExistingVirtualDevice(e.name,e.force),r=["-create",e.name,"-deviceType",e.deviceType,"-osVersion",e.osVersion];if(await this.runEmulatorChecked(r,{extraReject:[/Device create fail/i,/already exists/i,/Invalid OS version/i,/cannot be empty/i],printOutputOnSuccess:!0,transformOutput:o=>o.split(/\r?\n/).map(s=>s.trim().startsWith("Device create success.")?"Device create success.":s).join(`
|
|
48
|
+
`)}),!await this.waitForEmulatorPresenceByList(t))throw new Error(`Emulator "${e.name}" was reported as created, but it did not appear in the emulator list within the waiting period. Open the device manager list in DevEco Studio, then run this command again.`)}async waitForEmulatorPresenceByList(e,t=1e4,r=500){let i=Date.now()+t;for(;Date.now()<i;){if((await this.listEmulators()).some(a=>de(a.name)===e))return!0;await new Promise(a=>setTimeout(a,r))}return!1}async deleteVirtualDevice(e){let t=await this.listEmulators(),r=de(e),i=t.find(s=>de(s.name)===r);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;if(i.isRunning===!0||await this.isAlreadyRunning(o,i))throw new Error(`Failed to delete device: ${o}
|
|
49
|
+
The device may be running.`);return await this.runEmulatorChecked(["-delete",o,"-force"],{printOutputOnSuccess:!1}),o}};import{red as mc,yellow as Zu,gray as Qu}from"colorette";import TS from"ora";import{red as IS}from"colorette";function _o(n,e){n?n.fail(e):console.error(IS(e)),process.exit(1)}import{green as AS}from"colorette";function Xu(n,e){return n+" ".repeat(Math.max(0,e-n.length))}function DS(n,e){return n.map((t,r)=>{let i=t.length;for(let o of e){let s=o.cells[r]??"";i=Math.max(i,s.length)}return i})}function yt(n,e){let t=DS(n,e),r=[];r.push(n.map((i,o)=>Xu(i,t[o])).join(" ")),r.push(t.map(i=>"-".repeat(i)).join(" "));for(let i of e){let o=i.cells.map((s,a)=>Xu(s??"",t[a])).join(" ").trimEnd();r.push(i.highlight?AS(o):o)}return r.join(`
|
|
50
|
+
`)}function kS(n,e){if(e.size!==0)for(let t of n){if(!t.isEmulator||!t.name)continue;let r=e.get(de(t.name));r&&(t.deviceType=r)}}var xS=["Name","Serial","Kind","Device Type"];function NS(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function LS(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function OS(){console.log(Zu(" No active devices.")),console.log(Qu(" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function MS(n){let t=[...n].sort(LS).map(NS);console.log(yt(xS,t))}async function _S(n,e){if(!n.some(i=>i.isEmulator)||!e.emulatorPath)return;let r=await Wn.from(e).getDeviceTypeByName();kS(n,r)}async function FS(n,e,t){try{let r=await n.getConnectedEntries();await _S(r,e),t?.stop(),r.length===0?OS():MS(r)}catch(r){_o(t,`Failed to list devices: ${r.message}`)}}async function jS(n,e){let t=await n.listDevices();if(!(t.length<2)){console.error(mc("Multiple devices connected. Specify a device with:"));for(let r of t){let i=await n.getDeviceName(r.serial);console.error(Qu(` ${e} -t ${r.serial} # ${i}`))}process.exit(1)}}async function HS(n,e){try{e||await jS(n,"devecocli device view");let t=await n.listDevices(),r=await n.getDeviceInfo(t,e);r||(console.log(Zu("No connected device found.")),process.exit(1));let i=await n.getDeviceDetail(r.serial),o=await n.getDeviceName(r.serial);console.log(` Serial: ${r.serial}`),console.log(` Device Name: ${o}`),i.deviceType&&console.log(` Device Type: ${i.deviceType}`),i.osVersion&&console.log(` OS Version: ${i.osVersion}`)}catch(t){console.error(mc(`Failed to show device details: ${t.message}`)),process.exit(1)}}async function ep(){try{let n=await I.new();return{manager:Q.from(n),toolProvider:n}}catch(n){console.error(mc(`Failed to initialize device manager: ${n.message}`)),process.exit(1);return}}var hc=new RS("device").description("Manage connected devices");hc.command("list").description("List all connected devices").action(async()=>{let{manager:n,toolProvider:e}=await ep(),t=TS({text:"Querying connected devices\u2026",color:"cyan"}).start();await FS(n,e,t)});hc.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").action(async n=>{let{manager:e}=await ep();await HS(e,n.target)});var tp=hc;import{Argument as Ec,Command as Pc,Option as Jr}from"commander";import{green as Kr,cyan as zn,red as ge,yellow as lt,gray as Yr}from"colorette";import tb from"ora";import $S from"readline/promises";import{execa as rp}from"execa";import*as _t from"fs/promises";import*as yc from"os";import*as gn from"path";var gc=`1/4:\r
|
|
44
51
|
---------------------------------------\r
|
|
45
52
|
Statement About HarmonyOS and Privacy\r
|
|
46
53
|
\r
|
|
@@ -1210,13 +1217,13 @@ Part I: Chinese mainland.\r
|
|
|
1210
1217
|
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
|
|
1211
1218
|
\r
|
|
1212
1219
|
Part III: Other countries and regions.\r
|
|
1213
|
-
---------------------------------------\r`;var
|
|
1214
|
-
`),
|
|
1215
|
-
`)}function
|
|
1216
|
-
${t}.`);return
|
|
1217
|
-
`,"utf8"),!0}catch{}return!1}async function
|
|
1220
|
+
---------------------------------------\r`;var US=new Set,Fo=new Map,wc="HarmonyOS_Software_Service_Agreement",ip=["Emulator license agreements are not accepted yet.","","Accept the agreements interactively (shows full text + y/N prompt):"," devecocli emulator license","","Or accept non-interactively (no prompt, for CI/scripts):"," devecocli emulator license accept","","To review the agreement text (read-only):"," devecocli emulator license view"].join(`
|
|
1221
|
+
`),op=ip,vc="HarmonyOS_SDK_Agreement";function sp(n,e){return`${n}\0${e}`}function ap(){US.clear(),Fo.clear()}var BS=ip,Me=class extends Error{constructor(e=BS){super(e),this.name="EmulatorLicenseBlockedError"}};function cp(n,e){return[n??"",e??""].join(`
|
|
1222
|
+
`)}function lp(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 WS(n){return`Emulator${n.trim()}`}function dp(n){let e=WS(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 gn.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return gn.join(yc.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||gn.join(yc.homedir(),".cache");return gn.join(t,"Huawei",e,".emu_config")}async function GS(n,e,t){let r=sp(n,e),i=Fo.get(r);if(i!==void 0)return i;let o=await rp(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=cp(o.stdout,o.stderr).trim();if(o.exitCode!==0||!s)throw new Me(t);return Fo.set(r,s),s}function zS(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function VS(n){try{let e=JSON.parse(n);if(e&&typeof e=="object"&&!Array.isArray(e)){let t={};for(let[r,i]of Object.entries(e))t[r]={value:typeof i=="string"?i:String(i),delimiter:"json"};return t}}catch{return}}function qS(n){let e=n.trim();if(!(!e||e.startsWith("#")))for(let t of["=",":"]){let r=e.indexOf(t);if(r<=0)continue;let i=e.slice(0,r).trim();if(!i||t===":"&&i.includes("//"))continue;let o=zS(e.slice(r+1).trim());return{key:i,entry:{value:o,delimiter:t}}}}function YS(n){let e={};for(let t of n.split(/\r?\n/)){let r=qS(t);r&&(e[r.key]=r.entry)}return e}function JS(n){let e=n.trim();if(!e)return{};let t=VS(e);return t||YS(n)}function KS(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function up(n,e,t,r){let i=await GS(n,e,r),o=lp(i);if(!o)throw new Me(r);let s=dp(o),a;try{a=await _t.readFile(s,"utf8")}catch(d){throw d.code==="ENOENT"?new Me(r):d}let l=JS(a)[t];if(!l)throw new Me(r);if(l.delimiter==="=")throw new Me(r);if(!KS(l.value))throw new Me(r)}async function Sc(n,e){await up(n,e,wc,op)}async function bc(n,e){await up(n,e,vc,op)}async function XS(n,e){let t=await rp(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),r=cp(t.stdout,t.stderr).trim();if(t.exitCode!==0||!r)throw new Error(`Emulator -version failed (exit ${String(t.exitCode)}); cannot resolve .emu_config path.`);let i=sp(n,e);return Fo.set(i,r),r}async function pp(n,e){let t=await XS(n,e),r=lp(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
|
|
1223
|
+
${t}.`);return dp(r)}function np(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function ZS(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[wc]="agree",r[vc]="agree",await _t.writeFile(n,`${JSON.stringify(r,null,2)}
|
|
1224
|
+
`,"utf8"),!0}catch{}return!1}async function QS(n,e){let t=wc,r=vc,i=[{k:t,re:new RegExp(`^\\s*${np(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${np(r)}\\s*[:=]`)}],o=e.length===0?[]:e.split(/\r?\n/),s=[],a=new Set;for(let c of o){let l=!1;for(let{k:d,re:h}of i)if(h.test(c)){s.push(`${d}:agree`),a.add(d),l=!0;break}l||s.push(c)}a.has(t)||s.push(`${t}:agree`),a.has(r)||s.push(`${r}:agree`),await _t.writeFile(n,s.join(`
|
|
1218
1225
|
`)+(s.length>0?`
|
|
1219
|
-
`:""),"utf8")}async function
|
|
1226
|
+
`:""),"utf8")}async function fp(n){await _t.mkdir(gn.dirname(n),{recursive:!0});let e="";try{e=await _t.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await ZS(n,e,t)||await QS(n,e)}async function mp(n,e){return console.log(gc),0}var eb="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function hp(n,e){try{return await Sc(n,e),await bc(n,e),!0}catch(t){if(t instanceof Me)return!1;throw t}}async function gp(n,e){if(await hp(n,e))return console.log("Emulator license agreements are already accepted."),0;if(console.log(gc),!process.stdin.isTTY||!process.stdout.isTTY)return console.error("`devecocli emulator license` requires an interactive terminal.\nFor non-interactive environments, use: devecocli emulator license accept"),1;let r=$S.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await r.question(eb)}finally{r.close()}let o=i.trim().toLowerCase();if(o!=="y"&&o!=="yes")return console.error("Agreements not accepted. Emulator features will remain blocked until accepted."),1;try{let s=await pp(n,e);await fp(s),ap()}catch(s){return console.error(s.message),1}return console.log("Emulator license agreements accepted."),0}async function yp(n,e){if(await hp(n,e))return console.log("Emulator license agreements are already accepted."),0;try{let t=await pp(n,e);await fp(t),ap()}catch(t){return console.error(t.message),1}return console.log("Emulator license agreements accepted."),0}var nb=["ohos.qemu.hvd.name","const.product.name","const.product.model"],wp=["open","half-open","close","vertical-open","single","double","triple","left-folded-right-half-folded","left-half-folded-right-expanded","left-expanded-right-folded","left-half-folded-right-folded","left-expanded-right-half-folded","left-half-folded-right-half-folded"],rb=`
|
|
1220
1227
|
Folded state scene mappings:
|
|
1221
1228
|
foldableFold (3):
|
|
1222
1229
|
open Fully expanded state
|
|
@@ -1239,61 +1246,43 @@ Folded state scene mappings:
|
|
|
1239
1246
|
left-half-folded-right-folded
|
|
1240
1247
|
left-expanded-right-half-folded
|
|
1241
1248
|
left-half-folded-right-half-folded
|
|
1242
|
-
`;function Tm(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function km(n){let e=n.trim();if(!Da.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${Da.join(", ")}`);return e}function Aa(n,e,t,r){let i=e.trim();if(!/^-?\d+$/.test(i))throw new Error(`${n} must be an integer in [${t}, ${r}].`);let o=Number(i);if(o<t||o>r)throw new Error(`${n} must be in [${t}, ${r}].`);return o}function xa(n,e,t,r,i){let o=e.trim(),s=Number(o);if(!o||Number.isNaN(s))throw new Error(`${n} must be a number in [${t}, ${r}].`);if(i!==void 0&&!Rm(o,i))throw new Error(`${n} supports at most ${i} decimal place(s).`);if(s<t||s>r)throw new Error(`${n} must be in [${t}, ${r}].`);return o}function Rm(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function Mm(n,e,t,r,i){return Number(xa(n,e,t,r,i))}function Om(n){let e=n.trim();if(!e||!/^[A-Za-z0-9_ ]+$/.test(e))throw new Error("The virtual device name can only contain letters, spaces, numbers, and underscores (_).")}function Lm(n){let e=n.trim();if(!e)throw new Error("--os-version must not be empty.");if(/^\d+$/.test(e))throw new Error(`--os-version "${n}" is invalid. use the full image label, e.g. HarmonyOS 5.1.1(19).`);if(!/^HarmonyOS\s+/i.test(e))throw/^HarmonyOS$/i.test(e)?new Error('--os-version is incomplete (only "HarmonyOS"). On PowerShell/cmd, quote the full label, e.g. --os-version "HarmonyOS 6.0.1(21)".'):new Error(`Invalid --os-version "${n}". It must start with "HarmonyOS " (e.g. "HarmonyOS 5.1.1(19)").`)}function Nm(n,e){let t=i=>i.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(Ie("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(Ie("Run `devecocli emulator image download ...` followed by `devecocli emulator image list` and then copy an `osVersion` string exactly.")),new Error("No downloaded osVersion values parsed; cannot validate --os-version.");if(!e.some(i=>t(i)===r)){console.error(ee("--os-version does not match any downloaded image (exact string required).")),console.log(Ie("Use one of these --os-version values:"));for(let i of e)console.log(` ${i}`);throw new Error(`No downloaded image matches --os-version "${n}".`)}}var _m=["Name","Status","Serial","Device Type","OS Version"];function Hm(n,e,t){return{cells:[n.name,t?"running":"stopped",e??"-",n.deviceType??"-",n.osVersion??"-"],highlight:t}}async function Fm(n,e){let t=await Promise.all(e.map(async r=>{let i=await yt(n,r,Am);return[r,i]}));return new Map(t)}async function jm(n){let e=await Wi(n),t=await Fm(n,e);return{serials:e,params:t}}function $m(n,e,t,r,i){if(e)for(let o of["const.product.name","const.product.model"]){let s=e.get(o);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),i.set(s,n);let c=r.indexOf(n);c!==-1&&r.splice(c,1);return}}function Bm(n,e,t){let r=new Map,i=new Map,o=[...n],s=[...t];for(let a of n){let c=e.get(a),l=c?.get("ohos.qemu.hvd.name");l&&i.set(l,a),t.length>0&&$m(a,c,s,o,r)}for(let a=0;a<s.length&&a<o.length;a++)r.set(s[a],o[a]);return{productSerialMap:r,hvdSerialMap:i}}function Wm(n,e,t){let r=n.map(i=>({emu:i,serial:e.get(i.name)??t.get(i.name),effectiveRunning:i.isRunning===!0||t.has(i.name)}));return r.sort((i,o)=>i.effectiveRunning!==o.effectiveRunning?i.effectiveRunning?-1:1:i.emu.name.localeCompare(o.emu.name)),r.map(i=>Hm(i.emu,i.serial,i.effectiveRunning))}async function Um(n,e,t){try{let[r,i]=await Promise.all([n.listEmulators(),jm(e)]);if(r.length===0){t?.stop(),console.log(Ie(" No emulator instances found."));return}let o=r.filter(l=>l.isRunning).map(l=>l.name),{productSerialMap:s,hvdSerialMap:a}=Bm(i.serials,i.params,o);t?.stop();let c=Wm(r,s,a);console.log(en(_m,c))}catch(r){Qn(t,`Failed to list emulators: ${r.message}`)}}function Ta(n,e,t){let r=!1;for(let i=0;i<n.length;i++){let o=n[i];if(o.status!=="rejected")continue;r=!0;let s=o.reason;console.error(ee(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(rn(s.stdout)),s.stderr&&console.error(rn(s.stderr))}return r}var zm=2e3,qm=6e4;async function Gm(n,e){let t=V(e);return(await Ui(n)).some(i=>V(i)===t)}async function ka(n,e,t,r=qm,i=zm){let o=Date.now()+r;for(;Date.now()<o;){if(await Gm(n,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}async function Vm(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(Ie(`Emulator "${t}" is already running.`));return}console.log(Pt(`Starting emulator "${t}"...`));let i=await ka(e,t,!0);console.log(i?sn(`Emulator "${t}" started successfully.`):Ie(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function Ym(n,e,t){let r=await Promise.allSettled(t.map(o=>Vm(n,e,o)));Ta(r,t,"start")&&process.exit(1)}async function Ra(n,e){let t=e.trim();if(!Xt(t))return t;let r=await G.withHdcPath(n).getDeviceName(t);if(r===t)throw new Error(`Cannot resolve a running emulator with serial "${t}". Use \`devecocli emulator list\` or pass the emulator name instead.`);return r}async function Jm(n,e,t){let r=await Ra(e,t);if(console.log(Pt(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(Ie(`Emulator "${r}" is already stopped.`));return}let o=await ka(e,r,!1);console.log(o?sn(`Emulator "${r}" stopped successfully.`):Ie(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function Km(n,e,t){let r=await Promise.allSettled(t.map(o=>Jm(n,e,o)));Ta(r,t,"stop")&&process.exit(1)}async function we(){try{let n=await N.new();return{manager:St.from(n),toolProvider:n}}catch(n){console.error(ee(`Failed to initialize emulator: ${n.message}`)),process.exit(1);return}}async function xe(n,e){try{let t=Tm(n.target),r=e(),{manager:i,toolProvider:o}=await we(),s=await Ra(o.hdcPath,t);await i.controlEmulator(s,r),console.log(sn(`Emulator "${t}" operation completed.`))}catch(t){let r=n.target?.trim()||"<unknown>";console.error(ee(`Failed to operate emulator "${r}": ${t.message}`)),process.exit(1)}}function Zm(n){let e=[];return tr(e,"longitude",n.longitude,-180,180,8),tr(e,"latitude",n.latitude,-90,90,8),tr(e,"altitude",n.altitude,-1e4,1e4,2),tr(e,"bearing",n.direction,0,360,2),Qi(e,"Specify one geolocation option.")}function Xm(n){let e=[];return tn(e,"light",n.lightIntensity,0,1e5,!1),tn(e,"humidity",n.humidity,0,100,!1),tn(e,"temperature",n.temperature,-273,100,!1),tn(e,"steps",n.steps,0,1e4,!0),tn(e,"heartrate",n.heartrate,0,255,!0),Qi(e,"Specify one sensor option.")}function Qi(n,e){if(n.length===0)throw new Error(e);if(n.length>1)throw new Error("Only one operation option can be specified.");return n[0]}function tr(n,e,t,r,i,o){t!==void 0&&n.push({type:"gps",key:e,value:xa(`--${e}`,t,r,i,o)})}function tn(n,e,t,r,i,o){if(t===void 0)return;let s=o?Aa(`--${e}`,t,r,i):Mm(`--${e}`,t,r,i,1);n.push({type:"sensor",key:e,value:s})}function Qm(n){let e=[];return n.level!==void 0&&e.push({type:"battery",level:Aa("--level",n.level,0,100)}),n.status!==void 0&&e.push({type:"battery-status",status:n.status==="charging"?1:0}),Qi(e,"Specify --level or --status.")}var U=new Xi("emulator").description("Manage emulator instances"),eh=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function nr(n){let e=new on("--device-type <type>","Emulator device type").choices([...eh]);return n?e.makeOptionMandatory():e}function Et(n,e){for(let t of e)if(t in n)return n[t]}function nn(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function Ia(n){let e=nn(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var th=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],nh="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function Ma(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function Oa(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let i=r,o=nn(Et(i,["osVersion","OsVersion","OSVersion","os_version"])),s=nn(Et(i,["deviceType","DeviceType","device_type"])),a=Ia(Et(i,["downloaded","Downloaded","isDownloaded"])),c=nn(Et(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=nn(Et(i,["releaseType","ReleaseType","release_type"])),u=Ia(Et(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,l,u,a],highlight:e&&a==="true"})}return t}function rh(n){let e=n.trim();if(!e)return!0;let t=Ma(e);return t===null?!1:t.length===0?!0:Oa(t,!0).length===0}function ih(n,e){let t=n.trim();if(!t)return"";let r=Ma(t);if(!r)return n.trimEnd();let i=Oa(r,e);return en(th,i)}var rr=new Xi("image").description("HarmonyOS emulator system images (download, list, remove)");rr.command("download").description("Download system image").addOption(nr(!1)).option("--os-version <version>","Example: HarmonyOS 5.1.1(19) or HarmonyOS 6.0.1(21) (required)").option("--force","Overwrite an existing image").action(async n=>{let{manager:e,toolProvider:t}=await we();try{await Ea(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof ve&&(console.error(ee(r.message)),process.exit(1)),r}n.deviceType?.trim()||(console.error(ee("Error: missing required option '--device-type <type>'")),process.exit(1)),n.osVersion?.trim()||(console.error(ee("Error: misssing required option '--os-version <version>'")),process.exit(1));try{await e.installEmulatorImage({deviceType:n.deviceType.trim(),osVersion:n.osVersion.trim(),force:n.force===!0})}catch(r){console.error(ee(`Failed to download system image: ${r.message}`)),process.exit(1)}});rr.command("remove").description("Remove a downloaded system image").addOption(nr(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let{manager:e}=await we();try{await e.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})}catch(t){console.error(ee(`Failed to remove system image: ${t.message}`)),process.exit(1)}});rr.command("list").description("List system images").addOption(nr(!1)).option("--all","List all images (local and remote)").addOption(new on("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await we();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if(rh(r)){console.log(Ie(nh));return}if(n.format==="json"){console.log(r.trimEnd());return}let i=ih(r,n.all===!0);console.log(i)}catch(t){console.error(ee(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});U.addCommand(rr);var eo=new Xi("license").description("local emulator license");eo.command("view").description("Review agreement text(read-only)").action(async()=>{let{toolProvider:n}=await we(),e=await Pa(n.emulatorPath,n.sdkPath);process.exit(e)});eo.command("accept").description("review and accept agreements").action(async()=>{let{toolProvider:n}=await we(),e=await Ca(n.emulatorPath,n.sdkPath);process.exit(e)});U.addCommand(eo);U.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>xe(n,()=>({type:"shake"})));U.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>xe(n,()=>({type:"power"})));U.command("rotate").description("Rotate emulator").addOption(new on("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Zi("<direction>").choices(["left","right"])).action((n,e)=>xe(e,()=>({type:"rotation",direction:n})));U.command("volume").description("Change volume").addOption(new on("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Zi("<direction>").choices(["up","down"])).action((n,e)=>xe(e,()=>({type:"volume",direction:n})));U.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",xm).action((n,e)=>xe(e,()=>({type:"folded-state",state:km(n)})));U.command("battery").description("Set battery level or charging status").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--level <0-100>","Battery level, SOC (integer 0-100)").addOption(new on("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>xe(n,()=>Qm(n)));U.command("geolocation").description("Inject geographic coordinates and direction").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--longitude <value>","Longitude (-180.0 to 180.0)").option("--latitude <value>","Latitude (-90.0 to 90.0)").option("--altitude <value>","Altitude (-10000.0 to 10000.0)").option("--direction <value>","Heading direction in degrees (0 to 360)").action(n=>xe(n,()=>Zm(n)));U.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new Zi("<type>").choices(["outdoorRunning","outdoorCycling","drivingNavigation"])).action((n,e)=>{let t={outdoorRunning:{type:"outdoor-running"},outdoorCycling:{type:"outdoor-cycling"},drivingNavigation:{type:"driving-navigation"}};return xe(e,()=>t[n])});U.command("sensor").description("Inject sensor data").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--light-intensity <value>","Light sensor (0 to 100000)").option("--humidity <value>","Humidity sensor (0 to 100)").option("--temperature <value>","Temperature sensor (-273.0 to 100)").option("--steps <value>","Steps sensor (integer 0 to 10000)").option("--heartrate <value>","Heart rate sensor (integer 0 to 255)").action(n=>xe(n,()=>Xm(n)));U.command("list").description("List all emulator instances").action(async()=>{let{manager:n,toolProvider:e}=await we(),t=Im({text:"Listing emulators\u2026",color:"cyan"}).start();await Um(n,e.hdcPath,t)});U.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await we();try{await Sa(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof ve&&(console.error(ee(r.message)),process.exit(1)),r}n?.length||(console.error(ee("Error: missing required argument 'names'")),process.exit(1)),await Ym(e,t.hdcPath,n)});U.command("stop <names...>").description("Stop one or more emulator instances (by name or serial,e.g.,127.0.0.1:<port>)").action(async n=>{let{manager:e,toolProvider:t}=await we();n?.length||(console.error(ee("Error: missing required argument 'names'")),process.exit(1)),await Km(e,t.hdcPath,n)});var La=U.command("create <name>").description("Create a local emulator by running emulator -create <name> \u2026; --os-version must match a downloaded image from `emulator image list`.").addOption(nr(!0)).requiredOption("--os-version <version>",'Downloaded image label. which will be quoted in PowerShell (e.g. "HarmonyOS 6.0.1(21)") or be used in the format --os-version="\u2026";For details, run`devecocli emulator image list`').option("--force","Overwrite if supported");La.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
|
|
1243
|
-
${
|
|
1244
|
-
${
|
|
1245
|
-
${
|
|
1246
|
-
`)}});
|
|
1247
|
-
|
|
1248
|
-
${s}`)}let i=e.trim();if(!i)throw new Error("--device must not be empty.");let o=await t.getDeviceInfo(r,i);if(!o)throw new Error(`Device "${i}" not found.`);return o.serial}async function mh(n,e){return(await Promise.all(e.map(async r=>` - ${await n.getDeviceName(r.serial)} (${r.serial})`))).join(`
|
|
1249
|
-
`)}
|
|
1250
|
-
`).trim()}async function bh(n,e){let t;try{t=await dh(n.hdcPath,hh(n,e))}catch(i){t={stdout:i.stdout??"",stderr:i.stderr??i.message}}let r=await vh(n);return{created:r!==void 0&&r>0,output:wh(t)}}async function Sh(n){let e=[];for(let t of[void 0,"png"]){let r=await bh(n,t);if(r.created)return;r.output&&e.push(r.output)}throw new Error(e.length>0?`Screenshot was not created on device: ${n.remotePath}. snapshot_display output: ${e.join(`
|
|
1251
|
-
`)}`:`Screenshot was not created on device: ${n.remotePath}.`)}function Fa(n){try{return Ha(n),!0}catch{return!1}}function ja(n){let e=[];for(let t of se.readdirSync(n,{withFileTypes:!0})){let r=le.join(n,t.name);if(t.isDirectory()){e.push(...ja(r));continue}t.isFile()&&Fa(r)&&e.push(r)}return e}function Eh(n,e){let t=le.join(n,le.basename(e));if(Fa(t))return t;let r=ja(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}async function no(n,e,t,r){try{await ro(n.hdcPath,["-t",n.serial,"file","recv",n.remotePath,t],r)}catch(i){g(`hdc file recv failed: ${i.message}`)}return Eh(e,n.remotePath)}async function Ph(n){let e=se.mkdtempSync(le.join(le.dirname(n.localPath),".devecocli-screenshot-"));try{let t=await no(n,e,".",e)??await no(n,e,e)??await no(n,e,le.join(e,"screenshot.png"));if(!t)throw new Error(`Screenshot file was not created in ${e}.`);gh(t,n.localPath)}finally{se.rmSync(e,{recursive:!0,force:!0})}}async function Ch(n){await ro(n.hdcPath,["-t",n.serial,"shell","rm","-f",n.remotePath]).catch(()=>{})}async function Dh(n){try{await Sh(n),await Ph(n)}finally{await Ch(n)}}async function Ih(n){try{let e=await N.new(),t=await ph(e,n.device),r=lh(n.path),i=`/data/local/tmp/devecocli-${oh()}.png`;await Dh({hdcPath:e.hdcPath,serial:t,localPath:r,remotePath:i,display:n.display}),console.log(ah(`Screenshot saved to ${r}`))}catch(e){console.error(ch(`Failed to capture screenshot: ${e.message}`)),process.exit(1)}}var $a=new sh("ui").description("Inspect and interact with UI on a connected device");$a.command("screenshot").description("Capture a screenshot of the device screen").option("--device <name|serial>","Target device name or serial; required when multiple devices are connected").option("--display <displayId>","Target display id").option("--path <path>","Existing directory or PNG file path whose parent exists").action(Ih);var Ba=$a;import{Command as Wh}from"commander";import{green as Uh,red as un,cyan as dc,yellow as uc,dim as pc}from"colorette";import zh from"p-limit";import Ah from"ora";var ot=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=Ah(e),this.spinner.start(),this.isRunning=!0}stop(){this.spinner&&this.isRunning&&(this.spinner.stop(),this.isRunning=!1)}succeed(e){this.spinner&&(this.spinner.succeed(e),this.isRunning=!1)}fail(e){this.spinner&&(this.spinner.fail(e),this.isRunning=!1)}};import*as Wa from"fs";import*as Ua from"path";import{homedir as Th}from"os";import xh from"axios";var io=class{client;constructor(){let e={timeout:Li.HTTP_TIMEOUT_MS,headers:{"User-Agent":qn.USER_AGENT,"accept-language":qn.ACCEPT_LANGUAGE},transformResponse:[t=>t],proxy:!1};this.client=xh.create(e),this.client.interceptors.response.use(t=>t,t=>{let r=`Network connection failed (${t.code}). Please check your proxy configuration or network settings`;throw new Error(`${t.message}
|
|
1252
|
-
${r}`)})}async get(e,t){let r=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}async post(e,t){let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,headers:e.headers}}parseJson(e){return JSON.parse(e.data)}async getBinary(e,t){let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout});if(r.status!==200)throw new Error(`HTTP ${r.status}`);return Buffer.from(r.data)}},$e=new io;var za=["DevEco"];async function ir(){let n=await $e.get(fe.TAGS_API_URL),t=or(n,"Tags API").data.skill.filter(r=>r.name==="HMOS");if(t.length===0)throw new Error("No HMOS tag found.");return t.map(r=>r.id)}async function kh(n){let e=[],t=fe.DEFAULT_PAGE_SIZE,r=1;for(;;){let i=await $e.post(fe.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:r,pageSize:t,tagIds:[n]}}),o=or(i,"Skills API");if(e.push(...o.data.list),o.data.list.length<t)break;r++}return e}async function oo(n){let e=new Map,t=n.map(i=>kh(i)),r=await Promise.all(t);for(let i of r)for(let o of i)e.has(o.id)||e.set(o.id,o);return Array.from(e.values()).filter(i=>i.tags?.every(o=>!za.includes(o.name)))}async function Rh(n,e){let t=await $e.post(fe.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:fe.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return or(t,"Skills API").data.list}async function so(n,e){let t=new Map,r=e.map(o=>Rh(n,o)),i=await Promise.all(r);for(let o of i)for(let s of o)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(o=>o.tags?.every(s=>!za.includes(s.name)))}function qa(n){let e=[];for(let[,t]of Object.entries(ge)){let r=Ua.join(Th(),t.path,n);Wa.existsSync(r)&&e.push(t.displayName)}return e.sort()}function or(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=$e.parseJson(n);if(t.code!==fe.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Ga(n){let e=`${fe.SKILL_API_BASE}/${n}/checksum`,t=await $e.get(e);return or(t,"Checksum API").data}import Mh from"adm-zip";import Oh from"crypto";import Ya from"fs";import F from"path";import{fileURLToPath as Lh}from"url";import{homedir as Ja}from"os";import{red as Nh}from"colorette";var Te=Ya.promises;function ao(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function Va(n,e){let t=F.resolve(e),r=F.resolve(n),i=F.relative(r,t);if(i.startsWith("..")||F.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function co(n){return F.isAbsolute(n)?n:F.resolve(process.cwd(),n)}function _h(n){return Oh.createHash("sha256").update(n).digest("hex")}async function Hh(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=_h(n),i=e.sha256.toLowerCase();if(r!==i)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function Ka(n){let e=`${fe.SKILL_API_BASE}/${n}/install?format=zip`,t=await $e.getBinary(e),r=await Ga(n);return await Hh(t,r),t}async function Fh(n,e,t){ao(t);let r=new Mh(n),i=r.getEntries();try{await Te.stat(e)}catch{await Te.mkdir(e,{recursive:!0})}let o=F.join(e,t);Va(e,o);for(let s of i){let a=F.join(o,s.entryName);Va(o,a)}r.extractAllTo(o,!0)}async function lo(n){let e=ge[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(ge).join(", ")}`);let t=F.join(Ja(),e.path.replace("/skills",""));try{return await Te.access(t),!0}catch{return!1}}function uo(n){let e=ge[n];return F.join(Ja(),e.path)}function jh(n){let e=ge[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(ge).join(", ")}`);return e}function po(n,e){let t=jh(e),r="projectPath"in t?t.projectPath:F.join("."+e,"skills");return F.join(n,r)}async function $h(n,e,t){ao(e);let r=F.join(n,e);try{if(await Te.access(r),t)await Te.rm(r,{recursive:!0,force:!0});else return console.log(`Skill ${e} exists in ${n}.`),{skillDir:r,shouldSkip:!0}}catch{}return{skillDir:r,shouldSkip:!1}}async function mo(n,e,t){await Fh(n,e,t),console.log(`Skill ${t} installed to ${F.join(e,t)}.`)}async function ho(n,e,t){let r=F.join(e,t);await Te.mkdir(r,{recursive:!0});let i=F.join(r,F.basename(n));await Te.copyFile(n,i),console.log(`Skill ${t} installed to ${r}.`)}function Za(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(Nh(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function Ct(n,e,t,r){try{let i=await e(),{shouldSkip:o}=await $h(i,n,r);return o?{success:!0,skipped:!0}:(await t(i),{success:!0})}catch(i){return Za(n,i,"Installation failed")}}async function fo(n,e){try{ao(n);let t=await e(),r=F.join(t,n);try{await Te.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await Te.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return Za(n,t,"Removal failed")}}async function Xa(n,e,t,r=!1){return Ct(n,()=>uo(e),i=>mo(t,i,n),r)}async function Qa(n,e,t,r=!1){return Ct(n,()=>t,i=>mo(e,i,n),r)}async function ec(n,e,t,r,i=!1){return Ct(n,()=>po(t,r),o=>mo(e,o,n),i)}async function tc(n,e,t,r=!1){return Ct(n,()=>uo(t),i=>ho(e,i,n),r)}async function nc(n,e,t,r,i=!1){return Ct(n,()=>po(t,r),o=>ho(e,o,n),i)}async function rc(n,e,t,r=!1){return Ct(n,()=>t,i=>ho(e,i,n),r)}async function ic(n,e){return fo(n,()=>uo(e))}async function oc(n,e){return fo(n,()=>e)}async function sc(n,e,t){return fo(n,()=>po(e,t))}function ac(){let e=F.dirname(Lh(import.meta.url));for(;;){let t=F.join(e,"SKILL.md");if(Ya.existsSync(t))return t;let r=F.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import cc from"fs";import{cyan as Bh}from"colorette";async function an(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await lo(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function cn(){let n=[];for(let e of Object.keys(ge))await lo(e)&&n.push(e);return n}function ln(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(Bh("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function Be(n,e,t){if(!cc.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!cc.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function dn(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?co(n):void 0,resolvedProject:e?co(e):void 0}}async function sr(n,e,t){let r=[],i=[],o;if(e?o=e:t&&n.agent?i=(await an(n.agent)).map(a=>({project:t,agent:a})):t?i=(await cn()).map(a=>({project:t,agent:a})):n.agent?r=await an(n.agent):r=await cn(),!o&&r.length===0&&i.length===0)throw new Error("No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location.");return{agents:r,projectAgents:i,customPath:o}}async function qh(n){let e=await ir();if(n.all)return(await oo(e)).map(r=>r.enName);{let r=(await so(n.skill,e)).find(i=>i.enName===n.skill);if(!r)throw new Error(`Skill "${n.skill}" not found`);return[r.enName]}}async function Gh(n,e,t,r){let i=[];if(t.customPath){let o=await Qa(n,e,t.customPath,r);return i.push(o),i}for(let o of t.agents){let s=await Xa(n,o,e,r);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await ec(n,e,o,s,r);i.push(a)}return i}function Vh(n){if(n.all&&n.skill)throw new Error("`--all` and `--skill` cannot be specified together.");if(!n.all&&!n.skill)throw new Error("Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=dn(n.path,n.project,n.agent);return t&&Be(t,"Project directory",n.force),e&&Be(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}async function Yh(n,e,t){let r=await sr(n,e,t);return{skillNames:await qh(n),targets:r}}async function Jh(n,e,t,r){let i=[],o=n.length,s=zh(5),a=n.map(async c=>s(async()=>{try{let l=await Ka(c);return{name:c,buffer:l,success:!0}}catch(l){let u=l instanceof Error?l.message:"unknown error";return{name:c,error:u,success:!1}}}));for(let c=0;c<n.length;c++){let l=n[c],u=o>1?` (${c+1}/${o})`:"";r.start(`Installing ${l}${u}...`);let f=await a[c];if(!f.success){r.fail(),console.log(un(`${l}: Download failed - ${f.error}`)),i.push({success:!1});continue}r.stop();let P=await Gh(l,f.buffer,e,t);i.push(...P)}return i}async function Kh(n){let e=new ot;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=Vh(n),{skillNames:i,targets:o}=await Yh(n,t,r),s=await Jh(i,o,n.force||!1,e);e.stop(),ln(s)}catch(t){throw e.stop(),t}}function Zh(n){let{resolvedPath:e,resolvedProject:t}=dn(n.path,n.project,n.agent);return t&&Be(t,"Project directory"),e&&Be(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function Xh(n,e){let t=new ot;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:i}=Zh(e);t.stop();let o=await Qh(e,n,r,i);t.stop(),ln(o)}catch(r){throw t.stop(),r}}function lc(n,e=""){if(n.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function ar(n,e){let t=[];for(let r of e){let i=r.type==="agent"?await ic(n,r.agent):await sc(n,r.project,r.agent);t.push(i)}return t}async function Qh(n,e,t,r){if(t)return[await oc(e,t)];if(r&&n.agent){let a=(await an(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return ar(e,a)}if(r){let s=await cn();lc(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return ar(e,a)}if(n.agent){let a=(await an(n.agent)).map(c=>({type:"agent",agent:c}));return ar(e,a)}let i=await cn();lc(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return ar(e,o)}var pn=new Wh("skills").description("Manage HarmonyOS skills");pn.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async n=>{let e=new ot;try{e.start("Fetching skills...");let t=await ir(),r=await oo(t);if(r.length===0){e.stop(),console.log(uc("No skills available."));return}e.succeed(`Fetched ${r.length} skills`);for(let i of r)if(n.long){console.log(dc(i.enName)),console.log(pc(i.description));let o=qa(i.enName);o.length>0&&console.log(Uh(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName)}catch(t){e.stop(),console.error(un(t.message)),process.exit(1)}});pn.command("find <keyword>").description("Search skills by keyword").action(async n=>{let e=new ot;try{e.start("Searching skills...");let t=await ir(),r=await so(n,t);if(r.length===0){console.log(uc(`No skills found matching '${n}'.`)),e.stop();return}e.succeed(`Found ${r.length} skills.`);for(let i of r)console.log(dc(i.enName)),console.log(pc(i.description)),console.log()}catch(t){e.stop(),console.error(un(t.message)),process.exit(1)}});pn.command("add").description("Install skills to AI agents").option("--all","Install all available skills").option("--agent <agents>","Target agents, comma-separated; Omit to install to all available agents").option("--skill <skill-name>","Name of the skill to install").option("-f, --force","Overwrite an existing skill installation").option("--project <path>","Project root directory for skill installation").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").action(async n=>{try{await Kh(n)}catch(e){console.error(un(e.message)),process.exit(1)}});pn.command("remove").description("Remove an installed skill from AI agents").requiredOption("--skill <skill-name>","Name of the skill to remove").option("--agent <agents>","Target agents, comma-separated.Omit to remove from all available agents").option("--project <path>","Project root directory for skill removal").option("--path <path>","Path for skill removal").action(async n=>{try{await Xh(n.skill,n)}catch(e){console.error(un(e.message)),process.exit(1)}});var mc=pn;import{Command as tf,InvalidArgumentError as fc}from"commander";import{cyan as cr}from"colorette";function st(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=gt(t);return r==="transient"?new Error(`${e}: Device communication channel unavailabel. Retry in a few seconds.`):r==="fatal"?new Error(`${e}: ${t.trim()}`):null}var go=[800,1500,2500];function ef(n){return new Promise(e=>setTimeout(e,n))}var lr=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=G.from(e)}createFollowLineHandler(e){return(t,r)=>{let i=e.keyword?t.filter(o=>o.includes(e.keyword)):t;if(r!=="stderr")for(let o of i)console.log(o)}}findDeviceByArg(e,t){return e.find(r=>r.serial===t||r.name===t)}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
|
|
1253
|
-
`)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let i=t[0];return g(cr(`Using device serial: ${i}`)),i}if(e&&t.includes(e))return g(cr(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let i=this.findDeviceByArg(r,e);if(i)return g(cr(`Using device: ${i.name} (${i.serial})`)),i.serial;let o=this.formatConnectedDeviceList(r);throw new Error(`Device '${e}' not found.
|
|
1249
|
+
`;function ib(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function ob(n){let e=n.trim();if(!wp.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${wp.join(", ")}`);return e}function Sp(n,e,t,r){let i=e.trim();if(!/^-?\d+$/.test(i))throw new Error(`${n} must be an integer in [${t}, ${r}].`);let o=Number(i);if(o<t||o>r)throw new Error(`${n} must be in [${t}, ${r}].`);return o}function bp(n,e,t,r,i){let o=e.trim(),s=Number(o);if(!o||Number.isNaN(s))throw new Error(`${n} must be a number in [${t}, ${r}].`);if(i!==void 0&&!sb(o,i))throw new Error(`${n} supports at most ${i} decimal place(s).`);if(s<t||s>r)throw new Error(`${n} must be in [${t}, ${r}].`);return o}function sb(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function ab(n,e,t,r,i){return Number(bp(n,e,t,r,i))}function cb(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 lb(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 db(n,e){let t=i=>i.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(lt("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(lt("Run `devecocli emulator image download ...` followed by `devecocli emulator image list` and then copy an `osVersion` string exactly.")),new Error("No downloaded osVersion values parsed; cannot validate --os-version.");if(!e.some(i=>t(i)===r)){console.error(ge("--os-version does not match any downloaded image (exact string required).")),console.log(lt("Use one of these --os-version values:"));for(let i of e)console.log(` ${i}`);throw new Error(`No downloaded image matches --os-version "${n}".`)}}var ub=["Name","Status","Serial","Device Type","OS Version"];function pb(n,e,t){return{cells:[n.name,t?"running":"stopped",e??"-",n.deviceType??"-",n.osVersion??"-"],highlight:t}}async function fb(n,e){let t=await Promise.all(e.map(async r=>{let i=await jn(n,r,nb);return[r,i]}));return new Map(t)}async function mb(n){let e=await uc(n),t=await fb(n,e);return{serials:e,params:t}}function hb(n,e,t,r,i){if(e)for(let o of["const.product.name","const.product.model"]){let s=e.get(o);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),i.set(s,n);let c=r.indexOf(n);c!==-1&&r.splice(c,1);return}}function gb(n,e,t){let r=new Map,i=new Map,o=[...n],s=[...t];for(let a of n){let c=e.get(a),l=c?.get("ohos.qemu.hvd.name");l&&i.set(l,a),t.length>0&&hb(a,c,s,o,r)}for(let a=0;a<s.length&&a<o.length;a++)r.set(s[a],o[a]);return{productSerialMap:r,hvdSerialMap:i}}function yb(n,e,t){let r=n.map(i=>({emu:i,serial:e.get(i.name)??t.get(i.name),effectiveRunning:i.isRunning===!0||t.has(i.name)}));return r.sort((i,o)=>i.effectiveRunning!==o.effectiveRunning?i.effectiveRunning?-1:1:i.emu.name.localeCompare(o.emu.name)),r.map(i=>pb(i.emu,i.serial,i.effectiveRunning))}async function wb(n,e,t){try{let[r,i]=await Promise.all([n.listEmulators(),mb(e)]);if(r.length===0){t?.stop(),console.log(lt(" No emulator instances found."));return}let o=r.filter(l=>l.isRunning).map(l=>l.name),{productSerialMap:s,hvdSerialMap:a}=gb(i.serials,i.params,o);t?.stop();let c=yb(r,s,a);console.log(yt(ub,c))}catch(r){_o(t,`Failed to list emulators: ${r.message}`)}}function Ep(n,e,t){let r=!1;for(let i=0;i<n.length;i++){let o=n[i];if(o.status!=="rejected")continue;r=!0;let s=o.reason;console.error(ge(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(Yr(s.stdout)),s.stderr&&console.error(Yr(s.stderr))}return r}var vb=2e3,Sb=6e4;async function bb(n,e){let t=de(e);return(await pc(n)).some(i=>de(i)===t)}async function Pp(n,e,t,r=Sb,i=vb){let o=Date.now()+r;for(;Date.now()<o;){if(await bb(n,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}async function Eb(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(lt(`Emulator "${t}" is already running.`));return}console.log(zn(`Starting emulator "${t}"...`));let i=await Pp(e,t,!0);console.log(i?Kr(`Emulator "${t}" started successfully.`):lt(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function Pb(n,e,t){let r=await Promise.allSettled(t.map(o=>Eb(n,e,o)));Ep(r,t,"start")&&process.exit(1)}async function Cp(n,e){let t=e.trim();if(!hn(t))return t;let r=await Q.withHdcPath(n).getDeviceName(t);if(r===t)throw new Error(`Cannot resolve a running emulator with serial "${t}". Use \`devecocli emulator list\` or pass the emulator name instead.`);return r}async function Cb(n,e,t){let r=await Cp(e,t);if(console.log(zn(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(lt(`Emulator "${r}" is already stopped.`));return}let o=await Pp(e,r,!1);console.log(o?Kr(`Emulator "${r}" stopped successfully.`):lt(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function Ib(n,e,t){let r=await Promise.allSettled(t.map(o=>Cb(n,e,o)));Ep(r,t,"stop")&&process.exit(1)}async function _e(){try{let n=await I.new();return{manager:Wn.from(n),toolProvider:n}}catch(n){console.error(ge(`Failed to initialize emulator: ${n.message}`)),process.exit(1);return}}async function wt(n,e){try{let t=ib(n.target),r=e(),{manager:i,toolProvider:o}=await _e(),s=await Cp(o.hdcPath,t);await i.controlEmulator(s,r),console.log(Kr(`Emulator "${t}" operation completed.`))}catch(t){let r=n.target?.trim()||"<unknown>";console.error(ge(`Failed to operate emulator "${r}": ${t.message}`)),process.exit(1)}}function Ab(n){let e=[];return jo(e,"longitude",n.longitude,-180,180,8),jo(e,"latitude",n.latitude,-90,90,8),jo(e,"altitude",n.altitude,-1e4,1e4,2),jo(e,"bearing",n.direction,0,359.99,2,"--direction"),Cc(e,"Specify one geolocation option.")}function Db(n){let e=[];return Vr(e,"light",n.lightIntensity,0,1e5,!1,"--light-intensity"),Vr(e,"humidity",n.humidity,0,100,!1),Vr(e,"temperature",n.temperature,-273.1,100,!1),Vr(e,"steps",n.steps,0,1e4,!0),Vr(e,"heartrate",n.heartrate,0,255,!0),Cc(e,"Specify one sensor option.")}function Cc(n,e){if(n.length===0)throw new Error(e);if(n.length>1)throw new Error("Only one operation option can be specified.");return n[0]}function jo(n,e,t,r,i,o,s=`--${e}`){t!==void 0&&n.push({type:"gps",key:e,value:bp(s,t,r,i,o)})}function Vr(n,e,t,r,i,o,s=`--${e}`){if(t===void 0)return;let a=o?Sp(s,t,r,i):ab(s,t,r,i,1);n.push({type:"sensor",key:e,value:a})}function Rb(n){let e=[];return n.level!==void 0&&e.push({type:"battery",level:Sp("--level",n.level,1,100)}),n.status!==void 0&&e.push({type:"battery-status",status:n.status==="charging"?1:0}),Cc(e,"Specify --level or --status.")}var se=new Pc("emulator").description("Manage emulator instances"),Tb=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Ho(n){let e=new Jr("--device-type <type>","Emulator device type").choices([...Tb]);return n?e.makeOptionMandatory():e}function Gn(n,e){for(let t of e)if(t in n)return n[t]}function qr(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function vp(n){let e=qr(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var kb=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],xb="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function Ip(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function Ap(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let i=r,o=qr(Gn(i,["osVersion","OsVersion","OSVersion","os_version"])),s=qr(Gn(i,["deviceType","DeviceType","device_type"])),a=vp(Gn(i,["downloaded","Downloaded","isDownloaded"])),c=qr(Gn(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=qr(Gn(i,["releaseType","ReleaseType","release_type"])),d=vp(Gn(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,l,d,a],highlight:e&&a==="true"})}return t}function Nb(n){let e=n.trim();if(!e)return!0;let t=Ip(e);return t===null?!1:t.length===0?!0:Ap(t,!0).length===0}function Lb(n,e){let t=n.trim();if(!t)return"";let r=Ip(t);if(!r)return n.trimEnd();let i=Ap(r,e);return yt(kb,i)}var $o=new Pc("image").description("HarmonyOS emulator system images (download, list, remove)");$o.command("download").description("Download system image").addOption(Ho(!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 _e();try{await bc(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof Me&&(console.error(ge(r.message)),process.exit(1)),r}n.deviceType?.trim()||(console.error(ge("Error: missing required option '--device-type <type>'")),process.exit(1)),n.osVersion?.trim()||(console.error(ge("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(ge(`Failed to download system image: ${r.message}`)),process.exit(1)}});$o.command("remove").description("Remove a downloaded system image").addOption(Ho(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let{manager:e}=await _e();try{await e.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})}catch(t){console.error(ge(`Failed to remove system image: ${t.message}`)),process.exit(1)}});$o.command("list").description("List system images").addOption(Ho(!1)).option("--all","List all images (local and remote)").addOption(new Jr("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await _e();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if(Nb(r)){console.log(lt(xb));return}if(n.format==="json"){console.log(r.trimEnd());return}let i=Lb(r,n.all===!0);console.log(i)}catch(t){console.error(ge(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});se.addCommand($o);var Uo=new Pc("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");Uo.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let{toolProvider:n}=await _e(),e=await mp(n.emulatorPath,n.sdkPath);process.exit(e)});Uo.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let{toolProvider:n}=await _e(),e=await yp(n.emulatorPath,n.sdkPath);process.exit(e)});Uo.action(async()=>{let{toolProvider:n}=await _e(),e=await gp(n.emulatorPath,n.sdkPath);process.exit(e)});se.addCommand(Uo);se.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>wt(n,()=>({type:"shake"})));se.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>wt(n,()=>({type:"power"})));se.command("rotate").description("Rotate emulator").addOption(new Jr("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Ec("<direction>").choices(["left","right"])).action((n,e)=>wt(e,()=>({type:"rotation",direction:n})));se.command("volume").description("Change volume").addOption(new Jr("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Ec("<direction>").choices(["up","down"])).action((n,e)=>wt(e,()=>({type:"volume",direction:n})));se.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",rb).action((n,e)=>wt(e,()=>({type:"folded-state",state:ob(n)})));se.command("battery").description("Set battery level or charging status").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--level <1-100>","Battery level, SOC (integer 1-100)").addOption(new Jr("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>wt(n,()=>Rb(n)));se.command("geolocation").description("Inject geographic coordinates and direction").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--longitude <value>","Longitude (-180.0 to 180.0)").option("--latitude <value>","Latitude (-90.0 to 90.0)").option("--altitude <value>","Altitude (-10000.0 to 10000.0)").option("--direction <value>","Heading direction in degrees (0.00 to 359.99)").action(n=>wt(n,()=>Ab(n)));se.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new Ec("<type>","Motion simulation scene").choices(["outdoorRunning","outdoorCycling","drivingNavigation"])).action((n,e)=>{let t={outdoorRunning:{type:"outdoor-running"},outdoorCycling:{type:"outdoor-cycling"},drivingNavigation:{type:"driving-navigation"}};return wt(e,()=>t[n])});se.command("sensor").description("Inject sensor data").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--light-intensity <value>","Light sensor (0 to 100000)").option("--humidity <value>","Humidity sensor (0 to 100)").option("--temperature <value>","Temperature sensor (-273.1 to 100)").option("--steps <value>","Steps sensor (integer 0 to 10000)").option("--heartrate <value>","Heart rate sensor (integer 0 to 255)").action(n=>wt(n,()=>Db(n)));se.command("list").description("List all emulator instances").action(async()=>{let{manager:n,toolProvider:e}=await _e(),t=tb({text:"Listing emulators\u2026",color:"cyan"}).start();await wb(n,e.hdcPath,t)});se.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await _e();try{await Sc(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof Me&&(console.error(ge(r.message)),process.exit(1)),r}n?.length||(console.error(ge("Error: missing required argument 'names'")),process.exit(1)),await Pb(e,t.hdcPath,n)});se.command("stop <names...>").description("Stop one or more emulator instances (by name or serial,e.g.,127.0.0.1:<port>)").action(async n=>{let{manager:e,toolProvider:t}=await _e();n?.length||(console.error(ge("Error: missing required argument 'names'")),process.exit(1)),await Ib(e,t.hdcPath,n)});var Dp=se.command("create <name>").description("Create a local emulator by running emulator -create <name> \u2026; --os-version must match a downloaded image from `emulator image list`.").addOption(Ho(!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");Dp.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
|
|
1250
|
+
${lt("Tip: ")}${Yr("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
|
|
1251
|
+
${zn('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
|
|
1252
|
+
${zn('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
|
|
1253
|
+
`)}});Dp.action(async(n,e)=>{try{cb(n),lb(e.osVersion);let{manager:t}=await _e(),r=await t.listDownloadedImageOsVersions();db(e.osVersion,r),console.log(zn(`Creating emulator "${n}"...`)),await t.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(Kr(`Emulator "${n}" created successfully.`))}catch(t){console.error(ge(`${t.message}`)),process.exit(1)}});se.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let{manager:e}=await _e();console.log(zn(`Deleting emulator "${n}"...`));try{let t=await e.deleteVirtualDevice(n);console.log(Kr(`Emulator "${t}" deleted successfully.`))}catch(t){let r=t;console.error(ge(r.message)),r.stdout&&console.error(Yr(r.stdout)),r.stderr&&console.error(Yr(r.stderr)),process.exit(1)}});var Rp=se;import{Command as Xb}from"commander";import{cyan as He}from"colorette";import*as zp from"readline";import*as Bp from"crypto";import*as Tp from"http";import*as kp from"crypto";import{URL as Ob}from"url";var Bo=class{server=null;port=0;clientSecret;callbackPath="/callback";resolveCallback=null;rejectCallback=null;timeoutId=null;baseUrl;successRedirectUrl;failedRedirectUrl;constructor(e,t,r,i){this.clientSecret=e,this.baseUrl=t,this.successRedirectUrl=r,this.failedRedirectUrl=i}async start(){return new Promise((e,t)=>{let r=Tp.createServer((i,o)=>{this.handleRequest(i,o)});r.keepAliveTimeout=1,r.on("error",i=>{t(new Error("Failed to start local auth server",{cause:i}))}),r.listen(0,"127.0.0.1",()=>{this.server=r;let i=r.address();this.port=i.port,e()})})}async waitForCallback(e=3e4){return new Promise((t,r)=>{this.resolveCallback=i=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),t(i)},this.rejectCallback=i=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),r(i)},this.timeoutId=setTimeout(()=>{this.timeoutId=null,this.rejectCallback?.(new Error("Callback timeout"))},e)})}async stop(){return this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.server?new Promise(e=>{let t=this.server;this.server=null,typeof t.closeAllConnections=="function"&&t.closeAllConnections();let r=setTimeout(()=>{e()},100);t.close(()=>{clearTimeout(r),e()})}):Promise.resolve()}handleRequest(e,t){let r=e.headers.host||"";if(![`127.0.0.1:${this.port}`,`localhost:${this.port}`].includes(r.toLowerCase())){t.writeHead(400),t.end("Bad Host");return}let o=new Ob(e.url??"",`http://${r}`);if(o.pathname!==this.callbackPath){t.writeHead(404),t.end("Not Found");return}try{let s=o.searchParams;if(e.method==="POST"){let a="";e.on("data",c=>{a+=c.toString()}),e.on("end",()=>{this.handleCallbackRequest(e,t,s,a)})}else this.handleCallbackRequest(e,t,s,"")}catch(s){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(s)}}handleCallbackRequest(e,t,r,i){try{let o=this.parseParams(r,i),s=o.get("code"),a=o.get("tempToken"),c=o.get("siteId"),l=o.get("quit");if(!this.validateCode(s)){t.writeHead(400),t.end("Bad Request");return}if(this.isQuitRequest(l)){this.handleQuitRequest(t);return}if(!a||!c){t.writeHead(400),t.end("Bad Request");return}let d={tempToken:a,siteId:c,quit:l??void 0};this.resolveCallback?.(d),this.sendSuccessResponse(t)}catch(o){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(o)}}parseParams(e,t){return t&&t.trim()?new URLSearchParams(t):e}validateCode(e){let t=Buffer.from(e||"","utf8"),r=Buffer.from(this.clientSecret,"utf8");return t.length===r.length&&kp.timingSafeEqual(t,r)}isQuitRequest(e){return e==="true"||e==="access_denied"||e==="quit"}handleQuitRequest(e){this.rejectCallback?.(new Error("User quit the login process")),e.writeHead(302,{Location:`${this.baseUrl}/${this.failedRedirectUrl}`}),e.end()}sendSuccessResponse(e){e.writeHead(302,{Location:`${this.baseUrl}/${this.successRedirectUrl}`}),e.end()}getPort(){return this.port}};import*as Fe from"fs";import*as Qr from"path";import{homedir as Ub}from"os";var yn={};lw(yn,{LocalCrypto:()=>yn,decryptForLocalStorage:()=>Hb,encryptForLocalStorage:()=>jb,isEncryptedBlob:()=>$b});import*as K from"fs";import*as Zr from"path";import*as ye from"crypto";import{homedir as xp}from"os";var Vn=cn.ALGORITHM,Np=cn.IV_LENGTH,Wo=cn.KEY_LENGTH,Go=cn.KEY_LENGTH,Xr=cn.KEK_VERSIONS,Ic=process.env.DEVECO_CLI_DATA_DIR||Zr.join(xp(),Ie.CONFIG_DIR_NAME,Ie.APP_NAME),Ac=Zr.join(xp(),".local","share",Ie.APP_NAME,"keys"),qn=Zr.join(Ic,Ie.KEY_FILE_NAME);function Dc(n){return Zr.join(Ac,`${n}.bin`)}function Lp(){K.existsSync(Ic)||K.mkdirSync(Ic,{recursive:!0,mode:448}),K.existsSync(Ac)||K.mkdirSync(Ac,{recursive:!0,mode:448})}function Op(){Lp();for(let n of Xr){let e=Dc(n);K.existsSync(e)||K.writeFileSync(e,ye.randomBytes(Wo),{mode:384})}}function Mp(n){Op();let e=Dc(n),t=K.readFileSync(e);if(t.length===Wo)return t;let r=ye.randomBytes(Wo);return K.writeFileSync(e,r,{mode:384}),r}function Rc(n,e){let t=ye.randomBytes(Np),r=Mp(e),i=ye.createCipheriv(Vn,r,t),o=Buffer.concat([i.update(n),i.final()]),s=i.getAuthTag();return{version:1,algorithm:Vn,kekId:e,encryptedDek:o.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function Mb(n){let e=Mp(n.kekId),t=Buffer.from(n.iv,"base64"),r=Buffer.from(n.authTag,"base64"),i=Buffer.from(n.encryptedDek,"base64"),o=ye.createDecipheriv(Vn,e,t);return o.setAuthTag(r),Buffer.concat([o.update(i),o.final()])}function _b(){if(Op(),K.existsSync(qn))return;let n=ye.randomBytes(Go),e=Rc(n,Xr[0]);K.writeFileSync(qn,JSON.stringify(e,null,2),{mode:384})}function _p(){_b();let n=JSON.parse(K.readFileSync(qn,"utf8")),e=Mb(n);if(e.length===Go)return e;let t=ye.randomBytes(Go),r=Rc(t,Xr[0]);return K.writeFileSync(qn,JSON.stringify(r,null,2),{mode:384}),t}function Fb(){Lp();for(let t of Xr){let r=Dc(t);K.existsSync(r)||K.writeFileSync(r,ye.randomBytes(Wo),{mode:384})}if(K.existsSync(qn))return;let n=ye.randomBytes(Go),e=Rc(n,Xr[0]);K.writeFileSync(qn,JSON.stringify(e,null,2),{mode:384})}function jb(n){let e=_p(),t=ye.randomBytes(Np),r=ye.createCipheriv(Vn,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o=r.getAuthTag();return{version:1,algorithm:Vn,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:o.toString("base64"),timeStamp:Date.now()}}function Hb(n){try{let e=_p(),t=Buffer.from(n.iv,"base64"),r=Buffer.from(n.authTag,"base64"),i=Buffer.from(n.ciphertext,"base64"),o=ye.createDecipheriv(Vn,e,t);return o.setAuthTag(r),Buffer.concat([o.update(i),o.final()]).toString("utf8")}catch{throw Fb(),new Error("Failed to decrypt local ciphertext")}}function $b(n){if(!n||typeof n!="object")return!1;let e=n;return e.algorithm==="aes-256-gcm"&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}var zo=class{tokenFilePath;constructor(e){let t=e||process.env.DEVECO_CLI_DATA_DIR||Qr.join(Ub(),Ie.CONFIG_DIR_NAME,Ie.APP_NAME);this.tokenFilePath=Qr.join(t,Ie.TOKEN_FILE_NAME)}ensureConfigDir(){let e=Qr.dirname(this.tokenFilePath);Fe.existsSync(e)||Fe.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=yn.encryptForLocalStorage(e);this.ensureConfigDir(),Fe.writeFileSync(this.tokenFilePath,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){try{if(!Fe.existsSync(this.tokenFilePath))return null;let e=JSON.parse(Fe.readFileSync(this.tokenFilePath,"utf8"));return yn.isEncryptedBlob(e)?yn.decryptForLocalStorage(e):null}catch{return await this.clearToken(),null}}async clearToken(){try{Fe.existsSync(this.tokenFilePath)&&Fe.unlinkSync(this.tokenFilePath)}catch(e){throw new Error("Failed to clear token",{cause:e})}}},je=new zo;var dt={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},ei={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},Vo={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},Bb={[dt.CHINA]:ei.CHINA,[dt.RUSSIA]:ei.RUSSIA,[dt.EUROPE]:ei.EUROPE,[dt.SINGAPORE]:ei.CHINA},Wb={[Vo.CHINA]:dt.CHINA,[Vo.SINGAPORE]:dt.SINGAPORE,[Vo.EUROPE]:dt.EUROPE,[Vo.RUSSIA]:dt.RUSSIA};function Fp(n){return Bb[n]??ei.CHINA}function jp(n){return Wb[n]??dt.CHINA}function qo(n,e){return n?.toUpperCase()===dt.CHINA?ze.CN_LOGIN_URL:e}import{exec as Gb}from"child_process";import{promisify as zb}from"util";var Vb=zb(Gb);async function Hp(n){let e=process.platform,t;switch(e){case"win32":t=`start "" "${n}"`;break;case"darwin":t=`open "${n}"`;break;default:t=`xdg-open "${n}"`;break}try{await Vb(t)}catch(r){throw new Error("Failed to open browser",{cause:r})}}import qb from"axios";var Tc=class{client;constructor(){let e={timeout:_r.HTTP_TIMEOUT_MS,headers:{"User-Agent":so.USER_AGENT,"accept-language":so.ACCEPT_LANGUAGE},transformResponse:[t=>t],proxy:!1};this.client=qb.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}
|
|
1254
|
+
${r}`)})}async get(e,t){let r=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}async post(e,t){let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,statusText:e.statusText??"",headers:e.headers}}parseJson(e){return JSON.parse(e.data)}async getBinary(e,t){let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout});if(r.status!==200)throw new Error(`HTTP ${r.status}`);return Buffer.from(r.data)}async postAllowFailure(e,t){let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(r)}async deleteAllowFailure(e,t){let r=await this.client.request({method:"DELETE",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(r)}async getBinaryAllowFailure(e,t){let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0}),i=Buffer.from(r.data),o=i.toString("utf8");return{statusCode:r.status,statusText:r.statusText??"",buffer:i,body:o}}},N=new Tc;var kc=class{async checkJwtToken(e,t,r){let i={refresh:"false",jwtToken:e},s=`${t()}/${r}`,a=await N.get(s,{headers:i});if(a.statusCode!==200)throw new Error(`Failed to check jwtToken: ${a.statusCode}`);return N.parseJson(a)}async refreshToken(e,t){let r=await je.loadJwtToken();return r?this.refreshTokenWithToken(r,e,t):null}async refreshTokenWithToken(e,t,r){try{let i={refresh:"true",jwtToken:e},s=`${t()}/${r}`,a=await N.get(s,{headers:i});if(a.statusCode!==200)return null;let c=N.parseJson(a);return!c.status||!c.userInfo?null:{accessToken:c.userInfo.accessToken,refreshToken:c.userInfo.refreshToken??""}}catch(i){let o=i;return console.error(`Failed to refresh token: ${o.code??""} ${o.message??""}`),null}}},ti=new kc;function $p(n){try{let e=n.split(".");if(e.length!==3)return null;let r=e[1].replace(/-/g,"+").replace(/_/g,"/"),i=r.padEnd(r.length+(4-r.length%4)%4,"="),o=Buffer.from(i,"base64").toString("utf8");return JSON.parse(o)}catch{return null}}function Up(n){let e=n.split(".");return e.length===3&&e.every(t=>t.length>0)}var xc=class{async getJwtToken(e,t,r,i,o){let s=e.split("&")[0],a=jp(t),c=r(),l={tempToken:s,site:a,version:Ie.API_VERSION,appid:o},d=`${c}/${i}`,h=await N.get(d,{params:l});if(h.statusCode!==200)throw new Error(`Failed to get jwtToken: status=${h.statusCode}`);let w=h.data.trim();if(!Up(w))throw new Error("Invalid jwtToken format");return w}async getUserInfoFromJwt(e,t){let r=await t(e);if(!r.status||!r.userInfo)throw new Error("Invalid jwtToken");let i=$p(e);if(!i)throw new Error("Invalid jwtToken: failed to parse payload");return{userId:i.userId,userName:i.userName,accessToken:r.userInfo.accessToken,refreshToken:r.userInfo.refreshToken??"",jwtToken:e,countryCode:r.userInfo.nationalCode,language:Fp(r.userInfo.nationalCode),isRealName:String(r.userInfo.realName)==="true"}}},Yo=new xc;var Jo=class{config;server=null;constructor(e){this.config={...Fr,...e}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}async login(){try{let e=this.generateClientSecret();this.server=new Bo(e,this.getRegionalizedBaseUrl(),this.config.successRedirectUrl,this.config.failedRedirectUrl),await this.server.start(),await this.openLoginPage(this.server.getPort(),e);let t=await this.server.waitForCallback(this.config.timeout);if(t.siteId!=="1")throw new Error("Non-China accounts are not supported.");let r=await Yo.getJwtToken(t.tempToken,t.siteId,()=>this.getRegionalizedBaseUrl(),this.config.tempTokenCheckUrl,this.config.appId),i=await Yo.getUserInfoFromJwt(r,o=>ti.checkJwtToken(o,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl));return await je.saveJwtToken(r),i}finally{this.server&&(await this.server.stop(),this.server=null)}}async isLoggedIn(){let e=await je.loadJwtToken();return e==null?!1:(await ti.checkJwtToken(e,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)).status?!0:(await je.clearToken(),!1)}async logout(){let e=await je.loadJwtToken();if(e==null)return!1;let r=`${this.getRegionalizedBaseUrl()}/${this.config.logoutUrl}?jwtToken=${e}`;try{await N.post(r,{timeout:5e3})}finally{await je.clearToken()}return!0}async getUserInfo(){let e=await je.loadJwtToken();return e?Yo.getUserInfoFromJwt(e,t=>ti.checkJwtToken(t,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)):null}generateClientSecret(){return Bp.randomUUID().replace(/-/g,"")}getRegionalizedBaseUrl(){return qo(this.config.countryCode??"",this.config.baseUrl)}async openLoginPage(e,t){let i=`${this.getRegionalizedBaseUrl()}/${this.config.authUrl}?port=${e}&appid=${this.config.appId}&code=${t}`;await Hp(i)}async refreshToken(){return ti.refreshToken(()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)}},ne=new Jo;import Wp from"axios";var Jb="No JWT in local storage. Run `devecocli auth login` first.";function Kb(n){if(n==null||typeof n!="object")return[];let e=n;if(e.ret&&e.ret.code!==0)throw new Error(`team list request failed: code=${e.ret.code}${e.ret.msg?`, msg=${e.ret.msg}`:""}`);return Array.isArray(e.teams)?e.teams.filter(t=>typeof t=="object"&&t!==null).map(t=>({id:String(t.id??""),upSiteId:Number(t.upSiteId??0),name:String(t.name??""),countryCode:String(t.countryCode??""),siteId:Number(t.siteId??0),userType:Number(t.userType??0),lastLoginTime:String(t.lastLoginTime??""),isMirror:t.isMirror===!0})).filter(t=>t.id.length>0):[]}var Ko=class{config;constructor(e){this.config={...Fr,...e}}updateConfig(e){this.config={...this.config,...e}}async listTeams(){let e=await je.loadJwtToken();if(!e)throw new Error(Jb);let{accessToken:t,userId:r}=await this.fetchAccessToken(e);if(!t)throw new Error("Session expired. Run `devecocli auth login` again.");let i=await this.fetchTeamList(t,r??""),o=Kb(i);return{userId:r??"",teamList:o}}async fetchTeamList(e,t){let r=this.config.agcTeamListUrl;m(`Executing: GET ${r}`);let i;try{i=await Wp.request({method:"GET",url:r,headers:{oauth2Token:e,uid:t,source:"cli",lang:"zh_CN"},timeout:15e3,transformResponse:[o=>o],proxy:!1,validateStatus:()=>!0})}catch(o){throw new Error(`Network error while listing teams: ${o.message}`,{cause:o})}if(i.status===401)throw new Error("AGC rejected the AGC token. Run `devecocli auth login` again.");if(i.status!==200)throw new Error(`Failed to list teams: HTTP ${i.status}`);return typeof i.data=="string"?JSON.parse(i.data):i.data}async fetchAccessToken(e){let r=`${this.getRegionalizedBaseUrl()}/${this.config.jwtTokenCheckUrl}`;m(`Executing: GET ${r} (accessToken refresh)`);let i;try{i=await Wp.request({method:"GET",url:r,headers:{refresh:"true",jwtToken:e},timeout:15e3,transformResponse:[a=>a],proxy:!1,validateStatus:()=>!0})}catch(a){throw new Error(`Network error while refreshing accessToken: ${a.message}`,{cause:a})}if(i.status!==200)throw new Error(`Failed to refresh accessToken: HTTP ${i.status}. Run \`devecocli auth login\` again.`);let s=typeof i.data=="string"?JSON.parse(i.data):i.data;if(!s.status)throw new Error("JWT is invalid. Run `devecocli auth login` again.");return{accessToken:s.userInfo?.accessToken,userId:s.userInfo?.userId}}getRegionalizedBaseUrl(){return qo(this.config.countryCode??"",this.config.baseUrl)}},Gp=new Ko;async function Ft(){return Gp.listTeams()}function Zb(n){if(n.length===0)return He("No teams found for the current user.");let e=["Id","Name"],t=n.map(s=>[s.id,s.name]),r=e.map((s,a)=>Math.max(s.length,...t.map(c=>c[a].length))),i=s=>s.map((a,c)=>a.padEnd(r[c])).join(" "),o=r.map(s=>"-".repeat(s)).join(" ");return[i(e),o,...t.map(i)].join(`
|
|
1255
|
+
`)}function Qb(){return new Promise(n=>{let e=zp.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}var ni=new Xb("auth").description("Authentication commands (login, logout, status, team)");ni.command("login").description("Log in to your Huawei Developer account").action(async()=>{try{if(await ne.isLoggedIn()){let t=await ne.getUserInfo();if(t){console.log(He(`Already logged in, User Name:${t.userName}`));return}}console.log(He("Starting login process...")),console.log(He("Press Enter to open browser for login...")),await Qb();let e=await ne.login();console.log(He(`Login successful. Logged in as ${e.userName}.`))}catch(n){throw new Error("Login failed",{cause:n})}});ni.command("logout").description("Log out of your Huawei Developer account").action(async()=>{try{let n=await ne.logout();console.log(n?He("Logout successful"):He("Already logged out."))}catch(n){throw new Error("Logout failed",{cause:n})}});ni.command("status").description("Show the currently logged-in user").action(async()=>{try{if(!await ne.isLoggedIn()){console.log(He("Not logged in"));return}let e=await ne.getUserInfo();if(!e){console.log(He("Not logged in"));return}console.log(He(`Current user: ${e.userName}`))}catch{console.log(He("Not logged in"))}});var eE=ni.command("team").description("Team-related commands");eE.command("list").description("List team accounts the current user has joined").option("--json","output as JSON",!1).action(async n=>{try{if(!await ne.isLoggedIn()){console.log(He("Please run `devecocli auth login` first."));return}let t=await Ft();if(n.json){console.log(JSON.stringify(t,null,2));return}console.log(Zb(t.teamList))}catch(e){throw new Error("Failed to list teams",{cause:e})}});var Vp=ni;import{Command as hE}from"commander";import{green as gE,red as ai,cyan as gf,yellow as yf,dim as wf}from"colorette";import yE from"p-limit";import tE from"ora";var Qe=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=tE(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 qp from"fs";import*as Yp from"path";import{homedir as nE}from"os";var Jp=["DevEco"];async function Xo(){let n=await N.get(Ve.TAGS_API_URL),t=Zo(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 rE(n){let e=[],t=Ve.DEFAULT_PAGE_SIZE,r=1;for(;;){let i=await N.post(Ve.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:r,pageSize:t,tagIds:[n]}}),o=Zo(i,"Skills API");if(e.push(...o.data.list),o.data.list.length<t)break;r++}return e}async function Nc(n){let e=new Map,t=n.map(i=>rE(i)),r=await Promise.all(t);for(let i of r)for(let o of i)e.has(o.id)||e.set(o.id,o);return Array.from(e.values()).filter(i=>i.tags?.every(o=>!Jp.includes(o.name)))}async function iE(n,e){let t=await N.post(Ve.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:Ve.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return Zo(t,"Skills API").data.list}async function Lc(n,e){let t=new Map,r=e.map(o=>iE(n,o)),i=await Promise.all(r);for(let o of i)for(let s of o)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(o=>o.tags?.every(s=>!Jp.includes(s.name)))}function Kp(n){let e=[];for(let[,t]of Object.entries(qe)){let r=Yp.join(nE(),t.path,n);qp.existsSync(r)&&e.push(t.displayName)}return e.sort()}function Zo(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=N.parseJson(n);if(t.code!==Ve.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Xp(n){let e=`${Ve.SKILL_API_BASE}/${n}/checksum`,t=await N.get(e);return Zo(t,"Checksum API").data}import oE from"adm-zip";import sE from"crypto";import Qp from"fs";import V from"path";import{fileURLToPath as aE}from"url";import{homedir as ef}from"os";import{red as cE}from"colorette";var vt=Qp.promises;function Oc(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function Zp(n,e){let t=V.resolve(e),r=V.resolve(n),i=V.relative(r,t);if(i.startsWith("..")||V.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function Mc(n){return V.isAbsolute(n)?n:V.resolve(process.cwd(),n)}function lE(n){return sE.createHash("sha256").update(n).digest("hex")}async function dE(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=lE(n),i=e.sha256.toLowerCase();if(r!==i)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function tf(n){let e=`${Ve.SKILL_API_BASE}/${n}/install?format=zip`,t=await N.getBinary(e),r=await Xp(n);return await dE(t,r),t}async function uE(n,e,t){Oc(t);let r=new oE(n),i=r.getEntries();try{await vt.stat(e)}catch{await vt.mkdir(e,{recursive:!0})}let o=V.join(e,t);Zp(e,o);for(let s of i){let a=V.join(o,s.entryName);Zp(o,a)}r.extractAllTo(o,!0)}async function _c(n){let e=qe[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(qe).join(", ")}`);let t=V.join(ef(),e.path.replace("/skills",""));try{return await vt.access(t),!0}catch{return!1}}function Fc(n){let e=qe[n];return V.join(ef(),e.path)}function pE(n){let e=qe[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(qe).join(", ")}`);return e}function jc(n,e){let t=pE(e),r="projectPath"in t?t.projectPath:V.join("."+e,"skills");return V.join(n,r)}async function fE(n,e,t){Oc(e);let r=V.join(n,e);try{if(await vt.access(r),t)await vt.rm(r,{recursive:!0,force:!0});else return console.log(`Skill ${e} exists in ${n}.`),{skillDir:r,shouldSkip:!0}}catch{}return{skillDir:r,shouldSkip:!1}}async function Hc(n,e,t){await uE(n,e,t),console.log(`Skill ${t} installed to ${V.join(e,t)}.`)}async function $c(n,e,t){let r=V.join(e,t);await vt.mkdir(r,{recursive:!0});let i=V.join(r,V.basename(n));await vt.copyFile(n,i),console.log(`Skill ${t} installed to ${r}.`)}function nf(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(cE(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function Yn(n,e,t,r){try{let i=await e(),{shouldSkip:o}=await fE(i,n,r);return o?{success:!0,skipped:!0}:(await t(i),{success:!0})}catch(i){return nf(n,i,"Installation failed")}}async function Uc(n,e){try{Oc(n);let t=await e(),r=V.join(t,n);try{await vt.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await vt.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return nf(n,t,"Removal failed")}}async function rf(n,e,t,r=!1){return Yn(n,()=>Fc(e),i=>Hc(t,i,n),r)}async function of(n,e,t,r=!1){return Yn(n,()=>t,i=>Hc(e,i,n),r)}async function sf(n,e,t,r,i=!1){return Yn(n,()=>jc(t,r),o=>Hc(e,o,n),i)}async function af(n,e,t,r=!1){return Yn(n,()=>Fc(t),i=>$c(e,i,n),r)}async function cf(n,e,t,r,i=!1){return Yn(n,()=>jc(t,r),o=>$c(e,o,n),i)}async function lf(n,e,t,r=!1){return Yn(n,()=>t,i=>$c(e,i,n),r)}async function df(n,e){return Uc(n,()=>Fc(e))}async function uf(n,e){return Uc(n,()=>e)}async function pf(n,e,t){return Uc(n,()=>jc(e,t))}function ff(){let e=V.dirname(aE(import.meta.url));for(;;){let t=V.join(e,"SKILL.md");if(Qp.existsSync(t))return t;let r=V.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import mf from"fs";import{cyan as mE}from"colorette";async function ri(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await _c(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function ii(){let n=[];for(let e of Object.keys(qe))await _c(e)&&n.push(e);return n}function oi(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(mE("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function jt(n,e,t){if(!mf.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!mf.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function si(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?Mc(n):void 0,resolvedProject:e?Mc(e):void 0}}async function Qo(n,e,t){let r=[],i=[],o;if(e?o=e:t&&n.agent?i=(await ri(n.agent)).map(a=>({project:t,agent:a})):t?i=(await ii()).map(a=>({project:t,agent:a})):n.agent?r=await ri(n.agent):r=await ii(),!o&&r.length===0&&i.length===0)throw new Error("No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location.");return{agents:r,projectAgents:i,customPath:o}}async function wE(n){let e=await Xo();if(n.all)return(await Nc(e)).map(r=>r.enName);{let r=(await Lc(n.skill,e)).find(i=>i.enName===n.skill);if(!r)throw new Error(`Skill "${n.skill}" not found`);return[r.enName]}}async function vE(n,e,t,r){let i=[];if(t.customPath){let o=await of(n,e,t.customPath,r);return i.push(o),i}for(let o of t.agents){let s=await rf(n,o,e,r);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await sf(n,e,o,s,r);i.push(a)}return i}function SE(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}=si(n.path,n.project,n.agent);return t&&jt(t,"Project directory",n.force),e&&jt(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}async function bE(n,e,t){let r=await Qo(n,e,t);return{skillNames:await wE(n),targets:r}}async function EE(n,e,t,r){let i=[],o=n.length,s=yE(5),a=n.map(c=>s(()=>PE(c)));for(let c=0;c<n.length;c++){let l=n[c],d=o>1?` (${c+1}/${o})`:"";r.start(`Installing ${l}${d}...`);let h=await a[c];if(!h.success){r.fail(),console.log(ai(`${l}: Download failed - ${h.error}`)),i.push({success:!1});continue}r.stop();let w=await vE(l,h.buffer,e,t);i.push(...w)}return i}async function PE(n){try{let e=await tf(n);return{name:n,buffer:e,success:!0}}catch(e){let t=e instanceof Error?e.message:"unknown error";return{name:n,error:t,success:!1}}}async function CE(n){let e=new Qe;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=SE(n),{skillNames:i,targets:o}=await bE(n,t,r),s=await EE(i,o,n.force||!1,e);e.stop(),oi(s)}catch(t){throw e.stop(),t}}function IE(n){let{resolvedPath:e,resolvedProject:t}=si(n.path,n.project,n.agent);return t&&jt(t,"Project directory"),e&&jt(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function AE(n,e){let t=new Qe;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:i}=IE(e);t.stop();let o=await DE(e,n,r,i);t.stop(),oi(o)}catch(r){throw t.stop(),r}}function hf(n,e=""){if(n.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function es(n,e){let t=[];for(let r of e){let i=r.type==="agent"?await df(n,r.agent):await pf(n,r.project,r.agent);t.push(i)}return t}async function DE(n,e,t,r){if(t)return[await uf(e,t)];if(r&&n.agent){let a=(await ri(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return es(e,a)}if(r){let s=await ii();hf(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return es(e,a)}if(n.agent){let a=(await ri(n.agent)).map(c=>({type:"agent",agent:c}));return es(e,a)}let i=await ii();hf(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return es(e,o)}var ci=new hE("skills").description("Manage HarmonyOS skills");ci.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 Qe;try{e.start("Fetching skills...");let t=await Xo(),r=await Nc(t);if(r.length===0){e.stop(),console.log(yf("No skills available."));return}e.succeed(`Fetched ${r.length} skills`);for(let i of r)if(n.long){console.log(gf(i.enName)),console.log(wf(i.description));let o=Kp(i.enName);o.length>0&&console.log(gE(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName)}catch(t){e.stop(),console.error(ai(t.message)),process.exit(1)}});ci.command("find <keyword>").description("Search skills by keyword").action(async n=>{let e=new Qe;try{e.start("Searching skills...");let t=await Xo(),r=await Lc(n,t);if(r.length===0){console.log(yf(`No skills found matching '${n}'.`)),e.stop();return}e.succeed(`Found ${r.length} skills.`);for(let i of r)console.log(gf(i.enName)),console.log(wf(i.description)),console.log()}catch(t){e.stop(),console.error(ai(t.message)),process.exit(1)}});ci.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 CE(n)}catch(e){console.error(ai(e.message)),process.exit(1)}});ci.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 AE(n.skill,n)}catch(e){console.error(ai(e.message)),process.exit(1)}});var vf=ci;import{Command as TE,InvalidArgumentError as bf}from"commander";import{cyan as ts}from"colorette";function wn(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=Fn(t);return r==="transient"?new Error(`${e}: Device communication channel unavailable. Retry in a few seconds.`):r==="fatal"?new Error(`${e}: ${t.trim()}`):null}var Bc=[800,1500,2500];function RE(n){return new Promise(e=>setTimeout(e,n))}var Jn=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=Q.from(e)}createFollowLineHandler(){return(e,t)=>{if(t==="stderr"){for(let r of e)console.error(r);return}for(let r of e)console.log(r)}}findDeviceByArg(e,t){return e.find(r=>r.serial===t||r.name===t)}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
|
|
1256
|
+
`)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let i=t[0];return m(ts(`Using device serial: ${i}`)),i}if(e&&t.includes(e))return m(ts(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let i=this.findDeviceByArg(r,e);if(i)return m(ts(`Using device: ${i.name} (${i.serial})`)),i.serial;let o=this.formatConnectedDeviceList(r);throw new Error(`Device '${e}' not found.
|
|
1254
1257
|
Available devices:
|
|
1255
|
-
${o}`)}if(r.length===1){let i=r[0];return
|
|
1256
|
-
${o.stdout}`),o.stdout.split(`
|
|
1257
|
-
`).map(c=>c.trim()).filter(c=>c.length>0).filter(c=>{try{return b.assertCrashFilename(c),!0}catch{return!1}}).filter(c=>r?c.toLowerCase().includes(r.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){g(`Fetching latest crash log file: ${r}`);let i=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];g(`Executing command: ${e} ${i.join(" ")}`);let o=await Fe(e,i),s=st(o,"Failed to fetch crash log content");if(s)throw s;return o.exitCode!==0&&o.stderr&&console.error(`Warning: Failed to fetch crash logs: ${o.stderr}`),o.stdout+o.stderr}};import{cyan as yo,red as gc}from"colorette";import nf from"ora";function rf(n){try{return b.parsePositiveInteger(n,"tail")}catch{throw new fc("`tail` must be a positive integer.")}}function hc(n,e){try{return b.parseDurationToSeconds(n,e)}catch{throw new fc(`${e} must be a valid duration string (e.g.,30s, 5m or 2.5m).Supported units: s and m.when specified in seconds(with \`s\` or as a raw number), the value must be an integer.`)}}function of(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.");b.assertRelativeTimeRange(n.from,n.to)}async function sf(n,e,t,r,i){return t.crash?await n.getCrashLog(e,t.bundleName):await n.getHilog(e,{level:t.level,bundleName:t.bundleName,keyword:t.keyword,isFollow:!!t.follow,tail:t.tail,fromSeconds:r,toSeconds:i})}function af(n,e,t,r){let i=b.filterLogsByRelativeWindow(n,t,r);return e.tail?b.getLastLines(i,e.tail):i}var cf=new tf("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(gc(n))}).option("--device <device>","Target device (name or serial)").option("--crash","Only obtain crash logs").option("--level <level>","Log level filter: D, I, W, E, F").option("--bundle-name <bundle-name>","Filter by application bundle name").option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",rf).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>hc(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>hc(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await lf(n)});async function lf(n){let e=nf({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),of(n);let r=n.from,i=n.to,o=await N.new(),s=new lr(o),a=await s.selectDevice(n.device);a||(t(),process.exit(1)),g(yo(`deviceId: ${a}`)),g(yo(`type: ${n.crash?"Crash logs":"Common logs"}`)),g(yo("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await sf(s,a,n,r,i);t(),n.crash&&c&&(c=af(c,n,r,i)),c&&console.log(c)}catch(r){t(),console.error(gc(r.message)),process.exit(1)}}var yc=cf;import hn from"path";import ke from"fs";import wo from"process";import Dc from"os";import{Command as Ef}from"commander";import{green as Sc,red as vo,cyan as Pf,yellow as Ec}from"colorette";import $ from"fs-extra";import k from"path";import*as vc from"os";import{fileURLToPath as df}from"url";var uf={17:{sdkVersion:"5.0.5(17)",modelVersion:"5.0.5"},18:{sdkVersion:"5.1.0(18)",modelVersion:"5.1.0"},19:{sdkVersion:"5.1.1(19)",modelVersion:"5.1.1"},20:{sdkVersion:"6.0.0(20)",modelVersion:"6.0.0"},21:{sdkVersion:"6.0.1(21)",modelVersion:"6.0.1"},22:{sdkVersion:"6.0.2(22)",modelVersion:"6.0.2"},23:{sdkVersion:"6.1.0(23)",modelVersion:"6.1.0"},24:{sdkVersion:"6.1.1(24)",modelVersion:"6.1.1"}},pf=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function mf(){let n=import.meta.url,e=df(n);if(e.includes("dist")){let o=k.dirname(e),s=k.dirname(o);return k.join(s,"templates","application")}let t=k.dirname(e),r=k.dirname(t),i=k.dirname(r);return k.join(i,"templates","application")}function wc(n,e){$.mkdirSync(e,{recursive:!0});for(let t of $.readdirSync(n,{withFileTypes:!0})){let r=k.join(n,t.name),i=k.join(e,t.name);if(t.isDirectory()){wc(r,i);continue}$.existsSync(i)||($.mkdirSync(k.dirname(i),{recursive:!0}),$.copyFileSync(r,i))}}function mn(n,e){let t=$.readFileSync(n,"utf-8"),r=t;for(let[i,o]of e)r=r.replaceAll(i,o);r!==t&&$.writeFileSync(n,r,"utf-8")}function hf(n,e){if(e===22)return;let t=uf[e];t&&(mn(k.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),mn(k.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),mn(k.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function ff(n){return pf.filter(t=>!$.existsSync(k.join(n,t))).length===0}function gf(){return Buffer.from([137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,1,0,0,0,1,8,2,0,0,0,144,119,83,222,0,0,0,12,73,68,65,84,8,215,99,248,255,255,255,0,5,254,2,254,0,0,0,0,73,69,78,68,174,66,96,130])}function yf(n){return vc.platform()==="darwin"?k.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):k.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function vf(n,e){let t=yf(e);if(!$.existsSync(t))return!1;let r=[["AppScope/resources/base/media/background.png","AppScope/resources/base/media/background.png"],["AppScope/resources/base/media/foreground.png","AppScope/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/background.png"],["entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/startIcon.png","entry/src/main/resources/base/media/startIcon.png"]];for(let[i,o]of r){let s=k.join(t,i),a=k.join(n,o);$.existsSync(s)&&($.mkdirSync(k.dirname(a),{recursive:!0}),$.copyFileSync(s,a))}return!0}function wf(n){let e=gf(),t=["AppScope/resources/base/media/background.png","AppScope/resources/base/media/foreground.png","entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/startIcon.png"];for(let r of t){let i=k.join(n,r);$.mkdirSync(k.dirname(i),{recursive:!0}),$.writeFileSync(i,e)}}function bf(n,e){e&&vf(n,e)||wf(n)}function Sf(n){let e=[k.join(n,"gitignore.txt"),k.join(n,"entry","gitignore.txt")];for(let t of e)if($.existsSync(t)){let r=k.dirname(t);$.renameSync(t,k.join(r,".gitignore"))}}function bc(n,e,t,r,i){let o=mf();if(!$.existsSync(o))throw new Error(`Template directory not found: ${o}`);$.mkdirSync(n,{recursive:!0}),wc(o,n),Sf(n),bf(n,i),mn(k.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),mn(k.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),hf(n,r);let s=ff(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function Cf(n){if(n.length<1||n.length>200)throw new Error(`App name length must be 1-200 characters. Current: ${n.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(n))throw new Error("Application name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function Df(n){if(n.length<7||n.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${n.length}`);if(n.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let e=n.split(".");if(e.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let t=/^[a-zA-Z0-9_]+$/;for(let r=0;r<e.length;r++){let i=e[r];if(!t.test(i))throw new Error(`Segment "${i}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(r===0){if(!/^[a-zA-Z]/.test(i))throw new Error(`First segment "${i}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(i))throw new Error(`Segment "${i}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(i))throw new Error(`Segment "${i}" must end with a letter or digit.`)}}function Ic(n){if(Dc.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function Pc(n){if(n.length===0)throw new Error("Project path cannot be empty.");if(n.length>120)throw new Error(`Project path cannot exceed 120 characters (current: ${n.length}).`);let e=Dc.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(n)){let o=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new Error(`Project path can only contain ${o}.`)}let r=Ic(n);if(/[\u4e00-\u9fff]/.test(r))throw new Error("Project path cannot contain Chinese characters.");if(r.endsWith("."))throw new Error("Project path cannot end with a dot (.)")}function If(n){let e=n,t=hn.parse(n).root;for(;e!==t;){if(ke.existsSync(e))return e;e=hn.dirname(e)}return ke.existsSync(t)?t:null}function Cc(n){let e=If(n);if(!e)throw new Error(`No existing parent directory found for '${n}'. Cannot create project directory.`);try{ke.accessSync(e,ke.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=hn.join(e,`.deveco_write_test_${Date.now()}`);try{ke.writeFileSync(t,"test"),ke.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function Af(n){return`com.example.${n.toLowerCase()}`}function xf(n,e){if(e){let i=Ic(e),o=hn.resolve(i);if(ke.existsSync(o)){if(ke.readdirSync(o).length>0)throw new Error(`Directory '${o}' is not empty. Cannot create project here.`)}else Cc(o);return o}let t=wo.cwd(),r=hn.join(t,n);if(ke.existsSync(r))throw new Error(`Directory '${r}' already exists. Cannot create project here.`);return Cc(r),r}function Tf(n,e){let t=e?.getMaxApiLevel(),r=23;if(n.apiLevel){let i=Number(n.apiLevel);if(!Number.isInteger(i)||i<17)throw new Error(`Invalid API version ${n.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(i>t)throw new Error(`Invalid API version ${n.apiLevel}. Your SDK supports API version 17-${t}`)}else if(i>r)throw new Error(`Invalid API version ${n.apiLevel}. Without DevEco Studio, supported range is API version 17-${r}`);return i}return t!==void 0?t:23}async function kf(){try{return await N.new()}catch(n){console.error(Ec(`DevEco Studio not found: ${n.message}`)),console.log(Ec("Use placeholder API level instead."));return}}var Rf=new Ef("create").description("Scaffold a new HarmonyOS application project").option("--project-path <path>","Project directory path (default: ./<app-name>)").option("--app-name <name>","Application name").option("--bundle-name <bundle>","Bundle name (auto-derived as com.example.<app-name> if omitted)").option("--api-level <level>","API level (auto-detected from SDK if omitted; minimum: 17)").action(async n=>{try{n.appName||(console.error(vo("Error: --app-name is required")),wo.exit(1));let e=n.appName;Cf(e);let t=n.bundleName||Af(e);Df(t),n.projectPath&&Pc(n.projectPath);let r=xf(e,n.projectPath);Pc(r),console.log(Pf("Initializing project...")),console.log(`Project path: ${r}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let i=await kf(),o=Tf(n,i);console.log(`API level: ${o}`);let s=i?.devecoStudioPath,a=bc(r,e,t,o,s);console.log(`
|
|
1258
|
-
`+
|
|
1259
|
-
Failed to create project.`)),console.error(vo(t.message)),wo.exit(1)}}),Ac=Rf;import{Command as Ff}from"commander";import{red as jf,cyan as Lc}from"colorette";import Mf from"fs";import dr from"path";import{cyan as Of}from"colorette";import*as ur from"smol-toml";var Dt=Mf.promises;async function Lf(n){try{let e=await Dt.readFile(n,"utf8");return e.trim()===""?{}:JSON.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read configuration file ${n}: ${e.message}`,{cause:e})}}async function Nf(n){try{let e=await Dt.readFile(n,"utf8");return e.trim()===""?{}:ur.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read TOML config file ${n}: ${e.message}`,{cause:e})}}async function _f(n,e){let t=dr.dirname(n);await Dt.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await Dt.writeFile(n,r,"utf8")}async function Hf(n,e){let t=dr.dirname(n);await Dt.mkdir(t,{recursive:!0});let r=ur.stringify(e);await Dt.writeFile(n,r,"utf8")}function xc(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function Tc(n,e,t,r,i){(!n[e]||typeof n[e]!="object")&&(n[e]={});let o=n[e];return t in o&&!i?!1:(o[t]=r,!0)}async function kc(n,e){return n.format==="codex"?Nf(e):Lf(e)}async function Rc(n,e,t){return n.format==="codex"?Hf(e,t):_f(e,t)}async function Mc(n,e,t=!1){let r=_e[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(_e).join(", ")}`};if(!r.supportsGlobal)return{success:!1,error:`${r.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let i=await kc(r,r.globalConfigPath);if(xc(i,r.mcpServersKey,Ce)&&!t)return console.log(`MCP server ${Ce} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let o=Gn(r,void 0);return Tc(i,r.mcpServersKey,Ce,o,t),await Rc(r,r.globalConfigPath,i),console.log(`MCP server ${Ce} configured in ${r.globalConfigPath}.`),{success:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${i.message}`}}}async function bo(n,e,t=!1){let r=_e[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(_e).join(", ")}`};let i=dr.isAbsolute(r.projectConfigPath)?r.projectConfigPath:dr.join(e,r.projectConfigPath);try{let o=await kc(r,i);if(xc(o,r.mcpServersKey,Ce)&&!t)return console.log(`MCP server ${Ce} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:n,installType:"project"};let s=Gn(r,e);return Tc(o,r.mcpServersKey,Ce,s,t),await Rc(r,i,o),console.log(`MCP server ${Ce} configured in ${i}.`),{success:!0,configPath:i,agentName:n,installType:"project"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${o.message}`}}}function Oc(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(Of("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`);for(let i of n)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);r>0&&(process.exitCode=1)}var So="deveco-cli";async function $f(n,e,t){if(n.customPath)return[await rc(So,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>nc(So,e,s,a,t.force)),...n.agents.map(s=>()=>tc(So,e,s,t.force))],i=5,o=[];for(let s=0;s<r.length;s+=i){let a=r.slice(s,s+i);o.push(...await Promise.all(a.map(c=>c())))}return o}async function Bf(n,e,t){let r=[];for(let{project:i,agent:o}of n.projectAgents){let s=await bo(o,i,t);r.push(s)}for(let i of n.agents){let o=await bo(i,e,t);r.push(o)}return r}async function Wf(n,e){let t=[];for(let r of n){if(!_e[r])continue;let o=await Mc(r,process.cwd(),e);t.push(o)}return t}async function Uf(n,e,t){if(t.agent&&t.agent.split(",").map(l=>l.trim()).includes("qoder"))throw new Error("Qoder does not support MCP configuration via DevEco CLI. Use other supported agents instead.");let r=t.force??!1,i=n.projectAgents.filter(c=>c.agent!=="qoder"),o=n.agents.filter(c=>c!=="qoder"),s={...n,projectAgents:i,agents:o},a=e?await Bf(s,e,r):await Wf(s.agents,r);a.length>0&&(console.log(Lc("MCP Configuration:")),Oc(a))}async function zf(n){if(n.skill&&n.mcp)throw new Error("Cannot use `--skill` and `--mcp` together. Use `--skill` for skill installation only, or `--mcp` for MCP configuration only.");let{resolvedPath:e,resolvedProject:t}=dn(n.path,n.project,n.agent);t&&Be(t,"Project directory",n.force),e&&Be(e,"Directory",n.force);let r=await sr(n,e,t);if(n.mcp){await Uf(r,t,n);return}let i=ac(),o=await $f(r,i,n);console.log(),o.length>0&&(console.log(Lc("Skill Installation:")),ln(o))}var qf=new Ff("init").description("Install the deveco-cli skill or configure the deveco-mcp server into AI agents").option("--agent <agents>","Target agents, comma-separated; installs to all available agents if omitted").option("--project <path>","Project root directory for skill or MCP configuration").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").option("--skill","Install the deveco-cli skill only (same as default behavior; explicit for symmetry with --mcp)").option("--mcp","Configure the deveco-mcp server (syntax checking for .ets and C/C++) only; no skill installation").option("-f, --force","Overwrite existing skill/MCP configuration").action(async n=>{try{await zf(n)}catch(e){console.error(jf(e.message)),process.exit(1)}}),Nc=qf;import{Command as wy}from"commander";import{McpServer as cy}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as ly}from"@modelcontextprotocol/sdk/server/stdio.js";import*as ut from"path";import*as Cl from"fs";import{z as J}from"zod";var pr=class{tools=new Map;add(e,t){return this.tools.set(e.name,{definition:e,handler:t}),this}getAll(){return Array.from(this.tools.values())}registerToServer(e){for(let{definition:t,handler:r}of this.getAll())e.registerTool(t.name,{description:t.description,inputSchema:t.inputSchema},(async i=>r(i)))}};function Eo(){return new pr}import*as re from"fs";import*as Y from"path";import{z as Lo}from"zod";import x from"fs";import*as mr from"os";import*as E from"path";import Gf from"json5";var Po="Huawei";var Vf=3,jc=3,_c="DevEco Studio",$c={DevEcoStudio:"deveco_studio"};function Co(n){if(!x.existsSync(n)||!x.statSync(n).isDirectory())return!1;let e=x.existsSync(E.join(n,"build-profile.json5")),t=x.existsSync(E.join(n,"hvigorfile.js"))||x.existsSync(E.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=x.readFileSync(E.join(n,"build-profile.json5"),"utf-8");return Gf.parse(r).app!==void 0}catch{return!1}}function Bc(n,e,t){if(e>=t)return null;let r=Yf(n),i=Jf(r);if(i)return i;for(let o of r){let s=Bc(o,e+1,t);if(s)return s}return null}function Yf(n){try{let e=x.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(E.join(n,r.name));return t}catch{return[]}}function Jf(n){for(let e of n)if(Co(e))return e;return null}function Re(n){if(!n||n.trim()==="")return null;let e=E.resolve(n),t;try{t=x.realpathSync(e)}catch{t=e}if(!x.existsSync(t))return null;if(Co(t))return t;let r=t;for(let i=1;i<=3;i++){let o=E.dirname(r);if(o===r)break;if(Co(o))return o;r=o}if(x.statSync(t).isDirectory()){let i=Bc(t,0,Vf);if(i)return i}return null}function It(n){if(process.platform==="linux")return null;let e=n??be();if(!e)return null;let t;if(process.platform==="win32")t=E.join(e,"plugins","openharmony");else if(process.platform==="darwin")t=E.join(e,"contents","plugins","openharmony");else return null;let r=E.join(t,"ace-server","out","index.js");return x.existsSync(r)?t:null}var Kf=["sdk","default","openharmony","native","llvm","bin","clangd"],Do=[".idea",".deveco","cxx","compile_commands.json"];function Zf(n){return process.platform==="darwin"&&n.endsWith(".app")?E.join(n,"Contents"):n}function Hc(n){let e=new Set,t=[n,Zf(n)];for(let r of t){let i=E.join(r,...Kf);e.add(process.platform==="win32"?i+".exe":i)}return[...e]}function Wc(n){let e=[],t=process.env.DEVECO_HOME??process.env.DEVECO_PATH;if(t&&t.trim()){for(let i of Hc(t.trim()))if(e.push(i),x.existsSync(i))return i}let r=n??be();if(r){for(let i of Hc(r))if(e.push(i),x.existsSync(i))return i}return null}function hr(n){return E.join(n,...Do)}function be(){if(process.platform==="win32"){let n=[E.join("C:\\Program Files",Po,_c),E.join("C:\\Program Files (x86)",Po,_c)];return Fc(n)}if(process.platform==="darwin"){let n=["/Applications/DevEco Studio.app",E.join(process.env.HOME??"","Applications","DevEco Studio.app")];return Fc(n)}return null}function Fc(n){for(let e of n)if(x.existsSync(e))return e;return null}function de(n){return process.platform==="darwin"?E.join(n,"Contents"):n}function Xf(n){if(!n||!x.existsSync(n)||!Uc(n))return!1;let e=de(n);return[E.join(e,"plugins","openharmony"),E.join(e,"sdk"),E.join(e,"tools")].some(r=>x.existsSync(r))}function Uc(n){try{return x.statSync(n).isDirectory()}catch{return!1}}function Io(n,e){return!n||!x.existsSync(n)?!1:e===$c.DevEcoStudio?Xf(n):!1}function fr(n,e=$c.DevEcoStudio){if(!n)return"";if(Io(n,e))return n;let t=Qf(n,e);if(t)return t;let r=eg(n,e);return r||n}function Qf(n,e){let t=n;for(let r=0;r<jc;r++){let i=E.dirname(t);if(!i||i===t)break;if(Io(i,e))return i;t=i}return null}function eg(n,e){if(!x.existsSync(n)||!Uc(n))return null;let t=[{p:n,depth:0}];for(;t.length>0;){let{p:r,depth:i}=t.shift();if(i>=jc)continue;let o=tg(r,i,e,t);if(o)return o}return null}function tg(n,e,t,r){let i;try{i=x.readdirSync(n,{withFileTypes:!0})}catch{return null}for(let o of i){if(!o.isDirectory())continue;let s=E.join(n,o.name);if(Io(s,t))return s;r.push({p:s,depth:e+1})}return null}function zc(n){return new Promise(e=>setTimeout(e,n))}var ng=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function gr(n){let e=E.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&ng.has(e)}function qc(n){return E.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function ue(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function rg(n){return ue(n)}function at(n){let e=rg(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function At(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??E.join(mr.homedir(),"AppData","Local");return E.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?E.join(mr.homedir(),"Library","Logs","devecocli-mcp-server"):E.join(mr.homedir(),".local","share","devecocli-mcp-server","logs")}function Gc(n,e){let t=ig(e),r=og(t,n);if(r!==null)return r;let i=Date.now(),s=`${n.replace(/:/g,"\\:")}=${i}`,a=sg(t,n,s);return ag(e,a),i}function ig(n){let e;try{e=x.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function og(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let o=parseInt(t.slice(r+1),10);return Number.isFinite(o)&&o>0?o:null}return null}function sg(n,e,t){let r=!1,i=n.map(o=>{if(r)return o;let s=o.indexOf("=");return s<=0?o:o.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):o});return r||i.push(t),i}function ag(n,e){try{x.mkdirSync(E.dirname(n),{recursive:!0})}catch{}try{x.writeFileSync(n,e.join(`
|
|
1260
|
-
`)+`
|
|
1261
|
-
`,"utf8")}catch{}}function Ao(n,e,t="[Cleanup]"){try{let r=E.dirname(n);if(!x.existsSync(r))return;let i=Date.now();for(let o of x.readdirSync(r,{withFileTypes:!0}))o.isDirectory()&&cg(E.join(r,o.name),i,e,t)}catch{}}function cg(n,e,t,r){try{let{mtimeMs:i}=x.statSync(n);if(e-i<=t)return;x.rmSync(n,{recursive:!0,force:!0});let o=Math.floor((e-i)/1e3);console.error(`${r} Removed expired dir (age ${Math.floor(o/86400)}d ${Math.floor(o%86400/3600)}h): ${n}`)}catch(i){console.error(`${r} Failed to remove expired dir ${n}: ${i}`)}}function yr(n){let e=n.replace(/sdk\/?$/i,"tools"),t=process.platform==="win32"?"node.exe":"node",r=E.join(e,"node",t);return x.existsSync(r)||process.platform!=="win32"&&(r=E.join(e,"node","bin","node"),x.existsSync(r))?r:process.execPath??"node"}import*as R from"fs";import*as wr from"path";var Vc="mcp-server.log",lg="mcp-server",dg={maxSize:10*1024*1024,maxFiles:4},xo=class n{fd=null;logDir=null;currentLogFile=null;mode;rotationOptions;currentFileSize=0;currentDate="";isRotating=!1;minLevel;static LEVEL_ORDER={debug:0,info:1,warn:2,error:3};constructor(e,t){this.rotationOptions={...dg,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=At(),this.currentLogFile=wr.join(this.logDir,Vc),R.existsSync(this.logDir)||R.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${i}`}getRotatedFileName(e,t){return wr.join(this.logDir,`${lg}-${e}.log.${t}`)}fileExists(e){try{return R.accessSync(e,R.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=R.readdirSync(this.logDir),t=[];for(let i of e)if(i===Vc||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=wr.join(this.logDir,i),s=R.statSync(o);t.push({name:i,mtime:s.mtime,path:o})}t.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let i=r;i<t.length;i++)try{R.unlinkSync(t[i].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&R.unlinkSync(t);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(e,i),s=this.getRotatedFileName(e,i+1);this.fileExists(o)&&R.renameSync(o,s)}let r=this.getRotatedFileName(e,1);R.renameSync(this.currentLogFile,r),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let e=R.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=R.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{R.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...r){if(this.mode==="silent"||n.LEVEL_ORDER[e]<n.LEVEL_ORDER[this.minLevel])return;let i=r.map(c=>typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),o=i?`${t} ${i}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] ${o}
|
|
1262
|
-
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);R.writeSync(this.fd,c),this.checkRotation(c.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{R.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},pe=null;function fn(n=!1){pe&&pe.dispose(),pe=new xo(n)}function Yc(){pe&&(pe.dispose(),pe=null)}function Jc(){pe&&pe.flush()}function Kc(){return pe?.getLogFilePath()??null}function Zc(){return pe?.getLogDirectory()??null}function vr(){return pe||fn(!1),pe}var h={debug:(n,...e)=>vr().debug(n,...e),info:(n,...e)=>vr().info(n,...e),warn:(n,...e)=>vr().warn(n,...e),error:(n,...e)=>vr().error(n,...e)};function Xc(n){return"method"in n&&!("id"in n)}import{spawn as pg}from"child_process";import{EventEmitter as mg}from"events";import*as Tt from"fs";import*as sl from"path";import*as Qc from"util";var To="";function el(n){if(!n||n==="auto"||n==="stdout"||n==="none"){To="";return}To=n}function tl(){return To||(Zc()??"")}function br(n,...e){if(e.length===0)return n;try{return Qc.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var d={info(n,...e){h.info(`[lsp] ${br(n,...e)}`)},warn(n,...e){h.warn(`[lsp] ${br(n,...e)}`)},error(n,...e){h.error(`[lsp] ${br(n,...e)}`)},debug(n,...e){h.debug(`[lsp] ${br(n,...e)}`)}};import*as gn from"fs";import*as yn from"os";import*as xt from"path";import ug from"json5";var y={INITIALIZE:"initialize",INITIALIZED:"initialized",SHUTDOWN:"shutdown",EXIT:"exit",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",DID_CLOSE:"textDocument/didClose",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",DECLARATION:"textDocument/declaration",REFERENCES:"textDocument/references",IMPLEMENTATION:"textDocument/implementation",COMPLETION:"textDocument/completion",COMPLETION_ITEM_RESOLVE:"completionItem/resolve",SIGNATURE_HELP:"textDocument/signatureHelp",CODE_ACTION:"textDocument/codeAction",PREPARE_RENAME:"textDocument/prepareRename",RENAME:"textDocument/rename",DOCUMENT_HIGHLIGHT:"textDocument/documentHighlight",DOCUMENT_LINK:"textDocument/documentLink",INLAY_HINT:"textDocument/inlayHint",DOCUMENT_SYMBOL:"textDocument/documentSymbol",WORKSPACE_SYMBOL:"workspace/symbol",DIAGNOSTIC:"textDocument/diagnostic",WORKSPACE_DIAGNOSTIC:"workspace/diagnostic",PREPARE_CALL_HIERARCHY:"textDocument/prepareCallHierarchy",INCOMING_CALLS:"callHierarchy/incomingCalls",OUTGOING_CALLS:"callHierarchy/outgoingCalls",PREPARE_TYPE_HIERARCHY:"textDocument/prepareTypeHierarchy",SUPERTYPES:"typeHierarchy/supertypes",SUBTYPES:"typeHierarchy/subtypes",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",DID_CREATE_FILES:"workspace/didCreateFiles",DID_DELETE_FILES:"workspace/didDeleteFiles",PROGRESS:"$/progress",WINDOW_SHOW_MESSAGE:"window/showMessage",WINDOW_LOG_MESSAGE:"window/logMessage",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing",ARKTS_ERROR:"arkts/error",BROADCAST:"lsp/broadcast"},A="2.0";var nl=8192,ko=100,rl=.03,il=.7,We=900*1e3;function ae(n){if(!gn.existsSync(n))return null;try{let e=gn.readFileSync(n,"utf-8");return e.trim()?ug.parse(e):null}catch{return null}}function Sr(n,e){let t=Math.floor(yn.totalmem()/1048576),r=Math.floor(t*il),i,o;e!==void 0&&Number.isFinite(e)&&e>0?(i=e,o=`override(${e})`):(i=nl,n>ko&&(i+=(n-ko)*rl*1024),o=`formula(moduleCount=${n})`);let s=r>0&&i>r;s&&(i=r);let a=Math.round(i);return d.info(`[computeLspServerMaxSize] source=${o}, physicalTotal=${t}MB, physicalCap(70%)=${r}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function Ue(n){if(n.startsWith("file:"))return n;try{let e=xt.resolve(n),t=new URL(`file://${e}`).toString();if(yn.platform()==="win32"){let r=t.match(/^file:\/\/\/([A-Za-z]):/);if(r){let i=r[1].toUpperCase(),o=t.substring(`file:///${r[1]}:`.length);t=`file:///${i}%3A${o}`}}return t}catch{return n}}function Er(n){return n&&n.replace(/\\/g,"/")}function j(n){let e=xt.normalize(n).replace(/\\/g,"/");if(yn.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function ol(n){return xt.join(n,"build-profile.json5")}var kt=class extends mg{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;ensureDirectories(){let t=sl.join(this.config.logPath,"lspLog");return Tt.existsSync(t)||Tt.mkdirSync(t,{recursive:!0}),Tt.existsSync(this.config.indexingDataLocation)||Tt.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let r=this.ensureDirectories();d.info(`[LspClient] serverMaxSize=${t}MB`);let i=j(r),o=["--expose-gc",`--max-old-space-size=${t}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${i}`,this.config.serverPath,"--stdio",`--logger-path=${i}`,"--logger-level=TRACE"];d.info(`[LspClient] Starting process: node ${o.join(" ")}`);let s=process.execPath??"node";d.info(`[LspClient] nodePath: ${s}`),this.process=pg(s,o,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0}),this.process.stdout?.on("data",a=>{this.handleData(a)}),this.process.stderr?.on("data",a=>{let c=a.toString("utf8").trim();d.error(`[LspClient] stderr: ${c}`),this.isClosing||this.emit("error",new Error(`[LspClient] stderr: ${c}`))}),this.process.on("exit",a=>{d.info(`[LSP EXIT] code=${a}`),this.isClosing||this.emit("error",new Error(`LSP process exited with code ${a}`))}),await new Promise(a=>setTimeout(a,500)),d.info("[LspClient] start lsp process success")}sendRaw(t,r){if(!this.process?.stdin?.writable){d.warn("[LspClient] Cannot send message, stdin not writable");return}d.info(`[LspClient] send message: ${r}`);let i=this.buildLspMessage(t);this.process.stdin.write(i,"utf8")}send(t,r,i){let o={jsonrpc:"2.0",method:t,params:r};i!==void 0&&(o.id=i),this.sendRaw(JSON.stringify(o),t)}sendNotification(t,r){this.sendRaw(JSON.stringify({jsonrpc:"2.0",method:t,params:r}),t)}sendRequest(t,r,i){this.sendRaw(JSON.stringify({jsonrpc:"2.0",id:i,method:t,params:r}),t)}buildLspMessage(t){return`Content-Length: ${Buffer.from(t,"utf8").length}\r
|
|
1258
|
+
${o}`)}if(r.length===1){let i=r[0];return m(ts(`Using device: ${i.name} (${i.serial})`)),i.serial}throw new Error("Multiple devices found. Specify a target device using `--device <name>` or `--device <serial>`.\nAvailable devices:\n"+this.formatConnectedDeviceList(r))}async getConnectedDeviceSerials(){let e=await this.deviceManager.listDevices();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e}async getPidForBundle(e,t,r){m(`Retrieving PID for bundle ${r}`),P.assertBundleName(r);let i=await ke(e,["-t",t,"shell","pidof",r]),o=wn(i,"Failed to look up PID");if(o)throw o;if(i.exitCode===0&&i.stdout.trim()){let s=i.stdout.trim(),a=s.split(/\s+/)[0]||s;return m(`Found PID for ${r}: ${a}`),a}return m(`No PID found for bundle: ${r}`),null}async resizeHilogBuffer(e,t,r){m(`Setting hilog buffer size to: ${r}`);let i=await ke(e,["-t",t,"shell","hilog","-G",r]),o=wn(i,"Failed to resize hilog buffer");if(o)throw o;i.exitCode!==0&&console.error(`Failed to resize hilog buffer: ${i.stderr||i.stdout}`)}buildHilogCommand(e,t,r,i){let o=this.buildHilogShellCommand(r,i);return[e,["-t",t,"shell",o]]}buildHilogShellCommand(e,t){let r=["hilog"];return e.isFollow||r.push("-x"),e.tag&&(P.assertHilogToken(e.tag,"tag"),r.push("-T",e.tag)),e.level&&(P.assertHilogLevel(e.level),r.push("-L",e.level)),e.domain&&(P.assertHilogToken(e.domain,"domain"),r.push("-D",e.domain)),t&&r.push("-P",t),e.keyword&&(P.assertHilogKeyword(e.keyword),r.push("-e",P.quotePosixShellArg(e.keyword))),r.join(" ")}async followHilog(e,t,r,i,o){let a=await Iu(e,t,{onData:r,onError:i,onClose:o});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}async runHilogWithSpawnRetry(e,t,r,i,o){let s=1+Bc.length,a={stdout:"",stderr:"",exitCode:-1};for(let c=0;c<s;c++){if(a=await this.followHilog(e,t,r,i,o),a.exitCode===0||Fn(a.stderr)!=="transient"||c>=s-1)return a;m(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${Bc[c]}ms`),await RE(Bc[c])}return a}async runHilogStreamingCollect(e,t,r){return this.runHilogWithSpawnRetry(e,t,()=>{},i=>{m(`Callback triggered when an error occurs during ${r}: ${i.message}`)},()=>{})}async printTailSnapshotIfNeeded(e,t,r,i){if(!r.tail&&!r.fromSeconds&&!r.toSeconds)return;let o={...r,isFollow:!1},[s,a]=this.buildHilogCommand(e,t,o,i);m(`Ready to run hilog snapshot command: ${s} ${a.join(" ")}`);let c=await this.runHilogStreamingCollect(s,a,"a hilog snapshot streaming read"),l=wn(c,"Failed to get hilog");if(l)throw l;if(c.exitCode!==0&&c.stderr)throw new Error(`Failed to get hilog: ${c.stderr}`);let d=P.filterLogsByRelativeWindow(c.stdout||c.stderr,r.fromSeconds,r.toSeconds);d=P.getLastLines(d,r.tail),d.trim()&&console.log(d)}async getHilogOnce(e,t,r,i){let[o,s]=this.buildHilogCommand(e,t,r,i);m(`Ready to run hilog command: ${o} ${s.join(" ")}`);let a=await this.runHilogStreamingCollect(o,s,"a single hilog streaming read"),c=wn(a,"Failed to get hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to get hilog: ${a.stderr}`);let l=a.stdout||a.stderr,d=P.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return d=P.getLastLines(d,r.tail),d}async runHilogFollow(e,t,r,i){try{await this.printTailSnapshotIfNeeded(e,t,r,i)}catch(l){console.error(`Warning: Failed to fetch log snapshot, continuing with live stream: ${l.message}`)}let[o,s]=this.buildHilogCommand(e,t,r,i);m(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${o} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(o,s,this.createFollowLineHandler(),l=>{m(`Spawn error during hilog follow: ${l.message}`)},()=>{}),c=wn(a,"Failed to follow hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to follow hilog: ${a.stderr}`);return""}async getHilog(e,t){let r=this.toolProvider.hdcPath,i=t.bundleName?await this.getPidForBundle(r,e,t.bundleName):void 0;if(t.bundleName&&!i)throw new Error(`No running process found for bundle '${t.bundleName}'. Ensure the app is launched on the device before fetching logs.`);return t.logSize&&await this.resizeHilogBuffer(r,e,t.logSize),t.isFollow?await this.runHilogFollow(r,e,t,i||""):await this.getHilogOnce(r,e,t,i||"")}async getCrashLog(e,t){m(`Fetching crash logs from device: ${e}`);let r=this.toolProvider.hdcPath,i=await this.listCrashLogs(r,e,t);if(i.length===0)return t?`No crash logs found for bundle '${t}'.`:"No crash logs found.";let s=[...i].sort((c,l)=>{let d=c.split("-").pop()||"";return(l.split("-").pop()||"").localeCompare(d)})[0],a=await this.fetchCrashLogContent(r,e,s);return`--- Latest Crash Log File: ${s} ---${a}`}async listCrashLogs(e,t,r){let i=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];m(`Running command: ${e} ${i.join(" ")}`);let o=await this.runHilogStreamingCollect(e,i,"a crash log list streaming read"),s=wn(o,"Failed to list crash logs");if(s)throw s;if(o.exitCode!==0)throw new Error(`Failed to list crash logs: ${o.stderr||o.stdout}`);return m(`Crash logs list output:
|
|
1259
|
+
${o.stdout}`),this.parseCrashLogFilenames(o.stdout,r)}parseCrashLogFilenames(e,t){return e.split(`
|
|
1260
|
+
`).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return P.assertCrashFilename(r),!0}catch{return!1}}).filter(r=>t?r.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){m(`Fetching latest crash log file: ${r}`);let i=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];m(`Executing command: ${e} ${i.join(" ")}`);let o=await this.runHilogStreamingCollect(e,i,"a crash log streaming read"),s=wn(o,"Failed to fetch crash log content");if(s)throw s;return o.exitCode!==0&&o.stderr&&console.error(`Warning: Failed to fetch crash logs: ${o.stderr}`),o.stdout+o.stderr}};import{cyan as Wc,red as Ef}from"colorette";import kE from"ora";function xE(n){try{return P.parsePositiveInteger(n,"tail")}catch{throw new bf("`tail` must be a positive integer.")}}function Sf(n,e){try{return P.parseDurationToSeconds(n,e)}catch{throw new bf(`${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 NE(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.");P.assertRelativeTimeRange(n.from,n.to)}async function LE(n,e,t,r,i){return t.crash?await n.getCrashLog(e,t.bundleName):await n.getHilog(e,{level:t.level,bundleName:t.bundleName,keyword:t.keyword,isFollow:!!t.follow,tail:t.tail,fromSeconds:r,toSeconds:i})}function OE(n,e,t,r){let i=P.filterLogsByRelativeWindow(n,t,r);return e.tail?P.getLastLines(i,e.tail):i}var ME=new TE("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(Ef(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",xE).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>Sf(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>Sf(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await _E(n)});async function _E(n){let e=kE({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),NE(n);let r=n.from,i=n.to,o=await I.new(),s=new Jn(o),a=await s.selectDevice(n.device);a||(t(),process.exit(1)),m(Wc(`deviceId: ${a}`)),m(Wc(`type: ${n.crash?"Crash logs":"Common logs"}`)),m(Wc("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await LE(s,a,n,r,i);t(),n.crash&&c&&(c=OE(c,n,r,i)),c&&console.log(c)}catch(r){t(),console.error(Ef(r.message)),process.exit(1)}}var Pf=ME;import di from"path";import St from"fs";import zc from"process";import Nf from"os";import{Command as JE}from"commander";import{green as Rf,red as Gc,cyan as KE,yellow as Tf}from"colorette";import re from"fs-extra";import F from"path";import*as If from"os";import{fileURLToPath as FE}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"}},jE=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function HE(){let n=import.meta.url,e=FE(n);if(e.includes("dist")){let o=F.dirname(e),s=F.dirname(o);return F.join(s,"templates","application")}let t=F.dirname(e),r=F.dirname(t),i=F.dirname(r);return F.join(i,"templates","application")}function Af(n,e){re.mkdirSync(e,{recursive:!0});for(let t of re.readdirSync(n,{withFileTypes:!0})){let r=F.join(n,t.name),i=F.join(e,t.name);if(t.isDirectory()){Af(r,i);continue}re.existsSync(i)||(re.mkdirSync(F.dirname(i),{recursive:!0}),re.copyFileSync(r,i))}}function li(n,e){let t=re.readFileSync(n,"utf-8"),r=t;for(let[i,o]of e)r=r.replaceAll(i,o);r!==t&&re.writeFileSync(n,r,"utf-8")}function $E(n){if(Cf[n])return Cf[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function UE(n,e){if(e===22)return;let t=$E(e);t&&(li(F.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),li(F.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),li(F.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function BE(n){return jE.filter(t=>!re.existsSync(F.join(n,t))).length===0}function WE(){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 GE(n){return If.platform()==="darwin"?F.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):F.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function zE(n,e){let t=GE(e);if(!re.existsSync(t))return!1;let r=[["AppScope/resources/base/media/background.png","AppScope/resources/base/media/background.png"],["AppScope/resources/base/media/foreground.png","AppScope/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/background.png"],["entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/startIcon.png","entry/src/main/resources/base/media/startIcon.png"]];for(let[i,o]of r){let s=F.join(t,i),a=F.join(n,o);re.existsSync(s)&&(re.mkdirSync(F.dirname(a),{recursive:!0}),re.copyFileSync(s,a))}return!0}function VE(n){let e=WE(),t=["AppScope/resources/base/media/background.png","AppScope/resources/base/media/foreground.png","entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/startIcon.png"];for(let r of t){let i=F.join(n,r);re.mkdirSync(F.dirname(i),{recursive:!0}),re.writeFileSync(i,e)}}function qE(n,e){e&&zE(n,e)||VE(n)}function YE(n){let e=[F.join(n,"gitignore.txt"),F.join(n,"entry","gitignore.txt")];for(let t of e)if(re.existsSync(t)){let r=F.dirname(t);re.renameSync(t,F.join(r,".gitignore"))}}function Df(n,e,t,r,i){let o=HE();if(!re.existsSync(o))throw new Error(`Template directory not found: ${o}`);re.mkdirSync(n,{recursive:!0}),Af(o,n),YE(n),qE(n,i),li(F.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),li(F.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),UE(n,r);let s=BE(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function XE(n){if(n.length<1||n.length>200)throw new 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 ZE(n){if(n.length<7||n.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${n.length}`);if(n.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let e=n.split(".");if(e.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let t=/^[a-zA-Z0-9_]+$/;for(let r=0;r<e.length;r++){let i=e[r];if(!t.test(i))throw new Error(`Segment "${i}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(r===0){if(!/^[a-zA-Z]/.test(i))throw new Error(`First segment "${i}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(i))throw new Error(`Segment "${i}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(i))throw new Error(`Segment "${i}" must end with a letter or digit.`)}}function Lf(n){if(Nf.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function kf(n){if(n.length===0)throw new Error("Project path cannot be empty.");if(n.length>120)throw new Error(`Project path cannot exceed 120 characters (current: ${n.length}).`);let e=Nf.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(n)){let o=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new Error(`Project path can only contain ${o}.`)}let r=Lf(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 QE(n){let e=n,t=di.parse(n).root;for(;e!==t;){if(St.existsSync(e))return e;e=di.dirname(e)}return St.existsSync(t)?t:null}function xf(n){let e=QE(n);if(!e)throw new Error(`No existing parent directory found for '${n}'. Cannot create project directory.`);try{St.accessSync(e,St.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=di.join(e,`.deveco_write_test_${Date.now()}`);try{St.writeFileSync(t,"test"),St.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function eP(n){return`com.example.${n.toLowerCase()}`}function tP(n,e){if(e){let i=Lf(e),o=di.resolve(i);if(St.existsSync(o)){if(St.readdirSync(o).length>0)throw new Error(`Directory '${o}' is not empty. Cannot create project here.`)}else xf(o);return o}let t=zc.cwd(),r=di.join(t,n);if(St.existsSync(r))throw new Error(`Directory '${r}' already exists. Cannot create project here.`);return xf(r),r}function nP(n,e){let t=e?.getMaxApiLevel(),r=23;if(n.apiLevel){let i=Number(n.apiLevel);if(!Number.isInteger(i)||i<17)throw new Error(`Invalid API version ${n.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(i>t)throw new Error(`Invalid API version ${n.apiLevel}. Your SDK supports API version 17-${t}`)}else if(i>r)throw new Error(`Invalid API version ${n.apiLevel}. Without DevEco Studio, supported range is API version 17-${r}`);return i}return t!==void 0?t:23}async function rP(){try{return await I.new()}catch(n){console.error(Tf(`DevEco Studio not found: ${n.message}`)),console.log(Tf("Use placeholder API level instead."));return}}var iP=new JE("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(Gc("Error: --app-name is required")),zc.exit(1));let e=n.appName;XE(e);let t=n.bundleName||eP(e);ZE(t),n.projectPath&&kf(n.projectPath);let r=tP(e,n.projectPath);kf(r),console.log(KE("Initializing project...")),console.log(`Project path: ${r}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let i=await rP(),o=nP(n,i);console.log(`API level: ${o}`);let s=i?.devecoStudioPath,a=Df(r,e,t,o,s);console.log(`
|
|
1261
|
+
`+Rf("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(Rf("Template integrity check passed."))}catch(e){let t=e;console.error(Gc(`
|
|
1262
|
+
Failed to create project.`)),console.error(Gc(t.message)),zc.exit(1)}}),Of=iP;import{Command as uP}from"commander";import{red as pP,cyan as Uf}from"colorette";import oP from"fs";import ns from"path";import{cyan as sP}from"colorette";import*as rs from"smol-toml";var Kn=oP.promises;async function aP(n){try{let e=await Kn.readFile(n,"utf8");return e.trim()===""?{}:JSON.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read configuration file ${n}: ${e.message}`,{cause:e})}}async function cP(n){try{let e=await Kn.readFile(n,"utf8");return e.trim()===""?{}:rs.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read TOML config file ${n}: ${e.message}`,{cause:e})}}async function lP(n,e){let t=ns.dirname(n);await Kn.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await Kn.writeFile(n,r,"utf8")}async function dP(n,e){let t=ns.dirname(n);await Kn.mkdir(t,{recursive:!0});let r=rs.stringify(e);await Kn.writeFile(n,r,"utf8")}function Mf(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function _f(n,e,t,r,i){(!n[e]||typeof n[e]!="object")&&(n[e]={});let o=n[e];return t in o&&!i?!1:(o[t]=r,!0)}async function Ff(n,e){return n.format==="codex"?cP(e):aP(e)}async function jf(n,e,t){return n.format==="codex"?dP(e,t):lP(e,t)}async function Hf(n,e,t=!1){let r=Lt[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Lt).join(", ")}`};if(!r.supportsGlobal)return{success:!1,error:`${r.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let i=await Ff(r,r.globalConfigPath);if(Mf(i,r.mcpServersKey,at)&&!t)return console.log(`MCP server ${at} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let o=ao(r,void 0);return _f(i,r.mcpServersKey,at,o,t),await jf(r,r.globalConfigPath,i),console.log(`MCP server ${at} configured in ${r.globalConfigPath}.`),{success:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${i.message}`}}}async function Vc(n,e,t=!1){let r=Lt[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Lt).join(", ")}`};let i=ns.isAbsolute(r.projectConfigPath)?r.projectConfigPath:ns.join(e,r.projectConfigPath);try{let o=await Ff(r,i);if(Mf(o,r.mcpServersKey,at)&&!t)return console.log(`MCP server ${at} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:n,installType:"project"};let s=ao(r,e);return _f(o,r.mcpServersKey,at,s,t),await jf(r,i,o),console.log(`MCP server ${at} configured in ${i}.`),{success:!0,configPath:i,agentName:n,installType:"project"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${o.message}`}}}function $f(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(sP("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`);for(let i of n)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);r>0&&(process.exitCode=1)}var qc="deveco-cli";async function fP(n,e,t){if(n.customPath)return[await lf(qc,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>cf(qc,e,s,a,t.force)),...n.agents.map(s=>()=>af(qc,e,s,t.force))],i=5,o=[];for(let s=0;s<r.length;s+=i){let a=r.slice(s,s+i);o.push(...await Promise.all(a.map(c=>c())))}return o}async function mP(n,e,t){let r=[];for(let{project:i,agent:o}of n.projectAgents){let s=await Vc(o,i,t);r.push(s)}for(let i of n.agents){let o=await Vc(i,e,t);r.push(o)}return r}async function hP(n,e){let t=[];for(let r of n){if(!Lt[r])continue;let o=await Hf(r,process.cwd(),e);t.push(o)}return t}async function gP(n,e,t){if(t.agent&&t.agent.split(",").map(l=>l.trim()).includes("qoder"))throw new Error("Qoder does not support MCP configuration via DevEco CLI. Use other supported agents instead.");let r=t.force??!1,i=n.projectAgents.filter(c=>c.agent!=="qoder"),o=n.agents.filter(c=>c!=="qoder"),s={...n,projectAgents:i,agents:o},a=e?await mP(s,e,r):await hP(s.agents,r);a.length>0&&(console.log(Uf("MCP Configuration:")),$f(a))}async function yP(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}=si(n.path,n.project,n.agent);t&&jt(t,"Project directory",n.force),e&&jt(e,"Directory",n.force);let r=await Qo(n,e,t);if(n.mcp){await gP(r,t,n);return}let i=ff(),o=await fP(r,i,n);console.log(),o.length>0&&(console.log(Uf("Skill Installation:")),oi(o))}var wP=new uP("init").description("Install the deveco-cli skill or configure the deveco-mcp server into AI agents").option("--agent <agents>","Target agents, comma-separated; installs to all available agents if omitted").option("--project <path>","Project root directory for skill or MCP configuration").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").option("--skill","Install the deveco-cli skill only (same as default behavior; explicit for symmetry with --mcp)").option("--mcp","Configure the deveco-mcp server (syntax checking for .ets and C/C++) only; no skill installation").option("-f, --force","Overwrite existing skill/MCP configuration").action(async n=>{try{await yP(n)}catch(e){console.error(pP(e.message)),process.exit(1)}}),Bf=wP;import{Command as pC}from"commander";import{McpServer as KP}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as XP}from"@modelcontextprotocol/sdk/server/stdio.js";import*as En from"path";import*as rm from"fs";import{z as pe}from"zod";var is=class{tools=new Map;add(e,t){return this.tools.set(e.name,{definition:e,handler:t}),this}getAll(){return Array.from(this.tools.values())}registerToServer(e){for(let{definition:t,handler:r}of this.getAll())e.registerTool(t.name,{description:t.description,inputSchema:t.inputSchema},(async i=>r(i)))}};function Yc(){return new is}import*as Se from"fs";import*as ue from"path";import{z as Xc}from"zod";function Wf(n){return"method"in n&&!("id"in n)}import{spawn as vP}from"child_process";import{EventEmitter as SP}from"events";import*as Xn from"fs";import*as Gf from"path";var Ht=class extends SP{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;ensureDirectories(){let t=Gf.join(this.config.logPath,"lspLog");return Xn.existsSync(t)||Xn.mkdirSync(t,{recursive:!0}),Xn.existsSync(this.config.indexingDataLocation)||Xn.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let r=this.ensureDirectories();f.info(`[LspClient] serverMaxSize=${t}MB`);let i=H(r),o=["--expose-gc",`--max-old-space-size=${t}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${i}`,this.config.serverPath,"--stdio",`--logger-path=${i}`,"--logger-level=TRACE"];f.info(`[LspClient] Starting process: node ${o.join(" ")}`);let s=process.execPath??"node";f.info(`[LspClient] nodePath: ${s}`),this.process=vP(s,o,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0}),this.bindProcessEvents(),await new Promise(a=>setTimeout(a,500)),f.info("[LspClient] start lsp process success")}attachProcess(t,r){if(this.process)throw new Error("[LspClient] process already attached");this.process=t,this.bindProcessEvents(r?.stderrAsError??!0),f.info("[LspClient] attached to external process")}bindProcessEvents(t=!0){this.process&&(this.process.stdout?.on("data",r=>{this.handleData(r)}),this.process.stderr?.on("data",r=>{let i=r.toString("utf8").trim();f.error(`[LspClient] stderr: ${i}`),!this.isClosing&&t&&this.emit("error",new Error(`[LspClient] stderr: ${i}`))}),this.process.on("exit",r=>{f.info(`[LSP EXIT] code=${r}`),this.isClosing||this.emit("error",new Error(`LSP process exited with code ${r}`))}))}sendRaw(t,r){if(!this.process?.stdin?.writable){f.warn("[LspClient] Cannot send message, stdin not writable");return}f.info(`[LspClient] send message: ${r}`);let i=this.buildLspMessage(t);this.process.stdin.write(i,"utf8")}send(t,r,i){let o={jsonrpc:"2.0",method:t,params:r};i!==void 0&&(o.id=i),this.sendRaw(JSON.stringify(o),t)}sendNotification(t,r){this.sendRaw(JSON.stringify({jsonrpc:"2.0",method:t,params:r}),t)}sendRequest(t,r,i){this.sendRaw(JSON.stringify({jsonrpc:"2.0",id:i,method:t,params:r}),t)}buildLspMessage(t){return`Content-Length: ${Buffer.from(t,"utf8").length}\r
|
|
1263
1263
|
\r
|
|
1264
1264
|
${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this.buffer.indexOf(`\r
|
|
1265
1265
|
\r
|
|
1266
|
-
`);if(r===-1)break;let o=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!o){d.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(o[1],10),a=r+4,c=a+s;if(this.buffer.length<c)break;let l=this.buffer.slice(a,c).toString("utf8"),u=this.recoverFramedJson(l);if(u&&u.rest.length>0){d.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${l.length}, restLen=${u.rest.length}`),this.emit("message",u.json),this.buffer=Buffer.concat([Buffer.from(u.rest,"utf8"),this.buffer.slice(c)]);continue}this.emit("message",l),this.buffer=this.buffer.slice(c)}}waitForExitOrTimeout(t){let r=this.process;return!r||r.exitCode!==null||r.signalCode!==null?Promise.resolve():new Promise(i=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(c),r.off("exit",a),i())},a=()=>s();r.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let r=t.search(/\S/);if(r<0||t[r]!=="{"&&t[r]!=="[")return null;let i=0,o=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(o=!1);continue}if(c==='"'){o=!0;continue}if(c==="{"||c==="["){i++;continue}if((c==="}"||c==="]")&&(i--,i===0)){let l=t.slice(r,a+1),u=t.slice(a+1);return{json:l,rest:u}}}return null}stop(){this.isClosing=!0;let t=this.process;if(!t)return;if(this.process=null,t.exitCode===null&&t.signalCode===null)try{t.kill()}catch{}}};var Rt=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,r){return new Promise((i,o)=>{let s;r>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),o(new Error(`LSP request '${t}' (id=${e}) timeout after ${r}ms`))},r),this.timeouts.set(e,s)),this.pending.set(e,{resolve:i,reject:o,method:t,timer:s})})}resolvePending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.resolve(t),this.pending.delete(e),!0):!1}rejectPending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.reject(t),this.pending.delete(e),!0):!1}register(e,t){this.callbacks.set(e,t)}emit(e,t,r){d.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let i=this.callbacks.get(e);if(i)i(t,r),this.callbacks.delete(e);else{let o=[...this.callbacks.keys()].map(s=>String(s));d.info(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${o.join(",")}]`)}}registerTimeout(e,t,r,i){let o=this.timeouts.get(e);o&&clearTimeout(o);let s=setTimeout(()=>{d.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`),i(),this.timeouts.delete(e)},r);this.timeouts.set(e,s)}clearTimeout(e){let t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e))}deleteCallback(e){this.callbacks.delete(e)}hasCallback(e){return this.callbacks.has(e)||this.pending.has(e)}clear(e){this.clearTimeout(e);let t=this.pending.get(e);t&&(t.reject(new Error(`Request '${t.method}' (id=${e}) cancelled`)),this.pending.delete(e)),this.callbacks.delete(e)}rejectAll(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear();for(let[,t]of this.timeouts)clearTimeout(t);this.timeouts.clear(),this.callbacks.clear()}};var Pr=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var Mt=class{map=new Map;register(e,t){let r=this.map.get(e);r||(r=new Set,this.map.set(e,r)),r.add(t)}unregister(e,t){let r=this.map.get(e);r&&(t!==void 0?r.delete(t):r.clear(),r.size===0&&this.map.delete(e))}invoke(e,...t){let r=this.map.get(e);if(r)for(let i of r)try{i(...t)}catch(o){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,o)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function S(n){return typeof n=="object"&&n!==null}var al=20*1e3,hg=30*1e3,Cr=class{client;nextRequestId=1;stopOnce=null;callbacks=new Mt;requestCallbacks=new Rt;diagnosticMap=new Map;initProgressReset=null;constructor(e){this.client=new kt(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{d.info("[ClientMessageHandle] Sending shutdown request"),this.client.sendRequest(y.SHUTDOWN,null,this.nextRequestId++),d.info("[ClientMessageHandle] Sending exit notification"),this.client.sendNotification(y.EXIT,null),d.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),d.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(y.BROADCAST),this.callbacks.register(y.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(y.BROADCAST,e)}async sendInitialize(e){let t=this.nextRequestId++,r=this.requestCallbacks.registerPending(t,y.INITIALIZE,We);return this.client.sendRequest(y.INITIALIZE,e,t),r}sendInitializeResettable(e,t){let r=this.nextRequestId++,i=this.requestCallbacks.registerPending(r,y.INITIALIZE,0);return this.client.sendRequest(y.INITIALIZE,e,r),new Promise((o,s)=>{let a,c=()=>{a=setTimeout(()=>{this.initProgressReset=null,s(new Error(`LSP initialization timeout after ${t}ms`))},t)},l=()=>{clearTimeout(a),c()};this.initProgressReset=l,c(),i.then(()=>{clearTimeout(a),this.initProgressReset=null,o()},u=>{clearTimeout(a),this.initProgressReset=null,s(u)})})}sendInitialized(){this.client.sendNotification(y.INITIALIZED,{})}sendDidOpen(e){let t=e.textDocument.uri;this.diagnosticMap.has(t)||(this.diagnosticMap.set(t,new Pr(t)),this.registerDiagnosticTimeout(t)),this.client.sendNotification(y.DID_OPEN,e)}sendDidChange(e){let t=e.textDocument.uri,r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t)),this.client.sendNotification(y.DID_CHANGE,e)}closeFile(e){this.cleanupDiagnosticState(e.textDocument.uri),this.client.sendNotification(y.DID_CLOSE,e)}sendLspRequest(e,t,r=hg){let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}onDidChangeWatchedFiles(e){e.length!==0&&this.client.sendNotification(y.WORKSPACE_DID_CHANGE_WATCHED_FILES,{changes:e})}sendDidChangeConfiguration(e){this.client.sendNotification(y.WORKSPACE_DID_CHANGE_CONFIGURATION,{settings:e})}sendNotification(e,t){this.client.sendNotification(e,t)}getDiagnosticMessages(e){let t=this.diagnosticMap.get(e);return t?t.get():[]}clearDiagnostic(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let i=r instanceof Error?r.message:String(r);d.error(`[LSP] JSON parse error: ${i}, raw: ${e}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotificationOrRequest(t):d.warn(`[LSP] Unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t===void 0)return;let r=t;if(e.error){let i=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(r,i)}else this.requestCallbacks.resolvePending(r,e.result)}handleNotificationOrRequest(e){let t=e.method;if(t)switch(this.initProgressReset?.(),t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.handleProgress(e.params);break;case y.WINDOW_SHOW_MESSAGE:d.info(`[LSP] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:d.info(`[LSP] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.broadcastToClients(e)}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=e.uri,r=this.diagnosticMap.get(t);if(!r)return;let i=e.diagnostics||[];this.normalizeDiagnostics(i),r.set(i),this.finalizeDiagnostic(t,i)}normalizeDiagnostics(e){for(let t of e)if(t.severity!==void 0){let r={1:"Error",2:"Warning",3:"Information",4:"Hint"};t.severityStr=r[t.severity]||"Unknown"}}handleProgress(e){S(e)&&this.broadcastToClients({jsonrpc:A,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,al,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${al}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,r){let i={uri:e,diagnostics:t,...r?{errorMessage:r}:{}};this.requestCallbacks.emit(e,y.PUBLISH_DIAGNOSTICS,i),this.diagnosticMap.get(e)?.clear()}handleError(e){let t=Array.from(this.diagnosticMap.keys()).filter(r=>this.requestCallbacks.hasCallback(r));if(t.length>0){let r={range:{start:{line:0,character:0},end:{line:0,character:0}},severity:1,message:e.message};for(let i of t)this.finalizeDiagnostic(i,[r]);return}this.broadcastToClients({jsonrpc:A,method:y.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var Dr=class{uri;messages=[];receivedTypes=new Set;uniqueMessages=new Set;isFromEditor=!1;constructor(e){this.uri=e}setReceivedType(e){this.receivedTypes.add(e)}addMessage(e,t){this.receivedTypes.add(e);let r=`${e}:${t}`;if(this.uniqueMessages.has(r)){d.info(`[LegacyDiagnostic] addMessage: duplicate message=${r}`);return}this.uniqueMessages.add(r),this.messages.push(new Ro(e,t))}clearMessages(){this.messages=[]}clear(){this.receivedTypes.clear(),this.uniqueMessages.clear(),this.messages=[]}hasReceivedAllTypes(e){for(let t of e)if(!this.receivedTypes.has(t))return!1;return!0}getMessages(){return this.messages.map(e=>e.diagnostics)}},Ro=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var fg={EXIT:"exit",INITIALIZED:"initialized",ON_DID_CHANGE_PACKAGE_DEPENDENCIES:"aceProject/onDidChangePackageDependencies",ON_ASYNC_DID_OPEN:"aceProject/onAsyncDidOpen",ON_ASYNC_DID_CHANGE:"aceProject/onAsyncDidChange",DID_CLOSE:"textDocument/didClose",ON_ASYNC_HOVER:"aceProject/onAsyncHover",ON_ASYNC_DEFINITION:"aceProject/onAsyncDefinition",ON_ASYNC_FIND_USAGES:"aceProject/onAsyncFindUsages"},gg={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing"},D={...fg,...gg},ze={EXIT:"exit",INITIALIZED:"initialized",EMPTY:"empty",ON_DID_CHANGE_PACKAGE_DEPENDENCIES:"onDidChangePackageDependencies",ON_ASYNC_DID_OPEN:"onAsyncDidOpen",ON_ASYNC_DID_CHANGE:"onAsyncDidChange",DID_CLOSE:"didClose",ON_ASYNC_HOVER:"onAsyncHover",ON_ASYNC_DEFINITION:"onAsyncDefinition",ON_ASYNC_FIND_USAGES:"onAsyncFindUsages"},cl=new Set([1e3,2e3,3e3,3001]);function yg(n){if(!S(n))return!1;let e=n.textDocument;return S(e)&&typeof e.uri=="string"}function vg(n){return S(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function wg(n){return S(n)&&typeof n.moduleName=="string"&&typeof n.current=="number"&&typeof n.total=="number"?`indexing module '${n.moduleName}', ${n.current} of total ${n.total} modules`:`params=${JSON.stringify(n??null)}`}var Ir=class n{client;isInitialized=!1;stopOnce=null;callbacks=new Mt;requestCallbacks=new Rt;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;constructor(e){this.client=new kt(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{d.info("[LegacyClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:A,method:D.EXIT,params:{}}),ze.EXIT),d.info("[LegacyClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),d.info("[LegacyClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(D.BROADCAST),this.callbacks.register(D.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(D.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(D.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(D.INDEXING_PROGRESS_UPDATE,e)}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}sendInitialize(e,t){this.client.send("initialize",e,t)}sendInitialized(e){this.client.sendRaw(JSON.stringify({jsonrpc:A,method:D.INITIALIZED,params:{editors:e}}),ze.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:A,id:0,result:{}}),ze.EMPTY)}sendAsyncRequest(e,t,r,i){if(!S(t)){d.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!yg(t)){d.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof r!="number"){d.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(r)}`);return}let o=t.textDocument.uri,s=Ue(o);t.textDocument.uri=s,delete t.requestId;let a=i??e;d.info(`[LSP] sendAsyncRequest ${a}, filePath: ${o}`),this.client.sendRaw(JSON.stringify({jsonrpc:A,method:e,params:{params:t,requestId:r}}),a)}onDidChangeWatchedFiles(e){if(d.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let r of e){if(!vg(r)){d.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:A,method:D.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),D.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!S(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){d.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;d.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:A,method:D.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),ze.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let i=Ue(t);e.textDocument.uri=i,d.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new Dr(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,D.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:A,method:D.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),ze.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=Ue(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,D.PUBLISH_DIAGNOSTICS)),d.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:A,method:D.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),ze.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=Ue(e);d.info(`[LSP] didClose, uri: ${r}`);let i=this.diagnosticMap.get(r);if(!t&&(!i||i.isFromEditor)){d.info(`[LSP] closeFile skip, !diagnostic: ${!i}, isFromEditor: ${i?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:A,method:D.DID_CLOSE,params:{textDocument:{uri:r}}}),ze.DID_CLOSE)}getDiagnosticMessage(e){let t=Ue(e),r=this.diagnosticMap.get(t);return r?r.getMessages():[]}clear(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){try{let t=JSON.parse(e);this.handleLspMessage(t)}catch(t){let r=t instanceof Error?t.message:String(t);d.error(`[LSP] JSON parse error: ${r}, raw: ${e}`)}}handleError(e){let t=this.getPendingDiagnosticUris();if(t.length>0){let r=JSON.stringify({message:e.message,severity:"Error",severityStr:"Error"});for(let i of t)this.finalizeDiagnostic(i,D.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:A,method:D.ARKTS_ERROR,params:{message:e.message}})}handleLspMessage(e){let t=e.method;t!==void 0&&(!this.isInitialized&&this.handlePreInitMessage(t,e)||this.handlePostInitMessage(t,e))}handlePreInitMessage(e,t){switch(e){case D.MODULE_INIT_FINISH:return d.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(D.MODULE_INIT_FINISH),this.callbacks.unregister(D.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case D.INDEXING_PROGRESS_UPDATE:return d.info(`[LSP] onIndexingProgressUpdate: ${wg(t.params)}`),this.callbacks.invoke(D.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case D.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case D.ON_PACKAGE_CHANGE_FINISH:d.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case D.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case D.ON_ASYNC_HOVER:this.handleAsyncResponse(t,D.HOVER);return;case D.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,D.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case D.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,D.REFERENCES);return;default:d.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){d.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;S(t)&&S(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){d.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,r={jsonrpc:A,method:D.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){d.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(r);return}if(!(t.length>0&&t[0]===!0)){d.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(r);return}d.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){d.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let r=e.params;if(!S(r)){d.warn("[LSP] aceProject/onAsyncHover message invalid");return}let i=r.requestId;if(typeof i!="number"){d.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(i,t,r)}handleForceOpenFile(e){if(!e){d.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,D.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){d.info("[LSP] publishDiagnostics uri is null");return}let r=e.version??-1;if(r===-1)return;let i=this.diagnosticMap.get(t);if(!i){d.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let o=e.diagnostics||[];o.length!==0?o.forEach(s=>{this.normalizeDiagnostic(s),i.addMessage(r,JSON.stringify(s))}):i.setReceivedType(r),i.hasReceivedAllTypes(cl)&&this.finalizeDiagnostic(t,D.PUBLISH_DIAGNOSTICS,i.getMessages())}normalizeDiagnostic(e){let t=e;if(delete t.source,t.severity!==void 0){let r=typeof t.severity=="number"?t.severity:parseInt(t.severity),o={1:"Error",2:"Warning",3:"Information",4:"Hint"}[r]||"Unknown";t.severityStr=o,t.severity=o}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let r=e[t];r&&typeof r.line=="number"&&(r.line=r.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,n.DIAGNOSTIC_TIMEOUT_MS,()=>{let r=this.diagnosticMap.get(e),i=r?r.getMessages():[];this.finalizeDiagnostic(e,t,i,i.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,i){let o={uri:e,diagnostics:r,...i?{errorMessage:i}:{}};this.requestCallbacks.emit(e,t,o),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import Pn from"path";import*as Or from"path";var Ar=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var xr=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var Tr=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var kr=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Rr=class{typeSetting=new Tr;parameterNames=new kr};var Mr=class{constructor(e,t,r,i){this.rootUri=e;this.lspServerWorkspacePath=j(Or.dirname(t)),this.indexingDataLocation=j(i),this.loggerPath=j(Or.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new Ar;gutterIconsSetting=new xr;inlayHintsSetting=new Rr;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as ll from"path";var vn=class{productName="default";buildModeName="debug";targetName="default";arkTSVersion="1.1";resourceDirectories=[];targetESVersion="ES2021";maxFlowDepth=2e3;caseSensitiveCheck=!0;tsImportSendable=!1;compatibleSdkVersionStage="";useNormalizedOHMUrl=!0;reExportCheckMode="noCheck";skipOhModulesLint=!1;byteCodeHar=!0;obfuscationRuleOptionsEnable=!1;enableStrictCheckOHModules=!1;sourceRoots=[];constructor(e){e&&this.resourceDirectories.push(j(ll.join(e,"src","main","resources")))}};var bg="OS",Ot=class{deviceType=[5];aceLoaderPath;modulePath;jsComponentType="declarative";sdkJsPath;compatibleSdkVersion;compatibleSdkLevel;compileSdkLevel;compileSdkVersion="6.0.1.112";compileSdkType="Release";syscap={NDeviceSysCaps:[],addedSysCaps:[]};apiType="stageMode";hosSdkPath;runtimeOs=`Harmony${bg}`;moduleName;moduleType;compileMode="jsbundle";crossPlatform=!1;ignoreCrossPlatform=!1;packageManagerType="ohpm";permissions=[];testPermissions=[];buildProfileParam;appParam={bundleType:"app"};packageName;projectType="OHOS";projectName;moduleDependencies;moduleJsonParam=null;globalDeclarationFiles=[];constructor(e){e?(this.modulePath=e,this.buildProfileParam=new vn(e)):this.buildProfileParam=new vn}toString(){return JSON.stringify(this)}};var Lt=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as me from"path";import*as Ht from"fs";var Lr=class{modulePath;dependencies={};dynamicDependencies={}};var ct=class{registryType;resolved;name;version;type;constructor(e){let t=typeof e=="object"&&e!==null?e:{};this.name=typeof t.name=="string"?t.name:"",this.version=typeof t.version=="string"?t.version:"",typeof t.registryType=="string"?this.registryType=t.registryType:this.registryType=typeof t.path=="string"?"local":"ohpm",typeof t.resolved=="string"?this.resolved=t.resolved:typeof t.storePath=="string"?this.resolved=t.storePath:this.resolved="",this.type=typeof t.type=="string"?t.type:void 0}};var Nt=class{constructor(e,t,r){this.projectPath=e;this.moduleName=t;this.modulePath=r}projectPath;moduleName;modulePath;dependencies=[];devDependencies=[];dynamicDependencies=[];finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[]};import*as Me from"path";import*as Nr from"fs";var _t=class{name="";version="";storePath="";dependencyPath="";path=""};var T={HVIGOR_CACHE:".hvigor",DEPENDENCY:"dependencyMap",JSON5:".json5",KEY_DEPENDENCY:"dependencies",KEY_DYNAMIC_DEPENDENCY:"dynamicDependencies",KEY_DEV_DEPENDENCY:"devDependencies",OH_MODULES_PATH:"oh_modules",OHPM_PATH:".ohpm",LOCK_JSON5_FILE:"lock.json5",OH_PACKAGE_JSON5:ye.OH_PACKAGE_JSON5},wn=`${T.HVIGOR_CACHE}/${T.DEPENDENCY}`,lt=`${T.DEPENDENCY}${T.JSON5}`,PA=ye.SYNC_OUTPUT_PATH;var bn=class n{dependencyPath;modulePath;projectPath;static FILE_DEPENDENCY_PREFIX="file:";static PARAMETER_PREFIX="@param:";fileSpecPattern;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;static PACKAGE_JSON_PARSER_MAP=new Map;dependencies=[];devDependencies=[];dynamicDependencies=[];static getInstance(e,t,r){let i=this.PACKAGE_JSON_PARSER_MAP.get(e);return i||(i=new n(e,t,r),this.PACKAGE_JSON_PARSER_MAP.set(e,i)),i}constructor(e,t,r){this.dependencyPath=e,this.modulePath=t,this.projectPath=r,this.fileSpecPattern=n.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=Me.join(this.dependencyPath,T.OH_PACKAGE_JSON5),r=ae(t);r&&(this.dependencies=this.getDependencyList(r,T.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(r,T.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(r,T.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let r=[];if(!S(e))return r;let i=e[t];if(!S(i))return r;for(let[o,s]of Object.entries(i)){if(typeof s!="string"){d.error(`${o} package dependency value is not String ${t}`);continue}let a=new _t;a.name=o;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(n.PARAMETER_PREFIX)||this.parseDependencyPath(o,c,a,!1),r.push(a)}return r}parseDependencyPath(e,t,r,i){if(!(!e||!t))try{let o=Me.normalize(Me.join(this.modulePath,T.OH_MODULES_PATH,e));if(!(t.startsWith(n.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){r.dependencyPath=o;return}if(r.path=t,this.fileNameForOhpm.test(t)){r.dependencyPath=o;return}let s=t;if(t.startsWith(n.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(n.FILE_DEPENDENCY_PREFIX.length)),Me.isAbsolute(s)){r.dependencyPath=o;return}if(!i){let a=Me.resolve(this.modulePath,s);o=b.ensurePathWithinRoot(this.projectPath,a)}Nr.existsSync(o)&&Nr.statSync(o).isDirectory()&&(r.dependencyPath=o)}catch(o){d.error("parser dependency path is invalid",o)}}};import*as Sn from"fs";import*as En from"path";import Sg from"json5";var _r=class n{projectPath;static FILE_DEPENDENCY_PREFIX="file:";fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[];storePathMap=new Map;lockFileCache=null;lockFileParsed=!1;constructor(e=""){this.projectPath=e}parseDependencies(e){if(!this.ensureLockFileParsed())return!1;let t=this.lockFileCache;return this.extractDependencies(t.modules,t.storePathMap,e),!0}ensureLockFileParsed(){if(this.lockFileParsed)return this.lockFileCache!==null;this.lockFileParsed=!0;let e=this.getLockFilePath(),t=this.readLockFile(e);if(!t)return!1;let r=this.validateLockFile(t);return r.valid?(this.lockFileCache={modules:r.modules,storePathMap:this.parseStorePathMap(r.packages)},!0):!1}getLockFilePath(){return En.join(this.projectPath,T.OH_MODULES_PATH,T.OHPM_PATH,T.LOCK_JSON5_FILE)}readLockFile(e){if(!Sn.existsSync(e))return d.error("lock file does not exist"),this.clearDependencies(),null;try{let t=Sn.readFileSync(e,"utf8"),r=Sg.parse(t);return r||(d.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return d.error("Error parsing lock.json5:",t),this.clearDependencies(),null}}validateLockFile(e){if(!S(e))return d.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return d.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let r=e.packages;return r?{valid:!0,modules:t,packages:r}:(d.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,r){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,T.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,T.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,T.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!S(e))return t;for(let[r,i]of Object.entries(e)){if(!S(i)){d.error(`${r} value is not json object`);continue}typeof i.storePath=="string"&&t.set(r,i.storePath)}return t}getDependencyList(e,t,r){if(!S(e))return[];for(let[i,o]of Object.entries(e))if(S(o)){let s=typeof o.name=="string"?o.name:"";if(r==="."&&s===""||s===r)return this.getFinalDependencyList(e,t,i)}return[]}getFinalDependencyList(e,t,r){let i=e[r];if(!S(i))return d.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!S(s))return[];for(let[a,c]of Object.entries(s)){if(!S(c))continue;let l=typeof c.specifier=="string"?c.specifier:"",u=typeof c.version=="string"?c.version:"",f=new _t;f.name=a,f.version=u.startsWith(n.FILE_DEPENDENCY_PREFIX)?u.substring(n.FILE_DEPENDENCY_PREFIX.length):u,this.parseDependencyPath(f,r,a,l,u);let P=`${a}@${u}`;this.storePathMap.has(P)&&(f.storePath=this.storePathMap.get(P)||""),o.push(f)}return o}parseDependencyPath(e,t,r,i,o){let s=b.resolvePathWithinRoot(this.projectPath,En.join(t,T.OH_MODULES_PATH,r));try{let a=o.startsWith(n.FILE_DEPENDENCY_PREFIX)?o.substring(n.FILE_DEPENDENCY_PREFIX.length):o,c=En.isAbsolute(a)?b.ensurePathWithinRoot(this.projectPath,a):b.resolvePathWithinRoot(this.projectPath,a);Sn.existsSync(c)?(e.path=i,e.dependencyPath=this.fileNameForOhpm.test(o)?s:c):e.dependencyPath=s}catch(a){d.error("Invalid dependency path in lock.json5",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};var Oe=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=ol(this.projectRoot);try{let t=ae(e);if(typeof t!="object"||t===null)return[];let r=t.modules;return Array.isArray(r)?r.filter(i=>{if(typeof i!="object"||i===null)return!1;let o=i;return typeof o.name=="string"&&typeof o.srcPath=="string"}):[]}catch(t){return d.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};function dl(n){return S(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var dt=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new Oe(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=me.join(t,wn),i=me.join(r,lt);if(!Ht.existsSync(r)||!Ht.existsSync(i)){let c="Dependency map or JSON not found";return d.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let o=new Nt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(r,o),this.parseLockJson(o);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return d.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:c}}let a=Date.now();for(let c=0;c<s.length;c++){let l=s[c];dl(l)&&(this.parseSingleModule(l,r,o,e),(c+1)%100===0&&d.info(`[Parser] getAllDependencyMap progress: ${c+1}/${s.length} (${Date.now()-a}ms)`))}return d.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-a}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],r=this.projectPath,i=me.join(r,wn),o=me.join(i,lt);if(!Ht.existsSync(i)||!Ht.existsSync(o))return d.warn("[Parser] Dependency map or JSON not found."),t;let s=e&&e.length>0?new Set(e.map(l=>l.trim()).filter(Boolean)):null,a=new Nt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return d.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let l of c){if(!dl(l))continue;let u=l.name;if(s&&!s.has(u))continue;let f=b.resolvePathWithinRoot(this.projectPath,l.srcPath),P=me.join(i,u),C=j(f),L=this.buildModuleDependencies(u,C,P,a);L.moduleName=u,t.push(L)}return t}parseSingleModule(e,t,r,i){let o=e.name,s=b.resolvePathWithinRoot(this.projectPath,e.srcPath),a=me.join(t,o),c=j(s),l=new Ot(c),u=this.buildModuleDependencies(o,c,a,r);this.parseModuleJson5(c,l);let f=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=o,l.moduleType=o,l.packageName=o,l.moduleDependencies=u,l.moduleJsonParam=new Lt(f),i.push(l)}buildModuleDependencies(e,t,r,i){let o=new Nt(this.projectPath,e,t);bn.getInstance(r,t,this.projectPath).parseDependency(o),this.parseLockJson(o),o.finalDependencies.push(...i.finalDependencies),o.finalDevDependencies.push(...i.finalDevDependencies),o.finalDynamicDependencies.push(...i.finalDynamicDependencies),o.finalDependencies.push(...o.finalDevDependencies);let a=new Lr;return a.modulePath=t,this.toModuleDependencies(o,a),a}toModuleDependencies(e,t){let r={},i={};for(let o of e.finalDependencies)r[o.name]=new ct(o);for(let o of e.finalDynamicDependencies)i[o.name]=new ct(o);t.dependencies=r,t.dynamicDependencies=i}parseProjectDependencies(e,t){let r=me.join(e,T.OH_PACKAGE_JSON5);if(!Ht.existsSync(r))return;bn.getInstance(e,this.projectPath,this.projectPath).parseDependency(t)}parseLockJson(e){let t=this.getLockJson5Parser();t.parseDependencies(e.moduleName)?(e.finalDependencies=t.finalDependencies,e.finalDevDependencies=t.finalDevDependencies,e.finalDynamicDependencies=t.finalDynamicDependencies):(e.finalDependencies=e.dependencies,e.finalDevDependencies=e.devDependencies,e.finalDynamicDependencies=e.dynamicDependencies)}getLockJson5Parser(){return this.lockJson5Parser||(this.lockJson5Parser=new _r(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=me.join(e,"src","main","module.json5"),i=ae(r);if(!S(i)||!S(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(S(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)S(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=me.join(e,"src","main","resources","base","profile","main_pages.json"),r=ae(t);return!S(r)||!Array.isArray(r.src)?[]:r.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!S(t)||!S(t.data))){if(typeof t.data.apiVersion=="string"){let r=parseInt(t.data.apiVersion,10);!Number.isNaN(r)&&r>=26&&typeof t.data.platformVersion=="string"?e.compileSdkLevel=t.data.platformVersion:e.compileSdkLevel=t.data.apiVersion}typeof t.data.releaseType=="string"&&(e.compileSdkType=t.data.releaseType),typeof t.data.version=="string"&&(e.compileSdkVersion=t.data.version)}}getSdkPkg(){if(this.sdkPkgCache===void 0){let e=me.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=ae(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!S(t)||!S(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!S(r)||typeof r.compatibleSdkVersion!="string")return;let[i,o]=this.parseBySplit(r.compatibleSdkVersion);e.compatibleSdkVersion=i,e.compatibleSdkLevel=o}getBuildProfile(){if(this.buildProfileCache===void 0){let e=me.join(this.projectPath,"build-profile.json5");this.buildProfileCache=ae(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,e];let r=e.substring(0,t),i=e.substring(t+1,e.length-1);return[r,i]}parseDeviceTypes(e){return!S(e)||!Array.isArray(e.deviceTypes)?[]:e.deviceTypes.filter(t=>typeof t=="string").map(t=>this.getDeviceType(t))}getDeviceType(e){return{liteWearable:1,wearable:2,tv:3,car:4,phone:5,default:5,smartVision:6,tablet:7,router:8,pc:9,"2in1":10}[e]||0}};var Hr=class{constructor(e=[]){this.valueSet=e}valueSet};var Ft=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var ul=(v=>(v[v.File=1]="File",v[v.Module=2]="Module",v[v.Namespace=3]="Namespace",v[v.Package=4]="Package",v[v.Class=5]="Class",v[v.Method=6]="Method",v[v.Property=7]="Property",v[v.Field=8]="Field",v[v.Constructor=9]="Constructor",v[v.Enum=10]="Enum",v[v.Interface=11]="Interface",v[v.Function=12]="Function",v[v.Variable=13]="Variable",v[v.Constant=14]="Constant",v[v.String=15]="String",v[v.Number=16]="Number",v[v.Boolean=17]="Boolean",v[v.Array=18]="Array",v[v.Object=19]="Object",v[v.Key=20]="Key",v[v.Null=21]="Null",v[v.EnumMember=22]="EnumMember",v[v.Struct=23]="Struct",v[v.Event=24]="Event",v[v.Operator=25]="Operator",v[v.TypeParameter=26]="TypeParameter",v))(ul||{}),pl=()=>Object.values(ul).filter(n=>typeof n=="number");var Fr=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var jr=class{applyEdit=!0;workspaceEdit=new Fr;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Hr(pl());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Ft;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var $r=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Br=class{constructor(e=[]){this.valueSet=e}valueSet};var Wr=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var ml=(w=>(w[w.Text=1]="Text",w[w.Method=2]="Method",w[w.Function=3]="Function",w[w.Constructor=4]="Constructor",w[w.Field=5]="Field",w[w.Variable=6]="Variable",w[w.Class=7]="Class",w[w.Interface=8]="Interface",w[w.Module=9]="Module",w[w.Property=10]="Property",w[w.Unit=11]="Unit",w[w.Value=12]="Value",w[w.Enum=13]="Enum",w[w.Keyword=14]="Keyword",w[w.Snippet=15]="Snippet",w[w.Color=16]="Color",w[w.File=17]="File",w[w.Reference=18]="Reference",w[w.Folder=19]="Folder",w[w.EnumMember=20]="EnumMember",w[w.Constant=21]="Constant",w[w.Struct=22]="Struct",w[w.Event=23]="Event",w[w.Operator=24]="Operator",w[w.TypeParameter=25]="TypeParameter",w))(ml||{}),hl=()=>Object.values(ml).filter(n=>typeof n=="number");var Ur=class{completionItemKind=new Br(hl());completionItem=new Wr;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var zr=class{synchronization=new $r;completion=new Ur;hover={contentFormat:{},dynamicRegistration:{}};signatureHelp={signatureInformation:{},contextSupport:{},dynamicRegistration:{}};references={dynamicRegistration:{}};documentHighlight={dynamicRegistration:!0};documentSymbol=null;formatting={dynamicRegistration:{}};rangeFormatting={dynamicRegistration:{}};onTypeFormatting={dynamicRegistration:{}};declaration={};definition={linkSupport:{},dynamicRegistration:{}};codeLens=null;documentLink={tooltipSupport:{},dynamicRegistration:{}};colorProvider=null;rename={prepareSupport:!0,prepareSupportDefaultBehavior:null,honorsChangeAnnotations:null,dynamicRegistrationSupport:null};publishDiagnostics=null;foldingRage=null;typeHierarchy=null;callHierarchy={dynamicRegistration:{}};selectionRange=null;semanticTokens=new Ft;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var qr=class{workspace=new jr;textDocument=new zr;notebookDocument=null;window=null;general=null;experimental=null};var Gr=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var Vr=class{constructor(e,t,r,i,o,s=!0){this.sdkPath=e;this.rootUri=r;this.nodeMaxOldSpaceSize=o;this.useStandardProtocol=s;this.serverPath=this.useStandardProtocol?Pn.resolve(t,"ace-server","out","standardIndex","index.js"):Pn.resolve(t,"ace-server","out","index.js"),this.logPath=tl(),this.indexLogPath=i||this.logPath;let a={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath};this.messageHandle=this.useStandardProtocol?new Cr(a):new Ir(a),this.messageHandle.setBroadcastToClients(c=>this.onLspMessage(c))}sdkPath;rootUri;nodeMaxOldSpaceSize;useStandardProtocol;messageHandle;get stdHandle(){return this.messageHandle}get legacyHandle(){return this.messageHandle}onAsyncOpenFile(e){this.legacyHandle.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.legacyHandle.closeFile(e,t)}serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}async start(e,t){let r=!1;try{d.info(`serverPath: ${this.serverPath}`),d.info(`rootUri: ${this.rootUri}`),d.info(`sdkPath: ${this.sdkPath}`),d.info(`logPath: ${this.logPath}`);let i=Ue(this.rootUri),o=new Mr(i,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new dt(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),o.modules=s;let l=Sr(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new Gr(i,o,new qr),this.useStandardProtocol){let u=this.messageHandle;await u.sendInitializeResettable(this.currentParams,We),d.info("[LSP] initialize response received"),u.broadcastToClients({jsonrpc:A,method:y.ARKTS_INDEXING_PROGRESS,params:{}}),u.sendInitialized()}else await this.startLegacy(this.currentParams,e);r=!0}catch(i){this.lastStartErrorMessage=i instanceof Error?i.message:String(i),d.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(r)}async startLegacy(e,t){let r=this.messageHandle;r.sendInitialize(e,1),r.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:A,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((i,o)=>{r.onIndexingProgressUpdate(o),r.onInitializationCompleted(i)},"LSP initialization",We),r.sendInitialized(t)}withResettableTimeout(e,t,r){return new Promise((i,o)=>{let s,a=()=>{s=setTimeout(()=>{o(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),i()},c)})}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){d.info(`[LSP] registerDiagnosticCallback uri='${e}', useStandardProtocol=${this.useStandardProtocol}`),this.messageHandle.registerRequestCallback(e,(t,r)=>{let i=S(r)?r:{};d.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let o={jsonrpc:A,method:t,params:{uri:typeof i.uri=="string"?i.uri:e,diagnostics:Array.isArray(i.diagnostics)?i.diagnostics:[],...typeof i.errorMessage=="string"?{errorMessage:i.errorMessage}:{}}};this.onLspMessage(o)})}async hover(e){let t=e.textDocument.uri;return this.registerDiagnosticCallback(t),this.stdHandle.sendLspRequest(y.HOVER,e)}async definition(e){return this.stdHandle.sendLspRequest(y.DEFINITION,e)}async references(e){return this.stdHandle.sendLspRequest(y.REFERENCES,e)}async completion(e){return this.stdHandle.sendLspRequest(y.COMPLETION,e)}async documentSymbol(e){return this.stdHandle.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async diagnostic(e){return this.stdHandle.sendLspRequest(y.DIAGNOSTIC,e,120*1e3)}async sendFeatureRequest(e,t){return this.stdHandle.sendLspRequest(e,t)}reloadDependenciesOnly(e){let t=e?.fullReload??!1,r=new dt(this.rootUri,this.sdkPath),i=this.getModuleModelsByName();if(t){d.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let l=r.getDependenciesOnly();this.markDependencyTypesIncremental(l);let u=this.mergeDepsOnlyIntoModuleList(l,i);return this.applyModuleModelsUpdate(u),this.sendDidChangeConfiguration({moduleSet:u}),d.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${u.length}`),this.lastDepsOnlyForDiff=l,l}let o=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(o.length===0&&s.size===0)return d.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];d.info(`[LspServerProxy] Module-level deps changed, parsing: [${o.join(", ")}]`);let a=r.getDependenciesOnly(o);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),this.sendDidChangeConfiguration({moduleSet:c}),d.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}sendDidChangeConfiguration(e){this.stdHandle.sendDidChangeConfiguration(e)}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),r=new Map(this.lastDepsOnlyForDiff.map(i=>[i.moduleName??"",i]));for(let i of e){let o=i.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(o,t,r),c=i.dependencies??{},l=i.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(u,f)=>{(i.dependencies??={})[u]=this.makeDeleteEntry(u,f)}),this.markAddAndDeleteInDeps(a,l,(u,f)=>{(i.dynamicDependencies??={})[u]=this.makeDeleteEntry(u,f)})}}getOldDepsForModule(e,t,r){let i=t.get(e),o=i?.moduleDependencies?.dependencies??{},s=i?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(o).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(o=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:o,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let i of Object.keys(t))i in e||(t[i].type="add");for(let i of Object.keys(e))i in t||r(i,e[i])}makeDeleteEntry(e,t){return new ct({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Ot(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new Lt([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let i of e){let o=i.moduleName??"",s=t.get(o);s?(s.modulePath=i.modulePath,s.moduleDependencies=i):s=this.createMinimalModelFromDepsItem(i),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let i=new Map(r.map(s=>[s.moduleName??"",s])),o=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=i.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,i.delete(a)),o.push(s)}for(let[,s]of i)o.push(this.createMinimalModelFromDepsItem(s));return o}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=Er(Pn.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=Er(Pn.join(t,"default/openharmony/ets/api")),o=Er(Pn.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=i,s.hosSdkPath=o}sendRequest(e){switch(e.method){case y.HOVER:this.stdHandle.sendLspRequest(y.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:A,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:A,id:e.id,error:{code:-32603,message:t.message}}));break;case y.DEFINITION:this.stdHandle.sendLspRequest(y.DEFINITION,e.params).then(t=>this.onLspMessage({jsonrpc:A,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:A,id:e.id,error:{code:-32603,message:t.message}}));break;case y.REFERENCES:this.stdHandle.sendLspRequest(y.REFERENCES,e.params).then(t=>this.onLspMessage({jsonrpc:A,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:A,id:e.id,error:{code:-32603,message:t.message}}));break;default:d.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!Xc(e)){d.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case y.DID_OPEN:this.handleDidOpenNotification(e);break;case y.DID_CHANGE:this.handleDidChangeNotification(e);break;case y.DID_CLOSE:this.handleDidCloseNotification(e);break;case y.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;case y.DID_CREATE_FILES:this.handleDidCreateFiles(e);break;case y.DID_DELETE_FILES:this.handleDidDeleteFiles(e);break;default:d.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){d.error("Invalid textDocument/didOpen params");return}this.stdHandle.sendDidOpen(t)}handleDidChangeNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){d.error("Invalid textDocument/didChange params");return}this.stdHandle.sendDidChange(t)}handleDidCloseNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){d.error("Invalid textDocument/didClose params");return}this.stdHandle.closeFile(t)}handleDidChangeWatchedFiles(e){let t=e.params;!t||!Array.isArray(t.changes)||this.messageHandle.onDidChangeWatchedFiles(t.changes)}handleDidCreateFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(y.DID_CREATE_FILES,t)}handleDidDeleteFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(y.DID_DELETE_FILES,t)}async dispose(){await this.messageHandle.stop()}};import*as Le from"fs";import*as qe from"path";import{createHash as Pg}from"crypto";import{EventEmitter as Cg}from"events";var Yr=class extends Cg{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r}projectRoot;watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),r=new Set(this.watchers.keys());for(let i of t)r.has(i)||this.watchFile(i);for(let i of r)t.has(i)||(this.unwatchFile(i),d.info(`[ConfigFileWatcher] Stopped watching: ${i}`));d.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!Le.existsSync(t)){d.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Le.watch(t,r=>{r==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",r=>{d.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${r.message}`)}),d.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(r){d.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${r instanceof Error?r.message:String(r)}`)}}emitModuleAddedEvents(t,r){for(let i of t){let o=b.resolvePathWithinRoot(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:o,relativePath:i.srcPath,timestamp:r,moduleName:i.name})}}emitModuleRemovedEvents(t,r){for(let i of t){let o=b.resolvePathWithinRoot(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:o,relativePath:i.srcPath,timestamp:r,removedModuleName:i.name})}}emitModuleRenamedEvents(t,r){for(let i of t){let o=b.resolvePathWithinRoot(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name,removedModuleName:i.before.name})}}emitModuleMovedEvents(t,r){for(let i of t){let o=b.resolvePathWithinRoot(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let r=Date.now();this.emitModuleAddedEvents(t.added,r),this.emitModuleRemovedEvents(t.removed,r),this.emitModuleRenamedEvents(t.renamed,r),this.emitModuleMovedEvents(t.moved,r)}onBuildProfileChanged(){let t="__build_profile__",r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(o);if(s===this.lastModulesSnapshot){d.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,o);this.lastModules=o,this.lastModulesSnapshot=s,d.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,i)}computeModulesSnapshot(t){return t.map(i=>`${i.name}::${i.srcPath}`).sort().join("|")}diffModules(t,r){let i=this.buildModuleMatchState(r),o={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,i),this.matchRenamedModules(t,i,o),this.matchMovedModules(t,i,o),this.collectRemovedModules(t,i,o),this.collectAddedModules(r,i,o),o}buildModuleMatchState(t){let r=new Map,i=new Map;for(let o of t)r.set(o.srcPath,o),i.set(o.name,o);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:i}}matchExactModules(t,r){for(let i of t){let o=r.newBySrc.get(i.srcPath);o&&o.name===i.name&&(r.matchedOld.add(i),r.matchedNew.add(o))}}matchRenamedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newBySrc.get(o.srcPath);s&&!r.matchedNew.has(s)&&s.name!==o.name&&(i.renamed.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}matchMovedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newByName.get(o.name);s&&!r.matchedNew.has(s)&&s.srcPath!==o.srcPath&&(i.moved.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}collectRemovedModules(t,r,i){for(let o of t)r.matchedOld.has(o)||i.removed.push(o)}collectAddedModules(t,r,i){for(let o of t)r.matchedNew.has(o)||i.added.push(o)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=ae(t);if(typeof r!="object"||r===null)return[];let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return d.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=qe.join(this.projectRoot,T.OH_PACKAGE_JSON5);Le.existsSync(r)&&t.push(r);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=b.resolvePathWithinRoot(this.projectRoot,o.srcPath),a=qe.join(s,T.OH_PACKAGE_JSON5);Le.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return qe.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Le.readFileSync(t,"utf-8");return Pg("sha256").update(r).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let r=this.computeFileHash(t);r&&this.contentHashes.set(t,r);let i=Le.watch(t,o=>{o==="change"&&this.onFileChanged(t)});i.on("error",o=>{d.error(`[ConfigFileWatcher] Watch error for ${t}: ${o.message}`)}),this.watchers.set(t,i)}catch(r){d.error(`[ConfigFileWatcher] Failed to watch ${t}: ${r instanceof Error?r.message:String(r)}`)}}unwatchFile(t){let r=this.watchers.get(t);r&&(r.close(),this.watchers.delete(t)),this.contentHashes.delete(t);let i=this.debounceTimers.get(t);i&&(clearTimeout(i),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.computeFileHash(t);if(!o){d.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===o){d.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,o),d.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:qe.basename(t),relativePath:qe.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,i)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),d.info("[ConfigFileWatcher] All watchers stopped")}};import*as Ge from"fs";import*as Se from"path";import{createHash as Dg}from"crypto";import{EventEmitter as Ig}from"events";var Jr=class extends Ig{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=Se.join(t,wn)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!Ge.existsSync(this.depMapDir)){d.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=Ge.watch(this.depMapDir,{recursive:!0},(t,r)=>this.onDirEvent(t,r)),this.dirWatcher.on("error",t=>{d.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){d.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),d.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return j(Se.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let i=r.replace(/\\/g,"/"),o;if(i===T.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===lt)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=Se.join(this.depMapDir,r);Ge.existsSync(s)&&this.scheduleDebouncedFullScan()}stop(){this.dirWatcher&&(this.dirWatcher.close(),this.dirWatcher=null),this.fullScanTimer&&(clearTimeout(this.fullScanTimer),this.fullScanTimer=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.coalesceTimer&&(clearTimeout(this.coalesceTimer),this.coalesceTimer=null),this.pendingTags=[],this.pendingRenames=[],this.contentHashes.clear(),this.initialScanDone=!1,d.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=Se.join(this.depMapDir,T.OH_PACKAGE_JSON5),r=Se.join(this.depMapDir,lt),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...i.map(s=>({path:Se.join(this.depMapDir,s.name,T.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!Ge.existsSync(s))continue;let c=this.canonicalPath(s),l=this.computeFileHash(s);if(!l)continue;let u=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,l);continue}u!==l&&(this.contentHashes.set(c,l),d.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=Se.join(this.depMapDir,lt);try{let r=ae(t);if(typeof r!="object"||r===null)return[];let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return d.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${r instanceof Error?r.message:String(r)}`),[]}}scheduleCoalescedReload(t){this.pendingTags.push(t),t==="dep-map-json"&&this.applyDepMapJsonDiff(),this.coalesceTimer&&clearTimeout(this.coalesceTimer),this.coalesceTimer=setTimeout(()=>{this.coalesceTimer=null,this.flushPendingReload()},this.coalesceMs)}collectPendingState(){let t=this.pendingTags,r=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:r}}processTagsIntoSets(t,r,i,o){for(let s of t)s.startsWith("module:")?(i.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(i.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(o.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,i,o,s){for(let a of t)s.push(a.info),i.add(a.info.newName),o.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let i=new Set;for(let o of t)o.startsWith("dep-added:")&&i.add(o.substring(10));for(let o of r)i.add(o.info.newName);return i}emitIncrementalReload(t,r,i,o,s){d.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...i].join(",")}], added=[${[...o].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...i],addedModuleNames:[...o],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:r}=this.collectPendingState();if(t.length===0&&r.length===0)return;if(d.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${r.length}`),t.includes("root-oh-package")){d.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let i=new Set,o=new Set,s=new Set,a=[];this.processTagsIntoSets(t,i,o,s),this.processRenameEntries(r,i,o,s,a);for(let l of o)s.delete(l);if(o.size===0&&s.size===0&&a.length===0){d.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(i,o,s,c,a)}normalizeSrcPath(t){return j(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(o=>[o.name,o])),i=new Map(t.map(o=>[this.normalizeSrcPath(o.srcPath),o]));return{byName:r,bySrcPath:i}}detectModuleRenames(t,r,i,o){for(let[s,a]of t){let c=r.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),i.add(a.name),o.add(c.name);let l=Se.join(this.depMapDir,a.name,T.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(l)),d.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,r,i,o){for(let[s,a]of t){if(i.has(s))continue;let c=r.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),i.add(s),o.add(s),d.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,i){for(let[o]of t)i.has(o)||r.has(o)||(this.pendingTags.push(`dep-added:${o}`),i.add(o))}detectRemovedModules(t,r,i){for(let[o]of t)if(!i.has(o)&&!r.has(o)){this.pendingTags.push(`dep-removed:${o}`),i.add(o);let s=Se.join(this.depMapDir,o,T.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(i=>i.startsWith("dep-")),r=this.pendingRenames.map(i=>`${i.kind}(${i.info.oldName}\u2192${i.info.newName})`);d.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:i}=this.buildModuleLookupMaps(this.lastModules),{byName:o,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(i,s,a,c),this.detectModuleMoves(r,o,a,c),this.detectAddedModules(o,r,c),this.detectRemovedModules(r,o,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=Ge.readFileSync(t,"utf-8");return Dg("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as Ag}from"child_process";import*as Xr from"path";import*as Zr from"fs";var xg=600*1e3;function Tg(n,e,t){let r=t.split(/\s+/).filter(i=>i.length>0);return[n,[e,...r]]}function kg(n){let e=[],t=[];return n.stdout?.on("data",r=>{e.push(r.toString())}),n.stderr?.on("data",r=>{t.push(r.toString())}),{stdout:e,stderr:t}}function Kr(n){return n.join("")}function Rg(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
1267
|
-
Output so far:
|
|
1268
|
-
`+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function Mg(n,e,t){return new Promise(r=>{let i=Ag(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:o,stderr:s}=kg(i),a=setTimeout(()=>{i.kill();let c=[Kr(o),Kr(s)].filter(Boolean).join(`
|
|
1269
|
-
`).trim();r({success:!1,output:`Build process timeout after 10 minutes.
|
|
1270
|
-
Output so far:
|
|
1271
|
-
`+c,exitCode:-1})},xg);i.on("close",(c,l)=>{clearTimeout(a);let u=[Kr(o),Kr(s)].filter(Boolean).join(`
|
|
1272
|
-
`).trim()||"";r(Rg(c,l,u))}),i.on("error",c=>{clearTimeout(a),r({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function Mo(n,e,t,r,i){let o={...process.env,DEVECO_SDK_HOME:r},s=Tg(e,t,i);return await Mg(s,n,o)}function Og(n){let e=Xr.join(Xr.dirname(n),"tools","hvigor","bin","hvigorw.js");return{node_path:yr(n),hvigor_path:e,sdk_path:n}}function Lg(n){return!n.node_path||!Zr.existsSync(n.node_path)?`Node path not found or invalid: ${n.node_path}`:!n.hvigor_path||!Zr.existsSync(n.hvigor_path)?`Hvigor path not found or invalid: ${n.hvigor_path}`:!n.sdk_path||!Zr.existsSync(n.sdk_path)?`SDK path not found or invalid: ${n.sdk_path}`:null}var Ng="--sync -p product=default --analyze=normal --parallel --incremental --no-daemon";async function fl(n,e){try{let t=Og(e),r=Lg(t);return r!=null?(d.info(`Config validation failed: ${r}`),!1):(await Mo(n,t.node_path,t.hvigor_path,e,Ng)).success}catch(t){return d.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}import{spawn as _g}from"child_process";import*as Oo from"fs";import*as Cn from"path";var Hg=["install","--all"];function Fg(n){let e=n.replace(/sdk\/?$/i,"tools"),t=Cn.join(e,"ohpm","bin","pm-cli.js");if(Oo.existsSync(t))return t;let r=n.toLowerCase().endsWith("sdk")?Cn.dirname(n):n;return t=Cn.join(r,"ohpm","bin","pm-cli.js"),Oo.existsSync(t)?t:null}async function jg(n,e,t,r){return new Promise(i=>{let o=_g(n,[e,...Hg],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";o.stdout?.on("data",c=>{s+=c.toString()}),o.stderr?.on("data",c=>{a+=c.toString()}),o.on("close",c=>{let l=[s,a].filter(Boolean).join(`
|
|
1266
|
+
`);if(r===-1)break;let o=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!o){f.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(o[1],10),a=r+4,c=a+s;if(this.buffer.length<c)break;let l=this.buffer.slice(a,c).toString("utf8"),d=this.recoverFramedJson(l);if(d&&d.rest.length>0){f.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${l.length}, restLen=${d.rest.length}`),this.emit("message",d.json),this.buffer=Buffer.concat([Buffer.from(d.rest,"utf8"),this.buffer.slice(c)]);continue}this.emit("message",l),this.buffer=this.buffer.slice(c)}}waitForExitOrTimeout(t){let r=this.process;return!r||r.exitCode!==null||r.signalCode!==null?Promise.resolve():new Promise(i=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(c),r.off("exit",a),i())},a=()=>s();r.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let r=t.search(/\S/);if(r<0||t[r]!=="{"&&t[r]!=="[")return null;let i=0,o=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(o=!1);continue}if(c==='"'){o=!0;continue}if(c==="{"||c==="["){i++;continue}if((c==="}"||c==="]")&&(i--,i===0)){let l=t.slice(r,a+1),d=t.slice(a+1);return{json:l,rest:d}}}return null}stop(){this.isClosing=!0;let t=this.process;if(!t)return;if(this.process=null,t.exitCode===null&&t.signalCode===null)try{t.kill()}catch{}}};var $t=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,r){return new Promise((i,o)=>{let s;r>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),o(new Error(`LSP request '${t}' (id=${e}) timeout after ${r}ms`))},r),this.timeouts.set(e,s)),this.pending.set(e,{resolve:i,reject:o,method:t,timer:s})})}resolvePending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.resolve(t),this.pending.delete(e),!0):!1}rejectPending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.reject(t),this.pending.delete(e),!0):!1}register(e,t){this.callbacks.set(e,t)}emit(e,t,r){f.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let i=this.callbacks.get(e);if(i)i(t,r),this.callbacks.delete(e);else{let o=[...this.callbacks.keys()].map(s=>String(s));f.info(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${o.join(",")}]`)}}registerTimeout(e,t,r,i){let o=this.timeouts.get(e);o&&clearTimeout(o);let s=setTimeout(()=>{f.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`),i(),this.timeouts.delete(e)},r);this.timeouts.set(e,s)}clearTimeout(e){let t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e))}deleteCallback(e){this.callbacks.delete(e)}hasCallback(e){return this.callbacks.has(e)||this.pending.has(e)}clear(e){this.clearTimeout(e);let t=this.pending.get(e);t&&(t.reject(new Error(`Request '${t.method}' (id=${e}) cancelled`)),this.pending.delete(e)),this.callbacks.delete(e)}rejectAll(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear();for(let[,t]of this.timeouts)clearTimeout(t);this.timeouts.clear(),this.callbacks.clear()}};var os=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var Zn=class{map=new Map;register(e,t){let r=this.map.get(e);r||(r=new Set,this.map.set(e,r)),r.add(t)}unregister(e,t){let r=this.map.get(e);r&&(t!==void 0?r.delete(t):r.clear(),r.size===0&&this.map.delete(e))}invoke(e,...t){let r=this.map.get(e);if(r)for(let i of r)try{i(...t)}catch(o){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,o)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function A(n){return typeof n=="object"&&n!==null}var zf=20*1e3,bP=30*1e3,ss=class{client;nextRequestId=1;stopOnce=null;callbacks=new Zn;requestCallbacks=new $t;diagnosticMap=new Map;initProgressReset=null;constructor(e){this.client=new Ht(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{f.info("[ClientMessageHandle] Sending shutdown request"),this.client.sendRequest(y.SHUTDOWN,null,this.nextRequestId++),f.info("[ClientMessageHandle] Sending exit notification"),this.client.sendNotification(y.EXIT,null),f.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),f.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(y.BROADCAST),this.callbacks.register(y.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(y.BROADCAST,e)}async sendInitialize(e){let t=this.nextRequestId++,r=this.requestCallbacks.registerPending(t,y.INITIALIZE,Oe);return this.client.sendRequest(y.INITIALIZE,e,t),r}sendInitializeResettable(e,t){let r=this.nextRequestId++,i=this.requestCallbacks.registerPending(r,y.INITIALIZE,0);return this.client.sendRequest(y.INITIALIZE,e,r),new Promise((o,s)=>{let a,c=()=>{a=setTimeout(()=>{this.initProgressReset=null,s(new Error(`LSP initialization timeout after ${t}ms`))},t)},l=()=>{clearTimeout(a),c()};this.initProgressReset=l,c(),i.then(()=>{clearTimeout(a),this.initProgressReset=null,o()},d=>{clearTimeout(a),this.initProgressReset=null,s(d)})})}sendInitialized(){this.client.sendNotification(y.INITIALIZED,{})}sendDidOpen(e){let t=e.textDocument.uri;this.diagnosticMap.has(t)||(this.diagnosticMap.set(t,new os(t)),this.registerDiagnosticTimeout(t)),this.client.sendNotification(y.DID_OPEN,e)}sendDidChange(e){let t=e.textDocument.uri,r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t)),this.client.sendNotification(y.DID_CHANGE,e)}closeFile(e){this.cleanupDiagnosticState(e.textDocument.uri),this.client.sendNotification(y.DID_CLOSE,e)}sendLspRequest(e,t,r=bP){let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}onDidChangeWatchedFiles(e){e.length!==0&&this.client.sendNotification(y.WORKSPACE_DID_CHANGE_WATCHED_FILES,{changes:e})}sendDidChangeConfiguration(e){this.client.sendNotification(y.WORKSPACE_DID_CHANGE_CONFIGURATION,{settings:e})}sendNotification(e,t){this.client.sendNotification(e,t)}getDiagnosticMessages(e){let t=this.diagnosticMap.get(e);return t?t.get():[]}clearDiagnostic(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let i=r instanceof Error?r.message:String(r);f.error(`[LSP] JSON parse error: ${i}, raw: ${e}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotificationOrRequest(t):f.warn(`[LSP] Unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t===void 0)return;let r=t;if(e.error){let i=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(r,i)}else this.requestCallbacks.resolvePending(r,e.result)}handleNotificationOrRequest(e){let t=e.method;if(t)switch(this.initProgressReset?.(),t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.handleProgress(e.params);break;case y.WINDOW_SHOW_MESSAGE:f.info(`[LSP] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:f.info(`[LSP] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.broadcastToClients(e)}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=e.uri,r=this.diagnosticMap.get(t);if(!r)return;let i=e.diagnostics||[];this.normalizeDiagnostics(i),r.set(i),this.finalizeDiagnostic(t,i)}normalizeDiagnostics(e){for(let t of e)if(t.severity!==void 0){let r={1:"Error",2:"Warning",3:"Information",4:"Hint"};t.severityStr=r[t.severity]||"Unknown"}}handleProgress(e){A(e)&&this.broadcastToClients({jsonrpc:R,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,zf,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${zf}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,r){let i={uri:e,diagnostics:t,...r?{errorMessage:r}:{}};this.requestCallbacks.emit(e,y.PUBLISH_DIAGNOSTICS,i),this.diagnosticMap.get(e)?.clear()}handleError(e){let t=Array.from(this.diagnosticMap.keys()).filter(r=>this.requestCallbacks.hasCallback(r));if(t.length>0){let r={range:{start:{line:0,character:0},end:{line:0,character:0}},severity:1,message:e.message};for(let i of t)this.finalizeDiagnostic(i,[r]);return}this.broadcastToClients({jsonrpc:R,method:y.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var as=class{uri;messages=[];receivedTypes=new Set;uniqueMessages=new Set;isFromEditor=!1;constructor(e){this.uri=e}setReceivedType(e){this.receivedTypes.add(e)}addMessage(e,t){this.receivedTypes.add(e);let r=`${e}:${t}`;if(this.uniqueMessages.has(r)){f.info(`[LegacyDiagnostic] addMessage: duplicate message=${r}`);return}this.uniqueMessages.add(r),this.messages.push(new Jc(e,t))}clearMessages(){this.messages=[]}clear(){this.receivedTypes.clear(),this.uniqueMessages.clear(),this.messages=[]}hasReceivedAllTypes(e){for(let t of e)if(!this.receivedTypes.has(t))return!1;return!0}getMessages(){return this.messages.map(e=>e.diagnostics)}},Jc=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var EP={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"},PP={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing"},T={...EP,...PP},Ut={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"},Vf=new Set([1e3,2e3,3e3,3001]);function CP(n){if(!A(n))return!1;let e=n.textDocument;return A(e)&&typeof e.uri=="string"}function IP(n){return A(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function AP(n){return A(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 cs=class n{client;isInitialized=!1;stopOnce=null;callbacks=new Zn;requestCallbacks=new $t;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;constructor(e){this.client=new Ht(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{f.info("[LegacyClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:T.EXIT,params:{}}),Ut.EXIT),f.info("[LegacyClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),f.info("[LegacyClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(T.BROADCAST),this.callbacks.register(T.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(T.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(T.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(T.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:R,method:T.INITIALIZED,params:{editors:e}}),Ut.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:R,id:0,result:{}}),Ut.EMPTY)}sendAsyncRequest(e,t,r,i){if(!A(t)){f.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!CP(t)){f.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof r!="number"){f.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(r)}`);return}let o=t.textDocument.uri,s=Ke(o);t.textDocument.uri=s,delete t.requestId;let a=i??e;f.info(`[LSP] sendAsyncRequest ${a}, filePath: ${o}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:e,params:{params:t,requestId:r}}),a)}onDidChangeWatchedFiles(e){if(f.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let r of e){if(!IP(r)){f.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:R,method:T.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),T.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!A(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){f.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;f.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:T.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),Ut.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let i=Ke(t);e.textDocument.uri=i,f.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new as(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,T.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:T.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),Ut.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=Ke(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,T.PUBLISH_DIAGNOSTICS)),f.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:T.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),Ut.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=Ke(e);f.info(`[LSP] didClose, uri: ${r}`);let i=this.diagnosticMap.get(r);if(!t&&(!i||i.isFromEditor)){f.info(`[LSP] closeFile skip, !diagnostic: ${!i}, isFromEditor: ${i?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:T.DID_CLOSE,params:{textDocument:{uri:r}}}),Ut.DID_CLOSE)}getDiagnosticMessage(e){let t=Ke(e),r=this.diagnosticMap.get(t);return r?r.getMessages():[]}clear(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){try{let t=JSON.parse(e);this.handleLspMessage(t)}catch(t){let r=t instanceof Error?t.message:String(t);f.error(`[LSP] JSON parse error: ${r}, raw: ${e}`)}}handleError(e){let t=this.getPendingDiagnosticUris();if(t.length>0){let r=JSON.stringify({message:e.message,severity:"Error",severityStr:"Error"});for(let i of t)this.finalizeDiagnostic(i,T.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:R,method:T.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 T.MODULE_INIT_FINISH:return f.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(T.MODULE_INIT_FINISH),this.callbacks.unregister(T.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case T.INDEXING_PROGRESS_UPDATE:return f.info(`[LSP] onIndexingProgressUpdate: ${AP(t.params)}`),this.callbacks.invoke(T.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case T.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case T.ON_PACKAGE_CHANGE_FINISH:f.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case T.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case T.ON_ASYNC_HOVER:this.handleAsyncResponse(t,T.HOVER);return;case T.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,T.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case T.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,T.REFERENCES);return;default:f.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){f.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;A(t)&&A(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){f.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,r={jsonrpc:R,method:T.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){f.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(r);return}if(!(t.length>0&&t[0]===!0)){f.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(r);return}f.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){f.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let r=e.params;if(!A(r)){f.warn("[LSP] aceProject/onAsyncHover message invalid");return}let i=r.requestId;if(typeof i!="number"){f.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(i,t,r)}handleForceOpenFile(e){if(!e){f.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,T.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){f.info("[LSP] publishDiagnostics uri is null");return}let r=e.version??-1;if(r===-1)return;let i=this.diagnosticMap.get(t);if(!i){f.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let o=e.diagnostics||[];o.length!==0?o.forEach(s=>{this.normalizeDiagnostic(s),i.addMessage(r,JSON.stringify(s))}):i.setReceivedType(r),i.hasReceivedAllTypes(Vf)&&this.finalizeDiagnostic(t,T.PUBLISH_DIAGNOSTICS,i.getMessages())}normalizeDiagnostic(e){let t=e;if(delete t.source,t.severity!==void 0){let r=typeof t.severity=="number"?t.severity:parseInt(t.severity),o={1:"Error",2:"Warning",3:"Information",4:"Hint"}[r]||"Unknown";t.severityStr=o,t.severity=o}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let r=e[t];r&&typeof r.line=="number"&&(r.line=r.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,n.DIAGNOSTIC_TIMEOUT_MS,()=>{let r=this.diagnosticMap.get(e),i=r?r.getMessages():[];this.finalizeDiagnostic(e,t,i,i.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,i){let o={uri:e,diagnostics:r,...i?{errorMessage:i}:{}};this.requestCallbacks.emit(e,t,o),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import gi from"path";import*as hs from"path";var ls=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var ds=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var us=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var ps=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var fs=class{typeSetting=new us;parameterNames=new ps};var ms=class{constructor(e,t,r,i){this.rootUri=e;this.lspServerWorkspacePath=H(hs.dirname(t)),this.indexingDataLocation=H(i),this.loggerPath=H(hs.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new ls;gutterIconsSetting=new ds;inlayHintsSetting=new fs;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as qf from"path";var ui=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(H(qf.join(e,"src","main","resources")))}};var DP="OS",Qn=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${DP}`;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 ui(e)):this.buildProfileParam=new ui}toString(){return JSON.stringify(this)}};var er=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as $e from"path";import*as rr from"fs";var gs=class{modulePath;dependencies={};dynamicDependencies={}};var vn=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 tr=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 bt from"path";import*as ys from"fs";var nr=class{name="";version="";storePath="";dependencyPath="";path=""};var O={HVIGOR_CACHE:".hvigor",DEPENDENCY:"dependencyMap",JSON5:".json5",KEY_DEPENDENCY:"dependencies",KEY_DYNAMIC_DEPENDENCY:"dynamicDependencies",KEY_DEV_DEPENDENCY:"devDependencies",OH_MODULES_PATH:"oh_modules",OHPM_PATH:".ohpm",LOCK_JSON5_FILE:"lock.json5",OH_PACKAGE_JSON5:Ye.OH_PACKAGE_JSON5},pi=`${O.HVIGOR_CACHE}/${O.DEPENDENCY}`,Sn=`${O.DEPENDENCY}${O.JSON5}`,L0=Ye.SYNC_OUTPUT_PATH;var fi=class n{dependencyPath;modulePath;projectPath;static FILE_DEPENDENCY_PREFIX="file:";static PARAMETER_PREFIX="@param:";fileSpecPattern;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;static PACKAGE_JSON_PARSER_MAP=new Map;dependencies=[];devDependencies=[];dynamicDependencies=[];static getInstance(e,t,r){let i=this.PACKAGE_JSON_PARSER_MAP.get(e);return i||(i=new n(e,t,r),this.PACKAGE_JSON_PARSER_MAP.set(e,i)),i}constructor(e,t,r){this.dependencyPath=e,this.modulePath=t,this.projectPath=r,this.fileSpecPattern=n.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=bt.join(this.dependencyPath,O.OH_PACKAGE_JSON5),r=Re(t);r&&(this.dependencies=this.getDependencyList(r,O.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(r,O.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(r,O.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let r=[];if(!A(e))return r;let i=e[t];if(!A(i))return r;for(let[o,s]of Object.entries(i)){if(typeof s!="string"){f.error(`${o} package dependency value is not String ${t}`);continue}let a=new nr;a.name=o;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(n.PARAMETER_PREFIX)||this.parseDependencyPath(o,c,a,!1),r.push(a)}return r}parseDependencyPath(e,t,r,i){if(!(!e||!t))try{let o=bt.normalize(bt.join(this.modulePath,O.OH_MODULES_PATH,e));if(!(t.startsWith(n.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){r.dependencyPath=o;return}if(r.path=t,this.fileNameForOhpm.test(t)){r.dependencyPath=o;return}let s=t;if(t.startsWith(n.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(n.FILE_DEPENDENCY_PREFIX.length)),bt.isAbsolute(s)){r.dependencyPath=o;return}if(!i){let a=bt.resolve(this.modulePath,s);o=P.ensurePathWithinRoot(this.projectPath,a)}ys.existsSync(o)&&ys.statSync(o).isDirectory()&&(r.dependencyPath=o)}catch(o){f.error("parser dependency path is invalid",o)}}};import*as mi from"fs";import*as hi from"path";import RP from"json5";var ws=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 hi.join(this.projectPath,O.OH_MODULES_PATH,O.OHPM_PATH,O.LOCK_JSON5_FILE)}readLockFile(e){if(!mi.existsSync(e))return f.error("lock file does not exist"),this.clearDependencies(),null;try{let t=mi.readFileSync(e,"utf8"),r=RP.parse(t);return r||(f.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return f.error("Error parsing lock.json5:",t),this.clearDependencies(),null}}validateLockFile(e){if(!A(e))return f.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return f.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let r=e.packages;return r?{valid:!0,modules:t,packages:r}:(f.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,r){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,O.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,O.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,O.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!A(e))return t;for(let[r,i]of Object.entries(e)){if(!A(i)){f.error(`${r} value is not json object`);continue}typeof i.storePath=="string"&&t.set(r,i.storePath)}return t}getDependencyList(e,t,r){if(!A(e))return[];for(let[i,o]of Object.entries(e))if(A(o)){let s=typeof o.name=="string"?o.name:"";if(r==="."&&s===""||s===r)return this.getFinalDependencyList(e,t,i)}return[]}getFinalDependencyList(e,t,r){let i=e[r];if(!A(i))return f.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!A(s))return[];for(let[a,c]of Object.entries(s)){if(!A(c))continue;let l=typeof c.specifier=="string"?c.specifier:"",d=typeof c.version=="string"?c.version:"",h=new nr;h.name=a,h.version=d.startsWith(n.FILE_DEPENDENCY_PREFIX)?d.substring(n.FILE_DEPENDENCY_PREFIX.length):d,this.parseDependencyPath(h,r,a,l,d);let w=`${a}@${d}`;this.storePathMap.has(w)&&(h.storePath=this.storePathMap.get(w)||""),o.push(h)}return o}parseDependencyPath(e,t,r,i,o){let s=P.resolvePathWithinRoot(this.projectPath,hi.join(t,O.OH_MODULES_PATH,r));try{let a=o.startsWith(n.FILE_DEPENDENCY_PREFIX)?o.substring(n.FILE_DEPENDENCY_PREFIX.length):o,c=hi.isAbsolute(a)?P.ensurePathWithinRoot(this.projectPath,a):P.resolvePathWithinRoot(this.projectPath,a);mi.existsSync(c)?(e.path=i,e.dependencyPath=this.fileNameForOhpm.test(o)?s:c):e.dependencyPath=s}catch(a){f.error("Invalid dependency path in lock.json5",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function Yf(n){return A(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var bn=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new gt(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=$e.join(t,pi),i=$e.join(r,Sn);if(!rr.existsSync(r)||!rr.existsSync(i)){let c="Dependency map or JSON not found";return f.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let o=new tr(this.projectPath,".",this.projectPath);this.parseProjectDependencies(r,o),this.parseLockJson(o);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return f.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:c}}let a=Date.now();for(let c=0;c<s.length;c++){let l=s[c];Yf(l)&&(this.parseSingleModule(l,r,o,e),(c+1)%100===0&&f.info(`[Parser] getAllDependencyMap progress: ${c+1}/${s.length} (${Date.now()-a}ms)`))}return f.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-a}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],r=this.projectPath,i=$e.join(r,pi),o=$e.join(i,Sn);if(!rr.existsSync(i)||!rr.existsSync(o))return f.warn("[Parser] Dependency map or JSON not found."),t;let s=e&&e.length>0?new Set(e.map(l=>l.trim()).filter(Boolean)):null,a=new tr(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return f.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let l of c){if(!Yf(l))continue;let d=l.name;if(s&&!s.has(d))continue;let h=P.resolvePathWithinRoot(this.projectPath,l.srcPath),w=$e.join(i,d),b=H(h),L=this.buildModuleDependencies(d,b,w,a);L.moduleName=d,t.push(L)}return t}parseSingleModule(e,t,r,i){let o=e.name,s=P.resolvePathWithinRoot(this.projectPath,e.srcPath),a=$e.join(t,o),c=H(s),l=new Qn(c),d=this.buildModuleDependencies(o,c,a,r);this.parseModuleJson5(c,l);let h=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=o,l.moduleType=o,l.packageName=o,l.moduleDependencies=d,l.moduleJsonParam=new er(h),i.push(l)}buildModuleDependencies(e,t,r,i){let o=new tr(this.projectPath,e,t);fi.getInstance(r,t,this.projectPath).parseDependency(o),this.parseLockJson(o),o.finalDependencies.push(...i.finalDependencies),o.finalDevDependencies.push(...i.finalDevDependencies),o.finalDynamicDependencies.push(...i.finalDynamicDependencies),o.finalDependencies.push(...o.finalDevDependencies);let a=new gs;return a.modulePath=t,this.toModuleDependencies(o,a),a}toModuleDependencies(e,t){let r={},i={};for(let o of e.finalDependencies)r[o.name]=new vn(o);for(let o of e.finalDynamicDependencies)i[o.name]=new vn(o);t.dependencies=r,t.dynamicDependencies=i}parseProjectDependencies(e,t){let r=$e.join(e,O.OH_PACKAGE_JSON5);if(!rr.existsSync(r))return;fi.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 ws(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=$e.join(e,"src","main","module.json5"),i=Re(r);if(!A(i)||!A(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(A(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)A(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=$e.join(e,"src","main","resources","base","profile","main_pages.json"),r=Re(t);return!A(r)||!Array.isArray(r.src)?[]:r.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!A(t)||!A(t.data))){if(typeof t.data.apiVersion=="string"){let r=parseInt(t.data.apiVersion,10);!Number.isNaN(r)&&r>=26&&typeof t.data.platformVersion=="string"?e.compileSdkLevel=t.data.platformVersion:e.compileSdkLevel=t.data.apiVersion}typeof t.data.releaseType=="string"&&(e.compileSdkType=t.data.releaseType),typeof t.data.version=="string"&&(e.compileSdkVersion=t.data.version)}}getSdkPkg(){if(this.sdkPkgCache===void 0){let e=$e.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=Re(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!A(t)||!A(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!A(r)||typeof r.compatibleSdkVersion!="string")return;let[i,o]=this.parseBySplit(r.compatibleSdkVersion);e.compatibleSdkVersion=i,e.compatibleSdkLevel=o}getBuildProfile(){if(this.buildProfileCache===void 0){let e=$e.join(this.projectPath,"build-profile.json5");this.buildProfileCache=Re(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,e];let r=e.substring(0,t),i=e.substring(t+1,e.length-1);return[r,i]}parseDeviceTypes(e){return!A(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 vs=class{constructor(e=[]){this.valueSet=e}valueSet};var ir=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Jf=(E=>(E[E.File=1]="File",E[E.Module=2]="Module",E[E.Namespace=3]="Namespace",E[E.Package=4]="Package",E[E.Class=5]="Class",E[E.Method=6]="Method",E[E.Property=7]="Property",E[E.Field=8]="Field",E[E.Constructor=9]="Constructor",E[E.Enum=10]="Enum",E[E.Interface=11]="Interface",E[E.Function=12]="Function",E[E.Variable=13]="Variable",E[E.Constant=14]="Constant",E[E.String=15]="String",E[E.Number=16]="Number",E[E.Boolean=17]="Boolean",E[E.Array=18]="Array",E[E.Object=19]="Object",E[E.Key=20]="Key",E[E.Null=21]="Null",E[E.EnumMember=22]="EnumMember",E[E.Struct=23]="Struct",E[E.Event=24]="Event",E[E.Operator=25]="Operator",E[E.TypeParameter=26]="TypeParameter",E))(Jf||{}),Kf=()=>Object.values(Jf).filter(n=>typeof n=="number");var Ss=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var bs=class{applyEdit=!0;workspaceEdit=new Ss;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new vs(Kf());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new ir;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Es=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Ps=class{constructor(e=[]){this.valueSet=e}valueSet};var Cs=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var Xf=(C=>(C[C.Text=1]="Text",C[C.Method=2]="Method",C[C.Function=3]="Function",C[C.Constructor=4]="Constructor",C[C.Field=5]="Field",C[C.Variable=6]="Variable",C[C.Class=7]="Class",C[C.Interface=8]="Interface",C[C.Module=9]="Module",C[C.Property=10]="Property",C[C.Unit=11]="Unit",C[C.Value=12]="Value",C[C.Enum=13]="Enum",C[C.Keyword=14]="Keyword",C[C.Snippet=15]="Snippet",C[C.Color=16]="Color",C[C.File=17]="File",C[C.Reference=18]="Reference",C[C.Folder=19]="Folder",C[C.EnumMember=20]="EnumMember",C[C.Constant=21]="Constant",C[C.Struct=22]="Struct",C[C.Event=23]="Event",C[C.Operator=24]="Operator",C[C.TypeParameter=25]="TypeParameter",C))(Xf||{}),Zf=()=>Object.values(Xf).filter(n=>typeof n=="number");var Is=class{completionItemKind=new Ps(Zf());completionItem=new Cs;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var As=class{synchronization=new Es;completion=new Is;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 ir;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var Ds=class{workspace=new bs;textDocument=new As;notebookDocument=null;window=null;general=null;experimental=null};var Rs=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var Ts=class{constructor(e,t,r,i,o,s=!0){this.sdkPath=e;this.rootUri=r;this.nodeMaxOldSpaceSize=o;this.useStandardProtocol=s;this.serverPath=this.useStandardProtocol?gi.resolve(t,"ace-server","out","standardIndex","index.js"):gi.resolve(t,"ace-server","out","index.js"),this.logPath=pu(),this.indexLogPath=i||this.logPath;let a={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath};this.messageHandle=this.useStandardProtocol?new ss(a):new cs(a),this.messageHandle.setBroadcastToClients(c=>this.onLspMessage(c))}sdkPath;rootUri;nodeMaxOldSpaceSize;useStandardProtocol;messageHandle;get stdHandle(){return this.messageHandle}get legacyHandle(){return this.messageHandle}onAsyncOpenFile(e){this.legacyHandle.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.legacyHandle.closeFile(e,t)}serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}async start(e,t){let r=!1;try{f.info(`serverPath: ${this.serverPath}`),f.info(`rootUri: ${this.rootUri}`),f.info(`sdkPath: ${this.sdkPath}`),f.info(`logPath: ${this.logPath}`);let i=Ke(this.rootUri),o=new ms(i,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new bn(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),o.modules=s;let l=Eo(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new Rs(i,o,new Ds),this.useStandardProtocol){let d=this.messageHandle;await d.sendInitializeResettable(this.currentParams,Oe),f.info("[LSP] initialize response received"),d.broadcastToClients({jsonrpc:R,method:y.ARKTS_INDEXING_PROGRESS,params:{}}),d.sendInitialized()}else await this.startLegacy(this.currentParams,e);r=!0}catch(i){this.lastStartErrorMessage=i instanceof Error?i.message:String(i),f.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(r)}async startLegacy(e,t){let r=this.messageHandle;r.sendInitialize(e,1),r.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:R,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((i,o)=>{r.onIndexingProgressUpdate(o),r.onInitializationCompleted(i)},"LSP initialization",Oe),r.sendInitialized(t)}withResettableTimeout(e,t,r){return new Promise((i,o)=>{let s,a=()=>{s=setTimeout(()=>{o(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),i()},c)})}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){f.info(`[LSP] registerDiagnosticCallback uri='${e}', useStandardProtocol=${this.useStandardProtocol}`),this.messageHandle.registerRequestCallback(e,(t,r)=>{let i=A(r)?r:{};f.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let o={jsonrpc:R,method:t,params:{uri:typeof i.uri=="string"?i.uri:e,diagnostics:Array.isArray(i.diagnostics)?i.diagnostics:[],...typeof i.errorMessage=="string"?{errorMessage:i.errorMessage}:{}}};this.onLspMessage(o)})}async hover(e){let t=e.textDocument.uri;return this.registerDiagnosticCallback(t),this.stdHandle.sendLspRequest(y.HOVER,e)}async definition(e){return this.stdHandle.sendLspRequest(y.DEFINITION,e)}async references(e){return this.stdHandle.sendLspRequest(y.REFERENCES,e)}async completion(e){return this.stdHandle.sendLspRequest(y.COMPLETION,e)}async documentSymbol(e){return this.stdHandle.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async diagnostic(e){return this.stdHandle.sendLspRequest(y.DIAGNOSTIC,e,120*1e3)}async sendFeatureRequest(e,t){return this.stdHandle.sendLspRequest(e,t)}reloadDependenciesOnly(e){let t=e?.fullReload??!1,r=new bn(this.rootUri,this.sdkPath),i=this.getModuleModelsByName();if(t){f.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let l=r.getDependenciesOnly();this.markDependencyTypesIncremental(l);let d=this.mergeDepsOnlyIntoModuleList(l,i);return this.applyModuleModelsUpdate(d),this.sendDidChangeConfiguration({moduleSet:d}),f.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${d.length}`),this.lastDepsOnlyForDiff=l,l}let o=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(o.length===0&&s.size===0)return f.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];f.info(`[LspServerProxy] Module-level deps changed, parsing: [${o.join(", ")}]`);let a=r.getDependenciesOnly(o);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),this.sendDidChangeConfiguration({moduleSet:c}),f.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}sendDidChangeConfiguration(e){this.stdHandle.sendDidChangeConfiguration(e)}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),r=new Map(this.lastDepsOnlyForDiff.map(i=>[i.moduleName??"",i]));for(let i of e){let o=i.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(o,t,r),c=i.dependencies??{},l=i.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(d,h)=>{(i.dependencies??={})[d]=this.makeDeleteEntry(d,h)}),this.markAddAndDeleteInDeps(a,l,(d,h)=>{(i.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,h)})}}getOldDepsForModule(e,t,r){let i=t.get(e),o=i?.moduleDependencies?.dependencies??{},s=i?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(o).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(o=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:o,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let i of Object.keys(t))i in e||(t[i].type="add");for(let i of Object.keys(e))i in t||r(i,e[i])}makeDeleteEntry(e,t){return new vn({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Qn(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new er([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let i of e){let o=i.moduleName??"",s=t.get(o);s?(s.modulePath=i.modulePath,s.moduleDependencies=i):s=this.createMinimalModelFromDepsItem(i),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let i=new Map(r.map(s=>[s.moduleName??"",s])),o=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=i.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,i.delete(a)),o.push(s)}for(let[,s]of i)o.push(this.createMinimalModelFromDepsItem(s));return o}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=_n(gi.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=_n(gi.join(t,"default/openharmony/ets/api")),o=_n(gi.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=i,s.hosSdkPath=o}sendRequest(e){switch(e.method){case y.HOVER:this.stdHandle.sendLspRequest(y.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;case y.DEFINITION:this.stdHandle.sendLspRequest(y.DEFINITION,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;case y.REFERENCES:this.stdHandle.sendLspRequest(y.REFERENCES,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;default:f.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!Wf(e)){f.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case y.DID_OPEN:this.handleDidOpenNotification(e);break;case y.DID_CHANGE:this.handleDidChangeNotification(e);break;case y.DID_CLOSE:this.handleDidCloseNotification(e);break;case y.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;case y.DID_CREATE_FILES:this.handleDidCreateFiles(e);break;case y.DID_DELETE_FILES:this.handleDidDeleteFiles(e);break;default:f.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didOpen params");return}this.stdHandle.sendDidOpen(t)}handleDidChangeNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didChange params");return}this.stdHandle.sendDidChange(t)}handleDidCloseNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didClose params");return}this.stdHandle.closeFile(t)}handleDidChangeWatchedFiles(e){let t=e.params;!t||!Array.isArray(t.changes)||this.messageHandle.onDidChangeWatchedFiles(t.changes)}handleDidCreateFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(y.DID_CREATE_FILES,t)}handleDidDeleteFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(y.DID_DELETE_FILES,t)}async dispose(){await this.messageHandle.stop()}};import*as Et from"fs";import*as Bt from"path";import{createHash as kP}from"crypto";import{EventEmitter as xP}from"events";var ks=class extends xP{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r}projectRoot;watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),r=new Set(this.watchers.keys());for(let i of t)r.has(i)||this.watchFile(i);for(let i of r)t.has(i)||(this.unwatchFile(i),f.info(`[ConfigFileWatcher] Stopped watching: ${i}`));f.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!Et.existsSync(t)){f.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Et.watch(t,r=>{r==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",r=>{f.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${r.message}`)}),f.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(r){f.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${r instanceof Error?r.message:String(r)}`)}}emitModuleAddedEvents(t,r){for(let i of t){let o=P.resolvePathWithinRoot(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:o,relativePath:i.srcPath,timestamp:r,moduleName:i.name})}}emitModuleRemovedEvents(t,r){for(let i of t){let o=P.resolvePathWithinRoot(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:o,relativePath:i.srcPath,timestamp:r,removedModuleName:i.name})}}emitModuleRenamedEvents(t,r){for(let i of t){let o=P.resolvePathWithinRoot(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name,removedModuleName:i.before.name})}}emitModuleMovedEvents(t,r){for(let i of t){let o=P.resolvePathWithinRoot(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let r=Date.now();this.emitModuleAddedEvents(t.added,r),this.emitModuleRemovedEvents(t.removed,r),this.emitModuleRenamedEvents(t.renamed,r),this.emitModuleMovedEvents(t.moved,r)}onBuildProfileChanged(){let t="__build_profile__",r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(o);if(s===this.lastModulesSnapshot){f.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,o);this.lastModules=o,this.lastModulesSnapshot=s,f.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,i)}computeModulesSnapshot(t){return t.map(i=>`${i.name}::${i.srcPath}`).sort().join("|")}diffModules(t,r){let i=this.buildModuleMatchState(r),o={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,i),this.matchRenamedModules(t,i,o),this.matchMovedModules(t,i,o),this.collectRemovedModules(t,i,o),this.collectAddedModules(r,i,o),o}buildModuleMatchState(t){let r=new Map,i=new Map;for(let o of t)r.set(o.srcPath,o),i.set(o.name,o);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:i}}matchExactModules(t,r){for(let i of t){let o=r.newBySrc.get(i.srcPath);o&&o.name===i.name&&(r.matchedOld.add(i),r.matchedNew.add(o))}}matchRenamedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newBySrc.get(o.srcPath);s&&!r.matchedNew.has(s)&&s.name!==o.name&&(i.renamed.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}matchMovedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newByName.get(o.name);s&&!r.matchedNew.has(s)&&s.srcPath!==o.srcPath&&(i.moved.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}collectRemovedModules(t,r,i){for(let o of t)r.matchedOld.has(o)||i.removed.push(o)}collectAddedModules(t,r,i){for(let o of t)r.matchedNew.has(o)||i.added.push(o)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=Re(t);if(typeof r!="object"||r===null)return[];let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=Bt.join(this.projectRoot,O.OH_PACKAGE_JSON5);Et.existsSync(r)&&t.push(r);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=P.resolvePathWithinRoot(this.projectRoot,o.srcPath),a=Bt.join(s,O.OH_PACKAGE_JSON5);Et.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Bt.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Et.readFileSync(t,"utf-8");return kP("sha256").update(r).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let r=this.computeFileHash(t);r&&this.contentHashes.set(t,r);let i=Et.watch(t,o=>{o==="change"&&this.onFileChanged(t)});i.on("error",o=>{f.error(`[ConfigFileWatcher] Watch error for ${t}: ${o.message}`)}),this.watchers.set(t,i)}catch(r){f.error(`[ConfigFileWatcher] Failed to watch ${t}: ${r instanceof Error?r.message:String(r)}`)}}unwatchFile(t){let r=this.watchers.get(t);r&&(r.close(),this.watchers.delete(t)),this.contentHashes.delete(t);let i=this.debounceTimers.get(t);i&&(clearTimeout(i),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.computeFileHash(t);if(!o){f.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===o){f.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,o),f.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:Bt.basename(t),relativePath:Bt.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,i)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),f.info("[ConfigFileWatcher] All watchers stopped")}};import*as Wt from"fs";import*as et from"path";import{createHash as NP}from"crypto";import{EventEmitter as LP}from"events";var xs=class extends LP{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=et.join(t,pi)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!Wt.existsSync(this.depMapDir)){f.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=Wt.watch(this.depMapDir,{recursive:!0},(t,r)=>this.onDirEvent(t,r)),this.dirWatcher.on("error",t=>{f.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){f.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),f.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return H(et.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let i=r.replace(/\\/g,"/"),o;if(i===O.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===Sn)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=et.join(this.depMapDir,r);Wt.existsSync(s)&&this.scheduleDebouncedFullScan()}stop(){this.dirWatcher&&(this.dirWatcher.close(),this.dirWatcher=null),this.fullScanTimer&&(clearTimeout(this.fullScanTimer),this.fullScanTimer=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.coalesceTimer&&(clearTimeout(this.coalesceTimer),this.coalesceTimer=null),this.pendingTags=[],this.pendingRenames=[],this.contentHashes.clear(),this.initialScanDone=!1,f.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=et.join(this.depMapDir,O.OH_PACKAGE_JSON5),r=et.join(this.depMapDir,Sn),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...i.map(s=>({path:et.join(this.depMapDir,s.name,O.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!Wt.existsSync(s))continue;let c=this.canonicalPath(s),l=this.computeFileHash(s);if(!l)continue;let d=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,l);continue}d!==l&&(this.contentHashes.set(c,l),f.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=et.join(this.depMapDir,Sn);try{let r=Re(t);if(typeof r!="object"||r===null)return[];let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return f.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${r instanceof Error?r.message:String(r)}`),[]}}scheduleCoalescedReload(t){this.pendingTags.push(t),t==="dep-map-json"&&this.applyDepMapJsonDiff(),this.coalesceTimer&&clearTimeout(this.coalesceTimer),this.coalesceTimer=setTimeout(()=>{this.coalesceTimer=null,this.flushPendingReload()},this.coalesceMs)}collectPendingState(){let t=this.pendingTags,r=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:r}}processTagsIntoSets(t,r,i,o){for(let s of t)s.startsWith("module:")?(i.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(i.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(o.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,i,o,s){for(let a of t)s.push(a.info),i.add(a.info.newName),o.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let i=new Set;for(let o of t)o.startsWith("dep-added:")&&i.add(o.substring(10));for(let o of r)i.add(o.info.newName);return i}emitIncrementalReload(t,r,i,o,s){f.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...i].join(",")}], added=[${[...o].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...i],addedModuleNames:[...o],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:r}=this.collectPendingState();if(t.length===0&&r.length===0)return;if(f.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${r.length}`),t.includes("root-oh-package")){f.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let i=new Set,o=new Set,s=new Set,a=[];this.processTagsIntoSets(t,i,o,s),this.processRenameEntries(r,i,o,s,a);for(let l of o)s.delete(l);if(o.size===0&&s.size===0&&a.length===0){f.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(i,o,s,c,a)}normalizeSrcPath(t){return H(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(o=>[o.name,o])),i=new Map(t.map(o=>[this.normalizeSrcPath(o.srcPath),o]));return{byName:r,bySrcPath:i}}detectModuleRenames(t,r,i,o){for(let[s,a]of t){let c=r.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),i.add(a.name),o.add(c.name);let l=et.join(this.depMapDir,a.name,O.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(l)),f.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,r,i,o){for(let[s,a]of t){if(i.has(s))continue;let c=r.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),i.add(s),o.add(s),f.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,i){for(let[o]of t)i.has(o)||r.has(o)||(this.pendingTags.push(`dep-added:${o}`),i.add(o))}detectRemovedModules(t,r,i){for(let[o]of t)if(!i.has(o)&&!r.has(o)){this.pendingTags.push(`dep-removed:${o}`),i.add(o);let s=et.join(this.depMapDir,o,O.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(i=>i.startsWith("dep-")),r=this.pendingRenames.map(i=>`${i.kind}(${i.info.oldName}\u2192${i.info.newName})`);f.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:i}=this.buildModuleLookupMaps(this.lastModules),{byName:o,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(i,s,a,c),this.detectModuleMoves(r,o,a,c),this.detectAddedModules(o,r,c),this.detectRemovedModules(r,o,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=Wt.readFileSync(t,"utf-8");return NP("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as OP}from"child_process";import*as Kc from"fs";import*as yi from"path";var MP=["install","--all"];function _P(n){let e=n.replace(/sdk\/?$/i,"tools"),t=yi.join(e,"ohpm","bin","pm-cli.js");if(Kc.existsSync(t))return t;let r=n.toLowerCase().endsWith("sdk")?yi.dirname(n):n;return t=yi.join(r,"ohpm","bin","pm-cli.js"),Kc.existsSync(t)?t:null}async function FP(n,e,t,r){return new Promise(i=>{let o=OP(n,[e,...MP],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";o.stdout?.on("data",c=>{s+=c.toString()}),o.stderr?.on("data",c=>{a+=c.toString()}),o.on("close",c=>{let l=[s,a].filter(Boolean).join(`
|
|
1273
1267
|
`);i({exitCode:c??-1,output:l})}),o.on("error",c=>{let l=[s,a].filter(Boolean).join(`
|
|
1274
1268
|
`);i({exitCode:-1,output:l+`
|
|
1275
|
-
`+c.message})})})}function $g(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>d.info("[ohpm] %s",e))}async function gl(n,e){try{let t=yr(e);if(!t)return d.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;let r=Fg(e);if(!r)return d.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:i,output:o}=await jg(t,r,n,e);return $g(o),i===0?(d.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(d.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",i),d.error("ohpm \u8F93\u51FA: %s",o),!1)}catch(t){return d.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var yl={UNINITIALIZED:-32099,UNKNOWN:-32e3},Dn=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,yl.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,yl.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var jt=class{config;lspProxy=null;configWatcher=null;depMapWatcher=null;isInitialized=!1;lastEditorOpenFiles=[];onMessage=()=>{};onConfigChanged=null;disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}async start(e=[]){this.lastEditorOpenFiles=e,this.startConfigWatcher(),this.startLspProxy(e)}sendNotification(e){if(!this.lspProxy){d.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){d.warn("[ArktsLspManager] sendRequest before LSP ready, dropped");return}this.lspProxy.sendRequest(e)}async diagnostic(e){if(!this.lspProxy)throw new Error("[ArktsLspManager] diagnostic before LSP ready");return this.lspProxy.diagnostic(e)}async sendFeatureRequest(e,t){if(!this.useStandardProtocol)throw new Error(`Language feature '${e}' is not supported on the installed DevEco Studio. The standard LSP protocol entry (plugins/openharmony/ace-server/out/standardIndex/index.js) was not found. Please upgrade DevEco Studio to version 26.0.0.610 or later to use this tool.`);if(!this.lspProxy)throw new Error("LSP not ready");return this.lspProxy.sendFeatureRequest(e,t)}get useStandardProtocol(){return this.config.useStandardProtocol}onAsyncOpenFile(e){this.lspProxy?.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.lspProxy?.closeFileLegacy(e,t)}registerDiagnosticCallback(e){this.lspProxy?.registerDiagnosticCallback(e)}static async handleSyncProject(e,t){if(d.info("[ArktsLspManager] Received arkts/syncProject"),!e||!t)return d.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let r=await Ls(e,async()=>await gl(e,t)?await fl(e,t)?(d.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(d.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(d.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return r.acquired?r.result:(d.info("[ArktsLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){try{this.configWatcher?.stop()}catch(e){d.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){d.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){d.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new Vr(this.config.sdkPath,this.config.arktsLangServerPath,this.config.workspaceRoot,this.config.indexLogPath,this.config.nodeMaxOldSpaceSize,this.config.useStandardProtocol);t.setOnMessage(r=>this.handleLspMessage(r)),t.start(e,r=>this.handleLspInitialized(r)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)d.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:A,method:y.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();d.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?Dn.uninitialized(t):Dn.unknown();this.onMessage({jsonrpc:A,method:y.ARKTS_INITIALIZATION_FAILED,params:r.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(d.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:A,method:y.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Yr(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Jr(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){d.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let r=this.lspProxy.reloadDependenciesOnly(e).map(i=>({modulePath:i.modulePath??"",dependencies:i.dependencies??{},dynamicDependencies:i.dynamicDependencies??{}}));this.onMessage({jsonrpc:A,method:y.ARKTS_SYNC_COMPLETED,params:{success:!0,moduleSet:r}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){d.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var Bg=10080*60*1e3,Wg=7200*60*1e3,Ug=120*1e3,$t=class n{manager=null;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;devecoPath;nodeMaxOldSpaceSize;onConfigChangedCallback=null;useStandardProtocol=!0;diagnosticWaiters=new Map;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION,completion:y.COMPLETION,signatureHelp:y.SIGNATURE_HELP,documentHighlight:y.DOCUMENT_HIGHLIGHT};constructor(e,t,r){this.projectPath=e,this.devecoPath=t??"",this.nodeMaxOldSpaceSize=r}setOnConfigChanged(e){this.onConfigChangedCallback=e}static getToolDefinition(){return{name:"check_ets_files",description:"\u5BF9\u4F20\u5165\u7684ets\u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5(ArkTS-Check)\u5E76\u5B9E\u65F6\u8FD4\u56DE\u8BCA\u65AD\u4FE1\u606F\u3002",inputSchema:Lo.object({files:Lo.array(Lo.string()).describe('\u5F85\u68C0\u67E5\u7684 ETS \u6587\u4EF6\u8DEF\u5F84\u5217\u8868\uFF0C\u683C\u5F0F\u4E3A ["file1.ets","file2.ets",...]')})}}isInitializing(){return this.initializing}isInitialized(){return this.initialized}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initializing=!0,this.initPromise=this.doInitialize().then(()=>{this.initialized=!0}).finally(()=>{this.initializing=!1}),await this.initPromise}}async doInitialize(){let{harmonyRoot:e,devecoPath:t,arktsLangServerPath:r,useStandardProtocol:i}=this.resolveProjectAndDeveco();this.useStandardProtocol=i;let o=ue(e),{logPath:s,indexPath:a}=this.getLogAndIndexPath(o);setImmediate(()=>{Ao(a,Bg,"[ArkTS-Check]"),Ao(s,Wg,"[ArkTS-Check]")}),el(s);let c=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,l=Number.isNaN(c)?void 0:c;h.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${l??"undefined \u2192 dynamic formula applies"}`);let u=Y.join(de(t),"sdk");h.info(`ArktsCheck devecoPath: ${t}, contentRoot: ${de(t)}, sdkPath: ${u}`),this.manager=new jt({sdkPath:u,arktsLangServerPath:r,workspaceRoot:j(o),indexLogPath:a,nodeMaxOldSpaceSize:l,useStandardProtocol:i}),this.manager.setOnMessage(f=>this.handleLspMessage(f)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((f,P)=>{this.initResolve=f,this.initReject=P,this.armInitTimer(We),this.manager.start([]).catch(C=>{let L=C instanceof Error?C:new Error(String(C));this.failInit(L)})})}resolveProjectAndDeveco(){let e=Re(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.devecoPath??be();if(h.debug(`DevEco Studio installation path: ${t}, this.devecoPath: ${this.devecoPath}`),!t)throw new Error("DevEco Studio installation path not found");this.devecoPath=t;let r=It(t);if(!r)throw new Error("arkts-lang-server path not found");let i=Y.resolve(r,"ace-server","out","standardIndex","index.js"),o=re.existsSync(i);return h.info(`ArktsCheck protocol: ${o?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${o})`),{harmonyRoot:e,devecoPath:t,arktsLangServerPath:r,useStandardProtocol:o}}armInitTimer(e){this.initDeadlineTimer&&clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=setTimeout(()=>{let t=this.initReject;this.clearInitHandlers(),t?.(new Error("LSP initialize timeout"))},e)}clearInitHandlers(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async checkFile(e){this.initialized||await this.initialize();let t=this.manager;if(!t)throw new Error("ArktsLspManager not initialized");let r=at(e),i=await re.promises.readFile(e,"utf8"),s=`deveco.apptool.${Y.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,r,i,s):this.checkFileLegacy(t,e,r,i,s)}async checkFileStandard(e,t,r,i){h.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:i,version:1}});try{h.debug(`textDocument/diagnostic uri=${t}`);let o=await e.diagnostic({textDocument:{uri:t}});return zg(o)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:t}})}}async checkFileLegacy(e,t,r,i,o){let s=r;e.registerDiagnosticCallback(r);let a=new Promise((c,l)=>{let u=setTimeout(()=>{this.diagnosticWaiters.delete(s)&&l(new Error("Wait for diagnostics timeout"))},Ug);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:u})});h.debug(`textDocument/didOpen(legacy) uri=${r} content_len=${i.length}`),e.onAsyncOpenFile({textDocument:{uri:r,text:i,languageId:o,version:i.length},editorFiles:[r],isFromEditor:!1});try{return await a}finally{e.closeFileLegacy(r,!1)}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],r=[],i=this.collectValidFiles(e.files,t);return i.length===0?{content:[{type:"text",text:t.length>0?t.join(`
|
|
1276
|
-
`):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],isError:!0}:(await this.runDiagnosticsForFiles(i,t,r),this.formatCallResult(t,r))}async handleLspFeature(e,t){if(!this.initialized)return this.buildNotReadyResponse();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};
|
|
1277
|
-
`).length,o=await this.withOpenFile(t,async a=>this.manager.sendFeatureRequest(y.INLAY_HINT,{textDocument:{uri:a},range:{start:{line:0,character:0},end:{line:i,character:0}}}));return{content:[{type:"text",text:o==null?"inlayHint: no result":`inlayHint: ${JSON.stringify(o,null,2)}`}]}}catch(r){return this.buildErrorResponse("inlayHint",r)}}async handleDocumentLink(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_LINK,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentLink: no result":`documentLink: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("documentLink",r)}}buildErrorResponse(e,t){let r=t instanceof Error?t.message:String(t);return
|
|
1269
|
+
`+c.message})})})}function jP(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>f.info("[ohpm] %s",e))}async function Qf(n,e){try{let t=yo(e);if(!t)return f.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;let r=_P(e);if(!r)return f.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:i,output:o}=await FP(t,r,n,e);return jP(o),i===0?(f.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(f.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",i),f.error("ohpm \u8F93\u51FA: %s",o),!1)}catch(t){return f.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var em={UNINITIALIZED:-32099,UNKNOWN:-32e3},wi=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,em.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,em.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var or=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){f.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){f.warn("[ArktsLspManager] sendRequest before LSP ready, dropped");return}this.lspProxy.sendRequest(e)}async diagnostic(e){if(!this.lspProxy)throw new Error("[ArktsLspManager] diagnostic before LSP ready");return this.lspProxy.diagnostic(e)}async sendFeatureRequest(e,t){if(!this.useStandardProtocol)throw new Error(`Language feature '${e}' is not supported on the installed DevEco Studio. The standard LSP protocol entry (plugins/openharmony/ace-server/out/standardIndex/index.js) was not found. Please upgrade DevEco Studio to version 26.0.0.610 or later to use this tool.`);if(!this.lspProxy)throw new Error("LSP not ready");return this.lspProxy.sendFeatureRequest(e,t)}get useStandardProtocol(){return this.config.useStandardProtocol}onAsyncOpenFile(e){this.lspProxy?.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.lspProxy?.closeFileLegacy(e,t)}registerDiagnosticCallback(e){this.lspProxy?.registerDiagnosticCallback(e)}static async handleSyncProject(e,t,r){if(f.info("[ArktsLspManager] Received arkts/syncProject"),!e||!t)return f.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let i=r?.skipHvigorSync===!0,o=await co(e,async()=>await Qf(e,t)?i?(f.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await yu(e,t)?(f.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(f.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(f.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return o.acquired?o.result:(f.info("[ArktsLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){try{this.configWatcher?.stop()}catch(e){f.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){f.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){f.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new Ts(this.config.sdkPath,this.config.arktsLangServerPath,this.config.workspaceRoot,this.config.indexLogPath,this.config.nodeMaxOldSpaceSize,this.config.useStandardProtocol);t.setOnMessage(r=>this.handleLspMessage(r)),t.start(e,r=>this.handleLspInitialized(r)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)f.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:R,method:y.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();f.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?wi.uninitialized(t):wi.unknown();this.onMessage({jsonrpc:R,method:y.ARKTS_INITIALIZATION_FAILED,params:r.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(f.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:R,method:y.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new ks(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new xs(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){f.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let r=this.lspProxy.reloadDependenciesOnly(e).map(i=>({modulePath:i.modulePath??"",dependencies:i.dependencies??{},dynamicDependencies:i.dynamicDependencies??{}}));this.onMessage({jsonrpc:R,method:y.ARKTS_SYNC_COMPLETED,params:{success:!0,moduleSet:r}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){f.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var HP=10080*60*1e3,$P=7200*60*1e3,UP=120*1e3,sr=class n{manager=null;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;devecoPath;nodeMaxOldSpaceSize;onConfigChangedCallback=null;useStandardProtocol=!0;diagnosticWaiters=new Map;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION,completion:y.COMPLETION,signatureHelp:y.SIGNATURE_HELP,documentHighlight:y.DOCUMENT_HIGHLIGHT};constructor(e,t,r){this.projectPath=e,this.devecoPath=t??"",this.nodeMaxOldSpaceSize=r}setOnConfigChanged(e){this.onConfigChangedCallback=e}static getToolDefinition(){return{name:"check_ets_files",description:"\u5BF9\u4F20\u5165\u7684ets\u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5(ArkTS-Check)\u5E76\u5B9E\u65F6\u8FD4\u56DE\u8BCA\u65AD\u4FE1\u606F\u3002",inputSchema:Xc.object({files:Xc.array(Xc.string()).describe('\u5F85\u68C0\u67E5\u7684 ETS \u6587\u4EF6\u8DEF\u5F84\u5217\u8868\uFF0C\u683C\u5F0F\u4E3A ["file1.ets","file2.ets",...]')})}}isInitializing(){return this.initializing}isInitialized(){return this.initialized}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initializing=!0,this.initPromise=this.doInitialize().then(()=>{this.initialized=!0}).finally(()=>{this.initializing=!1}),await this.initPromise}}async doInitialize(){let{harmonyRoot:e,devecoPath:t,arktsLangServerPath:r,useStandardProtocol:i}=this.resolveProjectAndDeveco();this.useStandardProtocol=i;let o=oe(e),{logPath:s,indexPath:a}=this.getLogAndIndexPath(o);setImmediate(()=>{Va(a,HP,"[ArkTS-Check]"),Va(s,$P,"[ArkTS-Check]")}),bo(s);let c=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,l=Number.isNaN(c)?void 0:c;g.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${l??"undefined \u2192 dynamic formula applies"}`);let d=ue.join(ct(t),"sdk");g.info(`ArktsCheck devecoPath: ${t}, contentRoot: ${ct(t)}, sdkPath: ${d}`),this.manager=new or({sdkPath:d,arktsLangServerPath:r,workspaceRoot:H(o),indexLogPath:a,nodeMaxOldSpaceSize:l,useStandardProtocol:i}),this.manager.setOnMessage(h=>this.handleLspMessage(h)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((h,w)=>{this.initResolve=h,this.initReject=w,this.armInitTimer(Oe),this.manager.start([]).catch(b=>{let L=b instanceof Error?b:new Error(String(b));this.failInit(L)})})}resolveProjectAndDeveco(){let e=ht(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.devecoPath??Je();if(g.debug(`DevEco Studio installation path: ${t}, this.devecoPath: ${this.devecoPath}`),!t)throw new Error("DevEco Studio installation path not found");this.devecoPath=t;let r=On(t);if(!r)throw new Error("arkts-lang-server path not found");let i=ue.resolve(r,"ace-server","out","standardIndex","index.js"),o=Se.existsSync(i);return g.info(`ArktsCheck protocol: ${o?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${o})`),{harmonyRoot:e,devecoPath:t,arktsLangServerPath:r,useStandardProtocol:o}}armInitTimer(e){this.initDeadlineTimer&&clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=setTimeout(()=>{let t=this.initReject;this.clearInitHandlers(),t?.(new Error("LSP initialize timeout"))},e)}clearInitHandlers(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async checkFile(e){this.initialized||await this.initialize();let t=this.manager;if(!t)throw new Error("ArktsLspManager not initialized");let r=pn(e),i=await Se.promises.readFile(e,"utf8"),s=`deveco.apptool.${ue.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,r,i,s):this.checkFileLegacy(t,e,r,i,s)}async checkFileStandard(e,t,r,i){g.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:i,version:1}});try{g.debug(`textDocument/diagnostic uri=${t}`);let o=await e.diagnostic({textDocument:{uri:t}});return BP(o)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:t}})}}async checkFileLegacy(e,t,r,i,o){let s=r;e.registerDiagnosticCallback(r);let a=new Promise((c,l)=>{let d=setTimeout(()=>{this.diagnosticWaiters.delete(s)&&l(new Error("Wait for diagnostics timeout"))},UP);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});g.debug(`textDocument/didOpen(legacy) uri=${r} content_len=${i.length}`),e.onAsyncOpenFile({textDocument:{uri:r,text:i,languageId:o,version:i.length},editorFiles:[r],isFromEditor:!1});try{return await a}finally{e.closeFileLegacy(r,!1)}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],r=[],i=this.collectValidFiles(e.files,t);return i.length===0?{content:[{type:"text",text:t.length>0?t.join(`
|
|
1270
|
+
`):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],isError:!0}:(await this.runDiagnosticsForFiles(i,t,r),this.formatCallResult(t,r))}async handleLspFeature(e,t){if(!this.initialized)return this.buildNotReadyResponse();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};g.info(`handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){let s=o instanceof Error?o.message:String(o);return g.error(`handleLspFeature ${e} failed: ${s}`),{content:[{type:"text",text:`${e} failed: ${s}`}],isError:!0}}}async handleWorkspaceSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();g.info(`handleWorkspaceSymbol: query="${e}"`);try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return{content:[{type:"text",text:t==null?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(t,null,2)}`}]}}catch(t){let r=t instanceof Error?t.message:String(t);return g.error(`handleWorkspaceSymbol failed: ${r}`),{content:[{type:"text",text:`workspaceSymbol failed: ${r}`}],isError:!0}}}async handleWorkspaceSymbolRaw(e){if(!this.initialized)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return g.error(`handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};g.info(`handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return g.error(`handleDocumentSymbol failed: ${i}`),{content:[{type:"text",text:`documentSymbol failed: ${i}`}],isError:!0}}}async handleCallHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};g.info(`handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,async o=>{let s=await this.manager.sendFeatureRequest(y.PREPARE_CALL_HIERARCHY,{textDocument:{uri:o},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],calls:[]};let c=e.direction==="incoming"?y.INCOMING_CALLS:y.OUTGOING_CALLS,l=[];for(let d of a){let h=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(h)?l.push(...h):h&&l.push(h)}return{items:a,calls:l}});return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return g.error(`handleCallHierarchy failed: ${i}`),{content:[{type:"text",text:`callHierarchy failed: ${i}`}],isError:!0}}}async handleCodeAction(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};g.info(`handleCodeAction: file=${t} line=${e.line} char=${e.character}`);try{let r=await this.withOpenFile(t,async o=>{let s={line:e.line,character:e.character};return this.manager.sendFeatureRequest(y.CODE_ACTION,{textDocument:{uri:o},range:{start:s,end:s},context:{diagnostics:[]}})});return{content:[{type:"text",text:r==null?"codeAction: no result":`codeAction: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("codeAction",r)}}async handleRename(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};g.info(`handleRename: file=${t} line=${e.line} char=${e.character} newName=${e.newName}`);try{let r=await this.withOpenFile(t,async o=>{let s={line:e.line,character:e.character};if(await this.manager.sendFeatureRequest(y.PREPARE_RENAME,{textDocument:{uri:o},position:s})==null)throw new Error("Symbol at this position cannot be renamed");return this.manager.sendFeatureRequest(y.RENAME,{textDocument:{uri:o},position:s,newName:e.newName})});return{content:[{type:"text",text:r==null?"rename: no result":`rename: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("rename",r)}}async handleTypeHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};g.info(`handleTypeHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,async o=>{let s=await this.manager.sendFeatureRequest(y.PREPARE_TYPE_HIERARCHY,{textDocument:{uri:o},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],results:[]};let c=e.direction==="supertypes"?y.SUPERTYPES:y.SUBTYPES,l=[];for(let d of a){let h=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(h)?l.push(...h):h&&l.push(h)}return{items:a,results:l}});return{content:[{type:"text",text:`typeHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("typeHierarchy",r)}}async handleCompletionItemResolve(e){if(!this.initialized)return this.buildNotReadyResponse();g.info("handleCompletionItemResolve");try{let t=await this.manager.sendFeatureRequest(y.COMPLETION_ITEM_RESOLVE,{item:e});return{content:[{type:"text",text:t==null?"completionItemResolve: no result":`completionItemResolve: ${JSON.stringify(t,null,2)}`}]}}catch(t){return this.buildErrorResponse("completionItemResolve",t)}}async handleInlayHint(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};try{let i=(await Se.promises.readFile(t,"utf8")).split(`
|
|
1271
|
+
`).length,o=await this.withOpenFile(t,async a=>this.manager.sendFeatureRequest(y.INLAY_HINT,{textDocument:{uri:a},range:{start:{line:0,character:0},end:{line:i,character:0}}}));return{content:[{type:"text",text:o==null?"inlayHint: no result":`inlayHint: ${JSON.stringify(o,null,2)}`}]}}catch(r){return this.buildErrorResponse("inlayHint",r)}}async handleDocumentLink(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_LINK,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentLink: no result":`documentLink: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("documentLink",r)}}buildErrorResponse(e,t){let r=t instanceof Error?t.message:String(t);return g.error(`${e} failed: ${r}`),{content:[{type:"text",text:`${e} failed: ${r}`}],isError:!0}}async withOpenFile(e,t){let r=pn(e),i=await Se.promises.readFile(e,"utf8"),s=`deveco.apptool.${ue.extname(e).replace(/^\./,"")||"plaintext"}`;g.debug(`withOpenFile didOpen uri=${r} len=${i.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,text:i,languageId:s,version:i.length}});try{return await t(r)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:r},isManual:!1})}}resolveSingleFile(e){let t=ue.isAbsolute(e)?e:ue.join(this.projectPath,e);return!Se.existsSync(t)||!Se.statSync(t).isFile()||!t.endsWith(".ets")?null:t}buildNotReadyResponse(){return{content:[{type:"text",text:this.initializing?"LSP \u6B63\u5728\u521D\u59CB\u5316\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5":this.projectPath?"LSP\u672A\u521D\u59CB\u5316":"\u6CA1\u6709\u914D\u7F6E\u5DE5\u7A0B\u8DEF\u5F84\uFF0C\u8BF7\u914D\u7F6EPROJECT_PATH\u53C2\u6570"}],isError:!0}}collectValidFiles(e,t){let r=this.projectPath,i=[];for(let o of e){let s=ue.isAbsolute(o)?o:ue.join(r,o);if(!Se.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!Se.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${o}`);continue}if(!s.endsWith(".ets")){t.push(`\u4E0D\u662F .ets \u6587\u4EF6: ${o}`);continue}i.push(s)}return i}async runDiagnosticsForFiles(e,t,r){for(let i of e){await iu(500);try{let o=await this.checkFile(i);r.push(WP(i,o))}catch(o){t.push(`${i} => wait for diagnostics failed: ${o.message}`)}}}formatCallResult(e,t){let r=[];e.length>0&&r.push(e.join(`
|
|
1278
1272
|
`)),t.length>0&&r.push(t.join(`
|
|
1279
1273
|
`));let i=r.join(`
|
|
1280
|
-
`).trim(),o=e.length>0;return!o&&t.length===0&&(i="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:i}],isError:o}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
`);if(t<0)return;let r=this.clangdBuffer.slice(0,t).toString("ascii"),i=/content-length:\s*(\d+)/i.exec(r);if(!i){this.clangdBuffer=this.clangdBuffer.slice(t+4);continue}let o=parseInt(i[1],10),s=t+4+o;if(this.clangdBuffer.length<s)return;let a=this.clangdBuffer.slice(t+4,s).toString("utf8");this.clangdBuffer=this.clangdBuffer.slice(s);try{let c=JSON.parse(a);this.dispatchMessage(c)}catch(c){h.error(`[CppCheck] Failed to parse C++ LSP JSON message: ${c}`)}}}dispatchMessage(e){if(typeof e.id=="number"){let t=this.pendingRequests.get(e.id);t&&(this.pendingRequests.delete(e.id),clearTimeout(t.timer),e.error?t.reject(new Error(e.error.message??JSON.stringify(e.error))):t.resolve(e.result??null));return}if(e.method==="textDocument/publishDiagnostics"&&e.params){let t=e.params,r=t.uri;if(!r)return;let i=Kg(r),o=this.diagnosticWaiters.get(i);if(o){this.diagnosticWaiters.delete(i),clearTimeout(o.timer);let s=Array.isArray(t.diagnostics)?t.diagnostics:[];h.info(`[CppCheck] Received C++ diagnostics for ${i} (${s.length} entries)`),o.resolve(s)}}}failAll(e){for(let[,t]of this.pendingRequests)clearTimeout(t.timer),t.reject(e);this.pendingRequests.clear();for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear()}async acquireFileCheckLock(){let e=this.fileCheckLock,t;return this.fileCheckLock=new Promise(r=>{t=r}),await e,t}};function Kg(n){try{let e=new URL(n);if(e.protocol==="file:"){let t=decodeURIComponent(e.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(t)&&(t=t.slice(1)),at(t)}}catch{}return n}function Zg(n){let e=B.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function Xg(n,e){let t=B.join(n,e.name);return e.isDirectory()?e.name===".cxx"||wl(t):Zg(t)}function wl(n){if(!M.existsSync(n))return!1;try{return M.readdirSync(n,{withFileTypes:!0}).some(t=>Xg(n,t))}catch{}return!1}function bl(n){let t=new Oe(n).getAllModuleInfo(),r=[];for(let i of t){let o=b.resolvePathWithinRoot(n,i.srcPath);wl(o)&&r.push(i)}return r}function Qg(n){let e=[],r=new Oe(n).getAllModuleInfo();for(let i of r){let o=b.resolvePathWithinRoot(n,i.srcPath),s=B.join(o,".cxx");M.existsSync(s)&&Sl(s,e)}return e}function Sl(n,e){try{let t=M.readdirSync(n,{withFileTypes:!0});for(let r of t){let i=B.join(n,r.name);r.isDirectory()?Sl(i,e):r.name==="compile_commands.json"&&e.push(i)}}catch{}}function ey(n){let e=[];for(let t of n)try{let r=M.readFileSync(t,"utf8"),i=JSON.parse(r);e.push(...i)}catch{}return e}function ty(n,e){let t=B.join(n,...Do.slice(0,-1));M.mkdirSync(t,{recursive:!0});let r=B.join(t,"compile_commands.json");M.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function ny(n){let e=Qg(n);if(e.length>0){let t=ey(e);ty(n,t),h.info(`[CppCheck] compile_commands.json \u5DF2\u751F\u6210\uFF0C\u5171 ${t.length} \u6761\u7F16\u8BD1\u547D\u4EE4`)}else h.warn("[CppCheck] \u672A\u627E\u5230\u4EFB\u4F55 compile_commands.json \u6587\u4EF6")}function ry(n){let e=new Set;for(let t of n)if(t.file)try{e.add(M.realpathSync(t.file))}catch{e.add(t.file)}return e}function iy(n,e){try{let t=M.realpathSync(n);if(!e.has(t))return h.info(`[CppCheck] File not covered by compile_commands.json: ${n}`),!1}catch{}return!0}function oy(n,e){if(!M.existsSync(n))return!1;try{let t=M.readFileSync(n,"utf8"),r=JSON.parse(t),i=ry(r);for(let o of e)if(!iy(o,i))return!1;return!0}catch(t){return h.warn(`[CppCheck] Failed to read/parse compile_commands.json: ${t}`),!1}}async function sy(n,e,t){let r=B.join(de(e),"sdk"),i=process.execPath||"node",o=B.join(de(e),"tools");h.info(`CppCheck devecoPath: ${e}, contentRoot: ${de(e)}, sdkPath: ${r}, toolsDir: ${o}`);let s=B.join(o,"hvigor","bin","hvigorw.js");for(let a of t){let c=["--mode","module","-p",`module=${a.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"].join(" ");h.info(`[CppCheck] Running compileNative for module: ${a.name}`);let l=await Mo(n,i,s,r,c);l.success?h.info(`[CppCheck] compileNative ${a.name} \u6210\u529F`):h.warn(`[CppCheck] compileNative ${a.name} \u5931\u8D25: ${l.output}`)}}async function ay(n,e){let t=bl(n);if(t.length===0){h.info("[CppCheck] \u672A\u53D1\u73B0\u542BC++\u7684\u6A21\u5757\uFF0C\u8DF3\u8FC7\u521D\u59CB\u5316");return}h.info(`[CppCheck] \u53D1\u73B0 ${t.length} \u4E2A\u542BC++\u7684\u6A21\u5757: ${t.map(r=>r.name).join(", ")}`),await sy(n,e,t),ny(n)}var Bt=class{projectPath;devecoPath;clangdProcess=null;client=null;initializedProjectPath=null;initializing=!1;initPromise=null;pollHandle=null;backendReady=!1;constructor(e,t){this.projectPath=e,this.devecoPath=fr(t??"")??t??null}static getToolDefinition(){return{name:"check_cpp_files",description:"\u5BF9\u4F20\u5165\u7684 C/C++ \u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5\u5E76\u8FD4\u56DE clangd \u8BCA\u65AD\u4FE1\u606F\u3002",inputSchema:No.object({files:No.array(No.string()).describe('\u5F85\u68C0\u67E5\u7684 C/C++ \u6587\u4EF6\u8DEF\u5F84\u5217\u8868\uFF0C\u683C\u5F0F\u4E3A ["file1.cpp","file2.hpp",...]')})}}isInitializing(){return this.initializing}isInitialized(){return this.client!==null&&this.initializedProjectPath!==null}async handleCall(e){let t=[],r=[],i=this.collectValidFiles(e.files,t);if(i.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
|
|
1285
|
-
`)
|
|
1286
|
-
`)}],isError:!0}}
|
|
1287
|
-
`),e.join(`
|
|
1288
|
-
`)].filter(o=>o.trim().length>0).join(`
|
|
1289
|
-
`).trim()}],isError:r}}async ensureInitializedWithFiles(e){let t=ue(this.projectPath);if(this.prepareCppCheck(t,e)){this.client&&this.initializedProjectPath&&(h.info("[CppCheck] Re-initializing C++ project due to file changes"),await this.shutdown());let i=this.devecoPath??be();if(!i)throw new Error("DevEco Studio installation path not found");this.devecoPath=i,await ay(t,i)}else if(this.client&&this.initializedProjectPath){let i=ue(this.projectPath);if(this.initializedProjectPath===i)return this.client;await this.shutdown()}return this.doEnsureInitialized()}prepareCppCheck(e,t){let r=hr(e);return M.existsSync(r)?bl(e).length===0?(h.info("[CppCheck] No cpp modules found, no initialization needed"),!1):oy(r,t)?(h.info("[CppCheck] All files covered, no initialization needed"),!1):(h.info("[CppCheck] Files not fully covered by compile_commands.json, needs initialization"),!0):(h.info("[CppCheck] compile_commands.json not found, needs initialization"),!0)}async doEnsureInitialized(){if(this.initPromise&&(await this.initPromise,this.client))return this.client;if(this.initializing=!0,this.initPromise=this.doInitialize().finally(()=>{this.initializing=!1,this.initPromise=null}),await this.initPromise,!this.client)throw new Error("C++ LSP failed to initialize");return this.client}async doInitialize(){let e=this.resolveProjectRoot();this.client=new _o,await this.client.initialize(e),this.initializedProjectPath=e,h.info(`[CppCheck] Client initialized in wrapper mode for workspace: ${e}`),this.startPollingForClangd(e)}resolveProjectRoot(){let e=Re(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);return this.projectPath=e,ue(e)}startPollingForClangd(e){let t=hr(e);if(M.existsSync(t)){h.info("[CppCheck] compile_commands.json found, spawning clangd immediately"),this.spawnAndConnectClangd(e).catch(r=>{h.error(`[CppCheck] Immediate clangd spawn failed: ${r}`)});return}h.info("[CppCheck] compile_commands.json not found, starting poll..."),this.pollHandle=setInterval(()=>{if(!this.client||this.client.isClosed()||this.backendReady){this.stopPolling();return}M.existsSync(t)&&(this.stopPolling(),h.info("[CppCheck] compile_commands.json found via poll, spawning clangd..."),this.spawnAndConnectClangd(e).catch(r=>{h.error(`[CppCheck] Clangd spawn from poll failed: ${r}`)}))},Jg)}stopPolling(){this.pollHandle&&(clearInterval(this.pollHandle),this.pollHandle=null)}async spawnAndConnectClangd(e){let{clangdPath:t,compileCommandsDir:r}=this.resolveClangdPaths(e);h.info(`[CppCheck] Starting clangd for workspace: ${e} (clangd=${t})`);let i=this.spawnClangd(t,e,r);this.clangdProcess=i;try{await this.client.connectClangdProcess(i.stdin,i.stdout),this.backendReady=!0,h.info(`[CppCheck] clangd connected for workspace: ${e}`)}catch(o){if(h.error(`[CppCheck] Failed to connect clangd: ${o}`),this.clangdProcess&&!this.clangdProcess.killed){try{this.clangdProcess.kill()}catch{}this.clangdProcess=null}throw o}}resolveClangdPaths(e){let t=this.devecoPath??be();if(!t)throw new Error("DevEco Studio installation path not found");this.devecoPath=t;let r=Wc(t);if(!r)throw new Error("clangd executable not found inside DevEco Studio SDK");let i=hr(e),o=B.dirname(i);return{clangdPath:r,compileCommandsDir:o}}spawnClangd(e,t,r){let i=Gg(e,[`--compile-commands-dir=${r}`],{cwd:t,stdio:["pipe","pipe","pipe"]});if(!i.stdin||!i.stdout||!i.stderr)throw new Error("Failed to start clangd: stdio not available");return i.stderr.on("data",o=>{let s=o.toString("utf8").trimEnd();s&&h.warn(`[CppLsp stderr] ${s}`)}),i.on("exit",(o,s)=>{h.warn(`[CppCheck] clangd exited code=${o} signal=${s??"null"}`),this.clangdProcess===i&&(this.clangdProcess=null,this.backendReady=!1)}),i.on("error",o=>{h.error(`[CppCheck] clangd spawn error: ${o}`)}),i}collectValidFiles(e,t){let r=this.projectPath,i=[];for(let o of e){let s=B.isAbsolute(o)?o:B.join(r,o);if(!M.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!M.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${o}`);continue}if(!gr(s)){t.push(`\u4E0D\u662F\u53D7\u652F\u6301\u7684 C/C++ \u6587\u4EF6: ${o}`);continue}try{i.push(M.realpathSync(s))}catch{i.push(s)}}return i}async shutdown(){this.stopPolling();let e=this.client,t=this.clangdProcess;if(this.client=null,this.clangdProcess=null,this.initializedProjectPath=null,this.backendReady=!1,e)try{await e.close()}catch(r){h.warn(`[CppCheck] client.close() failed: ${r}`)}if(t&&!t.killed)try{t.kill()}catch(r){h.warn(`[CppCheck] failed to kill clangd: ${r}`)}}};function El(n){let e=Yn(n);return d.info(`[SyncGuard] ${e.reason}`),e}var Fo=(s=>(s[s.IDLE=0]="IDLE",s[s.DISCOVERING=1]="DISCOVERING",s[s.SYNCING=2]="SYNCING",s[s.INITIALIZING=3]="INITIALIZING",s[s.READY=4]="READY",s[s.ERROR=5]="ERROR",s))(Fo||{}),Ho=3,Pl=600*1e3,Qr=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;projectState=0;workspaceRoot="";sdkPath="";initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;standardProtocolAvailable=!1;constructor(e={}){this.config=e,fn(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),h.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",h.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,h.info(`Constructor: using configured path as startPath: '${t}'`));let i=Re(t);h.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0,this.server=new cy({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=Eo(),this.standardProtocolAvailable=this.detectStandardProtocolAvailable(),this.registerTools()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools()}registerCheckTool(){this.toolRouter.add({name:"check",description:"Perform static syntax analysis on HarmonyOS project source files and return structured diagnostics. Supported languages: ArkTS and C/C++.",inputSchema:J.object({files:J.array(J.string()).min(1).describe("List of source file paths to check, relative to the project root. Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}registerLspFeatureTools(){if(!this.standardProtocolAvailable){h.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=J.object({file:J.string().describe("ArkTS (.ets) file path, relative to the project root"),line:J.number().describe("Line number (0-based)"),character:J.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature:i}of this.getPositionFeatures())this.toolRouter.add({name:t,description:r,inputSchema:e},async o=>this.handleLspFeatureCall(i,o));this.registerSymbolTools(),this.registerCallHierarchyTool()}getPositionFeatures(){return[{name:"hover",description:"Get hover information (type info, documentation) at a specific position in an ArkTS (.ets) file.",feature:"hover"},{name:"definition",description:"Find where the symbol at the given position is defined. Returns file path, line, and character.",feature:"definition"},{name:"declaration",description:"Find the declaration of the symbol at the given position. In ArkTS, this may differ from definition.",feature:"declaration"},{name:"references",description:"Find all references to the symbol at the given position across the HarmonyOS project.",feature:"references"},{name:"implementation",description:"Find implementations of the symbol at the given position (e.g., interface implementations).",feature:"implementation"}]}registerSymbolTools(){this.toolRouter.add({name:"workspaceSymbol",description:"Search for symbols by name across the entire HarmonyOS project.",inputSchema:J.object({query:J.string().describe("Symbol name (or partial) to search for")})},async e=>this.handleWorkspaceSymbolCall(e)),this.toolRouter.add({name:"documentSymbol",description:"Get the symbol tree (functions, classes, variables with ranges) of an ArkTS (.ets) file. Useful for file overview, structured code breakdown, and large file slicing.",inputSchema:J.object({file:J.string().describe("ArkTS (.ets) file path, relative to the project root")})},async e=>this.handleDocumentSymbolCall(e))}registerCallHierarchyTool(){this.toolRouter.add({name:"callHierarchy",description:'Query call hierarchy for a function at the given position. Use direction "incoming" to find callers, "outgoing" to find callees.',inputSchema:J.object({file:J.string().describe("ArkTS (.ets) file path, relative to the project root"),line:J.number().describe("Line number (0-based)"),character:J.number().describe("Character offset in the line (0-based)"),direction:J.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.config.devecoPath??be();if(!e)return h.info("Standard LSP protocol unavailable: DevEco Studio installation path not found"),!1;let t=It(e);if(!t)return h.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let r=ut.join(t,"ace-server","out","standardIndex","index.js"),i=Cl.existsSync(r);return h.info(`ArktsCheck protocol: ${i?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${i})`),i}catch(e){return h.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}validateContainment(e){let t=this.config.projectPath;if(t){let i=[];for(let o of e){let s=b.isPathContainedWithSymlink(o,t);s.contained||(h.warn(`Containment check failed: ${s.reason}`),i.push(s.reason))}return i.length>0?{content:[{type:"text",text:i.join(`
|
|
1290
|
-
`)}],isError:!0}:null}let r=e.filter(i=>ut.isAbsolute(i));return r.length>0?(h.warn(`Absolute paths rejected (no project root): ${r.join(", ")}`),{content:[{type:"text",text:r.map(i=>`Absolute path is not allowed: ${i}`).join(`
|
|
1291
|
-
`)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(f=>typeof f=="string"):[];if(t.length===0)return h.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};let r=this.validateContainment(t);if(r)return r;let{etsFiles:i,cppFiles:o,unsupported:s}=dy(t);s.length>0&&h.warn(`Unsupported file types in check request: ${s.join(", ")}`);let a=s.map(f=>`Unsupported file type: ${f} (only .ets and C/C++ source/header files are supported)`),c=[];i.length>0&&this.mergeCheckResult(await this.callArktsCheck(i),a,c),o.length>0&&this.mergeCheckResult(await this.callCppCheck(o),a,c);let l=a.length>0;return{content:[{type:"text",text:[c.join(`
|
|
1274
|
+
`).trim(),o=e.length>0;return!o&&t.length===0&&(i="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:i}],isError:o}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){g.warn(`Failed to dispose ArktsLspManager: ${t}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":{this.handleDiagnosticsNotification(t.params);break}case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(Oe),g.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{g.info("Received arkts/initialized");let i=this.initResolve;this.clearInitHandlers(),i?.();break}case"arkts/initializationFailed":{let o=t.params?.message??"unknown";g.error(`LSP initialization failed: ${o}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${o}`));break}case"workspace/didChangeConfiguration":g.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let r=this.popDiagnosticWaiter(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.popDiagnosticWaiter(s)}if(!r)return;if(typeof e.errorMessage=="string"){g.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let i=e.diagnostics,o=Array.isArray(i)?i.length:0;g.debug(`diagnostics received uri=${t} count=${o}`),r.resolve(Array.isArray(i)?i:[])}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}getLogAndIndexPath(e){try{let t=ue.join(Mt(),"ArkTSCheck"),r=ue.join(t,"mapping-config.properties"),i=ou(e,r),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=ue.join(t,"lsp-log",String(i),o),a=ue.join(t,"lsp-index",String(i));return Se.mkdirSync(s,{recursive:!0}),Se.mkdirSync(a,{recursive:!0}),{logPath:oe(s),indexPath:oe(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function BP(n){if(Array.isArray(n))return n;if(n&&typeof n=="object"){let e=n;if(e.kind==="full"&&Array.isArray(e.items))return e.items}return[]}function WP(n,e){if(Array.isArray(e))return e.length===0?`${n} => no diagnostics`:`${n} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${n} diagnostic failed, error_message: ${t}`}return`${n} => diagnostic failed, result: ${JSON.stringify(e)}`}import*as Gt from"fs";import*as Ls from"path";import{z as Zc}from"zod";function ar(){return{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}function Ns(n,e){let t=e instanceof Error?e.message:String(e);return g.error(`[CppLsp] ${n} failed: ${t}`),{content:[{type:"text",text:`${n} failed: ${t}`}],isError:!0}}var GP=500,cr=class{manager;constructor(e){this.manager=e}static getToolDefinition(){return{name:"check_cpp_files",description:"Perform static syntax checks on the provided C/C++ files and return clangd diagnostics.",inputSchema:Zc.object({files:Zc.array(Zc.string()).describe('List of C/C++ file paths to check, format: ["file1.cpp","file2.hpp",...]')})}}async handleCall(e){if(!this.manager.ready)return ar();let t=[],r=[],i=this.collectValidFiles(e.files,t);if(i.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
|
|
1275
|
+
`):"No valid C/C++ files"}],isError:!0};for(let c of i){await VP(GP);try{let l=await this.checkFile(c);r.push(zP(c,l))}catch(l){t.push(`${c} => wait for diagnostics failed: ${l.message}`)}}let o=t.length>0,s=[];t.length>0&&s.push(t.join(`
|
|
1276
|
+
`)),r.length>0&&s.push(r.join(`
|
|
1277
|
+
`));let a=s.join(`
|
|
1278
|
+
`).trim();return!o&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:o}}async checkFile(e){let t=pn(e),r=await Gt.promises.readFile(e,"utf8"),i=go(e),o=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:r,languageId:i,version:r.length}}});try{return await o}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let r=this.manager.projectRoot,i=[];for(let o of e){let s=Ls.isAbsolute(o)?o:Ls.join(r,o);if(!Gt.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!Gt.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!un(s)){t.push(`Not a supported C/C++ file: ${o}`);continue}try{i.push(Gt.realpathSync(s))}catch{i.push(s)}}return i}};function zP(n,e){if(Array.isArray(e))return e.length===0?`${n} => no diagnostics`:`${n} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${n} diagnostic failed, error_message: ${t}`}return`${n} => diagnostic failed, result: ${JSON.stringify(e)}`}function VP(n){return new Promise(e=>setTimeout(e,n))}import*as dr from"fs";import*as Os from"path";var lr=class n{manager;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION};constructor(e){this.manager=e}async handleLspFeature(e,t){if(!this.manager.ready)return ar();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};g.info(`[ClangdLspTool] handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){return Ns(e,o)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return g.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return ar();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};g.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return Ns("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return ar();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};g.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,o=>this.fetchCallHierarchyResult(o,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return Ns("callHierarchy",r)}}async fetchCallHierarchyResult(e,t){let r=await this.manager.sendFeatureRequest(y.PREPARE_CALL_HIERARCHY,{textDocument:{uri:e},position:{line:t.line,character:t.character}}),i=this.normalizeCallHierarchyItems(r);if(i.length===0)return{items:[],calls:[]};let o=await this.collectIncomingCalls(i);return{items:i,calls:o}}normalizeCallHierarchyItems(e){return Array.isArray(e)?e:e?[e]:[]}async collectIncomingCalls(e){let t=[];for(let r of e)t.push(...await this.fetchIncomingCalls(r));return t}async fetchIncomingCalls(e){let t=await this.manager.sendFeatureRequest(y.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let r=pn(e),i=await dr.promises.readFile(e,"utf8"),o=go(e);g.info(`[ClangdLspTool] withOpenFile didOpen uri=${r} langId=${o} len=${i.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:r,text:i,languageId:o,version:i.length}}});try{return await t(r)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:r}}})}}resolveSingleFile(e){let t=Os.isAbsolute(e)?e:Os.join(this.manager.projectRoot,e);return!dr.existsSync(t)||!dr.statSync(t).isFile()||!un(t)?null:t}};import{spawn as qP}from"child_process";import*as _s from"fs";import*as tm from"path";var YP=30*1e3,JP=30*1e3,Ms=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new $t;diagnosticWaiters=new Map;lastStartErrorMessage=null;onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}async start(e){let t=!1;try{f.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),f.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),f.info(`[ClangdLspProxy] compileCommandsDir: ${this.config.compileCommandsDir}`),this.ensureLogDir(),this.clangdProcess=this.spawnClangd();let r={serverPath:"",logPath:this.config.logPath,indexingDataLocation:this.config.logPath,cwd:this.config.workspaceRoot};this.client=new Ht(r),this.client.on("message",o=>this.handleRawMessage(o)),this.client.on("error",o=>this.handleError(o)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let i=this.buildInitializeParams();await this.sendLspRequest(y.INITIALIZE,i,Oe),f.info("[ClangdLspProxy] initialize response received"),this.sendNotification(y.INITIALIZED,{}),t=!0}catch(r){this.lastStartErrorMessage=r instanceof Error?r.message:String(r),f.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(y.HOVER,e)}async definition(e){return this.sendLspRequest(y.DEFINITION,e)}async declaration(e){return this.sendLspRequest(y.DECLARATION,e)}async references(e){return this.sendLspRequest(y.REFERENCES,e)}async implementation(e){return this.sendLspRequest(y.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(y.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(y.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(y.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(y.DID_OPEN,e)}sendDidChange(e){this.sendNotification(y.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(y.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){f.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){f.warn(`[ClangdLspProxy] overwrite existing diagnostic waiter for ${t}`);let r=this.diagnosticWaiters.get(t);clearTimeout(r.timer),this.diagnosticWaiters.delete(t)}return new Promise((r,i)=>{let o=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&i(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},JP);this.diagnosticWaiters.set(t,{resolve:r,reject:i,timer:o})})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){this.requestCallbacks.rejectAll(new Error("ClangdLspProxy disposing"));for(let[,e]of this.diagnosticWaiters)clearTimeout(e.timer),e.reject(new Error("ClangdLspProxy disposing"));if(this.diagnosticWaiters.clear(),this.client&&this.clangdProcess)try{await this.sendLspRequest(y.SHUTDOWN,null,3e3).catch(e=>{f.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(y.EXIT,null),await this.client.waitForExitOrTimeout(300)}catch(e){f.warn(`[ClangdLspProxy] dispose error: ${e}`)}if(this.clangdProcess){try{this.clangdProcess.exitCode===null&&this.clangdProcess.signalCode===null&&this.clangdProcess.kill()}catch{}this.clangdProcess=null}this.client=null}spawnClangd(){let e=[`--compile-commands-dir=${H(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];f.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=qP(this.config.clangdPath,e,{cwd:this.config.workspaceRoot,stdio:["pipe","pipe","pipe"],windowsHide:!0});if(!t.stdin||!t.stdout||!t.stderr)throw new Error("Failed to spawn clangd: stdio not available");return t}buildInitializeParams(){let e=_n(this.config.workspaceRoot),t=Ke(e),r=tm.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.0-Test.7"},rootPath:e,rootUri:t,workspaceFolders:[{uri:t,name:r}],capabilities:this.buildClientCapabilities(),initializationOptions:null}}buildClientCapabilities(){return{textDocument:{synchronization:{didOpen:!0,didChange:!0,didClose:!0,willSave:!1,save:!1},publishDiagnostics:{relatedInformation:!0,versionSupport:!1,tagSupport:{valueSet:[1,2]}},hover:{contentFormat:["markdown","plaintext"]},completion:{contextSupport:!1,completionItemKind:{valueSet:[]}},signatureHelp:{signatureInformation:{documentationFormat:["markdown","plaintext"]}},references:{},declaration:{linkSupport:!0},definition:{linkSupport:!0},implementation:{linkSupport:!0},documentSymbol:{hierarchicalDocumentSymbolSupport:!0,symbolKind:{valueSet:[]}},callHierarchy:{dynamicRegistration:!1}},workspace:{symbol:{symbolKind:{valueSet:[]}},configuration:!1,didChangeWatchedFiles:{dynamicRegistration:!1}}}}sendLspRequest(e,t,r=YP){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let i=r instanceof Error?r.message:String(r);f.error(`[ClangdLspProxy] JSON parse error: ${i}, raw: ${e.slice(0,200)}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotification(t):f.warn(`[ClangdLspProxy] unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t==null||typeof t!="string"&&typeof t!="number")return;let r=t;if(e.error!==void 0){let i=e.error;f.warn(`[ClangdLspProxy] LSP error id=${r}: code=${i.code??-1} message=${i.message??"unknown"}`),this.requestCallbacks.rejectPending(r,new Error(`LSP error ${i.code??-1}: ${i.message??"unknown"}`))}else this.requestCallbacks.resolvePending(r,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.onMessage({jsonrpc:R,method:y.PROGRESS,params:e.params});break;case y.WINDOW_SHOW_MESSAGE:f.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:f.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:R,method:t,params:e.params})}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=this.normalizeClangdUri(e.uri),r=this.diagnosticWaiters.get(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.diagnosticWaiters.get(s),r&&this.diagnosticWaiters.delete(s)}else r&&this.diagnosticWaiters.delete(t);if(!r)return;clearTimeout(r.timer);let i=Array.isArray(e.diagnostics)?e.diagnostics:[],o=i.length;f.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${o}`),r.resolve(i)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:R,method:y.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{_s.existsSync(this.config.logPath)||_s.mkdirSync(this.config.logPath,{recursive:!0})}catch{}}normalizeClangdUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=decodeURIComponent(t.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(r)&&(r=r.slice(1)),Ke(r)}}catch{}return e}};import*as vi from"path";import*as Qc from"fs";var Si=class{config;proxy=null;isInitialized=!1;onMessage=()=>{};disposeOnce=null;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;resolvedRoot="";constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get ready(){return this.isInitialized&&this.proxy!==null}get projectRoot(){return this.resolvedRoot}async start(){if(!this.isInitialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doStart();try{await this.initPromise}catch(e){throw this.initPromise=null,e}}}sendNotification(e){if(!this.proxy){f.warn("[ClangdLspManager] sendNotification before LSP ready, dropped");return}this.dispatchNotification(e)}async sendFeatureRequest(e,t){if(!this.proxy)throw new Error("[ClangdLspManager] LSP not ready");return this.proxy.sendFeatureRequest(e,t)}registerDiagnosticCallback(e){return this.proxy?this.proxy.registerDiagnosticCallback(e):Promise.reject(new Error("[ClangdLspManager] LSP not ready"))}static async handleSyncCppProject(e,t){if(f.info("[ClangdLspManager] Received cpp/syncProject"),!e||!t)return f.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or devecoPath is empty"),{status:"failed",reason:"workspaceRoot or devecoPath is empty"};if(mn(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let i=await co(e,async()=>{try{return await Su(e,t),f.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(o){let s=o instanceof Error?o.message:String(o);return f.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}});return i.acquired?i.result:(f.info("[ClangdLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}doStart(){return new Promise((e,t)=>{this.initResolve=e,this.initReject=t,this.armInitTimer(Oe);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=ht(this.config.workspaceRoot);this.resolvedRoot=e?oe(e):oe(this.config.workspaceRoot);let t=this.config.devecoPath??Je();if(!t){this.failInit(new Error("DevEco Studio installation path not found"));return}let r=this.config.logPath??this.getLogPath();bo(r);let i=ho(t);if(!i){let a="clangd executable not found inside DevEco Studio SDK";f.error(`[ClangdLspManager] ${a}`),this.failInit(new Error(a));return}let o=vi.dirname(Hr(this.resolvedRoot));try{Qc.mkdirSync(o,{recursive:!0})}catch(a){f.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${a}`)}f.info(`[ClangdLspManager] clangdPath: ${i}`),f.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),f.info(`[ClangdLspManager] compileCommandsDir: ${o}`);let s=new Ms({clangdPath:i,workspaceRoot:this.resolvedRoot,compileCommandsDir:o,logPath:r});s.setOnMessage(a=>this.handleLspMessage(a)),this.proxy=s,s.start(a=>this.handleProxyInitialized(a)).catch(a=>{let c=a instanceof Error?a:new Error(String(a));this.handleProxyInitialized(!1,c.message)})}handleProxyInitialized=(e,t)=>{if(this.clearInitTimer(),e){this.isInitialized=!0,f.info("[ClangdLspManager] clangd initialized");let r=this.initResolve;this.clearInitHandlers(),r?.()}else{let r=t??this.proxy?.consumeStartErrorMessage()??"unknown error";f.error(`[ClangdLspManager] clangd initialization failed: ${r}`),this.isInitialized=!1,this.proxy=null;let i=this.initReject;this.clearInitHandlers(),i?.(new Error(`C++ LSP initialize failed: ${r}`))}};handleLspMessage(e){this.onMessage(e)}dispatchNotification(e){if(!this.proxy)return;let t=e,r=t.method;if(!r){f.warn("[ClangdLspManager] dispatchNotification: missing method");return}let i=t.params;switch(r){case y.DID_OPEN:this.proxy.sendDidOpen(i);break;case y.DID_CHANGE:this.proxy.sendDidChange(i);break;case y.DID_CLOSE:this.proxy.sendDidClose(i);break;default:this.proxy.sendNotification(r,i)}}armInitTimer(e){this.clearInitTimer(),this.initDeadlineTimer=setTimeout(()=>{this.failInit(new Error("C++ LSP initialize timeout"))},e)}clearInitTimer(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null)}clearInitHandlers(){this.clearInitTimer(),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async performDispose(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("ClangdLspManager disposing")),this.proxy){try{await this.proxy.dispose()}catch(t){f.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){try{let e=vi.join(Mt(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=vi.join(e,"lsp-log",t);return Qc.mkdirSync(r,{recursive:!0}),oe(r)}catch{return"auto"}}};function nm(n){let e=uo(n);return f.info(`[SyncGuard] ${e.reason}`),e}var tl=(s=>(s[s.IDLE=0]="IDLE",s[s.DISCOVERING=1]="DISCOVERING",s[s.SYNCING=2]="SYNCING",s[s.INITIALIZING=3]="INITIALIZING",s[s.READY=4]="READY",s[s.ERROR=5]="ERROR",s))(tl||{}),im=(s=>(s[s.IDLE_CPP=0]="IDLE_CPP",s[s.DISCOVERING_CPP=1]="DISCOVERING_CPP",s[s.SYNCING_CPP=2]="SYNCING_CPP",s[s.INITIALIZING_CPP=3]="INITIALIZING_CPP",s[s.READY_CPP=4]="READY_CPP",s[s.ERROR_CPP=5]="ERROR_CPP",s))(im||{}),zt=3,el=600*1e3,Fs=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";sdkPath="";initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;standardProtocolAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;constructor(e={}){this.config=e,fn(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),g.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",g.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,g.info(`Constructor: using configured path as startPath: '${t}'`));let i=ht(t);g.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0,this.server=new KP({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=Yc(),this.standardProtocolAvailable=this.detectStandardProtocolAvailable(),this.registerTools()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools()}registerCheckTool(){this.toolRouter.add({name:"check",description:"Perform static syntax analysis on HarmonyOS project source files and return structured diagnostics. Supported languages: ArkTS and C/C++.",inputSchema:pe.object({files:pe.array(pe.string()).min(1).describe("List of source file paths to check, relative to the project root. Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}registerLspFeatureTools(){if(!this.standardProtocolAvailable){g.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=pe.object({file:pe.string().describe("Source file path, relative to the project root. Supports .ets (ArkTS) and C/C++ extensions."),line:pe.number().describe("Line number (0-based)"),character:pe.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature:i}of this.getPositionFeatures())this.toolRouter.add({name:t,description:r,inputSchema:e},async o=>this.handleLspFeatureCall(i,o));this.registerSymbolTools(),this.registerCallHierarchyTool()}getPositionFeatures(){return[{name:"hover",description:"Get hover information (type info, documentation) at a specific position in an ArkTS (.ets) or C/C++ file.",feature:"hover"},{name:"definition",description:"Find where the symbol at the given position is defined. Returns file path, line, and character.",feature:"definition"},{name:"declaration",description:"Find the declaration of the symbol at the given position. In ArkTS, this may differ from definition.",feature:"declaration"},{name:"references",description:"Find all references to the symbol at the given position across the HarmonyOS project.",feature:"references"},{name:"implementation",description:"Find implementations of the symbol at the given position (e.g., interface implementations).",feature:"implementation"}]}registerSymbolTools(){this.toolRouter.add({name:"workspaceSymbol",description:"Search for symbols by name across the entire HarmonyOS project.",inputSchema:pe.object({query:pe.string().describe("Symbol name (or partial) to search for")})},async e=>this.handleWorkspaceSymbolCall(e)),this.toolRouter.add({name:"documentSymbol",description:"Get the symbol tree (functions, classes, variables with ranges) of an ArkTS (.ets) or C/C++ file. Useful for file overview, structured code breakdown, and large file slicing.",inputSchema:pe.object({file:pe.string().describe("Source file path, relative to the project root. Supports .ets and C/C++ extensions.")})},async e=>this.handleDocumentSymbolCall(e))}registerCallHierarchyTool(){this.toolRouter.add({name:"callHierarchy",description:'Query call hierarchy for a function at the given position. Use direction "incoming" to find callers, "outgoing" to find callees. ArkTS supports both directions; C/C++ (clangd) supports incoming only.',inputSchema:pe.object({file:pe.string().describe("Source file path, relative to the project root. Supports .ets and C/C++ extensions."),line:pe.number().describe("Line number (0-based)"),character:pe.number().describe("Character offset in the line (0-based)"),direction:pe.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.config.devecoPath??Je();if(!e)return g.info("Standard LSP protocol unavailable: DevEco Studio installation path not found"),!1;let t=On(e);if(!t)return g.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let r=En.join(t,"ace-server","out","standardIndex","index.js"),i=rm.existsSync(r);return g.info(`ArktsCheck protocol: ${i?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${i})`),i}catch(e){return g.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}validateContainment(e){let t=this.config.projectPath;if(t){let i=[];for(let o of e){let s=P.isPathContainedWithSymlink(o,t);s.contained||(g.warn(`Containment check failed: ${s.reason}`),i.push(s.reason))}return i.length>0?{content:[{type:"text",text:i.join(`
|
|
1279
|
+
`)}],isError:!0}:null}let r=e.filter(i=>En.isAbsolute(i));return r.length>0?(g.warn(`Absolute paths rejected (no project root): ${r.join(", ")}`),{content:[{type:"text",text:r.map(i=>`Absolute path is not allowed: ${i}`).join(`
|
|
1280
|
+
`)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(h=>typeof h=="string"):[];if(t.length===0)return g.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};let r=this.validateContainment(t);if(r)return r;let{etsFiles:i,cppFiles:o,unsupported:s}=ZP(t);s.length>0&&g.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=[];i.length>0&&this.mergeCheckResult(await this.callArktsCheck(i),a,c),o.length>0&&this.mergeCheckResult(await this.callCppCheck(o),a,c);let l=a.length>0;return{content:[{type:"text",text:[c.join(`
|
|
1292
1281
|
`),a.join(`
|
|
1293
|
-
`)].filter(
|
|
1294
|
-
`).trim()||"No diagnostics collected"}],isError:l}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS check rejected: project is ${Fo[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e})}}async handleLspFeatureCall(e,t){let r=t.file,i=t.line,o=t.character;if(typeof r!="string"||typeof i!="number"||typeof o!="number")return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};let s=this.validateContainment([r]);return s||this.callArktsFeature(e,{file:r,line:i,character:o})}async handleWorkspaceSymbolCall(e){let t=e.query;return typeof t!="string"||t.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameter: query (non-empty string required)."}],isError:!0}:this.callArktsWorkspaceSymbol(t)}async handleDocumentSymbolCall(e){let t=e.file;if(typeof t!="string")return{content:[{type:"text",text:"Missing or invalid parameter: file (string required)."}],isError:!0};let r=this.validateContainment([t]);return r||this.routeArktsRequest("documentSymbol",()=>this.arktsCheckTool.handleDocumentSymbol(t))}async handleCallHierarchyCall(e){let t=e.file,r=e.line,i=e.character,o=e.direction;if(typeof t!="string"||typeof r!="number"||typeof i!="number")return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};if(o!=="incoming"&&o!=="outgoing")return{content:[{type:"text",text:'Parameter direction must be "incoming" or "outgoing".'}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest(`callHierarchy(${o})`,()=>this.arktsCheckTool.handleCallHierarchy({file:t,line:r,character:i,direction:o}))}async handleCodeActionCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e);if(!t)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};let o=this.validateContainment([t]);return o||this.routeArktsRequest("codeAction",()=>this.arktsCheckTool.handleCodeAction({file:t,line:r,character:i}))}async handleRenameCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e),o=e.newName;if(!t||typeof o!="string"||o.trim().length===0)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number), newName (non-empty string)."}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest("rename",()=>this.arktsCheckTool.handleRename({file:t,line:r,character:i,newName:o}))}async handleTypeHierarchyCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e),o=e.direction;if(!t)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};if(o!=="supertypes"&&o!=="subtypes")return{content:[{type:"text",text:'Parameter direction must be "supertypes" or "subtypes".'}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest(`typeHierarchy(${o})`,()=>this.arktsCheckTool.handleTypeHierarchy({file:t,line:r,character:i,direction:o}))}async handleCompletionItemResolveCall(e){let t=e.item;return t==null?{content:[{type:"text",text:"Missing parameter: item (completion item object required)."}],isError:!0}:this.routeArktsRequest("completionItemResolve",()=>this.arktsCheckTool.handleCompletionItemResolve(t))}extractPositionArgs(e){let t=e.file,r=e.line,i=e.character;return typeof t!="string"||typeof r!="number"||typeof i!="number"?{file:null,line:0,character:0}:{file:t,line:r,character:i}}async callArktsFeature(e,t){return this.routeArktsRequest(e,()=>this.arktsCheckTool.handleLspFeature(e,t))}async callArktsWorkspaceSymbol(e){return this.routeArktsRequest("workspaceSymbol",()=>this.arktsCheckTool.handleWorkspaceSymbol(e))}async routeArktsRequest(e,t){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS ${e} rejected: project is ${Fo[this.projectState]}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS ${e} rejected: LSP is initializing`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return t()}}async handleIdleCheck(){if(this.ensureProjectReady(),this.config.projectPath){let e,t;return this.syncSkippedDueToLock?(e=`Another build process is running, sync deferred (waiting ${this.syncSkipStartedAt>0?Math.round((Date.now()-this.syncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,t="lock contention",this.syncSkippedDueToLock=!1):this.configChangedTriggeredResync?(e="Config file changed, resyncing project, please retry in 10 seconds",t="config changed",this.configChangedTriggeredResync=!1):(e="HarmonyOS project detected, syncing, please retry in 10 seconds",t="initial"),h.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(h.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(h.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=Ho?(h.error(`Init retry limit reached (${this.initRetryCount}/${Ho}), will not auto-retry`),{content:[{type:"text",text:"Project initialization failed multiple times. Please check project configuration and restart the MCP Server."}],isError:!0}):(h.info(`Error check: auto-retrying (${this.initRetryCount}/${Ho})`),this.ensureProjectReady(),{content:[{type:"text",text:"Project initialization failed, auto-retrying, please retry in 10 seconds"}],isError:!0})}async callCppCheck(e){if(!this.cppCheckTool){let t=this.config.projectPath?"C++ LSP is not ready, please retry later":"Project path is not configured. Set the PROJECT_PATH parameter or open a project in DevEco Studio.";return h.warn(`C++ check rejected: ${t}, files: ${e.join(", ")}`),{content:[{type:"text",text:t}],isError:!0}}return this.cppCheckTool.handleCall({files:e})}mergeCheckResult(e,t,r){let i=e.content.map(o=>o.text).filter(o=>o&&o.trim().length>0).join(`
|
|
1295
|
-
`);i&&(e.isError?t.push(i):r.push(i))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{h.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool&&(this.cppCheckTool.shutdown().catch(t=>{h.warn("Failed to shutdown CppCheckTool during setProjectPath:",t)}),this.cppCheckTool=null),this.initPromise?(this.needsReinit=!0,h.info("Project path changed while init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{h.warn("Failed to re-init project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new ly;if(await this.server.connect(e),h.info("devecocli-mcp-server started"),!this.config.debug){let t=Kc();t&&h.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=Re(t);r?(h.info(`Detected project path from client root: ${r}`),this.config.projectPath=r,this.sdkPath=this.computeSdkPath()):h.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?h.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):h.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{h.warn("Background project init failed:",t)}),this.initializeCppCheck()}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return h.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return h.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){h.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,h.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{h.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{h.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}initializeCppCheck(){let e=this.config.projectPath;if(!e){h.warn("C++ LSP initialization skipped: project path is not configured");return}this.cppCheckTool=new Bt(e,this.config.devecoPath??null),h.info("CppCheckTool created (lazy initialization)")}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{h.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?Re(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=Re(this.originalProjectPath),t&&h.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.sdkPath=this.computeSdkPath(),this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&(this.sdkPath||(this.sdkPath=this.computeSdkPath()),!!await this.ensureProjectSynced())){this.projectState=3,this.arktsCheckTool=new $t(this.config.projectPath,this.config.devecoPath??null,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{h.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,h.info("Project fully initialized, check tool is available")}catch(e){h.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=El(e);return t.required?(h.info(`Sync required: ${t.reason}`),this.runSync(e)):(h.info(`Sync skipped: ${t.reason}`),!0)}async runSync(e){this.projectState=2,h.info("Starting project sync...");let t=await jt.handleSyncProject(e,this.sdkPath);switch(t.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let r=Date.now()-this.syncSkipStartedAt,i=Math.round(r/1e3);return r>=Pl?(h.error(`Sync skipped for ${i}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(h.warn(`Sync skipped: ${t.reason}, resetting to IDLE for retry (elapsed ${i}s / ${Pl/1e3}s)`),this.projectState=0,!1)}case"failed":return h.error(`Project sync failed: ${t.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}computeSdkPath(){let e=fr(this.config.devecoPath??""),t=de(e);return ut.join(t,"sdk")}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppCheckTool&&await this.cppCheckTool.shutdown();try{await this.server.close()}catch(e){h.warn("Failed to close MCP server connection:",e)}h.info("devecocli-mcp-server stopped"),Jc(),Yc()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function dy(n){let e=[],t=[],r=[];for(let i of n)ut.extname(i).toLowerCase()===".ets"?e.push(i):gr(i)?t.push(i):r.push(i);return{etsFiles:e,cppFiles:t,unsupported:r}}function jo(n={}){return new Qr(n)}import*as $o from"fs";import*as Wt from"path";import{spawn as uy}from"child_process";async function Dl(n){fn(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:i,serverMaxSize:o}=await py(n),s=gy(e,t,r,i,o);h.info("ace-server started, bridging stdio (initialize is left to the client)"),vy(s)}async function py(n){let e=await my();e||(h.error("DevEco Studio not found. Ensure DevEco Studio is installed."),process.exit(1));let t=ue(n.projectPath??process.cwd()),r=Wt.join(de(e),"sdk"),i=It(e);i||(h.error("ace-server not found in DevEco Studio installation."),process.exit(1));let o=Wt.resolve(i,"ace-server","out","standardIndex","index.js"),s=Wt.join(At(),"lsp-server",String(Date.now()));$o.mkdirSync(s,{recursive:!0});let a=hy(t,r);return h.info(`projectPath=${t}, sdkPath=${r}, serverPath=${o}, logPath=${s}, serverMaxSize=${a}MB`),{projectPath:t,sdkPath:r,serverPath:o,logPath:s,serverMaxSize:a}}function my(){return N.new().then(n=>n.devecoStudioPath).catch(()=>be())}function hy(n,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=t?parseInt(t,10):NaN,i=Number.isFinite(r)&&r>0?r:void 0,o=fy(n,e),s=Sr(o,i);return h.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${o}, override=${i??"none"})`),s}function fy(n,e){try{let t=[];return new dt(n,e).getAllDependencyMap(t).status==="OK"?t.length:new Oe(n).getAllModuleInfo().length}catch{return 0}}function gy(n,e,t,r,i){let o=Wt.join(e,"lspLog");$o.mkdirSync(o,{recursive:!0});let s=yy(n,o,t,r,i),a=process.execPath??"node";return h.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),uy(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function yy(n,e,t,r,i){let o=j(e);return["--expose-gc",`--max-old-space-size=${i}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${o}`,n,"--stdio",`--logger-path=${o}`,"--logger-level=TRACE",`--projectPath=${j(t)}`,`--sdkPath=${j(r)}`]}function vy(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{h.error(`[ace-server] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{h.info(`ace-server exited with code ${e}`),process.exit(e??0)})}async function by(){let n=process.env.PROJECT_PATH||"",e=process.env.DEVECO_PATH,t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=process.env.DEBUG==="true"||process.env.DEBUG==="1",i=await N.new(),o=n,s=e??i.devecoStudioPath,a=jo({projectPath:o,devecoPath:s,nodeMaxOldSpaceSize:t,debug:r}),c=async()=>{await a.shutdown(),process.exit(0)};process.once("SIGINT",c),process.once("SIGTERM",c),process.platform==="win32"&&process.once("SIGBREAK",c);try{await a.start()}catch(l){console.error("Failed to start MCP server:",l),process.exit(1)}}var Bo=new wy("serve").description("Host bundled auxiliary protocol servers");Bo.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await by()});Bo.command("lsp").description("Start a bundled LSP language server").option("--arkts","Start the ArkTS language server (ace-server)").option("--project-path <path>","HarmonyOS project root path",process.cwd()).action(async n=>{n.arkts||(console.error("Use --arkts to start the ArkTS language server."),process.exit(1)),await Dl({projectPath:n.projectPath})});var Il=Bo;import{Command as wb,InvalidArgumentError as As}from"commander";import{red as xi,dim as bb}from"colorette";import*as z from"fs";import*as Jt from"path";import rb from"adm-zip";import ib from"proper-lockfile";import Ru from"ora";import*as Ee from"fs";import*as Tn from"path";var Ve=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],pt={"harmonyos-guides":"\u5F00\u53D1\u6307\u5357","harmonyos-references":"API\u53C2\u8003","best-practices":"\u6700\u4F73\u5B9E\u8DF5","harmonyos-faqs":"FAQ","harmonyos-releases":"\u7248\u672C\u8BF4\u660E","harmonyos-roadmap":"\u53D8\u66F4\u9884\u544A"};var ei="1.9.1",fR=100*1024*1024,Al=280,xl=6,Tl=100,kl=3,Rl=28,Wo=10,Ml=/API参考|APIReference/i,In=200,Ol=12,Ll=4,Uo=8,Nl=6,ti=700,zo=250,qo=400,_l=1320,Hl=120,Fl=450,jl=250,$l=500,Bl=480,Wl=80,Ul=200,zl=60,ql=200,Gl=40,Vl=200,Yl=200,Jl=40,Ut=500,Kl=Object.fromEntries(Ve.map((n,e)=>[pt[n],e])),Ye=Object.fromEntries(Ve.map((n,e)=>[n,e]));import*as Ql from"fs";import*as O from"path";import{fileURLToPath as ed}from"url";import*as ni from"path";import{homedir as Sy}from"os";var Ey="deveco-cli";function Xl(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function Py(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&Xl(n)!==""}function Zl(){return ni.join(Sy(),".local","share",Ey)}function ri(n){let e=ii();return Py()?[`Data directory (DEVECO_CLI_DATA_DIR): ${e}`,"If you changed this in System Environment Variables, open a new terminal and retry.",`Log file: ${n}`]:[`Data directory (default): ${e}`,"To use a custom location, set DEVECO_CLI_DATA_DIR and open a new terminal.",`Log file: ${n}`]}function ii(){let n=process.env.DEVECO_CLI_DATA_DIR;if(n===void 0||n==="")return Zl();let e=Xl(n);return e?ni.resolve(e):Zl()}var Cy="docs";function oi(){return O.join(ii(),Cy)}function te(){return O.join(oi(),".index")}function td(){return O.join(te(),"build.lock")}function Go(){return O.join(te(),"build-status.json")}function si(){return O.join(te(),"build-meta.json")}function An(){return O.join(te(),"search.db")}function zt(){return O.join(te(),".tmp")}function Dy(){return O.join(ii(),"logs")}function qt(){return O.join(Dy(),"doc-init.log")}function Iy(n,e){let t=e;for(;!t.endsWith(`${O.sep}dist`)&&t!==O.dirname(t);)t=O.dirname(t);return t}function nd(n,e){return O.dirname(Iy(n,e))}function Ay(){let n=ed(import.meta.url),e=O.dirname(n);return n.includes(`${O.sep}dist${O.sep}`)?nd(n,e):O.join(e,"..","..","..")}function xy(...n){let e=ed(import.meta.url),t=O.dirname(e);return e.includes(`${O.sep}dist${O.sep}`)?[O.join(nd(e,t),...n)]:[O.join(t,"..","..","..",...n)]}function rd(...n){for(let e of xy(...n))if(Ql.existsSync(e))return e;return null}function Je(){return rd("docs.zip")}function Vo(){return rd("index.zip")}function id(){return O.join(Ay(),"index","data")}import*as Ne from"fs";import*as mt from"path";var ht=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],ai=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function od(n){return n instanceof ai}var Yo=null;function Jo(n){Yo=n}function Ko(){if(Yo)return Yo;let n=te();if(ht.every(i=>Ne.existsSync(mt.join(n,i))))return n;let t=id();if(ht.every(i=>Ne.existsSync(mt.join(t,i))))return t;throw new ai("Lexicon files not found. Install the documentation index first (index.zip).")}function sd(){Ko()}function Gt(n){let e=mt.join(Ko(),n);return Ne.readFileSync(e,"utf-8")}function ad(n,e){return Ne.readFileSync(mt.join(e,n),"utf-8")}async function cd(n,e=Ko()){await Ne.promises.mkdir(n,{recursive:!0});for(let t of ht){let r=mt.join(e,t),i=mt.join(n,t);await Ne.promises.copyFile(r,i)}}import*as ci from"fs";import*as ld from"path";import*as dd from"yauzl";var xn=null;function Ty(n){return new Promise((e,t)=>{dd.open(n,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(r,i)=>{if(r||!i){t(r??new Error(`Failed to open zip: ${n}`));return}e(i)})})}function ky(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function Ry(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",i=>{let o=ky(i);o.endsWith("/")||e.set(o,i),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function My(){xn?.zipfile.close(),xn=null}async function Oy(n){let e=ld.resolve(n),t=await ci.promises.stat(e),r=xn;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;My();let i=await Ty(e),o=await Ry(i);return xn={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:i,entries:o,readChain:Promise.resolve()},xn}function Ly(n,e){return new Promise((t,r)=>{n.openReadStream(e,(i,o)=>{if(i||!o){r(i??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];o.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),o.on("end",()=>{t(Buffer.concat(s))}),o.on("error",r)})})}async function Ny(n,e){let t=n.readChain,r;n.readChain=new Promise(i=>{r=i}),await t;try{return await Ly(n.zipfile,e)}finally{r()}}function _y(n){let e=n.replace(/\\/g,"/").replace(/\.md$/,"");return[`docs/${e}.md`,`${e}.md`,`docs/${e}`,e]}function Hy(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function ud(n){let e=Je();if(!e)throw new Error("docs.zip not found");let t=await Oy(e),r=Hy(t.entries,_y(n));if(!r)throw new Error(`Document not found: ${n}`);return(await Ny(t,r)).toString("utf-8")}function Zo(){let n=Je();return n!==null&&ci.existsSync(n)}import*as K from"fs";import*as Ke from"path";import pd from"adm-zip";var md=["search.db","build-meta.json",...ht],Fy=["corpus.json","corpus-offsets.json","orama.dpack"];async function jy(n){for(let e of Fy)await K.promises.rm(Ke.join(n,e),{force:!0})}async function $y(n){let e=await K.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await K.promises.rm(Ke.join(n,t.name),{recursive:!0,force:!0})}function By(n){let t=new pd(n).getEntry("build-meta.json");if(!t)throw new Error("index.zip is missing build-meta.json");return JSON.parse(t.getData().toString("utf-8"))}async function Wy(n){let e=te();await K.promises.mkdir(e,{recursive:!0});for(let t of md){let r=Ke.join(e,t);await K.promises.rm(r,{force:!0}),await K.promises.rename(Ke.join(n,t),r)}await jy(e),await K.promises.rm(zt(),{recursive:!0,force:!0})}function Xo(){let n=Vo();return n!==null&&K.existsSync(n)}async function hd(n){let e=Vo();if(!e)throw new Error("index.zip not found");let t=By(e);if(t.docsZipSha256!==n)throw new Error("Bundled index.zip does not match docs.zip. Rebuild index.zip with npm run build:index.");if(t.segmentCount<=0)throw new Error("Bundled index.zip is empty");let r=zt();await K.promises.rm(r,{recursive:!0,force:!0}),await K.promises.mkdir(r,{recursive:!0});let i=new pd(e);for(let s of md){let a=i.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await K.promises.writeFile(Ke.join(r,s),a.getData())}let o=JSON.parse(await K.promises.readFile(Ke.join(r,"build-meta.json"),"utf-8"));if(!K.existsSync(Ke.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await Wy(r),await K.promises.mkdir(oi(),{recursive:!0}),await $y(oi()),o}import{createHash as fd}from"crypto";import*as gd from"fs";async function li(n){return new Promise((e,t)=>{let r=fd("sha256"),i=gd.createReadStream(n);i.on("data",o=>r.update(o)),i.on("error",t),i.on("end",()=>e(r.digest("hex")))})}function yd(n){return fd("sha256").update(n,"utf8").digest("hex")}var Qo=null;function Uy(){let n=Gt("harmonyos-synonyms.json");return JSON.parse(n)}function zy(n){let e=new Map;for(let t of n){let r=t.map(i=>i.trim()).filter(Boolean);for(let i of r){let o=r.filter(s=>s!==i);e.set(i.toLowerCase(),o),i!==i.toLowerCase()&&e.set(i,o)}}return e}function qy(){let n=zy(Uy()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function Gy(){return Qo||(Qo=qy()),Qo}function es(n,e){let t=Gy(),r=n.split(/\s+/).filter(Boolean),i=new Set,o=Number.isFinite(e)?e:r.length;for(let s=0;s<r.length&&i.size<o;s+=1){let a=r[s];i.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(i.size>=o)break;i.add(l)}}return[...i].join(" ")}function vd(n,e){let t=e?ad(n,e):Gt(n);return yd(t)}function di(n){return vd("harmonyos-synonyms.json",n)}function ui(n){return vd("harmonyos-terms.txt",n)}var Vy={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function pi(){try{let n=await Ee.promises.readFile(Go(),"utf-8");return JSON.parse(n)}catch{return{...Vy}}}async function ts(n){let e=Go();await Ee.promises.mkdir(Tn.dirname(e),{recursive:!0}),await Ee.promises.writeFile(e,JSON.stringify(n,null,2))}function wd(n){let e=Date.now();return{state:"extracting",phase:1,phaseLabel:"Extracting documentation",current:0,total:0,message:n,startedAt:e,updatedAt:e,error:null}}async function Ze(n){let t={...await pi(),...n,updatedAt:Date.now()};return await ts(t),t}async function ns(){let n=Je();return n?li(n):null}async function rs(){try{let n=await Ee.promises.readFile(si(),"utf-8");return JSON.parse(n)}catch{return null}}async function is(n=!1){if(n)return"no-index";let e=await rs();if(!e||e.segmentCount===0)return"no-index";let t=await ns();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==ei?"engine-upgraded":e.termsHash!==ui()?"terms-changed":e.synonymsHash!==di()?"synonyms-changed":null}function kn(){if(!Zo()||!Ee.existsSync(An())||!Ee.existsSync(si()))return!1;let n=Tn.dirname(An());if(!ht.every(e=>Ee.existsSync(Tn.join(n,e))))return!1;try{let e=Ee.readFileSync(si(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function os(n=!1){return n?!0:Zo()?kn()?await is()!==null:!0:!1}async function bd(){let n=await pi();return["installing","indexing","persisting"].includes(n.state)}import*as Z from"fs";import*as Cu from"os";import*as ie from"path";var Sd=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),ss=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),Ed=new Set(["a","an","and","api","app","application","arkts","arkui","for","get","harmonyos","how","in","oh","ohos","on","or","set","the","to","use","using","what","when","where","which","with","without","data","file","main","model","name","network","stage","system","type","user"]),Pd=new Set(["ability","extension","module","service","context","options","config","info","event","code","state","type","data","request","response","client","server","handler","helper","utils","factory","builder","listener","callback","observer","provider","consumer","delegate","adapter","driver","buffer","stream","channel","session","task","worker","controller","component","container","attribute","descriptor","modifier","validator","parser","formatter","encoder","decoder","filter","converter","generator","iterator","dispatcher","resolver","scanner","tracker","monitor","scheduler","renderer","loader","subscriber","proxy","button","surface","stack","heap","map","set","array","list"]);var Yy=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,Jy=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,Ky=/[A-Z][a-zA-Z0-9]{2,}/g,Zy=/@[A-Z][a-zA-Z0-9]*/g,Xy=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,Cd=6,Qy=/^[a-z][a-z0-9]{2,}$/,ev=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,tv=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,nv=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,rv=/^[A-Z][a-zA-Z0-9]+$/;function iv(n){return`"${n.replace(/"/g,'""')}"`}function Mn(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(iv).join(` ${e} `)}function Rn(n){return Mn(n,"OR")}function Dd(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?Rn([...t,...r]):`(${Rn(t)}) AND (${Rn(r)})`}function On(n){return tv.test(n)}function Id(n){return nv.test(n)&&n.length>=Cd}function ov(n){return rv.test(n)}function Ln(n){return On(n)||Id(n)||ov(n)}function sv(n){let e=n.trim().toLowerCase();return Pd.has(e)?!1:Sd.has(e)}function av(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function mi(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function as(n){return[...n.matchAll(Yy)].map(e=>e[0])}function cs(n,e=Cd){let t=[];for(let r of n.matchAll(Jy))r[0].length>=e&&t.push(r[0]);return t}function Vt(n){return n.filter(e=>{let t=e.toLowerCase();return!n.some(r=>{if(r===e)return!1;let i=r.toLowerCase();return i.length>t.length&&i.endsWith(t)&&t.length>=4})})}function Pe(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function cv(n){let e=new Set;Pe(e,n);let t=mi(n);return t&&Pe(e,t),Vt([...e])}function hi(n){if(On(n))return cv(n);let e=new Set;return Pe(e,n),Vt([...e])}function fi(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(ev);if(!t)return null;let r=t[1].toLowerCase(),i=t[2].toLowerCase();if(!Qy.test(r)||Ed.has(r)||!sv(i))return null;let o=av(r,i);return{first:r,second:i,camelCase:o,lower:o.toLowerCase()}}function ls(n){let e=fi(n.trim());return!e||e.second!=="manager"?null:e}function lv(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function Ad(n){let e=n.trim(),t=ls(e);if(t&&ss.has(t.first))return!0;if(Id(e)){let r=lv(e);return r!==null&&ss.has(r)}return!1}function ds(n,e,t){let r=t.toLowerCase(),i=new RegExp(`@ohos\\.[^\\s(]*${t}`,"i");for(let o of[n,e])if(o&&(o.toLowerCase().includes(r)||i.test(o)))return!0;return!1}function us(n){let e=n.trim();if(Ln(e))return hi(e);let t=new Set;for(let r of as(n)){Pe(t,r);let i=mi(r);i&&Pe(t,i)}for(let r of cs(n))Pe(t,r);for(let r of n.matchAll(Zy))t.add(r[0]);for(let r of n.matchAll(Xy))t.add(r[0]);for(let r of n.matchAll(Ky))r[0].length>=4&&t.add(r[0]);return Vt([...t])}function xd(n){let e=n.trim();if(Ln(e))return hi(e);let t=new Set,r=fi(e);r&&Pe(t,r.camelCase);for(let i of us(e))t.add(i);for(let i of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let o=i[0];o!==o.toLowerCase()&&t.add(o)}return Vt([...t])}function Td(n){return Ln(n)}var _={pureApiSymbol:/^[A-Z][a-zA-Z0-9]+$/,stageModelExact:/^Stage\s*模型$/i,stageModelEnglishExact:/^stage\s+model$/i,stageModel:/Stage\s*模型/i,stageModelEntryPage:/Stage\s*模型.*EntryAbility.*(页面|新页面)/,declarePermissionBoost:/声明.*权限|应用权限.*声明|如何声明应用权限/,declarePermissionCatalog:/如何声明应用权限/,declarePermissionTokens:/如何声明应用权限|声明应用权限/,uiAbilityLifecycleBoost:/UIAbility.*生命周期|生命周期.*UIAbility|UIAblity/i,uiAbilityLifecycleCatalog:/UIAblity.*生命周期|UIAbility.*生命周期/i,entryAbilityPage:/EntryAbility.*(页面|启动|跳转|新页面)/,stateDecoratorBoost:/@State|@Prop|@Link|@Provide|@Consume/,stateDecoratorCatalog:/@State\s*装饰器|@Prop\s*装饰器|@Link\s*装饰器/,stateManagement:/状态管理原理/,routerRoute:/Router\s+路由/,dialogPopupExact:/^Dialog\s+弹窗$/,dialogPopupBoost:/Dialog\s+弹窗/};function kd(n){return _.pureApiSymbol.test(n.trim())}function Nn(n){let e=n.trim();return _.stageModelExact.test(e)||_.stageModelEnglishExact.test(e)}function Rd(n){let e=[];return Nn(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),_.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),_.stageModelEntryPage.test(n)&&e.push("\u9875\u9762\u8DEF\u7531","pushUrl"),/UIAblity|UIAbility/.test(n)&&/生命周期/.test(n)&&e.push("UIAbility\u7EC4\u4EF6\u751F\u547D\u5468\u671F"),e}function Md(n){return Nn(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var dv=[{matches:n=>_.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>Nn(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!Nn(n)&&_.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>_.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>_.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>_.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>_.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>_.routerRoute.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:1.4},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]},{matches:n=>_.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function uv(n,e){for(let{catalog:t,multiplier:r}of e){let i=Ye[t];n.set(i,(n.get(i)??1)*r)}}function Od(n,e){for(let t of dv)t.matches(n)&&uv(e,t.weights)}function Ld(n,e){if(e!==void 0)return!1;let t=n.trim();return On(t)||_.pureApiSymbol.test(t)||Ad(t)}function Nd(n){let e=n.trim();if(On(e)||_.pureApiSymbol.test(e))return"harmonyos-references";if(Nn(e)||_.uiAbilityLifecycleCatalog.test(e)||_.stateDecoratorCatalog.test(e)||_.stateManagement.test(e)||_.declarePermissionCatalog.test(e)||_.stageModelEntryPage.test(e)||_.routerRoute.test(e)||_.dialogPopupExact.test(e))return"harmonyos-guides"}import{Jieba as pv}from"@node-rs/jieba";import{dict as mv}from"@node-rs/jieba/dict.js";var gi=null,ps=null,ms=null;function hv(){if(gi)return gi;let n=Gt("harmonyos-stopwords.txt");return gi=new Set(n.split(`
|
|
1296
|
-
`).map(e=>e.trim()).filter(Boolean)),
|
|
1282
|
+
`)].filter(h=>h.trim().length>0).join(`
|
|
1283
|
+
`).trim()||"No diagnostics collected"}],isError:l}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return g.warn(`ArkTS check rejected: project is ${tl[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return g.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e});default:return g.error(`ArkTS check: unknown project state ${this.projectState}, files: ${e.join(", ")}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],isError:!0}}}async handleLspFeatureCall(e,t){let r=t.file,i=t.line,o=t.character;if(typeof r!="string"||typeof i!="number"||typeof o!="number")return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};let s=this.validateContainment([r]);return s||this.routeLspRequest(r,e,async()=>{if(r.endsWith(".ets"))return this.arktsCheckTool.handleLspFeature(e,{file:r,line:i,character:o});let a=e;return this.cppLspTool.handleLspFeature(a,{file:r,line:i,character:o})})}async handleWorkspaceSymbolCall(e){let t=e.query;return typeof t!="string"||t.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameter: query (non-empty string required)."}],isError:!0}:this.routeWorkspaceSymbolRequest(t)}async routeWorkspaceSymbolRequest(e){let t=this.projectState===4&&this.arktsCheckTool!==null,r=this.cppProjectState===4&&!this.cppHasNoCppCode&&this.cppLspTool!==null;if(!t&&!r){let a=this.describeArktsState(),c=this.describeCppState();return g.info(`workspaceSymbol rejected: ArkTS ${a}; C++ ${c}`),{content:[{type:"text",text:`workspaceSymbol: ArkTS ${a}; C++ ${c}`}],isError:!0}}let i=[],o=new Set;if(t)try{this.mergeSymbolItems(await this.arktsCheckTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){g.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(r)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){g.warn(`workspaceSymbol C++ query failed: ${a.message}`)}return{content:[{type:"text",text:i.length===0?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(i,null,2)}`}]}}symbolDedupKey(e){let t=e,r=t?.location?.uri??"",i=t?.location?.range?.start?.line??0,o=t?.location?.range?.start?.character??0;return`${r}:${i}:${o}`}mergeSymbolItems(e,t,r){if(e)for(let i of e){let o=this.symbolDedupKey(i);t.has(o)||(t.add(o),r.push(i))}}describeArktsState(){switch(this.projectState){case 0:return"idle";case 1:return"discovering";case 2:return"syncing (retry 10s)";case 3:return"initializing (retry 10s)";case 5:return`error (${this.initRetryCount}/${zt})`;case 4:return"ready";default:return"unknown"}}describeCppState(){switch(this.cppProjectState){case 0:return"idle";case 1:return"discovering";case 2:return"syncing (retry 25s)";case 3:return"initializing (retry 10s)";case 5:return`error (${this.cppInitRetryCount}/${zt})`;case 4:return this.cppHasNoCppCode?"ready (no C++ code)":"ready";default:return"unknown"}}async handleDocumentSymbolCall(e){let t=e.file;if(typeof t!="string")return{content:[{type:"text",text:"Missing or invalid parameter: file (string required)."}],isError:!0};let r=this.validateContainment([t]);return r||this.routeLspRequest(t,"documentSymbol",async()=>t.endsWith(".ets")?this.arktsCheckTool.handleDocumentSymbol(t):this.cppLspTool.handleDocumentSymbol(t))}async handleCallHierarchyCall(e){let t=e.file,r=e.line,i=e.character,o=e.direction;if(typeof t!="string"||typeof r!="number"||typeof i!="number")return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};if(o!=="incoming"&&o!=="outgoing")return{content:[{type:"text",text:'Parameter direction must be "incoming" or "outgoing".'}],isError:!0};let s=this.validateContainment([t]);return s||this.routeLspRequest(t,`callHierarchy(${o})`,async()=>t.endsWith(".ets")?this.arktsCheckTool.handleCallHierarchy({file:t,line:r,character:i,direction:o}):this.cppLspTool.handleCallHierarchy({file:t,line:r,character:i,direction:o}))}async handleCodeActionCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e);if(!t)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};let o=this.validateContainment([t]);return o||this.routeArktsRequest("codeAction",()=>this.arktsCheckTool.handleCodeAction({file:t,line:r,character:i}))}async handleRenameCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e),o=e.newName;if(!t||typeof o!="string"||o.trim().length===0)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number), newName (non-empty string)."}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest("rename",()=>this.arktsCheckTool.handleRename({file:t,line:r,character:i,newName:o}))}async handleTypeHierarchyCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e),o=e.direction;if(!t)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};if(o!=="supertypes"&&o!=="subtypes")return{content:[{type:"text",text:'Parameter direction must be "supertypes" or "subtypes".'}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest(`typeHierarchy(${o})`,()=>this.arktsCheckTool.handleTypeHierarchy({file:t,line:r,character:i,direction:o}))}async handleCompletionItemResolveCall(e){let t=e.item;return t==null?{content:[{type:"text",text:"Missing parameter: item (completion item object required)."}],isError:!0}:this.routeArktsRequest("completionItemResolve",()=>this.arktsCheckTool.handleCompletionItemResolve(t))}extractPositionArgs(e){let t=e.file,r=e.line,i=e.character;return typeof t!="string"||typeof r!="number"||typeof i!="number"?{file:null,line:0,character:0}:{file:t,line:r,character:i}}async routeArktsRequest(e,t){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return g.warn(`ArkTS ${e} rejected: project is ${tl[this.projectState]}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return g.warn(`ArkTS ${e} rejected: LSP is initializing`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return t()}}async handleIdleCheck(){if(this.ensureProjectReady(),this.config.projectPath){let e,t;return this.syncSkippedDueToLock?(e=`Another build process is running, sync deferred (waiting ${this.syncSkipStartedAt>0?Math.round((Date.now()-this.syncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,t="lock contention",this.syncSkippedDueToLock=!1):this.configChangedTriggeredResync?(e="Config file changed, resyncing project, please retry in 10 seconds",t="config changed",this.configChangedTriggeredResync=!1):(e="HarmonyOS project detected, syncing, please retry in 10 seconds",t="initial"),g.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(g.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(g.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=zt?(g.error(`Init retry limit reached (${this.initRetryCount}/${zt}), will not auto-retry`),{content:[{type:"text",text:"Project initialization failed multiple times. Please check project configuration and restart the MCP Server."}],isError:!0}):(g.info(`Error check: auto-retrying (${this.initRetryCount}/${zt})`),this.ensureProjectReady(),{content:[{type:"text",text:"Project initialization failed, auto-retrying, please retry in 10 seconds"}],isError:!0})}async routeCppRequest(e,t){switch(this.cppProjectState){case 0:return this.handleCppIdleCheck();case 1:case 2:return g.warn(`C++ ${e} rejected: C++ project is ${im[this.cppProjectState]}`),{content:[{type:"text",text:"C++ project is syncing (compileNative), please retry in 25 seconds"}],isError:!0};case 3:return g.warn(`C++ ${e} rejected: clangd is initializing`),{content:[{type:"text",text:"C++ LSP (clangd) is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleCppErrorCheck();case 4:return this.cppHasNoCppCode?{content:[{type:"text",text:"No C++ code in this project"}],isError:!0}:this.cppLspManager?.ready?t():{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}}async routeLspRequest(e,t,r){return e.endsWith(".ets")?this.routeArktsRequest(t,r):un(e)?this.routeCppRequest(t,r):{content:[{type:"text",text:`Unsupported file type: ${e} (only .ets and C/C++ source/header files are supported)`}],isError:!0}}async handleCppIdleCheck(){if(this.ensureCppProjectReady(),this.config.projectPath){let e;return this.cppSyncSkippedDueToLock?(e=`Another build process is running, C++ sync deferred (waiting ${this.cppSyncSkipStartedAt>0?Math.round((Date.now()-this.cppSyncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,this.cppSyncSkippedDueToLock=!1):e="C++ project detected, syncing (compileNative), please retry in 25 seconds",g.info(`C++ idle check: project '${this.config.projectPath}', triggering C++ init`),{content:[{type:"text",text:e}],isError:!0}}return{content:[{type:"text",text:"No HarmonyOS project detected for C++ tools."}],isError:!0}}async handleCppErrorCheck(){return this.cppInitRetryCount>=zt?(g.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${zt}), will not auto-retry`),{content:[{type:"text",text:"C++ project initialization failed multiple times. Please check project configuration and restart the MCP Server."}],isError:!0}):(g.info(`C++ error check: auto-retrying (${this.cppInitRetryCount}/${zt})`),this.ensureCppProjectReady(),{content:[{type:"text",text:"C++ project initialization failed, auto-retrying, please retry in 25 seconds"}],isError:!0})}async callCppCheck(e){return this.routeCppRequest("check",async()=>this.cppCheckTool.handleCall({files:e}))}mergeCheckResult(e,t,r){let i=e.content.map(o=>o.text).filter(o=>o&&o.trim().length>0).join(`
|
|
1284
|
+
`);i&&(e.isError?t.push(i):r.push(i))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{g.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(t=>{g.warn("Failed to dispose ClangdLspManager during setProjectPath:",t)}),this.cppLspManager=null),this.initPromise?(this.needsReinit=!0,g.info("Project path changed while ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{g.warn("Failed to re-init project after setProjectPath:",t)})),this.cppInitPromise?(this.cppNeedsReinit=!0,g.info("Project path changed while C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.cppHasNoCppCode=!1,this.cppInitRetryCount=0,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.ensureCppProjectReady().catch(t=>{g.warn("Failed to re-init C++ project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new XP;if(await this.server.connect(e),g.info("devecocli-mcp-server started"),!this.config.debug){let t=lu();t&&g.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=ht(t);r?(g.info(`Detected project path from client root: ${r}`),this.config.projectPath=r,this.sdkPath=this.computeSdkPath()):g.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?g.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):g.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{g.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return g.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return g.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){g.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,g.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{g.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{g.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{g.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?ht(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=ht(this.originalProjectPath),t&&g.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.sdkPath=this.computeSdkPath(),this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&(this.sdkPath||(this.sdkPath=this.computeSdkPath()),!!await this.ensureProjectSynced())){this.ensureCppProjectReady().catch(e=>{g.warn("Background C++ project init failed:",e)}),this.projectState=3,this.arktsCheckTool=new sr(this.config.projectPath,this.config.devecoPath??null,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{g.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,g.info("Project fully initialized, check tool is available")}catch(e){g.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=nm(e),r=!t.required;return g.info(`Sync check: skipHvigor=${r}, reason=${t.reason}`),this.runSync(e,{skipHvigorSync:r})}async runSync(e,t){this.projectState=2,g.info("Starting project sync...");let r=await or.handleSyncProject(e,this.sdkPath,t);switch(r.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let i=Date.now()-this.syncSkipStartedAt,o=Math.round(i/1e3);return i>=el?(g.error(`Sync skipped for ${o}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(g.warn(`Sync skipped: ${r.reason}, resetting to IDLE for retry (elapsed ${o}s / ${el/1e3}s)`),this.projectState=0,!1)}case"failed":return g.error(`Project sync failed: ${r.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return g.error(`Project sync: unknown status ${r.status}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}async ensureCppProjectReady(){if(!this.cppInitPromise){this.cppInitPromise=this.doEnsureCppProjectReady();try{await this.cppInitPromise}finally{this.cppInitPromise=null}this.cppNeedsReinit&&(this.cppNeedsReinit=!1,this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>{g.warn("Failed to re-init C++ project after cppNeedsReinit:",e)}))}}async doEnsureCppProjectReady(){let e=this.config.projectPath;if(!e){g.info("[Cpp] No project path, skipping C++ init");return}this.cppProjectState=1;let t=mn(e);if(t.length===0){g.info('[Cpp] No C++ modules found, C++ tools will return "no C++ code"'),this.cppHasNoCppCode=!0,this.cppProjectState=4,this.cppInitRetryCount=0;return}if(this.cppHasNoCppCode=!1,g.info(`[Cpp] Found ${t.length} C++ module(s): ${t.map(r=>r.name).join(", ")}`),!!await this.runSyncCpp(e)){this.cppProjectState=3,this.cppLspManager=new Si({workspaceRoot:e,devecoPath:this.config.devecoPath??null});try{await this.cppLspManager.start(),this.cppCheckTool=new cr(this.cppLspManager),this.cppLspTool=new lr(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,g.info("[Cpp] C++ project fully initialized, C++ tools are available")}catch(r){g.error("[Cpp] C++ LSP initialization failed:",r),this.cppLspManager&&this.cppLspManager.dispose().catch(()=>{}),this.cppLspManager=null,this.cppCheckTool=null,this.cppLspTool=null,this.cppInitRetryCount++,this.cppProjectState=5}}}async runSyncCpp(e){this.cppProjectState=2,g.info("[Cpp] Starting C++ project sync (compileNative)...");let t=this.config.devecoPath??Je();if(!t)return g.error("[Cpp] DevEco Studio installation path not found, cannot sync C++ project"),this.cppInitRetryCount++,this.cppProjectState=5,!1;let r=await Si.handleSyncCppProject(e,t);switch(r.status){case"success":return this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,!0;case"skipped":{this.cppSyncSkippedDueToLock=!0,this.cppSyncSkipStartedAt===0&&(this.cppSyncSkipStartedAt=Date.now());let i=Date.now()-this.cppSyncSkipStartedAt,o=Math.round(i/1e3);return i>=el?(g.error(`[Cpp] C++ sync skipped for ${o}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(g.warn(`[Cpp] C++ sync skipped: ${r.reason}, resetting to IDLE_CPP for retry (elapsed ${o}s)`),this.cppProjectState=0,!1)}case"failed":return g.error(`[Cpp] C++ project sync failed: ${r.reason}`),this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitRetryCount++,this.cppProjectState=5,!1}return!1}computeSdkPath(){let e=ru(this.config.devecoPath??""),t=ct(e);return En.join(t,"sdk")}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppLspManager&&await this.cppLspManager.dispose(),this.cppCheckTool=null,this.cppLspTool=null;try{await this.server.close()}catch(e){g.warn("Failed to close MCP server connection:",e)}g.info("devecocli-mcp-server stopped"),cu(),au()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function ZP(n){let e=[],t=[],r=[];for(let i of n)En.extname(i).toLowerCase()===".ets"?e.push(i):un(i)?t.push(i):r.push(i);return{etsFiles:e,cppFiles:t,unsupported:r}}function nl(n={}){return new Fs(n)}import*as rl from"fs";import*as ur from"path";import{spawn as QP}from"child_process";async function om(n){fn(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:i,serverMaxSize:o}=await eC(n),s=rC(e,t,r,i,o);g.info("ace-server started, bridging stdio (initialize is left to the client)"),oC(s)}async function eC(n){let e=await I.new();e.require({clt:!1});let t;if(n.projectPath)t=oe(ur.resolve(n.projectPath)),g.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let c=mo(process.cwd());t=oe(c??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=oe(process.cwd()),g.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,i=On(e.devecoStudioPath);i||(g.error("ace-server not found in DevEco Studio installation."),process.exit(1));let o=ur.resolve(i,"ace-server","out","standardIndex","index.js"),s=ur.join(Mt(),"lsp-server",String(Date.now()));rl.mkdirSync(s,{recursive:!0});let a=tC(t,r);return g.info(`projectPath=${t}, sdkPath=${r}, serverPath=${o}, logPath=${s}, serverMaxSize=${a}MB`),{projectPath:t,sdkPath:r,serverPath:o,logPath:s,serverMaxSize:a}}function tC(n,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=t?parseInt(t,10):NaN,i=Number.isFinite(r)&&r>0?r:void 0,o=nC(n,e),s=Eo(o,i);return g.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${o}, override=${i??"none"})`),s}function nC(n,e){try{let t=[];return new bn(n,e).getAllDependencyMap(t).status==="OK"?t.length:new gt(n).getAllModuleInfo().length}catch{return 0}}function rC(n,e,t,r,i){let o=ur.join(e,"lspLog");rl.mkdirSync(o,{recursive:!0});let s=iC(n,o,t,r,i),a=process.execPath??"node";return g.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),QP(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function iC(n,e,t,r,i){let o=H(e);return["--expose-gc",`--max-old-space-size=${i}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${o}`,n,"--stdio",`--logger-path=${o}`,"--logger-level=TRACE",`--projectPath=${H(t)}`,`--sdkPath=${H(r)}`]}function oC(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{g.error(`[ace-server] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{g.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as sm from"fs";import*as Pn from"path";import{spawn as sC}from"child_process";async function am(n){fn(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await aC(n),i=Pn.join(t,"compile_commands.json");sm.existsSync(i)||g.warn(`compile_commands.json not found at ${i}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let o=lC(e,t,r);g.info("clangd started, bridging stdio (initialize is left to the client)"),uC(o)}async function aC(n){let e=await cC();e||(g.error("DevEco Studio not found. Ensure DevEco Studio is installed."),process.exit(1));let t;if(n.projectPath)t=oe(Pn.resolve(n.projectPath)),g.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let s=mo(process.cwd());t=oe(s??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${s??"null, fallback to cwd"}`)}else t=oe(Pn.resolve(process.cwd())),g.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=ho(e);r||(g.error("clangd not found in DevEco Studio SDK. Expected at <deveco>/sdk/default/openharmony/native/llvm/bin/clangd"),process.exit(1));let i=Hr(t),o=Pn.dirname(i);return g.info(`projectPath=${t}, clangdPath=${r}, compileCommandsDir=${o}`),{projectPath:t,clangdPath:r,compileCommandsDir:o}}function cC(){return I.new().then(n=>n.devecoStudioPath).catch(()=>Je())}function lC(n,e,t){let r=dC(e);return g.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),sC(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function dC(n){return[`--compile-commands-dir=${H(n)}`,"--log=info","--pch-storage=memory"]}function uC(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{g.error(`[clangd] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{g.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function fC(){let n=process.env.PROJECT_PATH||"",e=process.env.NODE_MAX_OLD_SPACE_SIZE,t=process.env.DEBUG==="true"||process.env.DEBUG==="1",r=await I.new();r.require({clt:!1});let i=n,o=r.devecoStudioPath,s=nl({projectPath:i,devecoPath:o,nodeMaxOldSpaceSize:e,debug:t}),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 il=new pC("serve").description("Host bundled auxiliary protocol servers");il.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await fC()});il.command("lsp").description("Start a bundled LSP language server").option("--arkts","Start the ArkTS language server (ace-server)").option("--cpp","Start the C/C++ language server (clangd)").option("--project-path <path>","project root path (used as-is, no search)").option("--auto-detect","When --project-path is not specified, search the current directory and its subdirectories for the project root (no upward search)").action(async n=>{n.arkts&&n.cpp&&(console.error("--arkts and --cpp are mutually exclusive. Specify only one."),process.exit(1)),n.arkts?await om({projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await am({projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var cm=il;import{Command as mD,InvalidArgumentError as Yl}from"commander";import{red as ua,dim as hD}from"colorette";import*as X from"fs";import*as ut from"path";import ZA from"adm-zip";import QA from"proper-lockfile";import gg from"ora";import*as tt from"fs";import*as ki from"path";var Vt=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],Cn={"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 pr="1.9.1",K1=48*1024*1024,lm=280,dm=6,um=100,pm=3,fm=28,ol=10,mm=/API参考|APIReference/i,bi=200,hm=12,gm=4,sl=8,ym=6,js=700,al=250,cl=400,wm=1320,vm=120,Sm=450,bm=250,Em=500,Pm=480,Cm=80,Im=200,Am=60,Dm=200,Rm=40,Tm=200,km=200,xm=40,fr=500,Nm=Object.fromEntries(Vt.map((n,e)=>[Cn[n],e])),qt=Object.fromEntries(Vt.map((n,e)=>[n,e]));import*as Ei from"fs";import*as M from"path";import{fileURLToPath as _m}from"url";import*as Yt from"fs";import*as Lm from"path";import{homedir as mC}from"os";var hC="deveco-cli",ll,In=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function gC(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&io(n)!==""}function Om(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":io(n))||Lm.join(mC(),".local","share",hC);try{return oo(t)}catch(r){throw new In(r instanceof Error?r.message:String(r))}}async function Mm(){let n=Om();await Yt.promises.mkdir(n,{recursive:!0});let e;try{e=await Yt.promises.realpath(n)}catch(r){throw new In(`DEVECO_CLI_DATA_DIR is not usable: ${r instanceof Error?r.message:String(r)}`)}if(!(await Yt.promises.stat(e)).isDirectory())throw new In("DEVECO_CLI_DATA_DIR must be a writable directory.");return ll=e,e}function Hs(n){let e=mr();return gC()?[`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 mr(){if(ll!==void 0)return ll;let n=Om();try{if(Yt.existsSync(n))return Yt.realpathSync(n)}catch{}return n}var yC="docs";function hr(){return M.join(mr(),yC)}function q(){return M.join(hr(),".index")}function $s(){return M.join(q(),"build.lock")}function Pi(){return M.join(q(),"build-status.json")}function gr(){return M.join(q(),"build-meta.json")}function An(){return M.join(q(),"search.db")}function Ci(){return M.join(q(),"sqlite-backend.json")}function Ii(){return M.join(q(),"jieba-backend.json")}function Pt(){return M.join(q(),".tmp")}function wC(){return M.join(mr(),"logs")}function yr(){return M.join(wC(),"doc-init.log")}function vC(n,e){let t=e;for(;!t.endsWith(`${M.sep}dist`)&&t!==M.dirname(t);)t=M.dirname(t);return t}function Fm(n,e){return M.dirname(vC(n,e))}function jm(){let n=_m(import.meta.url),e=M.dirname(n);return n.includes(`${M.sep}dist${M.sep}`)?Fm(n,e):M.join(e,"..","..","..")}function SC(...n){let e=_m(import.meta.url),t=M.dirname(e);return e.includes(`${M.sep}dist${M.sep}`)?[M.join(Fm(e,t),...n)]:[M.join(t,"..","..","..",...n)]}function Hm(...n){let e=jm(),t=Ei.realpathSync(e);for(let r of SC(...n))try{let i=Ei.lstatSync(r);if(i.isSymbolicLink()||!i.isFile())throw new Error(`Unsafe documentation package asset: ${n.join("/")} must be a regular file.`);let o=Ei.realpathSync(r);if(!Mr(o,t))throw new Error(`Unsafe documentation package asset: ${n.join("/")} is outside the package.`);return o}catch(i){if(i.code!=="ENOENT")throw i}return null}function Jt(){return Hm("docs.zip")}function dl(){return Hm("index.zip")}function $m(){return M.join(jm(),"index","data")}import*as Ct from"fs";import*as Dn from"path";var It=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Us=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function Um(n){return n instanceof Us}var ul=null;function pl(n){ul=n}function fl(){if(ul)return ul;let n=q();if(It.every(i=>Ct.existsSync(Dn.join(n,i))))return n;let t=$m();if(It.every(i=>Ct.existsSync(Dn.join(t,i))))return t;throw new Us("Lexicon files not found. Install the documentation index first (index.zip).")}function Bm(){fl()}function wr(n){let e=Dn.join(fl(),n);return Ct.readFileSync(e,"utf-8")}function Wm(n,e){return Ct.readFileSync(Dn.join(e,n),"utf-8")}async function Gm(n,e=fl()){await Ct.promises.mkdir(n,{recursive:!0});for(let t of It){let r=Dn.join(e,t),i=Dn.join(n,t);await Ct.promises.copyFile(r,i)}}import*as Bs from"fs";import*as zm from"path";import*as Vm from"yauzl";var Ai=null;function bC(n){return new Promise((e,t)=>{Vm.open(n,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(r,i)=>{if(r||!i){t(r??new Error(`Failed to open zip: ${n}`));return}e(i)})})}function EC(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function PC(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",i=>{let o=EC(i);o.endsWith("/")||e.set(o,i),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function CC(){Ai?.zipfile.close(),Ai=null}async function IC(n){let e=zm.resolve(n),t=await Bs.promises.stat(e),r=Ai;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;CC();let i=await bC(e),o=await PC(i);return Ai={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:i,entries:o,readChain:Promise.resolve()},Ai}function AC(n,e){return new Promise((t,r)=>{n.openReadStream(e,(i,o)=>{if(i||!o){r(i??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];o.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),o.on("end",()=>{t(Buffer.concat(s))}),o.on("error",r)})})}async function DC(n,e){let t=n.readChain,r;n.readChain=new Promise(i=>{r=i}),await t;try{return await AC(n.zipfile,e)}finally{r()}}function RC(n){let e=n.replace(/\\/g,"/").replace(/\.md$/,"");if(e.split("/").includes(".."))throw new Error("Invalid document ID: path traversal is not allowed.");return[`docs/${e}.md`,`${e}.md`,`docs/${e}`,e]}function TC(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function qm(n){let e=Jt();if(!e)throw new Error("docs.zip not found");let t=await IC(e),r=TC(t.entries,RC(n));if(!r)throw new Error(`Document not found: ${n}`);return(await DC(t,r)).toString("utf-8")}function ml(){let n=Jt();return n!==null&&Bs.existsSync(n)}import*as ae from"fs";import*as At from"path";import Ym from"adm-zip";import*as Di from"fs";import*as Gs from"path";var Ws=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function Ri(n){return n instanceof In||n instanceof Ws||n instanceof Error&&(n.name==="CliDataDirError"||n.name==="DocPathSafetyError")}function yl(n){return new Ws(n)}function kC(){return st(mr())}function gl(n,e,t){let r=ro(n,e);if(r===null)throw yl(`${t} resolves outside the data directory.`);return r}async function hl(n,e){await Di.promises.mkdir(n,{recursive:!0});let t=gl(n,e,"directory");if(!(await Di.promises.stat(t)).isDirectory())throw yl("path must be a directory.")}function Ti(n){let e=kC();try{let t=gl(n,e,"file");if(!Di.statSync(t).isFile())throw yl("path must be a regular file.")}catch(t){if(t.code==="ENOENT"){gl(Gs.dirname(n),e,"file parent");return}throw t}}async function vr(n={}){let e=n.mode??"write",t=await Mm();await hl(hr(),t),await hl(q(),t),e==="write"&&await hl(Pt(),t);for(let r of[An(),gr(),Pi(),$s(),Ii(),Ci(),...It.map(i=>Gs.join(q(),i))])Ti(r)}var wl=["search.db","build-meta.json",...It],xC=["corpus.json","corpus-offsets.json","orama.dpack"];async function NC(n){for(let e of xC)await ae.promises.rm(At.join(n,e),{force:!0})}async function LC(n){let e=await ae.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await ae.promises.rm(At.join(n,t.name),{recursive:!0,force:!0})}function Jm(n){let t=new Ym(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 OC(n){let e=q();await ae.promises.mkdir(e,{recursive:!0});for(let t of wl){let r=At.join(e,t);await ae.promises.rm(r,{force:!0}),await ae.promises.rename(At.join(n,t),r)}await NC(e),await ae.promises.rm(Pt(),{recursive:!0,force:!0})}function Km(n){let e=dl();if(!e)return!1;try{let t=Jm(e);return t.indexVersion===pr&&t.docsZipSha256===n&&t.segmentCount>0}catch{return!1}}async function Xm(n){await vr({mode:"write"});let e=dl();if(!e)throw new Error("index.zip not found");let t=Jm(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=Pt();await ae.promises.rm(r,{recursive:!0,force:!0}),await ae.promises.mkdir(r,{recursive:!0});let i=new Ym(e);for(let s of wl){let a=i.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await ae.promises.writeFile(At.join(r,s),a.getData())}let o=JSON.parse(await ae.promises.readFile(At.join(r,"build-meta.json"),"utf-8"));if(!ae.existsSync(At.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await OC(r),await ae.promises.mkdir(hr(),{recursive:!0}),await LC(hr()),o}async function Zm(){await ae.promises.rm(Pt(),{recursive:!0,force:!0});let n=q();for(let e of wl)await ae.promises.rm(At.join(n,e),{force:!0})}import{createHash as Qm}from"crypto";import*as eh from"fs";async function zs(n){return new Promise((e,t)=>{let r=Qm("sha256"),i=eh.createReadStream(n);i.on("data",o=>r.update(o)),i.on("error",t),i.on("end",()=>e(r.digest("hex")))})}function th(n){return Qm("sha256").update(n,"utf8").digest("hex")}var vl=null;function MC(){let n=wr("harmonyos-synonyms.json");return JSON.parse(n)}function _C(n){let e=new Map;for(let t of n){let r=t.map(i=>i.trim()).filter(Boolean);for(let i of r){let o=r.filter(s=>s!==i);e.set(i.toLowerCase(),o),i!==i.toLowerCase()&&e.set(i,o)}}return e}function FC(){let n=_C(MC()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function jC(){return vl||(vl=FC()),vl}function Sl(n,e){let t=jC(),r=n.split(/\s+/).filter(Boolean),i=new Set,o=Number.isFinite(e)?e:r.length;for(let s=0;s<r.length&&i.size<o;s+=1){let a=r[s];i.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(i.size>=o)break;i.add(l)}}return[...i].join(" ")}function nh(n,e){let t=e?Wm(n,e):wr(n);return th(t)}function Vs(n){return nh("harmonyos-synonyms.json",n)}function qs(n){return nh("harmonyos-terms.txt",n)}var HC={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function Ys(){try{let n=await tt.promises.readFile(Pi(),"utf-8");return JSON.parse(n)}catch{return{...HC}}}async function bl(n){let e=Pi();await tt.promises.mkdir(ki.dirname(e),{recursive:!0}),await tt.promises.writeFile(e,JSON.stringify(n,null,2))}function rh(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 Kt(n){let t={...await Ys(),...n,updatedAt:Date.now()};return await bl(t),t}async function El(){let n=Jt();return n?zs(n):null}async function Pl(){try{let n=await tt.promises.readFile(gr(),"utf-8");return JSON.parse(n)}catch{return null}}async function Js(n=!1){if(n)return"no-index";let e=await Pl();if(!e||e.segmentCount===0)return"no-index";let t=await El();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==pr?"engine-upgraded":e.termsHash!==qs()?"terms-changed":e.synonymsHash!==Vs()?"synonyms-changed":null}function xi(){if(!ml()||!tt.existsSync(An())||!tt.existsSync(gr()))return!1;let n=ki.dirname(An());if(!It.every(e=>tt.existsSync(ki.join(n,e))))return!1;try{let e=tt.readFileSync(gr(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function Cl(n=!1){return n?!0:ml()?xi()?await Js()!==null:!0:!1}async function ih(){let n=await Ys();return["installing","indexing","persisting"].includes(n.state)}import*as fe from"fs";import*as lg from"os";import*as be from"path";var oh=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),Il=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),sh=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"]),ah=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 $C=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,UC=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,BC=/[A-Z][a-zA-Z0-9]{2,}/g,WC=/@[A-Z][a-zA-Z0-9]*/g,GC=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,ch=6,zC=/^[a-z][a-z0-9]{2,}$/,VC=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,qC=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,YC=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,JC=/^[A-Z][a-zA-Z0-9]+$/;function KC(n){return`"${n.replace(/"/g,'""')}"`}function Li(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(KC).join(` ${e} `)}function Ni(n){return Li(n,"OR")}function lh(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?Ni([...t,...r]):`(${Ni(t)}) AND (${Ni(r)})`}function Oi(n){return qC.test(n)}function dh(n){return YC.test(n)&&n.length>=ch}function XC(n){return JC.test(n)}function Mi(n){return Oi(n)||dh(n)||XC(n)}function ZC(n){let e=n.trim().toLowerCase();return ah.has(e)?!1:oh.has(e)}function QC(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function Ks(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function Al(n){return[...n.matchAll($C)].map(e=>e[0])}function Dl(n,e=ch){let t=[];for(let r of n.matchAll(UC))r[0].length>=e&&t.push(r[0]);return t}function Sr(n){return n.filter(e=>{let t=e.toLowerCase();return!n.some(r=>{if(r===e)return!1;let i=r.toLowerCase();return i.length>t.length&&i.endsWith(t)&&t.length>=4})})}function nt(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function eI(n){let e=new Set;nt(e,n);let t=Ks(n);return t&&nt(e,t),Sr([...e])}function Xs(n){if(Oi(n))return eI(n);let e=new Set;return nt(e,n),Sr([...e])}function Zs(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(VC);if(!t)return null;let r=t[1].toLowerCase(),i=t[2].toLowerCase();if(!zC.test(r)||sh.has(r)||!ZC(i))return null;let o=QC(r,i);return{first:r,second:i,camelCase:o,lower:o.toLowerCase()}}function Rl(n){let e=Zs(n.trim());return!e||e.second!=="manager"?null:e}function tI(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function uh(n){let e=n.trim(),t=Rl(e);if(t&&Il.has(t.first))return!0;if(dh(e)){let r=tI(e);return r!==null&&Il.has(r)}return!1}function Tl(n,e,t){let r=t.toLowerCase(),i=new RegExp(`@ohos\\.[^\\s(]*${t}`,"i");for(let o of[n,e])if(o&&(o.toLowerCase().includes(r)||i.test(o)))return!0;return!1}function kl(n){let e=n.trim();if(Mi(e))return Xs(e);let t=new Set;for(let r of Al(n)){nt(t,r);let i=Ks(r);i&&nt(t,i)}for(let r of Dl(n))nt(t,r);for(let r of n.matchAll(WC))t.add(r[0]);for(let r of n.matchAll(GC))t.add(r[0]);for(let r of n.matchAll(BC))r[0].length>=4&&t.add(r[0]);return Sr([...t])}function ph(n){let e=n.trim();if(Mi(e))return Xs(e);let t=new Set,r=Zs(e);r&&nt(t,r.camelCase);for(let i of kl(e))t.add(i);for(let i of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let o=i[0];o!==o.toLowerCase()&&t.add(o)}return Sr([...t])}function fh(n){return Mi(n)}var W={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 mh(n){return W.pureApiSymbol.test(n.trim())}function _i(n){let e=n.trim();return W.stageModelExact.test(e)||W.stageModelEnglishExact.test(e)}function hh(n){let e=[];return _i(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),W.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),W.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 gh(n){return _i(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var nI=[{matches:n=>W.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>_i(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!_i(n)&&W.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>W.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>W.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>W.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>W.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>W.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=>W.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function rI(n,e){for(let{catalog:t,multiplier:r}of e){let i=qt[t];n.set(i,(n.get(i)??1)*r)}}function yh(n,e){for(let t of nI)t.matches(n)&&rI(e,t.weights)}function wh(n,e){if(e!==void 0)return!1;let t=n.trim();return Oi(t)||W.pureApiSymbol.test(t)||uh(t)}function vh(n){let e=n.trim();if(Oi(e)||W.pureApiSymbol.test(e))return"harmonyos-references";if(_i(e)||W.uiAbilityLifecycleCatalog.test(e)||W.stateDecoratorCatalog.test(e)||W.stateManagement.test(e)||W.declarePermissionCatalog.test(e)||W.stageModelEntryPage.test(e)||W.routerRoute.test(e)||W.dialogPopupExact.test(e))return"harmonyos-guides"}import*as br from"fs";import*as bh from"path";var Qs=null,xl=null,Nl=null;function iI(){return br.existsSync(Ii())}function oI(n){let e=Ii(),t={backend:"jieba-wasm",reason:"native-jieba-load-failed",message:n,createdAt:new Date().toISOString()};br.mkdirSync(bh.dirname(e),{recursive:!0}),Ti(e),br.writeFileSync(e,JSON.stringify(t,null,2))}function sI(){if(Qs)return Qs;let n=wr("harmonyos-stopwords.txt");return Qs=new Set(n.split(`
|
|
1285
|
+
`).map(e=>e.trim()).filter(Boolean)),Qs}function aI(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t]?.trim();if(!r)continue;let i=n[t+1]?.trim();if(r==="@"&&i&&/^[A-Z][a-zA-Z0-9]*$/.test(i)){e.push(`@${i}`),t+=1;continue}e.push(r)}return e}function Eh(n){let e=sI(),t=[];for(let r of aI(n)){let i=r.trim();!i||e.has(i)||(t.push(i.toLowerCase()),/[A-Z]/.test(i)&&/[a-zA-Z]/.test(i)&&t.push(i))}return t}async function Ph(n){let{dict:e}=await import("@node-rs/jieba/dict.js"),t=n.withDict(e),r=wr("harmonyos-terms.txt");return t.loadDict(Buffer.from(r,"utf-8")),t}async function cI(){let{Jieba:n}=await import("@node-rs/jieba");return Ph(n)}async function Sh(){let{Jieba:n}=await import("@node-rs/jieba-wasm32-wasi");return Ph(n)}async function lI(){if(iI())return await Sh();try{let e=await cI();return m("doc-index: using @node-rs/jieba backend"),e}catch(e){let t=e instanceof Error?e.message:String(e);oI(t),m(`doc-index: @node-rs/jieba unavailable (${t}); falling back to wasm32-wasi`)}let n=await Sh();return m("doc-index: using @node-rs/jieba-wasm32-wasi backend"),n}async function Xt(){return xl||(Nl||(Nl=lI().then(n=>(xl=n,n))),Nl)}async function dI(n){let e=await Xt();return Eh(e.cutForSearch(n,!0))}async function Ch(n){let e=await Xt();return Eh(e.cut(n,!0))}async function ea(n,e){let t=n.trim();if(!t||e<=0)return"";let r=(await dI(t)).join(" ");return r.length<=e?r:r.slice(0,e)}async function uI(n,e){let t=[];for(let i of n){let o=i.trim();o&&(t.push(o.toLowerCase()),/[A-Z]/.test(o)&&t.push(o))}let r=[...new Set(t)].join(" ");return r.length<=e?r:r.slice(0,e)}async function ta(n){let e=!!n.sectionTitle.trim(),t=n.titleTokens.trim(),r=e?Pm:wm,i=e?Im:Sm,o=e?await uI(n.apiSymbols,i):await ea(n.apiSymbols.join(" "),i),a=(await Promise.all([ea(t,e?Cm:vm),Promise.resolve(o),ea(n.headingsText,e?Am:bm),ea(n.bodySample,e?Dm:Em)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}function pI(n){return n.join(" ").replace(/\s+/g," ").trim().slice(0,bi)}function Ll(n,e){let t=new Set,r=[];for(let i of[...n,...e]){let o=i.toLowerCase();if(!(!i||t.has(o))&&(t.add(o),r.push(i),r.length>=hm))break}return r}function fI(n){return n.length>=2&&n.length<=gm}function mI(n,e){let t=Sl(n,sl),r=t.split(/\s+/).filter(Boolean),i=[e.first,...r.filter(a=>a!==e.second),e.lower,e.camelCase],o=[e.second,e.lower,e.camelCase],s=Ll(i,o);return{rawQuery:n,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:lh(i,o)}}function hI(n,e){let t=Ll(Xs(e),[]);return{rawQuery:n,expandedQuery:n,tokens:t,preferAnd:!1,ftsMatch:Ni(t)}}async function Ih(n){let e=pI(n),t=e.trim(),r=gh(t);if(r)return{rawQuery:e,expandedQuery:r.expandedQuery,tokens:r.tokens,preferAnd:!1};let i=Zs(t);if(i)return mI(e,i);if(Mi(t))return hI(e,t);let o=hh(e),s=[...kl(e),...o],c=fh(t)?e:Sl(e,sl),l=await Ch(c),d=Ll(s,l);return{rawQuery:e,expandedQuery:c,tokens:d,preferAnd:o.length===0&&fI(d)}}var Ah=["harmonyos-releases","harmonyos-roadmap"],gI=new Set(Ah.map(n=>qt[n])),yI=Ah.map(n=>`${Cn[n]}/`);function wI(n){return gI.has(n)}function vI(n){return yI.some(e=>n.startsWith(e))}function Dh(n){let e=[],t=[];for(let r of n)wI(r.catalog_id)?t.push(r):e.push(r);return[...e,...t]}function Rh(n){let e=[],t=[];for(let r of n)vI(r.documentId)?t.push(r):e.push(r);return[...e,...t]}var SI=[{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 Fi(n,e,t){let r=qt[e];n.set(r,(n.get(r)??1)*t)}function bI(n,e){let t=n.trim(),r=/[\u4e00-\u9fff]/.test(t),i=/\b[A-Z][a-zA-Z0-9]{2,}\b/.test(t),o=/\b[a-z][a-zA-Z0-9]{3,}\b/.test(t);if(r&&(i||o)){Fi(e,"harmonyos-guides",1.45),Fi(e,"harmonyos-references",1.35);return}(i||o)&&Fi(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&Fi(e,"harmonyos-references",1.75)}function Th(n){let e=new Map,t=n.trim();if(!t)return e;let r=mh(t);bI(t,e),yh(t,e);for(let i of SI)i.pattern.test(t)&&(i.skipForPureApiSymbol&&r||Fi(e,i.catalog,i.multiplier));return e}function kh(n){return vh(n)}import*as Pr from"fs";import*as jh from"path";var EI=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function xh(n,e){let t=-1;for(let r of EI){let i=n.lastIndexOf(r);i>t&&(t=i)}return t>=e?t:-1}function Nh(n,e){let t=n.trim();if(t.length<=e)return{text:t,excerptTruncated:!1};let r=t.slice(0,e),i=xh(r,e-20),o=i>=0?i:e;return{text:t.slice(0,o).trimEnd(),excerptTruncated:!0}}function Lh(n,e,t={}){let{maxLen:r=km,contextChars:i=xm,excerptTruncated:o=!1}=t,s=n.replace(/\s+/g," ").trim();if(!s)return"";if(s.length<=r)return o?`${s}...`:s;let a=e.split(/\s+/).map(kt=>kt.trim()).filter(Boolean),c=0;for(let kt of a){let xt=s.toLowerCase().indexOf(kt.toLowerCase());if(xt>=0){c=xt;break}}let l=Math.max(0,c-i),d=Math.min(s.length,l+r),h=s.slice(l,d),w=xh(h,r-25);w>=0&&(d=l+w);let b=s.slice(l,d).trim(),L=l>0?"...":"",he=d<s.length||o?"...":"";return`${L}${b}${he}`}var PI=`
|
|
1297
1286
|
SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
|
|
1298
1287
|
d.catalog_id, bm25(segments_fts) AS bm25
|
|
1299
1288
|
FROM segments_fts
|
|
@@ -1302,7 +1291,7 @@ Output so far:
|
|
|
1302
1291
|
WHERE segments_fts MATCH ?
|
|
1303
1292
|
ORDER BY bm25(segments_fts)
|
|
1304
1293
|
LIMIT ?
|
|
1305
|
-
`,
|
|
1294
|
+
`,CI=`
|
|
1306
1295
|
SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
|
|
1307
1296
|
d.catalog_id, bm25(segments_fts) AS bm25
|
|
1308
1297
|
FROM segments_fts
|
|
@@ -1311,7 +1300,7 @@ Output so far:
|
|
|
1311
1300
|
WHERE segments_fts MATCH ? AND d.catalog_id = ?
|
|
1312
1301
|
ORDER BY bm25(segments_fts)
|
|
1313
1302
|
LIMIT ?
|
|
1314
|
-
`,
|
|
1303
|
+
`,II=3.5,AI=1.4,DI=4,RI=1.8,TI=1.35,kI=3.5,xI=1.8,NI=120,Oh=6;function Ml(n){return n.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function LI(n){return n.split(/[^\p{L}\p{N}@.]+/u).map(Ml).filter(e=>e.length>=2)}function OI(n,e){return e.length>1&&e.every(t=>n.includes(t))}function MI(n){return/^[a-z0-9]{1,4}$/.test(n.trim().toLowerCase())}function _I(n,e){return n===e?kI:n.startsWith(e)||n.includes(`@ohos.${e}`)?xI:1}function FI(n,e){let t=Ml(e);if(t.length<2)return 1;let r=Ml(n.doc_title);if(MI(e))return _I(r,t);if(r.includes(t))return DI;if(t.length>=Oh&&r.includes(t.slice(0,Oh)))return RI;let i=LI(e);return OI(r,i)?TI:1}function jI(n,e){return e<=1?n:n<0?n*e:n/e}function na(n,e,t,r){let i=n.bm25/(e.get(n.catalog_id)??1);return i=jI(i,FI(n,t)),r&&Tl(n.doc_title,n.section_title,r)&&(i/=II,n.catalog_id===qt["harmonyos-references"]&&(i/=AI)),i}function Ol(n,e,t,r){return n.reduce((i,o)=>na(o,e,t,r)<na(i,e,t,r)?o:i)}function HI(n,e){return e.some(t=>n.section_title.includes(t)||n.doc_title.includes(t))}function $I(n,e,t,r,i){if(i){let o=n.filter(s=>Tl(s.doc_title,s.section_title,i));if(o.length>0)return Ol(o,t,r,i)}if(e.length>0){let o=n.filter(s=>HI(s,e));if(o.length>0)return Ol(o,t,r,i)}return Ol(n,t,r,i)}function Mh(n,e,t,r,i){let o=Th(e),s=ph(e),c=Rl(e)?.camelCase,l=new Map;for(let b of n){let L=l.get(b.document_id)??[];L.push(b),l.set(b.document_id,L)}let d=[];for(let b of l.values())d.push($I(b,s,o,t,c));let h=d.sort((b,L)=>na(b,o,t,c)-na(L,o,t,c));return(i?Dh(h):h).slice(0,r)}function ra(n,e,t,r,i,o){let s=e?qt[e]:void 0,a=Math.max(t,t*ym,NI),c=s===void 0?n.all(PI,r,a):n.all(CI,r,s,a);return(s===void 0?Mh(c,o,i,t,!0):Mh(c,o,i,t,!1)).map(d=>({title:d.doc_title,documentId:d.document_id,sectionTitle:d.section_title||void 0,snippet:Lh(d.lead_text,i,{excerptTruncated:!!d.excerpt_truncated})}))}var ia=`
|
|
1315
1304
|
CREATE TABLE documents (
|
|
1316
1305
|
id INTEGER PRIMARY KEY,
|
|
1317
1306
|
document_id TEXT NOT NULL UNIQUE,
|
|
@@ -1349,18 +1338,54 @@ CREATE TRIGGER segments_au AFTER UPDATE ON segments BEGIN
|
|
|
1349
1338
|
END;
|
|
1350
1339
|
|
|
1351
1340
|
CREATE INDEX segments_doc_id_idx ON segments(doc_id);
|
|
1352
|
-
`;var
|
|
1341
|
+
`;var Er=null,_l=null;function UI(){Er?.close(),Er=null,_l=null}function BI(n,e){if(Er&&_l===e)return Er;Er?.close();let t=new n(e,{readonly:!0,fileMustExist:!0});return Er=t,_l=e,t.pragma("mmap_size = 268435456"),t.pragma("cache_size = -8000"),t.pragma("query_only = ON"),t}function WI(n,e){let t=new n(e);return t.pragma("journal_mode = OFF"),t.pragma("synchronous = OFF"),t.pragma("temp_store = MEMORY"),t.exec(ia),t}function GI(n,e,t){let r=e.get(t.documentId);if(r!==void 0)return r;let o=n.prepare("SELECT id FROM documents WHERE document_id = ?").get(t.documentId);if(o)return e.set(t.documentId,o.id),o.id;let a=n.prepare(`
|
|
1353
1342
|
INSERT INTO documents(document_id, catalog_id, doc_title)
|
|
1354
1343
|
VALUES (?, ?, ?)
|
|
1355
|
-
`).run(t.documentId,t.catalogId,t.docTitle),c=Number(a.lastInsertRowid);return e.set(t.documentId,c),c}async function
|
|
1344
|
+
`).run(t.documentId,t.catalogId,t.docTitle),c=Number(a.lastInsertRowid);return e.set(t.documentId,c),c}async function zI(n,e,t,r){await Xt();let i=WI(n,e),o=new Map,s=i.prepare(`
|
|
1356
1345
|
INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated)
|
|
1357
1346
|
VALUES (?, ?, ?, ?, ?)
|
|
1358
|
-
`),a=t.length;for(let c=0;c<a;c+=Ut){let l=t.slice(c,c+Ut),u=await Promise.all(l.map(async P=>({source:P,searchText:await vi(P)})));i.transaction(P=>{for(let C of P){let L=Zv(i,o,C.source);s.run(L,C.source.sectionTitle,C.source.leadText,C.searchText,C.source.excerptTruncated?1:0)}})(u),await r?.(Math.min(c+l.length,a),a)}i.exec("ANALYZE"),i.exec("VACUUM"),i.close()}function Qv(n,e,t,r,i,o,s){let a=Jv(n,e);return bi({all(c,...l){return a.prepare(c).all(...l)}},t,r,i,o,s)}async function Jd(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:Yv,buildSearchIndex:(t,r,i)=>Xv(e,t,r,i),searchIndex:(t,r,i,o,s,a,c)=>Promise.resolve(Qv(e,o,r,i,s,a,c))}}import{readFile as ew,stat as tw,writeFile as nw}from"fs/promises";var vs=null,Qe=null;async function ws(){return vs||(vs=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),vs}function rw(n){return{all(e,...t){let r=n.prepare(e);t.length>0&&r.bind(t);let i=[];for(;r.step();)i.push(r.get({}));return r.finalize(),i}}}async function iw(n){let e=await tw(n);if(Qe&&Qe.dbPath===n&&Qe.mtimeMs===e.mtimeMs)return Qe.db;Qe?.db.close();let t=await ws(),r=t.capi,i=t.wasm,o=new Uint8Array(await ew(n)),s=i.allocFromTypedArray(o),a=new t.oo1.DB(":memory:"),c=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE;return r.sqlite3_deserialize(a.pointer,"main",s,o.byteLength,o.byteLength,c),Qe={dbPath:n,mtimeMs:e.mtimeMs,db:a},a}function Kd(){Qe?.db.close(),Qe=null}async function ow(n,e,t,r){n.exec("BEGIN");for(let i of r){let o=t(i.source);e.bind([o,i.source.sectionTitle,i.source.leadText,i.searchText,i.source.excerptTruncated?1:0]),e.step(),e.reset()}n.exec("COMMIT")}function sw(n,e,t){return r=>{let i=e.get(r.documentId);if(i!==void 0)return i;let o=n.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(o!=null){let a=Number(o);return e.set(r.documentId,a),a}t.bind([r.documentId,r.catalogId,r.docTitle]),t.step(),t.reset();let s=Number(n.selectValue("SELECT last_insert_rowid()"));return e.set(r.documentId,s),s}}async function aw(n,e,t){await Xe();let r=await ws(),i=new r.oo1.DB(":memory:","c");i.exec(Si);let o=new Map,s=i.prepare("INSERT INTO documents(document_id, catalog_id, doc_title) VALUES (?, ?, ?)"),a=i.prepare("INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated) VALUES (?, ?, ?, ?, ?)"),c=sw(i,o,s),l=e.length;for(let f=0;f<l;f+=Ut){let P=e.slice(f,f+Ut),C=await Promise.all(P.map(async L=>({source:L,searchText:await vi(L)})));await ow(i,a,c,C),await t?.(Math.min(f+P.length,l),l)}i.exec("ANALYZE");let u=r.capi.sqlite3_js_db_export(i);await nw(n,u),i.close(),Kd()}async function cw(n,e,t,r,i,o){let s=await iw(n);return bi(rw(s),e,t,r,i,o)}async function Zd(){return await ws(),{kind:"sqlite-wasm",resetCache:Kd,buildSearchIndex:aw,searchIndex:(n,e,t,r,i,o,s)=>cw(r,e,t,i,o,s)}}var Ei=null,bs=null;async function lw(){try{let e=await Jd();return g("doc-index: using better-sqlite3 SQLite backend"),e}catch(e){g(`doc-index: better-sqlite3 unavailable (${e.message}); falling back to sqlite-wasm`)}let n=await Zd();return g("doc-index: using @sqlite.org/sqlite-wasm SQLite backend"),n}async function Hn(){return Ei||(Ei=lw().then(n=>(bs=n,n))),Ei}function Xd(){bs?.resetCache(),Ei=null,bs=null}async function dw(n,e,t,r,i,o,s){let a=await Hn(),c=s??An();return a.searchIndex(n,e,t,c,r,i,o)}function eu(){Xd()}async function tu(n,e,t){await(await Hn()).buildSearchIndex(n,e,t)}function nu(n,e,t){let r=new Set,i=[];for(let o of[...n,...e])if(!r.has(o.documentId)&&(r.add(o.documentId),i.push(o),i.length>=t))break;return i}function Pi(n,e,t,r,i,o){return dw(n,e,t,i,r.expandedQuery,r.rawQuery,o)}async function uw(n,e,t,r,i){let o=await Pi(n,e,t,r,Mn(r.tokens,"AND"),i);if(o.length>=t)return o;let s=await Pi(n,e,t,r,Mn(r.tokens,"OR"),i);return nu(o,s,t)}async function Ss(n,e,t,r,i){return r.ftsMatch?Pi(n,e,t,r,r.ftsMatch,i):r.preferAnd?uw(n,e,t,r,i):Pi(n,e,t,r,Mn(r.tokens,"OR"),i)}async function pw(n,e,t,r){let i=await Ss(n,"harmonyos-references",e,t,r);if(i.length>=e)return i;let o=await Ss(n,void 0,e,t,r);return nu(i,o,e)}function Qd(n,e){return e!==void 0?n:Bd(n)}async function ru(n,e,t=20,r){let i=await Fd(n);if(Ld(i.rawQuery,e)){let a=await pw(n,t,i,r);return Qd(a,e)}let o=e??Ud(i.rawQuery),s=await Ss(n,o,t,i,r);return Qd(s,e)}import{unified as uu}from"unified";import pu from"remark-parse";import mu from"remark-gfm";import{toString as Di}from"mdast-util-to-string";var mw=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,hw=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,fw=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,gw=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,yw=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function Ci(n){let e=n.trim(),t=e.match(gw);return t?t[1]:e}function vw(n){let e=n.match(mw);if(!e)return;let t=Ci(e[1].trim());return{displayTitle:n,symbolName:t,searchExtras:[t,e[3]]}}function ww(n){let e=Ci(n.replace(/\([^)]*\)$/,""));if(/^[A-Z][A-Za-z0-9]*$/.test(e))return{displayTitle:n,symbolName:e,searchExtras:[e]};if(/^[A-Z][A-Za-z0-9]*(\([^)]*\))?$/.test(n))return{displayTitle:n,symbolName:e,searchExtras:[e]}}function Fn(n){let e=n.trim();return e?vw(e)??(()=>{let t=e.match(hw);if(t){let r=t[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let t=e.match(fw);if(!t)return;let r=t[1].trim(),i=t[2].trim();return{displayTitle:e,symbolName:i,searchExtras:[r,i]}})()??ww(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function bw(n){if(n.length<2||n.length>36||yw.test(n))return!1;let e=[...n.replace(/\s/g,"")];return e.length===0?!1:e.filter(r=>new RegExp("\\p{Script=Han}","u").test(r)).length/e.length>=.4}function iu(n){for(let e of n){let t=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(bw(t))return t}return""}function ou(n,e,t){let r=[n,...t.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var Sw=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,jn=/@[A-Z][a-zA-Z]+/g,Ew=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,Pw=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,Cw=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,Dw=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),Iw=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),Aw=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function hu(n,e){let t=new Set,r=[n,...e];for(let i of r){for(let o of as(i)){Pe(t,o);let s=mi(o);s&&Pe(t,s)}for(let o of cs(i))Pe(t,o);for(let o of i.matchAll(Sw)){let s=o[0];xw(s)&&t.add(s)}for(let o of i.matchAll(jn))t.add(o[0])}return Vt([...t])}function xw(n){let e=n.trim();if(!e||jn.test(e))return!!e;if(e.includes(".")){let t=e.split(".")[0]??"";return Aw.has(t)?!1:/^[A-Z]/.test(t)}return Dw.has(e)?!1:Iw.has(e)?!0:e.length<=3?!1:/^[A-Z][a-z]+[A-Z]/.test(e)?!0:e.length>=6&&/^[A-Z][A-Za-z0-9]+$/.test(e)}function su(n){let e=n.trim();return!!(!e||Cw.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function fu(n,e){let t=e.jsonTitle?.trim(),r=Mw(n,"").trim(),i=e.fileName.trim();return t&&!su(t)?t:r&&!su(r)?r:t||r||i}function gu(n){return Ew.test(n.trim())}function Es(n){let e=n.trim().replace(/\([^)]*\)$/,""),t=Ci(e);return Pw.test(t)}function Ii(n){let e=n.trim();return e?jn.test(e)||gu(e)||Es(e)?!0:!!Fn(e).symbolName:!1}function Tw(n){let e=n.trim();return!(!e||gu(e)||Es(e))}function kw(n){let e=new Set,t=[];for(let r of n){let i=r.trim();!Tw(i)||e.has(i)||(e.add(i),t.push(i))}return t}function au(n){if(!n.includes("."))return 0;let e=n.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function Rw(n,e){let t=au(n)-au(e);return t!==0?t:n.localeCompare(e)}function yu(n,e=[]){let t=[...new Set(e.map(o=>o.trim()).filter(Boolean))],r=new Set(t),i=[...new Set(n.map(o=>o.trim()).filter(Boolean))].filter(o=>!r.has(o));return i.sort(Rw),[...t,...i].slice(0,Gl)}function Ai(n){return n.replace(/\s+/g," ").trim()}function cu(n){return n.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function Mw(n,e=""){let t=n.split(/\r?\n/),r=0;for(;r<t.length&&!t[r].trim();)r+=1;if(r>=t.length)return e;let i=cu(t[r].trim()),o=i.match(/^#+\s+(.+)$/);if(o)return cu(o[1].trim());if(r+1<t.length){let s=t[r+1].trim();if(/^=+$/.test(s)||/^-+$/.test(s))return i}return i||e}function vu(n){let e=Ai(n.join(" "));if(e.length<=ti)return e;let t=e.slice(0,ti);return e.length<=ti+zo?t:`${t} ${e.slice(-zo)}`}function Ow(n){let e=kw(n).join(" ");return e.length<=qo?e:e.slice(0,qo)}function wu(n){let e=Ai(n),{text:t,excerptTruncated:r}=qd(e,Vl);return{leadText:t,excerptTruncated:r}}function Lw(n,e){let{leadText:t,excerptTruncated:r}=wu(n);return{leadText:t,excerptTruncated:r||!!e.trim()}}function bu(n,e){if(n.type==="code"){e.codeBlocks.push(n.value??"");return}if("children"in n&&Array.isArray(n.children)){for(let r of n.children)bu(r,e);return}let t=Ai(Di(n));t&&e.bodyParts.push(t)}function Nw(n){let e=uu().use(pu).use(mu).parse(n),t=[],r=null,i=()=>{r&&((r.sectionTitle||r.bodyParts.length||r.codeBlocks.length)&&t.push(r),r=null)},o=()=>{r||(r={sectionTitle:"",bodyParts:[],codeBlocks:[]})};for(let s of e.children){if(s.type==="heading"){let a=s,c=Di(a).trim();if(a.depth>=4&&c&&Ii(c)){i(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}o(),c&&r.bodyParts.push(c);continue}o(),bu(s,r)}return i(),t.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:t}function _w(n){return Ml.test(n)}function Hw(n){return n.filter(e=>e.sectionTitle&&Ii(e.sectionTitle)).length}function Fw(n){return{sectionTitle:n.map(e=>e.sectionTitle.trim()).join(" | "),bodyParts:n.flatMap(e=>e.bodyParts).slice(0,40),codeBlocks:n.flatMap(e=>e.codeBlocks).slice(0,8)}}function lu(n){let e=n.trim();return!e||jn.test(e)?jn.test(e):/对象说明$|枚举说明$/.test(e)?!0:Es(e)}function jw(n){let e=n.filter(f=>!f.sectionTitle||!Ii(f.sectionTitle)),t=n.filter(f=>f.sectionTitle&&Ii(f.sectionTitle)),r=t.filter(f=>lu(f.sectionTitle)),i=t.filter(f=>!lu(f.sectionTitle)),o=Math.max(0,Rl-r.length),s=i.slice(0,o),a=i.slice(o),c=a.filter(f=>du(f.sectionTitle)),l=a.filter(f=>!du(f.sectionTitle)),u=[];for(let f=0;f<l.length;f+=Wo)u.push(Fw(l.slice(f,f+Wo)));return[...e,...r,...s,...c,...u]}function $w(n,e,t){let r=n.split(/\r?\n/).length,i=Hw(e);return i===0?!1:_w(t)?r>=Tl&&i>=kl:r>=Al&&i>=xl}var Bw=/^\[h2\][A-Za-z]/;function du(n){return Bw.test(n.trim())}function Su(n){if(!n.includes(" | ")){let t=Fn(n);return t.symbolName?[t.symbolName]:[]}let e=[];for(let t of n.split(" | ")){let r=Fn(t.trim()).symbolName;r&&e.push(r)}return e}function Ww(n,e,t,r){let i=Su(n),o=hu(t,r);return e.symbolName&&o.push(e.symbolName),yu([...i,...o],i)}function Uw(n,e){let t=vu(n.bodyParts),r=n.sectionTitle.trim(),i=Fn(r),o=iu(n.bodyParts),s=ou(r,o,i),a=Su(r),c=r?a.length>0?`${e.docTitle} ${a.join(" ")}`:`${e.docTitle} ${i.symbolName??r}`:e.docTitle,l=[e.docTitle,s,...n.bodyParts].join(" "),{leadText:u,excerptTruncated:f}=Lw(t,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:Ww(r,i,l,n.codeBlocks),bodySample:t,leadText:u,excerptTruncated:f}}function Eu(n,e){for(let t of n){if(t.type==="heading"){let i=Di(t).trim();i&&e.headings.push(i);continue}if(t.type==="code"){e.codeBlocks.push(t.value??"");continue}if("children"in t&&Array.isArray(t.children)){Eu(t.children,e);continue}let r=Ai(Di(t));r&&e.bodyParts.push(r)}}function zw(n){let e=uu().use(pu).use(mu).parse(n),t={headings:[],bodyParts:[],codeBlocks:[]};return Eu(e.children,t),t}function qw(n,e){let t=zw(n),r=e.docTitle?.trim()||e.documentId,i=vu(t.bodyParts),o=[r,...t.headings,i].join(" "),{leadText:s,excerptTruncated:a}=wu(i);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:Ow(t.headings),apiSymbols:yu(hu(o,t.codeBlocks)),bodySample:i,leadText:s,excerptTruncated:a}}function Pu(n,e){let t=e.docTitle?.trim()||e.documentId,r=Nw(n);return $w(n,r,e.documentId)?jw(r).filter(i=>i.sectionTitle||i.bodyParts.length>0||i.codeBlocks.length>0).map(i=>Uw(i,{...e,docTitle:t})):[qw(n,{...e,docTitle:t})]}async function Gw(n){let e=[];async function t(r){let i=await Z.promises.readdir(r,{withFileTypes:!0});for(let o of i){if(o.name.startsWith("."))continue;let s=ie.join(r,o.name);o.isDirectory()?await t(s):o.isFile()&&o.name.endsWith(".md")&&e.push(s)}}return await t(n),e}function Vw(n,e){let t=ie.relative(e,n).split(ie.sep).join("/").split("/");if(t[0]==="docs"&&(t=t.slice(1)),t.length<2)return null;let r=t[0],i=Kl[r];if(i===void 0)return null;let o=t[t.length-1].replace(/\.md$/,"");return t[t.length-1]=o,{documentId:t.join("/"),catalogId:i,docTitle:o}}async function Yw(n){let e=n.replace(/\.md$/,".json");try{let t=await Z.promises.readFile(e,"utf-8");return JSON.parse(t).title?.trim()||void 0}catch{return}}async function Jw(n,e){let t=Vw(n,e);if(!t)return[];let r=await Z.promises.readFile(n,"utf-8"),i=fu(r,{jsonTitle:await Yw(n),fileName:t.docTitle});return Pu(r,{...t,docTitle:i})}async function Kw(n,e,t){let r=ie.join(e,"search.db");return await tu(r,n,async(i,o)=>{await t?.({current:i,total:o,message:`Building search index\u2026 ${i.toLocaleString()} / ${o.toLocaleString()} segments`})}),n.length}async function Zw(n){let e=await Gw(n),t=[];for(let r of e){let i=await Jw(r,n);t.push(...i)}return t}function Xw(n,e){return{indexVersion:ei,docsZipSha256:n.docsZipSha256,termsHash:n.termsHash,synonymsHash:n.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:n.builtBy}}async function Du(n){n.lexiconDir&&Jo(n.lexiconDir);try{let e=await Zw(n.docsDir);await n.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await Z.promises.mkdir(n.tmpDir,{recursive:!0});let t=await Kw(e,n.tmpDir,n.onProgress),r=Xw(n,t);return await Z.promises.writeFile(ie.join(n.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await cd(n.tmpDir),r}finally{n.lexiconDir&&Jo(null)}}async function Iu(){return Z.promises.mkdtemp(ie.join(Cu.tmpdir(),"deveco-docs-"))}async function Qw(n,e){try{await Z.promises.rename(n,e)}catch(t){let r=t.code;if(r!=="EPERM"&&r!=="EXDEV")throw t;await Z.promises.cp(n,e,{recursive:!0}),await Z.promises.rm(n,{recursive:!0,force:!0})}}async function Au(n){let e=ie.join(n,"docs");try{await Z.promises.access(e)}catch{return}let t=new Set(["docs","docs.zip"]);for(let r of await Z.promises.readdir(e,{withFileTypes:!0})){if(t.has(r.name))continue;let i=ie.join(e,r.name),o=ie.join(n,r.name);await Z.promises.rm(o,{recursive:!0,force:!0}),await Qw(i,o)}await Z.promises.rm(ie.join(e,"docs"),{recursive:!0,force:!0}),await Z.promises.rm(ie.join(e,"docs.zip"),{force:!0}),await Z.promises.rm(e,{recursive:!0,force:!0})}var $n=class extends Error{constructor(e){super(e),this.name="NativeDepsError"}};function eb(){let n=qt(),e=te();return["Documentation search index is not installed yet.","",...ri(n),`Index directory: ${e}`,"","Try:"," 1. Wait a moment and run the docs command again (postinstall may still be running)"," 2. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 3. Check the log file above for setup errors"].join(`
|
|
1359
|
-
`)}function
|
|
1360
|
-
`)}function
|
|
1361
|
-
`)}async function
|
|
1347
|
+
`),a=t.length;for(let c=0;c<a;c+=fr){let l=t.slice(c,c+fr),d=await Promise.all(l.map(async w=>({source:w,searchText:await ta(w)})));i.transaction(w=>{for(let b of w){let L=GI(i,o,b.source);s.run(L,b.source.sectionTitle,b.source.leadText,b.searchText,b.source.excerptTruncated?1:0)}})(d),await r?.(Math.min(c+l.length,a),a)}i.exec("ANALYZE"),i.exec("VACUUM"),i.close()}function VI(n,e,t,r,i,o,s){let a=BI(n,e);return ra({all(c,...l){return a.prepare(c).all(...l)}},t,r,i,o,s)}async function _h(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:UI,buildSearchIndex:(t,r,i)=>zI(e,t,r,i),searchIndex:(t,r,i,o,s,a,c)=>Promise.resolve(VI(e,o,r,i,s,a,c))}}import{readFile as qI,stat as YI,writeFile as JI}from"fs/promises";var Fl=null,Zt=null;async function jl(){return Fl||(Fl=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),Fl}function KI(n){return{all(e,...t){let r=n.prepare(e);t.length>0&&r.bind(t);let i=[];for(;r.step();)i.push(r.get({}));return r.finalize(),i}}}async function XI(n){let e=await YI(n);if(Zt&&Zt.dbPath===n&&Zt.mtimeMs===e.mtimeMs)return Zt.db;Zt?.db.close();let t=await jl(),r=t.capi,i=t.wasm,o=new Uint8Array(await qI(n)),s=i.allocFromTypedArray(o),a=new t.oo1.DB(":memory:"),c=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE;return r.sqlite3_deserialize(a.pointer,"main",s,o.byteLength,o.byteLength,c),Zt={dbPath:n,mtimeMs:e.mtimeMs,db:a},a}function Fh(){Zt?.db.close(),Zt=null}async function ZI(n,e,t,r){n.exec("BEGIN");for(let i of r){let o=t(i.source);e.bind([o,i.source.sectionTitle,i.source.leadText,i.searchText,i.source.excerptTruncated?1:0]),e.step(),e.reset()}n.exec("COMMIT")}function QI(n,e,t){return r=>{let i=e.get(r.documentId);if(i!==void 0)return i;let o=n.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(o!=null){let a=Number(o);return e.set(r.documentId,a),a}t.bind([r.documentId,r.catalogId,r.docTitle]),t.step(),t.reset();let s=Number(n.selectValue("SELECT last_insert_rowid()"));return e.set(r.documentId,s),s}}async function eA(n,e,t){await Xt();let r=await jl(),i=new r.oo1.DB(":memory:","c");i.exec(ia);let o=new Map,s=i.prepare("INSERT INTO documents(document_id, catalog_id, doc_title) VALUES (?, ?, ?)"),a=i.prepare("INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated) VALUES (?, ?, ?, ?, ?)"),c=QI(i,o,s),l=e.length;for(let h=0;h<l;h+=fr){let w=e.slice(h,h+fr),b=await Promise.all(w.map(async L=>({source:L,searchText:await ta(L)})));await ZI(i,a,c,b),await t?.(Math.min(h+w.length,l),l)}i.exec("ANALYZE");let d=r.capi.sqlite3_js_db_export(i);await JI(n,d),i.close(),Fh()}async function tA(n,e,t,r,i,o){let s=await XI(n);return ra(KI(s),e,t,r,i,o)}async function Hl(){return await jl(),{kind:"sqlite-wasm",resetCache:Fh,buildSearchIndex:eA,searchIndex:(n,e,t,r,i,o,s)=>tA(r,e,t,i,o,s)}}var oa=null,$l=null;function nA(){return Pr.existsSync(Ci())}function rA(n){let e=Ci(),t={backend:"sqlite-wasm",reason:"better-sqlite3-load-failed",message:n,createdAt:new Date().toISOString()};Pr.mkdirSync(jh.dirname(e),{recursive:!0}),Ti(e),Pr.writeFileSync(e,JSON.stringify(t,null,2))}async function iA(){if(nA())return Hl();try{let n=await _h();return m("doc-index: using better-sqlite3 SQLite backend"),n}catch(n){let e=n instanceof Error?n.message:String(n);rA(e),m(`doc-index: better-sqlite3 unavailable (${e}); falling back to sqlite-wasm`)}return Hl()}async function ji(){return oa||(oa=iA().then(n=>($l=n,n))),oa}function Hh(){$l?.resetCache(),oa=null,$l=null}async function oA(n,e,t,r,i,o,s){let a=await ji(),c=s??An();return a.searchIndex(n,e,t,c,r,i,o)}function Cr(){Hh()}async function Uh(n,e,t){await(await ji()).buildSearchIndex(n,e,t)}function Bh(n,e,t){let r=new Set,i=[];for(let o of[...n,...e])if(!r.has(o.documentId)&&(r.add(o.documentId),i.push(o),i.length>=t))break;return i}function sa(n,e,t,r,i,o){return oA(n,e,t,i,r.expandedQuery,r.rawQuery,o)}async function sA(n,e,t,r,i){let o=await sa(n,e,t,r,Li(r.tokens,"AND"),i);if(o.length>=t)return o;let s=await sa(n,e,t,r,Li(r.tokens,"OR"),i);return Bh(o,s,t)}async function Ul(n,e,t,r,i){return r.ftsMatch?sa(n,e,t,r,r.ftsMatch,i):r.preferAnd?sA(n,e,t,r,i):sa(n,e,t,r,Li(r.tokens,"OR"),i)}async function aA(n,e,t,r){let i=await Ul(n,"harmonyos-references",e,t,r);if(i.length>=e)return i;let o=await Ul(n,void 0,e,t,r);return Bh(i,o,e)}function $h(n,e){return e!==void 0?n:Rh(n)}async function Bl(n,e,t=20,r){let i=await Ih(n);if(wh(i.rawQuery,e)){let a=await aA(n,t,i,r);return $h(a,e)}let o=e??kh(i.rawQuery),s=await Ul(n,o,t,i,r);return $h(s,e)}import{unified as Kh}from"unified";import Xh from"remark-parse";import Zh from"remark-gfm";import{toString as ca}from"mdast-util-to-string";var cA=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,lA=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,dA=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,uA=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,pA=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function aa(n){let e=n.trim(),t=e.match(uA);return t?t[1]:e}function fA(n){let e=n.match(cA);if(!e)return;let t=aa(e[1].trim());return{displayTitle:n,symbolName:t,searchExtras:[t,e[3]]}}function mA(n){let e=aa(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 Hi(n){let e=n.trim();return e?fA(e)??(()=>{let t=e.match(lA);if(t){let r=t[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let t=e.match(dA);if(!t)return;let r=t[1].trim(),i=t[2].trim();return{displayTitle:e,symbolName:i,searchExtras:[r,i]}})()??mA(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function hA(n){if(n.length<2||n.length>36||pA.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 Wh(n){for(let e of n){let t=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(hA(t))return t}return""}function Gh(n,e,t){let r=[n,...t.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var gA=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,$i=/@[A-Z][a-zA-Z]+/g,yA=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,wA=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,vA=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,SA=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),bA=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),EA=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function Qh(n,e){let t=new Set,r=[n,...e];for(let i of r){for(let o of Al(i)){nt(t,o);let s=Ks(o);s&&nt(t,s)}for(let o of Dl(i))nt(t,o);for(let o of i.matchAll(gA)){let s=o[0];PA(s)&&t.add(s)}for(let o of i.matchAll($i))t.add(o[0])}return Sr([...t])}function PA(n){let e=n.trim();if(!e||$i.test(e))return!!e;if(e.includes(".")){let t=e.split(".")[0]??"";return EA.has(t)?!1:/^[A-Z]/.test(t)}return SA.has(e)?!1:bA.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 zh(n){let e=n.trim();return!!(!e||vA.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function eg(n,e){let t=e.jsonTitle?.trim(),r=DA(n,"").trim(),i=e.fileName.trim();return t&&!zh(t)?t:r&&!zh(r)?r:t||r||i}function tg(n){return yA.test(n.trim())}function Wl(n){let e=n.trim().replace(/\([^)]*\)$/,""),t=aa(e);return wA.test(t)}function la(n){let e=n.trim();return e?$i.test(e)||tg(e)||Wl(e)?!0:!!Hi(e).symbolName:!1}function CA(n){let e=n.trim();return!(!e||tg(e)||Wl(e))}function IA(n){let e=new Set,t=[];for(let r of n){let i=r.trim();!CA(i)||e.has(i)||(e.add(i),t.push(i))}return t}function Vh(n){if(!n.includes("."))return 0;let e=n.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function AA(n,e){let t=Vh(n)-Vh(e);return t!==0?t:n.localeCompare(e)}function ng(n,e=[]){let t=[...new Set(e.map(o=>o.trim()).filter(Boolean))],r=new Set(t),i=[...new Set(n.map(o=>o.trim()).filter(Boolean))].filter(o=>!r.has(o));return i.sort(AA),[...t,...i].slice(0,Rm)}function da(n){return n.replace(/\s+/g," ").trim()}function qh(n){return n.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function DA(n,e=""){let t=n.split(/\r?\n/),r=0;for(;r<t.length&&!t[r].trim();)r+=1;if(r>=t.length)return e;let i=qh(t[r].trim()),o=i.match(/^#+\s+(.+)$/);if(o)return qh(o[1].trim());if(r+1<t.length){let s=t[r+1].trim();if(/^=+$/.test(s)||/^-+$/.test(s))return i}return i||e}function rg(n){let e=da(n.join(" "));if(e.length<=js)return e;let t=e.slice(0,js);return e.length<=js+al?t:`${t} ${e.slice(-al)}`}function RA(n){let e=IA(n).join(" ");return e.length<=cl?e:e.slice(0,cl)}function ig(n){let e=da(n),{text:t,excerptTruncated:r}=Nh(e,Tm);return{leadText:t,excerptTruncated:r}}function TA(n,e){let{leadText:t,excerptTruncated:r}=ig(n);return{leadText:t,excerptTruncated:r||!!e.trim()}}function og(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)og(r,e);return}let t=da(ca(n));t&&e.bodyParts.push(t)}function kA(n){let e=Kh().use(Xh).use(Zh).parse(n),t=[],r=null,i=()=>{r&&((r.sectionTitle||r.bodyParts.length||r.codeBlocks.length)&&t.push(r),r=null)},o=()=>{r||(r={sectionTitle:"",bodyParts:[],codeBlocks:[]})};for(let s of e.children){if(s.type==="heading"){let a=s,c=ca(a).trim();if(a.depth>=4&&c&&la(c)){i(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}o(),c&&r.bodyParts.push(c);continue}o(),og(s,r)}return i(),t.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:t}function xA(n){return mm.test(n)}function NA(n){return n.filter(e=>e.sectionTitle&&la(e.sectionTitle)).length}function LA(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 Yh(n){let e=n.trim();return!e||$i.test(e)?$i.test(e):/对象说明$|枚举说明$/.test(e)?!0:Wl(e)}function OA(n){let e=n.filter(h=>!h.sectionTitle||!la(h.sectionTitle)),t=n.filter(h=>h.sectionTitle&&la(h.sectionTitle)),r=t.filter(h=>Yh(h.sectionTitle)),i=t.filter(h=>!Yh(h.sectionTitle)),o=Math.max(0,fm-r.length),s=i.slice(0,o),a=i.slice(o),c=a.filter(h=>Jh(h.sectionTitle)),l=a.filter(h=>!Jh(h.sectionTitle)),d=[];for(let h=0;h<l.length;h+=ol)d.push(LA(l.slice(h,h+ol)));return[...e,...r,...s,...c,...d]}function MA(n,e,t){let r=n.split(/\r?\n/).length,i=NA(e);return i===0?!1:xA(t)?r>=um&&i>=pm:r>=lm&&i>=dm}var _A=/^\[h2\][A-Za-z]/;function Jh(n){return _A.test(n.trim())}function sg(n){if(!n.includes(" | ")){let t=Hi(n);return t.symbolName?[t.symbolName]:[]}let e=[];for(let t of n.split(" | ")){let r=Hi(t.trim()).symbolName;r&&e.push(r)}return e}function FA(n,e,t,r){let i=sg(n),o=Qh(t,r);return e.symbolName&&o.push(e.symbolName),ng([...i,...o],i)}function jA(n,e){let t=rg(n.bodyParts),r=n.sectionTitle.trim(),i=Hi(r),o=Wh(n.bodyParts),s=Gh(r,o,i),a=sg(r),c=r?a.length>0?`${e.docTitle} ${a.join(" ")}`:`${e.docTitle} ${i.symbolName??r}`:e.docTitle,l=[e.docTitle,s,...n.bodyParts].join(" "),{leadText:d,excerptTruncated:h}=TA(t,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:FA(r,i,l,n.codeBlocks),bodySample:t,leadText:d,excerptTruncated:h}}function ag(n,e){for(let t of n){if(t.type==="heading"){let i=ca(t).trim();i&&e.headings.push(i);continue}if(t.type==="code"){e.codeBlocks.push(t.value??"");continue}if("children"in t&&Array.isArray(t.children)){ag(t.children,e);continue}let r=da(ca(t));r&&e.bodyParts.push(r)}}function HA(n){let e=Kh().use(Xh).use(Zh).parse(n),t={headings:[],bodyParts:[],codeBlocks:[]};return ag(e.children,t),t}function $A(n,e){let t=HA(n),r=e.docTitle?.trim()||e.documentId,i=rg(t.bodyParts),o=[r,...t.headings,i].join(" "),{leadText:s,excerptTruncated:a}=ig(i);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:RA(t.headings),apiSymbols:ng(Qh(o,t.codeBlocks)),bodySample:i,leadText:s,excerptTruncated:a}}function cg(n,e){let t=e.docTitle?.trim()||e.documentId,r=kA(n);return MA(n,r,e.documentId)?OA(r).filter(i=>i.sectionTitle||i.bodyParts.length>0||i.codeBlocks.length>0).map(i=>jA(i,{...e,docTitle:t})):[$A(n,{...e,docTitle:t})]}async function UA(n){let e=[];async function t(r){let i=await fe.promises.readdir(r,{withFileTypes:!0});for(let o of i){if(o.name.startsWith("."))continue;let s=be.join(r,o.name);o.isDirectory()?await t(s):o.isFile()&&o.name.endsWith(".md")&&e.push(s)}}return await t(n),e}function BA(n,e){let t=be.relative(e,n).split(be.sep).join("/").split("/");if(t[0]==="docs"&&(t=t.slice(1)),t.length<2)return null;let r=t[0],i=Nm[r];if(i===void 0)return null;let o=t[t.length-1].replace(/\.md$/,"");return t[t.length-1]=o,{documentId:t.join("/"),catalogId:i,docTitle:o}}async function WA(n){let e=n.replace(/\.md$/,".json");try{let t=await fe.promises.readFile(e,"utf-8");return JSON.parse(t).title?.trim()||void 0}catch{return}}async function GA(n,e){let t=BA(n,e);if(!t)return[];let r=await fe.promises.readFile(n,"utf-8"),i=eg(r,{jsonTitle:await WA(n),fileName:t.docTitle});return cg(r,{...t,docTitle:i})}async function zA(n,e,t){let r=be.join(e,"search.db");return await Uh(r,n,async(i,o)=>{await t?.({current:i,total:o,message:`Building search index\u2026 ${i.toLocaleString()} / ${o.toLocaleString()} segments`})}),n.length}async function VA(n){let e=await UA(n),t=[];for(let r of e){let i=await GA(r,n);t.push(...i)}return t}function qA(n,e){return{indexVersion:pr,docsZipSha256:n.docsZipSha256,termsHash:n.termsHash,synonymsHash:n.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:n.builtBy}}async function dg(n){n.lexiconDir&&pl(n.lexiconDir);try{let e=await VA(n.docsDir);await n.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await fe.promises.mkdir(n.tmpDir,{recursive:!0});let t=await zA(e,n.tmpDir,n.onProgress),r=qA(n,t);return await fe.promises.writeFile(be.join(n.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await Gm(n.tmpDir),r}finally{n.lexiconDir&&pl(null)}}async function ug(){return fe.promises.mkdtemp(be.join(lg.tmpdir(),"deveco-docs-"))}async function YA(n,e){try{await fe.promises.rename(n,e)}catch(t){let r=t.code;if(r!=="EPERM"&&r!=="EXDEV")throw t;await fe.promises.cp(n,e,{recursive:!0}),await fe.promises.rm(n,{recursive:!0,force:!0})}}async function pg(n){let e=be.join(n,"docs");try{await fe.promises.access(e)}catch{return}let t=new Set(["docs","docs.zip"]);for(let r of await fe.promises.readdir(e,{withFileTypes:!0})){if(t.has(r.name))continue;let i=be.join(e,r.name),o=be.join(n,r.name);await fe.promises.rm(o,{recursive:!0,force:!0}),await YA(i,o)}await fe.promises.rm(be.join(e,"docs"),{recursive:!0,force:!0}),await fe.promises.rm(be.join(e,"docs.zip"),{force:!0}),await fe.promises.rm(e,{recursive:!0,force:!0})}var Ui=class extends Error{constructor(e){super(e),this.name="NativeDepsError"}};function JA(){let n=yr(),e=q();return["Documentation search index is not installed yet.","",...Hs(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(`
|
|
1348
|
+
`)}function KA(){let n=yr();return["Chinese tokenizer (@node-rs/jieba) failed to load.","",`Node.js: ${process.version} (required: >=18)`,"",...Hs(n),"","Try:"," 1. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 2. Use Node.js 18 or newer"," 3. Configure npm registry/proxy if your network blocks optional platform packages"].join(`
|
|
1349
|
+
`)}function XA(n){let e=yr();return[n,"",...Hs(e)].join(`
|
|
1350
|
+
`)}async function fg(){try{Bm()}catch(n){throw Um(n)?new Ui(`${JA()}
|
|
1362
1351
|
|
|
1363
|
-
Detail: ${n.message}`):n}try{await
|
|
1352
|
+
Detail: ${n.message}`):n}try{await Xt()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Ui(`${KA()}
|
|
1364
1353
|
|
|
1365
|
-
Detail: ${e}`)}try{await
|
|
1366
|
-
`)}async function
|
|
1354
|
+
Detail: ${e}`)}try{await ji()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Ui(XA(e))}}var Gl=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function eD(n){return new Promise(e=>setTimeout(e,n))}async function yg(n){let e=yr();await X.promises.mkdir(ut.dirname(e),{recursive:!0}),await X.promises.appendFile(e,`${new Date().toISOString()} ${n}
|
|
1355
|
+
`)}async function tD(n){let e=Jt();if(!e)throw new Error("docs.zip not found");await X.promises.rm(n,{recursive:!0,force:!0}),await X.promises.mkdir(n,{recursive:!0});let t=ut.resolve(n),r=new ZA(e);for(let i of r.getEntries()){let o=ut.resolve(t,i.entryName);if(!Mr(o,t))throw new Error(`Unsafe docs.zip entry path: ${i.entryName}`);if(i.isDirectory){await X.promises.mkdir(o,{recursive:!0});continue}await X.promises.mkdir(ut.dirname(o),{recursive:!0}),await X.promises.writeFile(o,i.getData())}await pg(n)}async function nD(){await vr({mode:"write"});let n=q(),e=Pt(),t=await X.promises.readdir(e);for(let r of t){let i=ut.join(n,r);await X.promises.rm(i,{force:!0}),await X.promises.rename(ut.join(e,r),i)}await X.promises.rm(e,{recursive:!0,force:!0}),await X.promises.rm(ut.join(n,"orama.dpack"),{force:!0})}async function mg(n,e,t){e?.start(t),await Kt({state:"installing",phase:1,phaseLabel:"Installing index",message:t}),await Xm(n),Cr(),e&&(e.text="Documentation index installed.")}async function rD(n,e){try{return await mg(n,e,"Installing documentation index\u2026"),await zl(e),!0}catch(t){if(Ri(t))throw t}try{return await Zm(),Cr(),await mg(n,e,"Retrying documentation index install\u2026"),await zl(e),!0}catch(t){if(Ri(t))throw t;let r=t instanceof Error?t.message:String(t);return await yg(`Bundled index install failed; falling back to local rebuild: ${r}`),!1}}async function iD(n,e,t){let r=Pt(),i=await ug();await X.promises.mkdir(q(),{recursive:!0}),await X.promises.rm(r,{recursive:!0,force:!0}),t?.start("Building search index\u2026"),await Kt({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"});try{await tD(i),await dg({docsDir:i,tmpDir:r,docsZipSha256:e,termsHash:qs(),synonymsHash:Vs(),builtBy:n.builtBy??"doc-init",onProgress:async o=>{t&&(t.text=o.message),await Kt({state:"indexing",current:o.current,total:o.total,message:o.message})}})}finally{await X.promises.rm(i,{recursive:!0,force:!0})}await Kt({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await nD(),Cr()}async function zl(n){await Kt({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function oD(n){let e=await Pl(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await Kt({state:"done",message:t,error:null})}async function sD(n,e){let t=n instanceof Error?n.message:String(n);throw await Kt({state:"error",error:t}),await yg(`ERROR: ${t}`),e?.fail(t),n}async function aD(){let n=q();await X.promises.mkdir(n,{recursive:!0});let e=$s();return X.existsSync(e)||await X.promises.writeFile(e,"","utf-8"),e}async function cD(){let n=await aD();return QA.lock(n,{stale:1800*1e3})}async function lD(){let n=Jt(),e=(n?await zs(n):null)??await El();if(!e)throw new Error("docs.zip not found");return e}async function dD(n,e){let t=await lD(),r=n.force||await Cl(n.force),i=await Js(n.force);if(!r&&!i&&xi()){await oD(e);return}!n.force&&Km(t)&&await rD(t,e)||(await iD(n,t,e),await zl(e))}var Bi=class{static async run(e={}){let t=e.background??!1,i=e.quiet??t?void 0:gg({text:"Checking documentation\u2026",color:"cyan"}),o;try{e.assumeStorageSafe||await vr({mode:"write"}),o=await cD(),await bl(rh("Starting documentation setup\u2026")),await dD(e,i)}catch(s){if(o)return sD(s,i);throw s}finally{o&&await o()}}};async function uD(n){for(;;){let e=await Ys();if(e.state==="done"&&xi())return;if(e.state==="error")throw new Gl("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 eD(500)}}async function hg(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await Bi.run({builtBy:"doc-init",force:e,quiet:!0})}async function pD(){let n=await Js()!==null;if(xi()&&!n)return;let e=gg({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await ih()){await uD(e),e.succeed("Documentation ready.");return}if(await Cl()){await hg(e),e.succeed("Documentation ready.");return}await hg(e,!0),e.succeed("Documentation ready.")}catch(t){throw e.fail(t.message),t}}async function Wi(){await vr({mode:"read"}),await pD(),await fg()}function fD(n){let e=n instanceof Error?n.message:String(n);return/file is not a database|database disk image is malformed|SQLITE_CORRUPT/i.test(e)}var Vl=class{async search(e,t,r=20){await Wi();try{return await Bl(e,t,r)}catch(i){if(!fD(i))throw i;return Cr(),await Bi.run({builtBy:"doc-init",force:!0,quiet:!0,assumeStorageSafe:!0}),Bl(e,t,r)}}async readDocument(e){return await Wi(),qm(e)}},ql=new Vl;function wg(...n){return e=>{if(!n.includes(e))throw new Yl(`Allowed values: ${n.join(", ")}`);return e}}function gD(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new Yl("Must be a positive integer.");return e}var yD=wg("json","default"),wD=wg("json","default");function Jl(n){let e=n instanceof Error?n.message:String(n);return Ri(n)?e:/\b(EACCES|EPERM|ENOSPC|ENOTDIR|ELOOP)\b/.test(e)?"Documentation data directory is unavailable. Check DEVECO_CLI_DATA_DIR and retry.":e}var pa=new mD("docs").description("Search and read HarmonyOS documentation from local docs directory");pa.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",SD,"all").option("--format <fmt>","Output format (default, json)",yD,"default").option("--limit <n>","Max number of results",gD,20).action(async(n,e)=>{try{let t=vD(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,i=await ql.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(i,null,2)):bD(i)}catch(t){console.error(ua(Jl(t))),process.exit(1)}});pa.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error(ua("Document ID cannot be empty.")),process.exit(1));let t=await ql.readDocument(e);console.log(t)}catch(e){console.error(ua(Jl(e))),process.exit(1)}});pa.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",wD,"default").action(async n=>{try{if(await Wi(),n.format==="json"){let e=Vt.map(t=>({name:t,title:Cn[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of Vt)console.log(` ${e.padEnd(20)} ${hD(Cn[e])}`)}catch(e){console.error(ua(Jl(e))),process.exit(1)}});function vD(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>bi)throw new Error(`Query exceeds ${bi} characters.`);return e}function SD(n){if(n==="all")return"all";if(!Vt.includes(n))throw new Yl(`Invalid catalog "${n}". Allowed: all, ${Vt.join(", ")}`);return n}function bD(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 vg=pa;import{Command as IR}from"commander";import{Command as LD,InvalidArgumentError as OD,Option as Xl}from"commander";import{readFileSync as PD,unlinkSync as CD}from"fs";import{tmpdir as ID}from"os";import{join as AD}from"path";var Dt=class{constructor(e,t){this.hdcPath=e;this.serial=t}hdcPath;serial;async listWindows(e){let t=await this.fetchDump(),r=ED(t);return e?.all||(r=r.filter(i=>i.type===1)),r}async fetchDump(){let e=["-t",this.serial,"shell","hidumper","-s","WindowManagerService","-a","-a"];m(`Executing: ${this.hdcPath} ${e.join(" ")}`);let t=await ke(this.hdcPath,e);if(t.exitCode!==0)throw new Error(`Failed to query windows: ${(t.stderr||t.stdout).trim()}`);return t.stdout}};function ED(n){let e=n.split(`
|
|
1356
|
+
`),t=e.findIndex(s=>s.trimStart().startsWith("WindowName"));if(t===-1)return[];let r=[];for(let s=t+1;s<e.length;s++){let a=e[s].trim();if(!a||/^-+$/.test(a)||a.startsWith("Focus window")||a.startsWith("total window"))break;let c=a.split(/\s+/);if(c.length<5)continue;let l=c[0],d=Number(c[1]),h=Number(c[2]),w=Number(c[3]),b=Number(c[4]);Number.isFinite(w)&&Number.isFinite(d)&&Number.isFinite(h)&&r.push({id:w,name:l,pid:h,displayId:d,type:b})}let i=e.find(s=>s.trim().startsWith("Focus window")),o=i?Number(i.replace(/.*:\s*/,"").trim()):NaN;return r.map(s=>({...s,focused:s.id===o}))}function Sg(n){if(!(!n||n==="HitTestMode.Default"))return n.startsWith("HitTestMode.")?n.slice(12):n}function Gi(n){if(!(n==null||n==="")){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1}}function bg(n){if(typeof n!="string")return;let e=n.match(/-?\d+/g);if(!(!e||e.length<4))return[Number(e[0]),Number(e[1]),Number(e[2]),Number(e[3])]}function Eg(n){return n.originalText||void 0}function Ir(n,e){let t=[],r=[...n].reverse();for(;r.length>0;){let i=r.pop();i.id===e&&t.push(i);for(let o=i.children.length-1;o>=0;o--)r.push(i.children[o])}return t}function Pg(n,e){let t=[],r=[{current:n,parent:null,depth:0}];for(;r.length>0;){let{current:i,parent:o,depth:s}=r.pop(),a=o===null,c=!i.id&&!i.text&&!i.clickable&&!i.longClickable&&!i.scrollable&&!i.checkable,l=a||!c,d=o;if(l){let w={...i,children:[]};if(a?t.push(w):o.children.push(w),d=w,e>0&&s+1>=e)continue}if(process.env.DEVECO_CLI_DEBUG){let w=i.type?i.id?`${i.type}#${i.id}`:i.type:"#";m(`collapse ${w} depth=${s} -> ${a?"root":c?"collapsed":"emitted"}`)}let h=l?s+1:s;for(let w=i.children.length-1;w>=0;w--)r.push({current:i.children[w],parent:d,depth:h})}return t}function DD(n){let e=PD(n,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function RD(n){return n.attributes??{}}function fa(n,e,t){let r=RD(n),i={id:r.id||void 0,type:r.type||void 0,text:Eg(r),bounds:bg(r.bounds),clickable:Gi(r.clickable)||void 0,longClickable:Gi(r.longClickable)||void 0,scrollable:Gi(r.scrollable)||void 0,checkable:Gi(r.checkable)||void 0,hitTestBehavior:Sg(r.hitTestBehavior),children:[]};return e>0&&t+1>=e||n.children&&(i.children=n.children.map(o=>fa(o,e,t+1))),i}function TD(n,e){if(e){let r=n.find(i=>String(i.id)===e);if(!r){let i=n.map(o=>`${o.id} (${o.name})`).join(", ");throw new Error(`Window '${e}' not found. Available windows: ${i||"none"}`)}return r}let t=n.find(r=>r.focused);if(t)return t;throw new Error("No window id specified and could not detect focused window")}var Rn=class{hdcPath;constructor(e){this.hdcPath=e}buildRemoteDumpPath(){return`/data/local/tmp/deveco_cli_dump_${Date.now()}_${process.pid}.json`}async fetchRawDump(e,t,r){let i=this.buildRemoteDumpPath(),o=["-t",e,"shell","uitest","dumpLayout","-p",i];r!==void 0&&o.push("-d",String(r)),t&&o.push("-w",t),m(`Executing: ${this.hdcPath} ${o.join(" ")}`);let s=await ke(this.hdcPath,o);if(s.exitCode!==0)throw new Error(`Failed to dump layout: ${(s.stderr||s.stdout).trim()}`);return this.recvAndParseDump(e,i)}async recvAndParseDump(e,t){let r=AD(ID(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,r),DD(r)}finally{await this.cleanupDumpArtifacts(e,r,t)}}async recvDumpFile(e,t,r){let i=["-t",e,"file","recv",t,r];m(`Executing: ${this.hdcPath} ${i.join(" ")}`);let o=await ke(this.hdcPath,i);if(o.exitCode!==0)throw new Error(`Failed to recv dump file: ${(o.stderr||o.stdout).trim()}`)}async cleanupDumpArtifacts(e,t,r){try{m(`Removing local dump file: ${t}`),CD(t)}catch(o){m(`Failed to clean local dump file ${t}: ${o.message}`)}let i=["-t",e,"shell","rm","-f",r];m(`Executing: ${this.hdcPath} ${i.join(" ")}`),await ke(this.hdcPath,i).catch(o=>{m(`Failed to clean remote dump file ${r}: ${o.message}`)})}async dumpRawNodes(e,t,r){let o=await new Dt(this.hdcPath,e).listWindows({all:!0});if(r){let a=[...new Set(o.map(l=>l.displayId))],c=[];for(let l of a)c.push(await this.fetchRawDump(e,void 0,l));return c}let s=TD(o,t);return[await this.fetchRawDump(e,String(s.id),s.displayId)]}async dumpFullTree(e,t,r,i){return(await this.dumpRawNodes(e,r,i)).map(s=>fa(s,t,0))}async dumpFullTreeByDisplays(e,t,r){let i=[];for(let o of r){let s=await this.fetchRawDump(e,void 0,o);i.push({displayId:o,tree:fa(s,t,0)})}return i}async dumpCollapsedTree(e,t,r,i){return(await this.dumpRawNodes(e,r,i)).flatMap(s=>Pg(fa(s,0,0),t))}};var ma={left:"0",right:"1",up:"2",down:"3"};function we(n,e){let t=Number(n);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function Kl(n,e){n!==void 0&&we(n,e)}function Cg(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function ha(n,e){if(n!==void 0&&n.length===0)throw new Error(`${e} must not be empty`)}function zi(n){if(n===void 0)return;let e=Number(n);if(!Number.isInteger(e)||e<200||e>4e4)throw new Error("--speed must be an integer between 200 and 40000");return n}function Ig(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function Ag(n,e,t,r=!0){if(t&&!e)throw new Error("--window must be used with --id");if(n&&e)throw new Error("Coordinates and --id are mutually exclusive");if(r&&!n&&!e)throw new Error("Either provide x y coordinates or use --id")}function Ar(n,e,t,r,i=!0){Cg(n,e),ha(t,"--id"),Kl(n,"x"),Kl(e,"y"),Ig(r),Ag(n!==void 0,!!t,!!r,i)}async function Dr(n,e){let r=await new Jn(n).selectDevice(e);if(!r)throw new Error("No device selected. Use `devecocli device list` to see targets.");return r}async function pt(n){let e=await I.new(),t=await Dr(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function Rr(n,e,t,r,i,o){if(t!==void 0&&r!==void 0)return{x:t,y:r};if(i===void 0)throw new Error("Either provide x y coordinates or use --id");let a=await new Dt(n,e).listWindows({all:!0}),c=new Rn(n);return kD(c,e,a,i,o)}async function kD(n,e,t,r,i){if(i!==void 0){let o=t.find(a=>String(a.id)===i);if(o&&o.displayId!==0)throw new Error(`Window "${i}" is on display ${o.displayId}. The current command only supports operations on the primary display.`);let s=await n.dumpFullTree(e,0,i,!1);return ND(s,r)}return xD(n,e,t,r)}async function xD(n,e,t,r){let i=[...new Set(t.map(a=>a.displayId))],o=await n.dumpFullTreeByDisplays(e,0,i),s=[];for(let{displayId:a,tree:c}of o)for(let l of Ir([c],r))s.push({node:l,displayId:a});if(s.length===0)throw new Error(`Node "${r}" not found.`);if(s.length>1)throw new Error(`Multiple nodes found with id "${r}".`);if(s[0].displayId!==0)throw new Error(`Node "${r}" is on display ${s[0].displayId}. The current command only supports operations on the primary display.`);return Dg(s[0].node,r)}function ND(n,e){let t=Ir(n,e);if(t.length===0)throw new Error(`Node "${e}" not found.`);if(t.length>1)throw new Error(`Multiple nodes found with id "${e}".`);return Dg(t[0],e)}function Dg(n,e){let t=n.bounds;if(!t)throw new Error(`Node "${e}" has no bounds.`);let[r,i,o,s]=t;return{x:Math.ceil((r+o)/2),y:Math.ceil((i+s)/2)}}async function Ue(n,e,t){let r=["-t",e,"shell",...t],i=await ke(n,r);if(i.exitCode!==0)throw new Error(i.stderr||i.stdout||`uitest exited with code ${i.exitCode}`);let o=i.stdout.toLowerCase();if(["illegal","fail","error","incorrect","please confirm that the coordinate values are correct"].some(a=>o.includes(a))&&!o.includes("no error"))throw new Error(i.stdout.trim()||"uitest command failed")}import MD from"ora";function _D(n){let e=parseInt(n,10);if(!Number.isInteger(e)||e<0||String(e)!==n.trim())throw new OD("depth must be a non-negative integer");return e}function FD(n){let e=[];(n.type||n.id)&&e.push(n.type?n.id?`${n.type}#${n.id}`:n.type:`#${n.id}`),e.push(n.bounds?`[${n.bounds.join(",")}]`:"[]"),n.text&&e.push(`"${JSON.stringify(n.text).slice(1,-1)}"`);let t=[];return n.clickable&&t.push("clickable"),n.longClickable&&t.push("longClickable"),n.scrollable&&t.push("scrollable"),n.checkable&&t.push("checkable"),t.length>0&&e.push(...t),e.join(" ")}function Rg(n,e=0){let t=[],r=" ".repeat(e);for(let i of n)t.push(`${r}${FD(i)}`),i.children.length>0&&t.push(...Rg(i.children,e+1).split(`
|
|
1357
|
+
`));return t.join(`
|
|
1358
|
+
`)}function jD(n){if(n.allWindows&&n.window)throw new Error("--all-windows and --window are mutually exclusive.")}function HD(n,e){let t=Ir(n,e);if(t.length===0)throw new Error(`Node '${e}' not found.`);let r=t.map(i=>({...i,children:[]}));console.log(JSON.stringify(r,null,2))}function $D(n,e){console.log(e==="json"?JSON.stringify(n,null,2):Rg(n))}async function UD(n){jD(n);let e=MD({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let r=await I.new(),i=await Dr(r,n.device),o=new Rn(r.hdcPath);t=n.mode==="full"?await o.dumpFullTree(i,n.depth,n.window,n.allWindows):await o.dumpCollapsedTree(i,n.depth,n.window,n.allWindows)}catch(r){throw e.stop(),new Error(`Failed to dump layout: ${r.message}`,{cause:r})}if(e.stop(),n.id){HD(t,n.id);return}$D(t,n.format)}var Tg=new LD("layout").description("Inspect on-screen node(s) for UI testing").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Layout node id").option("--window <windowId>","Target window id").option("--all-windows","Include all windows (mutually exclusive with --window)").addOption(new Xl("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(_D).default(0)).addOption(new Xl("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new Xl("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async n=>{await UD(n)});import{Command as BD,Option as WD}from"commander";import{yellow as GD}from"colorette";import zD from"ora";var VD=["Id","Name","Pid","DisplayId","Focused"];function qD(n,e){if(e==="json"){let r=n.map(i=>({id:i.id,name:i.name,pid:i.pid,displayId:i.displayId,focused:i.focused}));console.log(JSON.stringify(r,null,2));return}let t=n.map(r=>({cells:[String(r.id),r.name,String(r.pid),String(r.displayId),String(r.focused)],highlight:r.focused}));console.log(yt(VD,t))}async function YD(n){let e=zD({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let r=await I.new(),i=await Dr(r,n.device);t=await new Dt(r.hdcPath,i).listWindows({all:n.all})}catch(r){throw e.stop(),new Error(`Failed to list windows: ${r.message}`,{cause:r})}if(e.stop(),t.length===0){console.log(GD(" No windows found."));return}qD(t,n.format)}var Zl=new BD("window").description("Manage device windows");Zl.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new WD("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async n=>{await YD(n)});import{Command as JD}from"commander";import xe from"fs";import Be from"path";import{randomUUID as KD}from"crypto";import{execa as kg}from"execa";import{green as XD,red as ZD}from"colorette";function Ql(){return String(Date.now())}function QD(n){if(!n?.trim())return Be.resolve(`screenshot-${Ql()}.png`);let e=Be.resolve(n.trim());if(xe.existsSync(e)&&xe.statSync(e).isDirectory())return Be.join(e,`screenshot-${Ql()}.png`);if(Be.extname(e).toLowerCase()!==".png"){if(!xe.existsSync(e))throw new Error(`Screenshot directory does not exist: ${e}`);if(!xe.statSync(e).isDirectory())throw new Error(`Screenshot path is not a directory: ${e}`);return Be.join(e,`screenshot-${Ql()}.png`)}let t=Be.dirname(e);if(!xe.existsSync(t))throw new Error(`Screenshot directory does not exist: ${t}`);if(!xe.statSync(t).isDirectory())throw new Error(`Screenshot parent path is not a directory: ${t}`);return e}function xg(n){if(!xe.existsSync(n))throw new Error(`Screenshot file was not created: ${n}`);let e=xe.statSync(n);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${n}`);let t=xe.readFileSync(n).subarray(0,8),r=Buffer.from([137,80,78,71,13,10,26,10]);if(!t.equals(r))throw new Error(`Screenshot file is not a valid PNG: ${n}`)}async function td(n,e,t){m(`Executing: ${n} ${e.join(" ")}`);let{stdout:r}=await kg(n,e,{env:{...process.env},cwd:t});return r}async function eR(n,e,t){m(`Executing: ${n} ${e.join(" ")}`);let{stdout:r,stderr:i}=await kg(n,e,{env:{...process.env},cwd:t});return{stdout:r,stderr:i}}async function tR(n,e,t){try{return await td(n,e,t)}catch(r){return r.stdout??""}}async function nR(n,e){let t=Q.from(n),r=await t.listDevices();if(r.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");if(e===void 0){if(r.length===1)return r[0].serial;let s=await rR(t,r);throw new Error(`Multiple devices found. Specify a target device using \`--device <name|serial>\`.
|
|
1359
|
+
Available devices:
|
|
1360
|
+
${s}`)}let i=e.trim();if(!i)throw new Error("--device must not be empty.");let o=await t.getDeviceInfo(r,i);if(!o)throw new Error(`Device "${i}" not found.`);return o.serial}async function rR(n,e){return(await Promise.all(e.map(async r=>` - ${await n.getDeviceName(r.serial)} (${r.serial})`))).join(`
|
|
1361
|
+
`)}function iR(n,e){let t=["-t",n.serial,"shell","snapshot_display"];return n.display!==void 0&&t.push("-i",n.display),t.push("-f",n.remotePath),e&&t.push("-t",e),t}function oR(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}function sR(n,e){xe.copyFileSync(n,e),xg(e)}function aR(n){let e=n.trim();if(!e||/No such file|not found|cannot access/i.test(e))return;let t=e.split(/\s+/),r=Number(t[4]);return Number.isFinite(r)?r:void 0}async function cR(n){let e=await tR(n.hdcPath,["-t",n.serial,"shell","ls","-l",n.remotePath]);return aR(e)}function lR(n){return[n.stdout,n.stderr].filter(Boolean).join(`
|
|
1362
|
+
`).trim()}async function dR(n,e){let t;try{t=await eR(n.hdcPath,iR(n,e))}catch(i){t={stdout:i.stdout??"",stderr:i.stderr??i.message}}let r=await cR(n);return{created:r!==void 0&&r>0,output:lR(t)}}async function uR(n){let e=[];for(let t of[void 0,"png"]){let r=await dR(n,t);if(r.created)return;r.output&&e.push(r.output)}throw new Error(e.length>0?`Screenshot was not created on device: ${n.remotePath}. snapshot_display output: ${e.join(`
|
|
1363
|
+
`)}`:`Screenshot was not created on device: ${n.remotePath}.`)}function Ng(n){try{return xg(n),!0}catch{return!1}}function Lg(n){let e=[];for(let t of xe.readdirSync(n,{withFileTypes:!0})){let r=Be.join(n,t.name);if(t.isDirectory()){e.push(...Lg(r));continue}t.isFile()&&Ng(r)&&e.push(r)}return e}function pR(n,e){let t=Be.join(n,Be.basename(e));if(Ng(t))return t;let r=Lg(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}async function ed(n,e,t,r){try{await td(n.hdcPath,["-t",n.serial,"file","recv",n.remotePath,t],r)}catch(i){m(`hdc file recv failed: ${i.message}`)}return pR(e,n.remotePath)}async function fR(n){let e=xe.mkdtempSync(Be.join(Be.dirname(n.localPath),".devecocli-screenshot-"));try{let t=await ed(n,e,".",e)??await ed(n,e,e)??await ed(n,e,Be.join(e,"screenshot.png"));if(!t)throw new Error(`Screenshot file was not created in ${e}.`);sR(t,n.localPath)}finally{xe.rmSync(e,{recursive:!0,force:!0})}}async function mR(n){await td(n.hdcPath,["-t",n.serial,"shell","rm","-f",n.remotePath]).catch(()=>{})}async function hR(n){try{await uR(n),await fR(n)}finally{await mR(n)}}async function gR(n){try{let e=n.display!==void 0?oR(n.display):void 0,t=await I.new(),r=await nR(t,n.device),i=QD(n.path),o=`/data/local/tmp/devecocli-${KD()}.png`;await hR({hdcPath:t.hdcPath,serial:r,localPath:i,remotePath:o,display:e}),console.log(XD(`Screenshot saved to ${i}`))}catch(e){console.error(ZD(`Failed to capture screenshot: ${e.message}`)),process.exit(1)}}var Og=new JD("screenshot").description("Capture a screenshot of the device screen").option("--device <name|serial>","Target device name or serial; required when multiple devices are connected").option("--display <displayId>","Target display id; omit for default screen").option("--path <path>","Save path: directory or full file path with name; PNG only (default: ./screenshot-<timestamp>.png)").action(gR);import{Command as Qt}from"commander";async function en(n,e,t){let r=new Qe;r.start(n);try{await t(r)}catch(i){throw r.stop(),new Error(`${e}: ${i.message}`,{cause:i})}}async function yR(n,e,t){await en("Executing click...","click failed",async r=>{Ar(n,e,t.id,t.window);let{hdcPath:i,deviceId:o}=await pt(t.device),{x:s,y:a}=await Rr(i,o,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Ue(i,o,["uitest","uiInput","click",String(s),String(a)]),r.succeed(`click at (${s}, ${a})`)})}async function wR(n,e,t){await en("Executing doubleclick...","doubleclick failed",async r=>{Ar(n,e,t.id,t.window);let{hdcPath:i,deviceId:o}=await pt(t.device),{x:s,y:a}=await Rr(i,o,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Ue(i,o,["uitest","uiInput","doubleClick",String(s),String(a)]),r.succeed(`doubleclick at (${s}, ${a})`)})}async function vR(n,e,t){await en("Executing longclick...","longclick failed",async r=>{Ar(n,e,t.id,t.window);let{hdcPath:i,deviceId:o}=await pt(t.device),{x:s,y:a}=await Rr(i,o,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Ue(i,o,["uitest","uiInput","longClick",String(s),String(a)]),r.succeed(`longclick at (${s}, ${a})`)})}async function SR(n,e,t,r,i){await en("Executing swipe...","swipe failed",async o=>{we(n,"x1"),we(e,"y1"),we(t,"x2"),we(r,"y2");let s=zi(i.speed),{hdcPath:a,deviceId:c}=await pt(i.device),l=["uitest","uiInput","swipe",n,e,t,r];s&&l.push(s),await Ue(a,c,l),o.succeed(`swipe from (${n}, ${e}) to (${t}, ${r})`)})}async function bR(n,e,t,r,i){await en("Executing fling...","fling failed",async o=>{we(n,"x1"),we(e,"y1"),we(t,"x2"),we(r,"y2");let s=zi(i.speed),{hdcPath:a,deviceId:c}=await pt(i.device),l=["uitest","uiInput","fling",n,e,t,r];s&&l.push(s),await Ue(a,c,l),o.succeed(`fling from (${n}, ${e}) to (${t}, ${r})`)})}async function ER(n,e,t,r,i){await en("Executing drag...","drag failed",async o=>{we(n,"x1"),we(e,"y1"),we(t,"x2"),we(r,"y2");let s=zi(i.speed),{hdcPath:a,deviceId:c}=await pt(i.device),l=["uitest","uiInput","drag",n,e,t,r];s&&l.push(s),await Ue(a,c,l),o.succeed(`drag from (${n}, ${e}) to (${t}, ${r})`)})}async function PR(n,e){await en("Executing dircfling...","dircfling failed",async t=>{let r=ma[n];if(r===void 0)throw new Error(`Invalid direction "${n}". Valid values: ${Object.keys(ma).join(", ")}`);let{hdcPath:i,deviceId:o}=await pt(e.device);await Ue(i,o,["uitest","uiInput","dircFling",r]),t.succeed(`dircfling ${n}`)})}async function CR(n,e,t,r){await en("Executing text input...","input failed",async i=>{Ar(e,t,r.id,r.window,!1),ha(n,"text");let{hdcPath:o,deviceId:s}=await pt(r.device);if(e!==void 0)await Ue(o,s,["uitest","uiInput","inputText",`${e}`,`${t}`,n]),i.succeed(`input ${n} at (${e}, ${t})`);else if(r.id){let{x:a,y:c}=await Rr(o,s,void 0,void 0,r.id,r.window);await Ue(o,s,["uitest","uiInput","inputText",`${a}`,`${c}`,n]),i.succeed(`input ${n} at (${a}, ${c})`)}else await Ue(o,s,["uitest","uiInput","text",n]),i.succeed(`input ${n}`)})}var Mg=new Qt("click").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Tap at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(yR),_g=new Qt("doubleclick").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Double-tap at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(wR),Fg=new Qt("longclick").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Long-press at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(vR),jg=new Qt("swipe").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Swipe from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(SR),Hg=new Qt("fling").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Fling from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(bR),$g=new Qt("drag").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Drag from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(ER),Ug=new Qt("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action(PR),Bg=new Qt("text").argument("<text>","Text to input").argument("[x]","Optional X coordinate").argument("[y]","Optional Y coordinate").description("Input text at a target location or the currently focused field").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id to target before input (auto-resolves to center)").option("--window <windowId>","Target window id (used with --id)").action(CR);var We=new IR("ui").description("Inspect and interact with UI on a connected device");We.addCommand(Tg);We.addCommand(Zl);We.addCommand(Og);We.addCommand(Mg);We.addCommand(_g);We.addCommand(Fg);We.addCommand(jg);We.addCommand(Hg);We.addCommand($g);We.addCommand(Ug);We.addCommand(Bg);var Wg=We;import{Command as lk}from"commander";import{execa as qR}from"execa";import Rt from"fs";import*as od from"os";import*as G from"path";var AR=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),DR=/\r/g,RR=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,TR=/^<+\s*/,kR=/\s*>+$/,xR=[/^The configuration file .+ is in use\.$/,/^The configuration file .+ in the project is in use\.$/,/^Currently active product: ?.+$/,/^Writing the result to .+\.$/,/^Write finished\.$/,/^CodeLinter found some defects in your code\.$/];function nd(n){if(!n)return"";let e=n.replace(AR,"").replace(DR,`
|
|
1364
|
+
`).split(`
|
|
1365
|
+
`).map(t=>t.trimEnd()).filter(t=>LR(t));return e.length>0?`${e.join(`
|
|
1366
|
+
`)}
|
|
1367
|
+
`:""}function qg(n){let e=nd(n).trim();if(!e)return{jsonText:void 0,diagnostics:""};if(Yg(e))return{jsonText:e,diagnostics:""};let t=OR(e);if(!t)return{jsonText:void 0,diagnostics:`${e}
|
|
1368
|
+
`};let r=[e.slice(0,t.start).trim(),e.slice(t.end).trim()].filter(Boolean).join(`
|
|
1369
|
+
`);return{jsonText:e.slice(t.start,t.end),diagnostics:r?`${r}
|
|
1370
|
+
`:""}}function NR(n){return RR.test(n.trim())}function LR(n){let e=n.trim();return!!e&&!NR(e)&&!xR.some(t=>t.test(e))}function Yg(n){try{return JSON.parse(n),!0}catch{return!1}}function OR(n){for(let e=0;e<n.length;e++){if(n[e]!=="["&&n[e]!=="{")continue;let t=MR(n,e);if(t)return t}}function MR(n,e){for(let t=n.length;t>e;t--){let r=n[t-1];if(r!=="]"&&r!=="}")continue;let i=n.slice(e,t);if(Yg(i))return{start:e,end:t}}}var Gg=["Error","Warning","Suggestion","Info","Off","Unknown"];function Jg(n){let e=rd(n);return{issues:HR(e),summary:_R(n,e)}}function _R(n,e){let t=UR(e);return{filesChecked:BR(n).size,issues:e.length,errors:t.get("Error")??0,warnings:t.get("Warning")??0,suggestions:t.get("Suggestion")??0}}function rd(n,e=""){if(Array.isArray(n))return n.flatMap(o=>rd(o,e));if(!Kg(n))return[];let t=Vi(n,["filePath","file","path"])??e,r=FR(n,t);if(r.length>0)return r;let i=jR(n,t);return i?[i]:[]}function FR(n,e){let t=["messages","defects","issues","results","files"];for(let r of t){let i=n[r];if(Array.isArray(i)){let o=i.flatMap(s=>rd(s,e));if(o.length>0)return o}}return[]}function jR(n,e){let t=Vi(n,["message","description","desc","detail"])??"",r=VR(Vi(n,["rule","ruleId","ruleName"])),i=GR(n,["severity","level"]),o=Vi(n,["filePath","file","path"])??e;if(!(!t&&!r&&i==="Unknown"))return{file:o,line:Vg(n,["line","reportLine"]),column:Vg(n,["column","reportColumn"]),severity:i,rule:r,message:t}}function HR(n){return[...n].sort((e,t)=>{let r=zg(e.severity)-zg(t.severity);return r===0?$R(e,t):r})}function $R(n,e){let t=n.file.localeCompare(e.file);if(t!==0)return t;let r=(n.line??Number.MAX_SAFE_INTEGER)-(e.line??Number.MAX_SAFE_INTEGER);return r!==0?r:(n.column??Number.MAX_SAFE_INTEGER)-(e.column??Number.MAX_SAFE_INTEGER)}function UR(n){let e=new Map;for(let t of n){let r=t.severity;e.set(r,(e.get(r)??0)+1)}return e}function BR(n){let e=new Set;return id(e,n,""),e}function id(n,e,t){if(Array.isArray(e)){for(let i of e)id(n,i,t);return}if(!Kg(e))return;let r=Vi(e,["filePath","file","path"])??t;r&&n.add(r),WR(n,e,r)}function WR(n,e,t){let r=["messages","defects","issues","results","files"];for(let i of r){let o=e[i];if(Array.isArray(o))for(let s of o)id(n,s,t)}}function GR(n,e){for(let t of e){let r=n[t];if(typeof r=="string"||typeof r=="number")return zR(r)}return"Unknown"}function zR(n){let e=String(n).normalize("NFKC").trim().toLowerCase();return e==="2"||e==="error"||e==="err"?"Error":e==="1"||e==="warn"||e==="warning"?"Warning":e==="3"||e==="suggest"||e==="suggestion"?"Suggestion":e==="info"||e==="information"?"Info":e==="0"||e==="off"?"Off":"Unknown"}function VR(n){let e=n?.normalize("NFKC").trim();if(e)return e.replace(TR,"").replace(kR,"").toLowerCase()}function zg(n){let e=Gg.indexOf(n);return e===-1?Gg.length:e}function Vi(n,e){for(let t of e){let r=n[t];if(typeof r=="string")return r}}function Vg(n,e){for(let t of e){let r=n[t];if(typeof r=="number")return r}}function Kg(n){return typeof n=="object"&&n!==null}var Xg="deveco-codelinter-",qi=class n{resolution;cwd;constructor(e,t){this.resolution=n.resolveWithToolProvider(e),this.cwd=t}static resolveProjectRoot(e){try{return U.discover(e).rootDir}catch{return e}}async check(e){let t=Rt.mkdtempSync(G.join(od.tmpdir(),Xg)),r=G.join(t,"report.json");try{let i=n.resolveProjectRoot(this.cwd),o=this.resolveLintTarget(e.lintPath,i),s=this.resolveConfigPath(e.configPath,o),a=this.buildNativeArgs(e,o.path,s,r),c=await this.run(a),l=qg(c.stdout),d=l.diagnostics+nd(c.stderr);try{let h=this.readJsonReport(r,l.jsonText);return{exitCode:c.exitCode,diagnostics:d,report:Jg(h)}}catch(h){return{exitCode:c.exitCode,diagnostics:d,reportError:h}}}finally{this.removeTempDir(t)}}resolveLintTarget(e,t){let r=e?G.resolve(this.cwd,e):t,i=this.resolveRealPath(r,"Lint path"),o=Rt.statSync(i);if(!o.isFile()&&!o.isDirectory())throw new Error(`Lint path must be a file or directory: ${r}`);let s=this.discoverProjectRoot(i,o.isDirectory());if(e!==void 0&&s===void 0)throw new Error(`Lint path is not in a valid project directory (project-level build-profile.json5 not found or invalid): ${i}`);return{path:i,projectRoot:s}}resolveConfigPath(e,t){let r=e?G.resolve(this.cwd,e):G.join(t.projectRoot??this.cwd,"code-linter.json5"),i=this.resolveRealPath(r,"`--config-path`");if(!Rt.statSync(i).isFile())throw new Error(`--config-path must point to a file: ${r}`);if(t.projectRoot){let o=this.discoverProjectRoot(i,!1);if(o===void 0||G.relative(t.projectRoot,o)!=="")throw new Error(`\`--config-path\` must belong to the same project as the lint path. Lint project: ${t.projectRoot}; Config project: ${o??"not found"}.`)}return i}discoverProjectRoot(e,t){let r=t?e:G.dirname(e);try{return Rt.realpathSync(U.discover(r).rootDir)}catch{return}}resolveRealPath(e,t){try{return Rt.realpathSync(e)}catch(r){throw new Error(`${t} does not exist or cannot be resolved: ${e}`,{cause:r})}}buildNativeArgs(e,t,r,i){let o=["--config",r];return e.fix&&o.push("--fix"),e.incremental&&o.push("--incremental"),o.push("--product",e.product,"--format","json","--output",i,t),o}async run(e){let t=[...this.resolution.argsPrefix,...e],r=this.resolution.workingDirectory??this.cwd;this.prepareRuntimeDirectories(),m(`Executing: ${this.resolution.command} ${t.join(" ")}`),m(`[CodelinterAdapter] Working directory: ${r}`);let i=await qR(this.resolution.command,t,{cwd:r,env:this.resolution.env,stdout:"pipe",stderr:"pipe",reject:!1});return{exitCode:i.exitCode??1,stdout:i.stdout,stderr:i.stderr}}prepareRuntimeDirectories(){for(let e of this.resolution.runtimeDirectories??[])Rt.mkdirSync(e,{recursive:!0})}readJsonReport(e,t){let i=(Rt.existsSync(e)?Rt.readFileSync(e,"utf-8").trim():void 0)||t?.trim();if(!i)throw new Error("Native JSON report was not generated.");return JSON.parse(i)}removeTempDir(e){let t=G.resolve(e),r=G.resolve(od.tmpdir());!(t.startsWith(`${r}${G.sep}`)||t===r)||!G.basename(t).startsWith(Xg)||Rt.rmSync(t,{recursive:!0,force:!0})}static resolveWithToolProvider(e){let t=n.getSource(e),r=e.toolchainRoot,i=e.codelinterPath,o=e.sdkPath,s=n.getPathEntries(e,t),a=t==="ide"?"DevEco Studio":"DevEco Command Line Tools",c={command:e.nodePath,argsPrefix:[i,o],env:{...process.env,PATH:[...s,process.env.PATH||""].join(G.delimiter),DEVECO_SDK_HOME:o}};return t==="command-line-tools"&&(c.workingDirectory=r,c.runtimeDirectories=[n.getResultDirectory(i)]),m(`[CodelinterAdapter] Selected ${a} entry: ${i}`),c}static getPathEntries(e,t){let r=[G.dirname(e.nodePath)];return t==="ide"&&e.javaPath&&r.unshift(G.dirname(e.javaPath)),r}static getResultDirectory(e){return G.resolve(e,"..","linter","result")}static getSource(e){return e.sourceType==="studio"?"ide":"command-line-tools"}};import{red as ya,yellow as iT}from"colorette";import{Argument as oT,Command as sT,InvalidArgumentError as nn}from"commander";import Ji from"fs";import*as Ee from"path";import*as Yi from"path";var Zg="n/a",Qg=/\\/g,YR=/\|/g,JR=/\r?\n/g;function ey(n,e){if(n.issues.length===0)return`No defects found.
|
|
1371
|
+
${sd(n.summary)}
|
|
1372
|
+
`;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[XR(t),sd(n.summary)];return e!==void 0&&t.length<n.issues.length&&r.push(KR(n.issues.length,t.length)),`${r.join(`
|
|
1373
|
+
`)}
|
|
1374
|
+
`}function ty(n,e){return[sd(n.summary),`Full report: ${ad(e)}`,""].join(`
|
|
1375
|
+
`)}function ny(n){let e=["# CodeLinter report",""];return n.issues.length===0?e.push("No defects found.",""):e.push(...ZR(n.issues),""),e.push("## Summary","",...eT(n.summary),""),e.join(`
|
|
1376
|
+
`)}function ry(n){return`${JSON.stringify(n,null,2)}
|
|
1377
|
+
`}function sd(n){return`Summary: Issues: ${Ge(n.issues)} | Errors: ${Ge(n.errors)} | Warnings: ${Ge(n.warnings)} | Suggestions: ${Ge(n.suggestions)} | Files checked: ${Ge(n.filesChecked)}`}function KR(n,e){return`Showing ${Ge(e)} of ${Ge(n)} issues. Use --output-path <path> to write all results.`}function XR(n){let e=["No","File","Line","Column","Severity","Rule","Message"],t=n.map((r,i)=>({cells:nT(r,i+1)}));return["CodeLinter report","",yt(e,t)].join(`
|
|
1378
|
+
`)}function ZR(n){let e=["| No | File | Line | Column | Severity | Rule | Message |","| ---: | --- | ---: | ---: | --- | --- | --- |"];for(let[t,r]of n.entries())e.push(QR(r,t+1));return e}function QR(n,e){return`| ${[String(e),ad(tn(n.file)),ga(n.line),ga(n.column),tn(n.severity),tn(n.rule),tn(n.message)].map(tT).join(" | ")} |`}function eT(n){return[`- Issues: ${Ge(n.issues)}`,`- Errors: ${Ge(n.errors)}`,`- Warnings: ${Ge(n.warnings)}`,`- Suggestions: ${Ge(n.suggestions)}`,`- Files checked: ${Ge(n.filesChecked)}`]}function tT(n){return n.replace(Qg,"\\\\").replace(YR,"\\|").replace(JR,"<br>")}function nT(n,e){return[String(e),ad(tn(rT(n.file))),ga(n.line),ga(n.column),tn(n.severity),tn(n.rule),tn(n.message)]}function rT(n){if(!Yi.isAbsolute(n))return n;let e=Yi.relative(process.cwd(),n);return!e||e.startsWith("..")||Yi.isAbsolute(e)?n:e}function ad(n){return n.replace(Qg,"/")}function tn(n){let e=n?.trim();return e||Zg}function ga(n){return n===void 0?Zg:String(n)}function Ge(n){return n.toLocaleString("en-US")}var aT=/^\d+$/;function cd(){return new sT("lint").description("Run DevEco Code Linter checks for TS/ArkTS code").helpOption("--help","display help for command").addArgument(new oT("[path]","File or directory to lint").argParser(pT)).option("--fix","Auto-fix fixable code issues").option("--incremental","Only check uncommitted files").option("--config-path <path>","Path to lint configuration file",lT).option("--product <product>","Product name defined in build-profile.json5",dT,"default").option("--format <format>","Report format (choices: default, json)",cT,"default").option("--output-path <path>","Complete report file or directory",uT).option("--limit <number>","Maximum terminal issues to display when --output-path is omitted",fT).action(async(n,e)=>{await mT(n,e)})}function cT(n){if(n==="default"||n==="json")return n;throw new nn("Invalid --format. Expected one of: default, json.")}function lT(n){ld(n,"--config-path");let e=Ee.extname(n).toLowerCase();if(e!==".json"&&e!==".json5")throw new nn("`--config-path` must point to a .json or .json5 file.");return n}function dT(n){return iy(n,"product"),n}function uT(n){return ld(n,"--output-path"),n}function pT(n){return ld(n,"path"),n}function fT(n){if(iy(n,"limit"),!aT.test(n))throw new nn("`--limit` must be a positive integer.");let e=Number.parseInt(n,10);if(e<=0||!Number.isSafeInteger(e))throw new nn("`--limit` must be an integer greater than 0.");return e}function iy(n,e){if(n.trim().length===0||ay(n))throw new nn(`Invalid --${e} value.`)}function ld(n,e){let t=`\`${e}\``;if(n.length===0||ay(n))throw new nn(`${t} must be a non-empty path without control characters.`)}async function mT(n,e){let t=process.cwd(),r=vT(e.outputPath,e.format,t);e.fix&&console.warn(iT("Running codelinter with --fix. Ensure your project source is trusted."));let i=await hT(n,e,t);CT(i.diagnostics),process.exitCode=yT(i,r,e.format,e.limit,t)}async function hT(n,e,t){let r=await I.new(),i=new qi(r,t);return gT(i,{lintPath:n,configPath:e.configPath,product:e.product,fix:e.fix,incremental:e.incremental})}async function gT(n,e){let t=new Qe;process.stderr.isTTY&&t.start("Checking code...");try{let r=await n.check(e);return t.stop(),r}catch(r){throw t.fail("Code check failed"),r}}function yT(n,e,t,r,i){if(!n.report)return console.error(ya("Failed to generate Code Linter report.")),console.error(ya(n.reportError?.message??"Native JSON report was not generated.")),n.exitCode===0?1:n.exitCode;try{if(e){wT(e,t,n.report);let o=sy(e,i);process.stdout.write(ty(n.report,o))}else process.stdout.write(ey(n.report,r));return n.exitCode}catch(o){return console.error(ya("Failed to generate Code Linter report.")),console.error(ya(o.message)),n.exitCode===0?1:n.exitCode}}function wT(n,e,t){Ji.mkdirSync(Ee.dirname(n),{recursive:!0});let r=e==="json"?ry(t):ny(t);try{Ji.writeFileSync(n,r,{encoding:"utf-8",flag:"wx"})}catch(i){throw i.code==="EEXIST"?new Error(`Output file already exists: ${n}`,{cause:i}):i}}function vT(n,e,t){if(!n)return;let r=ET(n,t),i=bT(n,r),o=i?Ee.join(r,PT(e)):r;if(i||ST(n,e),Ji.existsSync(o))throw new nn(`Output file already exists: ${sy(o,t)}`);return o}function ST(n,e){let t=oy(e);if(Ee.extname(n).toLowerCase()!==t)throw new nn(`--output-path must use the ${t} extension for --format ${e}.`)}function bT(n,e){return Ji.existsSync(e)?Ji.statSync(e).isDirectory():n.endsWith("/")||n.endsWith("\\")||Ee.extname(n)===""}function ET(n,e){return Ee.resolve(e,n)}function PT(n){let e=new Date,t=[e.getFullYear(),e.getMonth()+1,e.getDate()].map((o,s)=>String(o).padStart(s===0?4:2,"0")).join(""),r=[e.getHours(),e.getMinutes(),e.getSeconds()].map(o=>String(o).padStart(2,"0")).join(""),i=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${r}-${i}${oy(n)}`}function oy(n){return n==="json"?".json":".md"}function sy(n,e){let t=Ee.relative(e,n);return t&&!t.startsWith("..")&&!Ee.isAbsolute(t)?t:n}function CT(n){n&&process.stderr.write(n)}function ay(n){for(let e of n){let t=e.charCodeAt(0);if(t<=31||t===127)return!0}return!1}import{Command as IT,InvalidArgumentError as uy}from"commander";import*as $ from"path";import*as dd from"os";import{readdirSync as AT,existsSync as wa,readFileSync as DT,unlinkSync as RT,copyFileSync as py,writeFileSync as fy}from"fs";import{execa as TT}from"execa";import{cyan as ce,yellow as my}from"colorette";import kT from"ora";var cy=["default","csv","json"];function hy(n){if(cy.includes(n))return n;throw new uy(`--format must be one of: ${cy.join(", ")} (got "${n}")`)}function xT(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new uy(`--limit must be a positive integer (got "${n}")`);return e}function NT(n){return[...n].sort((e,t)=>{let r=ly(e),i=ly(t);return r.apiVersion-i.apiVersion||r.suffix.localeCompare(i.suffix)})}function ly(n){let e=n.match(/\((\d+)\)/),t=e?Number(e[1]):0,r=n.lastIndexOf("_"),i=r>=0?n.slice(r+1):n;return{apiVersion:t,suffix:i}}function gy(n){let t=AT(n,{withFileTypes:!0}).filter(r=>r.isFile()&&r.name.toLowerCase().endsWith(".json")).map(r=>r.name.slice(0,-5));return NT(t)}function LT(n){let e=process.argv;for(let t=0;t<e.length;t+=1){let r=e[t],i;if(r==="--format"&&t+1<e.length?i=e[t+1]:r.startsWith("--format=")&&(i=r.slice(9)),i!==void 0){let o=hy(i);return o==="default"?"csv":o}}return n}async function OT(n){let e=await I.new(),{apiChangeDir:t}=e.getApiscanPaths();m(ce(`[compat:versions] apiChangeDir: "${t}"`));let r=gy(t);if(n==="json")console.log(JSON.stringify({versions:r,count:r.length},null,2));else{if(r.length===0){console.log("No SDK versions available.");return}console.log(r.join(`
|
|
1379
|
+
`))}}var dy=new Set([".ets",".c",".cpp"]);function MT(n,e){let t=new Set(n.profile.modules.map(s=>s.name)),r=e.filter(s=>!t.has(s));if(r.length===0)return;let i=n.profile.modules.map(s=>s.name).join(", "),o=r.length>1?"are":"is";throw new Error(`Module ${r.map(s=>`"${s}"`).join(", ")} ${o} not defined in build-profile.json5. Available modules: ${i}.`)}function _T(n){for(let e of n){let t=$.resolve(e);if(!wa(t))throw new Error(`File "${e}" does not exist.`);let r=$.extname(t).toLowerCase();if(!dy.has(r)){let i=Array.from(dy).join(", ");throw new Error(`Unsupported file extension "${r}" for "${e}". Supported: ${i}.`)}}}function FT(n){let e=[],t=[];for(let r of n)$.extname(r).toLowerCase()===".ets"?e.push(r):t.push(r);return{arkTs:e,cpp:t}}function jT(n){let e=[],t=[],r="",i=!1,o=0;for(;o<n.length;){let s=n[o];i?{field:r,inQuotes:i,i:o}=HT(n,o,s,r,i):s==='"'?(i=!0,o+=1):s===","?(t.push(r),r="",o+=1):s===`
|
|
1380
|
+
`?(t.push(r),e.push(t),t=[],r="",o+=1):(s==="\r"||(r+=s),o+=1)}return(r.length>0||t.length>0)&&(t.push(r),e.push(t)),e}function HT(n,e,t,r,i){return t!=='"'?{field:r+t,inQuotes:i,i:e+1}:n[e+1]==='"'?{field:r+'"',inQuotes:i,i:e+2}:{field:r,inQuotes:!1,i:e+1}}function $T(n,e){return e.map(t=>{let r=i=>{let o=n.indexOf(i);return o>=0&&o<t.length?t[o]:""};return{apiDefinition:r("Api Definition"),language:r("Language"),changeId:r("ChangeId"),changedInSdk:r("Changed in SDK"),affectedVersions:r("Affected Versions"),title:r("Title"),codeLocation:r("Code Location"),changeType:r("Change Type")}})}function UT(n){let e=DT(n,"utf8"),t=e.startsWith("\uFEFF")?e.slice(1):e,r=jT(t);if(r.length<2)return[];let[i,...o]=r;return $T(i,o)}function BT(n,e){let t=n.match(/CSV saved to:\s*([^\r\n]+\.csv)/);if(!t)return null;let r=t[1].trim();return $.isAbsolute(r)?r:$.join(e,r)}function WT(n,e){let t=new Map;for(let o of n){let s=o.changeType||"(unknown)";t.set(s,(t.get(s)??0)+1)}let r=Array.from(t.entries()).sort((o,s)=>s[1]-o[1]||o[0].localeCompare(s[0])),i=Math.max(5,...r.map(([o])=>o.length));console.log(ce("API change scan summary:")),console.log(` ${"Total".padEnd(i)} ${n.length}`);for(let[o,s]of r)console.log(` ${o.padEnd(i)} ${s}`);e&&console.log(` ${"Report".padEnd(i)} ${e}`)}function GT(n,e){if(console.log(),n.length===0){console.log("No API changes detected.");return}let t=n.slice(0,e),r=n.length-t.length;console.log(ce(`Details (showing ${t.length}${r>0?` of ${n.length}`:""}):`));let i=[["Title","title"],["Language","language"],["ChangeId","changeId"],["Changed in","changedInSdk"],["Affected Versions","affectedVersions"],["Code Location","codeLocation"]],o=Math.max(...i.map(([a])=>a.length)),s=a=>a||"<unknown>";for(let a of t){console.log(` [${s(a.changeType)}] ${s(a.apiDefinition)}`);for(let[c,l]of i)console.log(` ${c.padEnd(o)} ${s(a[l])}`)}r>0&&console.log(my(` ... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function zT(n,e){let t=n.slice(0,e),r=n.length-t.length;console.log(),console.log(JSON.stringify({count:n.length,records:t},null,2)),r>0&&console.log(my(`... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function VT(n,e){let t=[];for(let r of e){let i=n.profile.modules.find(o=>o.name===r);if(!i)throw new Error(`Module "${r}" not found in build-profile.json5.`);t.push($.resolve(n.rootDir,i.srcPath))}return t}function qT(n,e,t,r){if(!r.sourceVersion||!r.targetVersion)throw new Error("source-version and target-version are required.");let i=[n,"--startVersion",r.sourceVersion,"--endVersion",r.targetVersion];if(e.length>0){let{arkTs:o,cpp:s}=FT(e),a=d=>$.resolve(process.cwd(),d),c=o.map(a),l=s.map(a);c.length>0&&i.push("--arkTsFiles",c.join(",")),l.length>0&&i.push("--cppFiles",l.join(","))}else if(r.modules&&r.modules.length>0){let o=VT(t,r.modules);i.push("--modulePaths",o.join(","))}else i.push("--projectPath",t.rootDir);return i.push("--outputPath",dd.tmpdir()),i}async function YT(n,e){let t=$.dirname(e[0]);try{let i=(await TT(n.nodePath,e,{cwd:t,stdin:"ignore",stdout:"pipe",stderr:"inherit"})).stdout;return process.env.DEVECO_CLI_DEBUG&&(console.log(ce("[compat:check] === scan stdout ===")),process.stdout.write(i),i.endsWith(`
|
|
1381
|
+
`)||process.stdout.write(`
|
|
1382
|
+
`),console.log(ce("[compat:check] === end stdout ==="))),i}catch(r){let i=r;process.env.DEVECO_CLI_DEBUG&&i.stdout&&(console.log(ce("[compat:check] === scan stdout (on error) ===")),process.stdout.write(i.stdout),i.stdout.endsWith(`
|
|
1383
|
+
`)||process.stdout.write(`
|
|
1384
|
+
`),console.log(ce("[compat:check] === end stdout ===")));let o=new Error(`Compatibility scan failed: ${i.message}`+(i.stderr?`
|
|
1385
|
+
${i.stderr}`:""));throw i.stdout&&(o.stdout=i.stdout),o}}function JT(n,e){if(n.length>0&&e.modules&&e.modules.length>0)throw new Error("Cannot use `--modules` together with file arguments. Use either file-level scanning (with files) or module-level scanning (with --modules).");if(!e.sourceVersion)throw new Error("--source-version is required.");if(!e.targetVersion)throw new Error("--target-version is required.");if(!e.outputPath&&e.format==="csv")throw new Error("--format csv requires --output-path. For console output, use --format json or --format default (or omit the flag).")}function KT(n,e){let t=[];if(n.sourceVersion&&!e.includes(n.sourceVersion)&&t.push(`--source-version "${n.sourceVersion}"`),n.targetVersion&&!e.includes(n.targetVersion)&&t.push(`--target-version "${n.targetVersion}"`),t.length>0){let r=t.length>1?"are":"is";throw new Error(`${t.join(" and ")} ${r} not in the available SDK version list.
|
|
1386
|
+
Run \`devecocli compat versions\` to see all available versions.`)}if(n.sourceVersion&&n.targetVersion){let r=e.indexOf(n.sourceVersion),i=e.indexOf(n.targetVersion);if(r>=i)throw new Error(`--target-version "${n.targetVersion}" must be later than --source-version "${n.sourceVersion}". Run \`devecocli compat versions\` to see the available order.`)}}function XT(n,e,t,r,i){i==="none"&&(t==="json"?zT(n,r):GT(n,r)),WT(n,e)}function ZT(n,e){let t=$.dirname(n),r=$.basename(n),i=e.slice(1).map(o=>o.startsWith("--")?o:`"${o}"`).join(" ");m(ce(`[compat:check] command: cd "${t}" && node "${r}" ${i}`))}function QT(n){try{RT(n),m(ce(`[compat:check] cleaned up tmp report: "${n}"`))}catch(e){m(ce(`[compat:check] failed to clean up tmp report: ${e.message}`))}}var ek=[".csv",".json"];function tk(n){return ek.includes(n.toLowerCase())}function nk(n,e){if(!n)return{kind:"none"};let t=$.extname(n).toLowerCase();if(!tk(t))return{kind:"dir",dirPath:$.resolve(n)};if(t===".csv"&&!(e==="default"||e==="csv")||t===".json"&&e!=="json")throw new Error(`The --output-path file extension '${t}' does not match --format ${e}. Use --format ${t===".json"?"json":"default"}, or rename the file.`);return{kind:"file",filePath:$.resolve(n),ext:t}}function rk(n){if(n.kind==="file"){if(wa(n.filePath))throw new Error(`Target file "${n.filePath}" already exists. Remove it first, or choose a different --output-path.`);let e=$.dirname(n.filePath);if(!wa(e))throw new Error(`Target directory "${e}" does not exist. Create it first, or choose a different --output-path.`)}else if(n.kind==="dir"&&!wa(n.dirPath))throw new Error(`Target directory "${n.dirPath}" does not exist. Create it first, or choose a different --output-path.`)}function yy(n){return JSON.stringify({count:n.length,records:n},null,2)+`
|
|
1387
|
+
`}function ik(n,e,t,r){r===".csv"?py(n,t):fy(t,yy(e),"utf8"),m(ce(`[compat:check] saved report: "${t}"`))}function ok(n,e,t,r){if(r==="json"){let o=$.basename(n,".csv"),s=$.join(t,`${o}.json`);return fy(s,yy(e),"utf8"),m(ce(`[compat:check] saved report: "${s}"`)),s}let i=$.join(t,$.basename(n));return py(n,i),m(ce(`[compat:check] saved report: "${i}"`)),i}async function sk(n,e){let t=new mt(n,process.cwd(),!0),r=e.modules&&e.modules.length>0?e.modules[0]:void 0;try{await t.compileNative("default",r)}catch(i){throw new Error(`hvigorw compileNative failed (module=${r??"<project>"}): `+i.message,{cause:i})}}async function ak(n,e){JT(n,e);let t=U.discover(process.cwd());e.modules&&e.modules.length>0&&MT(t,e.modules),n.length>0&&_T(n);let r=await I.new(),{apiChangeDir:i,scriptPath:o}=r.getApiscanPaths();m(ce(`[compat:check] script: "${o}"`));let s=gy(i);KT(e,s),e.outputPath&&m(ce(`[compat:check] outputPath: "${e.outputPath}"`));let a=nk(e.outputPath,e.format);return m(ce(`[compat:check] outputTarget: ${a.kind}`)),rk(a),{project:t,scriptPath:o,target:a,toolProvider:r}}async function ck(n,e){let{project:t,scriptPath:r,target:i,toolProvider:o}=await ak(n,e),s=kT({text:"Running compatibility check...",color:"cyan"}).start();try{await sk(o,e);let a=qT(r,n,t,e);ZT(r,a);let c=await YT(o,a),l=BT(c,dd.tmpdir());if(!l)throw new Error("Scanner output format unexpected: missing report path.");m(ce(`[compat:check] tmp csv: "${l}"`));let d=UT(l),h=null;if(i.kind==="file")ik(l,d,i.filePath,i.ext),h=i.filePath;else if(i.kind==="dir")h=ok(l,d,i.dirPath,e.format);else if(i.kind!=="none")throw new Error(`Unexpected output target kind: ${i.kind}`);QT(l),s.stop(),XT(d,h,e.format,e.limit,i.kind)}catch(a){throw s.fail("Compatibility check failed"),a}}var ud=new IT("compat").description("Compatibility checking utilities.");ud.description("Check source code compatibility against a target SDK version. By default, performs a project-level scan; pass positional `files...` for file-level scanning; pass `--modules` for module-level scanning.").arguments("[files...]").option("--source-version <version>","Current project SDK version (required; use `compat versions` to list available versions). On zsh, quote the value because version strings contain parentheses; run `compat versions` first to copy a real example.").option("--target-version <version>","Target SDK version (required; use `compat versions` to list available versions). On zsh, quote the value because version strings contain parentheses; run `compat versions` first to copy a real example.").option("--modules <modules...>","Modules to check (default: all modules in the project). Mutually exclusive with positional file arguments.").option("--format <format>",'Output format: "json" or "default" (text) for console; "csv", "json", or "default" for file output (--output-path). "csv" requires --output-path.',hy,"default").option("--output-path <path>","Directory to write the detailed report CSV to (default: ./compat-output)").option("--limit <num>","Maximum number of change records to display (default: 100)",xT,100).action(async(n,e)=>{await ck(n,e)});ud.command("versions").description("List all available target SDK versions for compatibility checking").action(async()=>{let n=LT("csv");await OT(n)});var wy=ud;var dk=new lk("check").description("Run DevEco project checks").addCommand(wy).addCommand(cd()),vy=dk;import{Command as Kx}from"commander";import{green as Od,red as Xx}from"colorette";import Md from"fs";import nw from"path";import rw from"json5";import{readFileSync as Fk}from"fs";import{join as uk}from"path";var Y={BASE_URL:"https://connect-api.cloud.huawei.com",CERT_LIST_PATH:"/api/cps/harmony-cert-manage/v1/cert/list",CERT_DELETE_PATH:"/api/cps/harmony-cert-manage/v1/cert/delete",CERT_ADD_PATH:"/api/cps/harmony-cert-manage/v1/cert/add",CERT_DOWNLOAD_URL_PATH:"/api/amis/app-manage/v1/objects/url/reapply",DEVICE_ADD_PATH:"/api/cps/device-manage/v1/device/add",DEVICE_LIST_PATH:"/api/cps/device-manage/v1/device/list",PROVISION_ADD_REAL_PATH:"/api/cps/provision-manage/v1/ide/real/provision/add",PROVISION_ADD_TEST_PATH:"/api/cps/provision-manage/v1/ide/test/provision/add",PROVISION_DELETE_PATH:"/api/cps/provision-manage/v1/provision/delete"},Pe={CERT_NAME_PREFIX:"auto_debug_",CERT_TYPE_DEBUG:"1",TEAM_ID_INVALID_CHARS:/[\\/.:]/g,CERT_PATTERN:/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/,TARGET_FRIENDLY_NAME:"debugKey",CERTIFICATE_PATTERN_GLOBAL:/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g,BUNDLE_NAME_REGEX:/^[a-zA-Z][a-zA-Z0-9._-]*$/,CERT_BEGIN_HEADER:"-----BEGIN CERTIFICATE-----",CERT_SAVE_DIR:uk(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},le={SUCCESS_MARKER:'"code":0',SQUARE_BRACKETS:"[]",OPENPROXY_BLOCKED_URL:"Openproxy_Blocked_URL_list",CERT_LIMIT_CODE:"205389872",USER_NOT_HARMONY_CODE:"205389904",DEVICE_EXCEEDS_LIMIT_CODE:"205389859",DEVICE_NAME_REPEAT_CODE:"205389857",PROVISION_EXCEEDS_LIMIT_CODE:"205389938",PROVISION_NAME_REPEAT_CODE:"205389830"},rt={FORBIDDEN:403,UNAUTHORIZED:401},v={ERR_FORBIDDEN:"You do not have AppGallery Connect permissions for the current team. Request access from the team administrator or switch to a team where you have permissions.",ERR_UNAUTHORIZED:"Invalid AccessToken. Sign in and try again.",ERR_CERT_LIMIT_REACHED:"The number of certificates has reached the limit. Delete some certificates and try again.",ERR_CERT_NETWORK_ERROR:"Ensure the external network connection is available before downloading the certificate.",ERR_CERT_INVALIDATE:"The downloaded .cer file is invalid. Try again.",ERR_DOWNLOAD_CER:"Failed to download the certificate file. Check the following configurations: Network connection, HTTP Proxy, etc.",ERR_USER_NOT_HARMONY:"The user is not in harmony allow list, please grant the permission",ERR_READ_CSR:"Failed to read the .csr file, please try again later",ERROR_WHILE_ADD_DEVICE:"Failed to add the device, please try again.",DEVICE_LIMIT_REACHED:"The number of devices has reached the limit. Delete some unused devices and try again.",DEVICE_NAME_REPEAT:"Duplicate device name, please try again.",DEVICE_LIST_EMPTY:"No devices available.",ADD_PROFILE_FAIL:"Failed to add the profile, please try again.",NO_AGC_PERMISSION:"You do not have the AppGallery Connect permission with the current team. Apply for the permission form the team administrator, or switch to a team with which you already have the permission.",ERROR_WHILE_DOWNLOAD_PROFILE:"Failed to download the profile, please try again.",PROFILE_NAME_REPEAT:"The profile name already exists in the AGC.",ERROR_WHILE_PARSE_PROFILE:"Failed to parse the profile, please try again.",TEST_PROVISION_EXCEEDS_LIMIT:"Provision number exceeds limit.",CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT:"The certificate application file is inconsistent with the file in profile, please try again.",CERTIFICATE_HAS_EXPIRED:"The signature does not take effect or has expired. It may be the current system time is inaccurate, please calibrate the system time and sign again.",ERROR_SIGN_BUNDLE_NAME_VALIDATE:"The bundle name contains 7 to 128 characters, including only letters, digits, and underscores (_). It must be start with a letter and contain at least three segments separated by periods (.), each of the segments ending with a digit or letter."},z={TOOLCHAIN_INIT_FAILED:"Auto-sign failed: unable to initialize toolchain",LOGIN_REQUIRED:"Failed to automatically generate signatures.Run devecocli auth login to sign in.",TEAM_INFO_FAILED:"Failed to obtain user team information.Check the network connection, HTTP proxy, and other configurations.",REALNAME_REQUIRED:"Users without real-name verification are not supported.Complete real-name verification in AppGallery Connect.",SESSION_EXPIRED:"User session expired or token invalid. Please login again.",REGION_CHINA_ONLY:"This feature is only available for accounts registered in Chinese mainland.",DEVICE_MISSING:"Unable to create the profile file due to missing devices.Connect a device through IP or USB, or manually add a device in AppGallery Connect first.If you are installing the HAP package on an emulator, you can skip the signing step.",DEVICE_DETECT_FAILED:"Unable to detect devices. Please check hdc status. If installing HAP on an emulator, signature step can be skipped.",JAVA_PLATFORM_UNSUPPORTED:"Java environment not found (Windows/macOS/Linux only).",JAVA_REQUIRED:"Java runtime is required to run hvigor.Set JAVA_HOME or add Java to PATH.",PROJECT_DIR_MISSING:"Not in a valid project directory (project-level build-profile.json5 not found).",ATOMIC_SERVICE_UNSUPPORTED:"AtomicService projects are not yet supported. Please configure signing manually."};function va(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function pd(n){let e=n.replace(Pe.TEAM_ID_INVALID_CHARS,"");return`${Pe.CERT_NAME_PREFIX}${e}.cer`}function Tr(n,e,t){if(n===rt.FORBIDDEN)return e===le.OPENPROXY_BLOCKED_URL?new Error(v.ERR_CERT_NETWORK_ERROR):new Error(v.ERR_FORBIDDEN);if(n===rt.UNAUTHORIZED)return new Error(v.ERR_UNAUTHORIZED);if(t.includes(le.USER_NOT_HARMONY_CODE))return new Error(v.ERR_USER_NOT_HARMONY);if(t.includes(le.CERT_LIMIT_CODE))return new Error(v.ERR_CERT_LIMIT_REACHED);let r=pk(t);return new Error(r??v.ERR_DOWNLOAD_CER)}function pk(n){let e=Sy(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?Sy(t):t;if(r&&typeof r=="object"){let i=r.msg;if(typeof i=="string"&&i.trim()!=="")return i}return null}function Sy(n){try{return JSON.parse(n)}catch{return null}}function fd(n){return JSON.parse(n)}async function by(n){let e=`${Y.BASE_URL}${Y.CERT_LIST_PATH}`,t=await N.postAllowFailure(e,{headers:va(n)});if(t.statusCode!==200)throw Tr(t.statusCode,t.statusText,t.data);return fd(t.data)?.certList??[]}async function Sa(n,e){return(await by(n)).find(r=>r.certName===e)??null}async function md(n,e){let t=`${Y.BASE_URL}${Y.CERT_DELETE_PATH}`,r=await N.deleteAllowFailure(t,{headers:va(n),params:{certIds:[e]}});if(r.statusCode!==200)throw Tr(r.statusCode,r.statusText,r.data);return fd(r.data)?.ret?.code===0}async function hd(n,e,t){let r=`${Y.BASE_URL}${Y.CERT_ADD_PATH}`,i={csr:e,certName:t,certType:Pe.CERT_TYPE_DEBUG},o=await N.postAllowFailure(r,{headers:va(n),params:i});if(o.statusCode!==200)throw Tr(o.statusCode,o.statusText,o.data);if(!o.data.includes(le.SUCCESS_MARKER))throw Tr(void 0,o.statusText,o.data)}async function gd(n,e){let t=`${Y.BASE_URL}${Y.CERT_DOWNLOAD_URL_PATH}`,r=await N.postAllowFailure(t,{headers:va(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw Tr(r.statusCode,r.statusText,r.data);return fd(r.data)?.urlsInfo?.[0]?.newUrl??null}import{mkdirSync as fk,writeFileSync as mk,existsSync as hk}from"fs";import{dirname as gk}from"path";async function Ki(n,e){let{statusCode:t,statusText:r,buffer:i}=await N.getBinaryAllowFailure(n,{timeout:Pe.DOWNLOAD_CONNECT_TIMEOUT_MS});if(t!==200)throw t===rt.FORBIDDEN&&r===le.OPENPROXY_BLOCKED_URL?new Error(v.ERR_CERT_NETWORK_ERROR):new Error(v.ERR_DOWNLOAD_CER);let o=gk(e);hk(o)||fk(o,{recursive:!0}),mk(e,i)}import Ok from"fs/promises";import{readFileSync as Mk}from"fs";import ba from"path";import Cy from"crypto";import yk from"os";import Xi from"fs/promises";var Iy={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},Ey=["ECC","RSA"],Py=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],wk={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},vk=8,yd=64,Sk=/[\\:*?"<>|=-]/g,it={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function bk(n){if(!n.keyAlias.trim())throw new Error("keyAlias cannot be empty");if(!n.keystoreFile.trim())throw new Error("keystoreFile cannot be empty");if(n.keyAlias.length>yd)throw new Error(`The length of keyAlias cannot exceed ${yd}`);if(!Ey.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${Ey.join(" / ")}`);let e=wk[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function Ek(n){if(!n.keyAlias.trim())throw new Error("keyAlias cannot be empty");if(!n.keystoreFile.trim())throw new Error("keystoreFile cannot be empty");if(!n.subject.trim())throw new Error("subject cannot be empty");if(!Py.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${Py.join(" / ")}`)}function Pk(n){return Cy.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function Ck(n){let e=n?.trim()??"";return e&&e.replace(Sk,"_").slice(0,yd)||it.productName}async function Ay(){let n=await I.new(),e=n.javaPath;if(!e)throw new Error("Java runtime not found. DevEco Studio JBR is required to run hap-sign-tool.jar.");let t=n.sdkPath;f.info(`\u8BFB\u53D6SDK\u6839\u76EE\u5F55\uFF1A${t}`);let r=ba.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");try{await Xi.access(r)}catch(i){throw new Error(`Sign tool jar not found: ${r}`,{cause:i})}return{javaPath:e,jarPath:r}}async function Ik(n){let{javaPath:e,jarPath:t}=await Ay(),r=["-jar",t,Iy.GENERATE_KEYPAIR,"-keyAlias",n.keyAlias,"-keyAlg",n.keyAlg,"-keySize",n.keySize,"-keystoreFile",n.keystoreFile,"-keystorePwd",n.keystorePwd];n.keyPwd&&r.push("-keyPwd",n.keyPwd),n.pwdInputMode&&r.push("-pwdInputMode",n.pwdInputMode);let i=r.map(o=>["-keyPwd","-keystorePwd"].includes(o)?`${o} ******`:o);return f.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),[e,...r]}async function Ak(n){let{javaPath:e,jarPath:t}=await Ay(),r=["-jar",t,Iy.GENERATE_CSR,"-keyAlias",n.keyAlias,"-subject",n.subject,"-signAlg",n.signAlg,"-keystoreFile",n.keystoreFile,"-keystorePwd",n.keystorePwd];n.outFile&&r.push("-outFile",n.outFile),n.keyPwd&&r.push("-keyPwd",n.keyPwd),n.pwdInputMode&&r.push("-pwdInputMode",n.pwdInputMode);let i=r.map(o=>["-keyPwd","-keystorePwd"].includes(o)?`${o} ******`:o);return f.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),[e,...r]}async function Dk(n){f.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),bk(n);let e=await Ik(n),t=await Wr(e[0],e.slice(1));if(t.exitCode!==0){let r=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the private key P12, exit code${t.exitCode}\uFF1A${r}`)}return f.info("\u751F\u6210P12\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}async function Rk(n){f.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),Ek(n);let e=await Ak(n),t=await Wr(e[0],e.slice(1));if(t.exitCode!==0){let r=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the CSR, exit code${t.exitCode}\uFF1A${r}`)}return f.info("\u751F\u6210CSR\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}function Tk(n=vk){return Cy.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function kk(){let n=yk.homedir();try{await Xi.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=ba.join(n,".ohos","config");try{await Xi.mkdir(e,{recursive:!0,mode:448})}catch(t){throw new Error(`Failed to create directory ${e}`,{cause:t})}return f.info(`\u7B7E\u540D\u914D\u7F6E\u76EE\u5F55\u5C31\u7EEA\uFF1A${e}`),e}async function me(n,e,t){let r=Ck(n),i=ba.basename(e),o=Pk(e),s=`${r}_${i}_${o}=.${t}`,a=await kk();return ba.join(a,s)}function xk(n){let e;try{e=U.discover(n).rootDir}catch(t){throw new Error(`Current directory ${n} is not a valid project root`,{cause:t})}return e}async function Nk(n){try{await Xi.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function Lk(n){try{await Xi.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function wd(n,e,t){let r=process.cwd(),i=xk(r);await Nk(i),f.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${i}`);let o=Tk(),s=await me(n??"",i,"p12"),a=await me(n??"",i,"csr");return console.log("Start generating p12"),await Dk({keyAlias:e?.keyAlias??it.keyAlias,keyPwd:o,keyAlg:e?.keyAlg??it.keyAlg,keySize:e?.keySize??it.keySize,keystoreFile:s,keystorePwd:o}),await Lk(s),console.log("Start generating csr"),await Rk({subject:t?.subject??it.csrSubject,outFile:a,keyAlias:t?.keyAlias??it.keyAlias,keyPwd:o,signAlg:t?.signAlg??it.signAlg,keystoreFile:s,keystorePwd:o}),{p12FilePath:s,csrFilePath:a,keyPwd:o,keyAlias:e?.keyAlias??it.keyAlias}}var _k=["p12","cer","csr","p7b"];async function vd(n,e){for(let t of _k){let r=await me(n,e,t);await Ok.rm(r,{force:!0})}}function Sd(n){let e;try{e=Mk(n,"utf-8")}catch{throw new Error(v.ERR_CERT_INVALIDATE)}if(!Pe.CERT_PATTERN.test(e))throw new Error(v.ERR_CERT_INVALIDATE)}async function Dy(n,e){return{certPath:await me(n,e,"cer"),csrPath:await me(n,e,"csr"),p12Path:await me(n,e,"p12"),profilePath:await me(n,e,"p7b")}}async function bd(n,e){let t=e??"",r=U.discover(process.cwd()).rootDir;await vd(t,r);let i=pd(n.teamId),o=await Sa(n,i);if(o&&!await md(n,o.id))throw new Error(v.ERR_DOWNLOAD_CER);let s=await wd(e),a;try{a=Fk(s.csrFilePath,"utf-8")}catch{throw new Error(v.ERR_READ_CSR)}console.log("Start generating certificate"),await hd(n,a,i);let c=await Sa(n,i);if(!c)throw new Error(v.ERR_DOWNLOAD_CER);let l=await gd(n,c.certObjectId);if(!l)throw new Error(v.ERR_DOWNLOAD_CER);let d=await me(t,r,"cer");await Ki(l,d),Sd(d);let h=await me(t,r,"p7b");return{p12FilePath:s.p12FilePath,csrFilePath:s.csrFilePath,cerFilePath:d,profileFilePath:h,certId:c.id,keyAlias:s.keyAlias,keyPwd:s.keyPwd,storePassword:s.keyPwd}}import xa from"crypto";import an from"fs";import*as By from"path";import ox from"json5";import{execa as Hy}from"execa";import $y from"node-forge";import{createCipheriv as jk,createDecipheriv as Hk,pbkdf2Sync as $k,randomBytes as Id}from"crypto";import{promises as kn}from"fs";import{dirname as Uk,join as ot}from"path";var Ea=3,Zi=16,Bk=1e4,Ry="material",Wk=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Ny="aes-128-gcm",Tn=12,Pa=16,rn=4;function Ed(n){return new Uint8Array(Id(n))}function Gk(n){return Id(n).toString("hex")}function zk(...n){if(n.length===0)return new Uint8Array(0);let e=n[0].length,t=new Uint8Array(e);for(let r=0;r<e;r++){let i=0;for(let o of n)i^=o[r];t[r]=i}return t}function Ty(n,e,t=Bk,r=Zi){let i=[...n,Wk],o=zk(...i),s=Buffer.from(o).toString("utf8"),a=Buffer.from(s,"utf8"),c=$k(a,e,t,r,"sha256");return new Uint8Array(c)}function ky(n,e){let t=Id(Tn),r=jk(Ny,n,t),i=Buffer.concat([r.update(e),r.final()]),o=r.getAuthTag(),s=Buffer.concat([i,o]),a=s.length,c=Buffer.alloc(rn+Tn+s.length);return c.writeUInt32BE(a,0),t.copy(c,rn),s.copy(c,rn+Tn),c}function xy(n,e){if(e.length<rn+Tn+Pa)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(rn,rn+Tn),i=e.subarray(rn+Tn,rn+Tn+t);if(i.length<Pa)throw new Error("Ciphertext too short for auth tag");let o=i.subarray(0,i.length-Pa),s=i.subarray(i.length-Pa),a=Hk(Ny,n,r);return a.setAuthTag(s),Buffer.concat([a.update(o),a.final()])}async function Vk(n){try{await kn.rm(n,{recursive:!0,force:!0})}catch{}}async function Pd(n){let e=await kn.readdir(n),t=e.filter(r=>r!==".DS_Store");if(t.length!==1)throw new Error(`Expected exactly 1 file in ${n}, but found ${t.length} (filtered from ${e.length})`);return kn.readFile(ot(n,t[0]))}async function Cd(n,e){let t=Gk(Zi),r=ot(n,t);return await kn.writeFile(r,e),t}var on=class{static async generateMaterial(e){let t=ot(e,Ry);await Vk(t);let r=ot(t,"ac"),i=ot(t,"ce");await kn.mkdir(r,{recursive:!0}),await kn.mkdir(i,{recursive:!0});for(let d=0;d<Ea;d++)await kn.mkdir(ot(t,"fd",String(d)),{recursive:!0});let o=Ed(Zi),s=[];for(let d=0;d<Ea;d++)s.push(Ed(Zi));let a=Ed(Zi),c=Ty(s,o),l=ky(c,a);await Cd(r,o),await Cd(i,l);for(let d=0;d<Ea;d++){let h=ot(t,"fd",String(d));await Cd(h,s[d])}return a}static async readMaterial(e){let t=ot(e,Ry),r=ot(t,"ac"),i=new Uint8Array(await Pd(r)),o=[];for(let d=0;d<Ea;d++){let h=ot(t,"fd",String(d)),w=await Pd(h);o.push(new Uint8Array(w))}let s=ot(t,"ce"),a=await Pd(s),c=Ty(o,i),l=xy(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t=Uk(e);try{return await this.readMaterial(t)}catch{return await this.generateMaterial(t)}}static async encryptedPassword(e,t){let r=await this.getStoreKey(t),i=Buffer.from(e,"utf8");return ky(r,i).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),i=Buffer.from(e,"hex");return xy(r,i).toString("utf8")}};import Fy from"fs";import Ta from"path";import Zk from"json5";import*as Ca from"fs";import*as Ly from"path";function Ia(n){let e=Ly.resolve(n);if(!Ca.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=Ca.readFileSync(e,"utf-8")}catch(s){throw new Error(`Failed to read SDK info file: ${e}`,{cause:s})}let r;try{r=JSON.parse(t)}catch(s){throw new Error(`Invalid JSON in SDK info file: ${e}`,{cause:s})}let i=r?.data?.apiVersion;if(i==null||i==="")throw new Error(`Missing data.apiVersion in SDK info file: ${e}`);let o=Number(i);if(!Number.isFinite(o))throw new Error(`Invalid data.apiVersion in SDK info file: ${String(i)}`);return o}import*as xr from"fs";import*as Ce from"path";import{debuglog as kr}from"util";var Oy={"acl.SYSTEM_FLOAT_WINDOW.instead.name":"PiPWindow","acl.READ_CONTACTS.instead.name":"contact.selectContacts","acl.READ_IMAGEVIDEO.instead.name":"PhotoViewPicker","acl.WRITE_IMAGEVIDEO.instead.name":"SaveButton","acl.READ_AUDIO.instead.name":"AudioViewPicker","acl.WRITE_AUDIO.instead.name":"AudioViewPicker","acl.READ_PASTEBOARD.instead.name":"PasteButton"};function qk(n){return Object.prototype.hasOwnProperty.call(Oy,n)}function Aa(n){if(qk(n))return Oy[n]}var My={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as Yk}from"url";var Ra=class{permissionName;permissionDisplayName;minSupportApiLevel;permissionInsteadName;permissionHelpUrlKey;constructor(e={}){this.permissionName=e.permissionName??"",this.permissionDisplayName=e.permissionDisplayName??"",this.minSupportApiLevel=e.minSupportApiLevel??"",this.permissionInsteadName=e.permissionInsteadName,this.permissionHelpUrlKey=e.permissionHelpUrlKey}};function Da(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function _y(n){return n==null||n.length===0}function Jk(n){return!_y(n)}function Ad(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function Kk(n,e){let t=n[e];if(typeof t=="boolean")return t;if(typeof t=="number")return t!==0;if(typeof t=="string"){let r=t.trim().toLowerCase();return r==="true"||r==="1"}return!1}function Xk(n,e){let t=n[e];if(typeof t=="number")return Math.trunc(t);if(typeof t=="string"){let r=Number.parseInt(t,10);return Number.isNaN(r)?0:r}return 0}var sn=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=Ce.join("aclPermission","aclPermissionsInfo.json");static ACL_HAVE_INSTEAD_NAME=new Set(["ohos.permission.SYSTEM_FLOAT_WINDOW","ohos.permission.READ_CONTACTS","ohos.permission.READ_IMAGEVIDEO","ohos.permission.WRITE_IMAGEVIDEO","ohos.permission.READ_AUDIO","ohos.permission.WRITE_AUDIO","ohos.permission.READ_PASTEBOARD"]);static ACL_AVAILABLE_LEVEL_VALUE="system_basic";static ACL_AVAILABLE_TYPE_VALUE="NORMAL";static ACL_AVAILABLE_LEVEL_KEY="availableLevel";static ACL_AVAILABLE_TYPE_KEY="availableType";static ACL_PROVISION_ENABLE_KEY="provisionEnable";static ACL_NAME_KEY="name";static ACL_CONFIG_PREFIX="acl.";static ACL_INSTEAD_NAME_SUFFIX=".instead.name";static ACL_HELP_URL_KEY_SUFFIX=".help.key";static ACL_DEFINE_PERMISSION_KEY="definePermissions";static ACL_SINCE_KEY="since";static PERMISSION_DEFINITIONS_RELATIVE_PATH=Ce.join("lib","permissionDefinitions.json");static INCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.FILE_ACCESS_PERSIST","ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORY","ohos.permission.READ_WRITE_DOCUMENTS_DIRECTORY"]);static EXCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.READ_DOCUMENT","ohos.permission.WRITE_DOCUMENT"]);static handleSpecificAclPermissions(){this.addAclWhiteList(this.INCLUDE_ACL_PERMISSIONS),this.addAclBlackList(this.EXCLUDE_ACL_PERMISSIONS)}static aclPermissionInfoMap=new Map;static aclPermissionNamesMap=new Map;static aclWhiteList=new Set;static aclBlackList=new Set;static builtInConfigTextLoader;static initAclPermission(e,t){let r=e.rootDir,i=this.getOrCreateSet(this.aclPermissionNamesMap,r),o=this.getOrCreateSet(this.aclPermissionInfoMap,r);i.clear(),o.clear();let s=Ce.join(t.sdkPath,"default","sdk-pkg.json"),a=Ia(s);this.MIN_API_TO_FIND_ACL_IN_SDK-a>0?this.initAclPermissionFromBuiltInConfig(i,o):this.initAclPermissionFromSDK(t,i,o)}static getAclPermissionInfos(e){return this.aclPermissionInfoMap.get(e.rootDir)??new Set}static getAclPermissionNames(e){return this.aclPermissionNamesMap.get(e.rootDir)??new Set}static addAclWhiteList(e){for(let t of e)this.aclWhiteList.add(t)}static addAclBlackList(e){for(let t of e)this.aclBlackList.add(t)}static getOrCreateSet(e,t){let r=e.get(t);return r||(r=new Set,e.set(t,r)),r}static readBuiltInConfigText(){if(this.builtInConfigTextLoader)return this.builtInConfigTextLoader();let e=Ce.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(xr.existsSync(e))return xr.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=Yk(e);if(t.includes("dist")){let s=Ce.dirname(t),a=Ce.dirname(s);return Ce.join(a,"src","resources")}let r=Ce.dirname(t),i=Ce.dirname(r),o=Ce.dirname(i);return Ce.join(o,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{kr("read builtin acl permission failed.");return}if(r!==void 0)try{let i=JSON.parse(r),s=(Array.isArray(i)?i:Da(i)?Object.values(i):[]).filter(Da).map(a=>new Ra(a));s.forEach(a=>{let c=a.permissionInsteadName;Jk(c)&&(a.permissionInsteadName=Aa(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(i){kr(`failed to parse aclPermissionsInfo.json: ${i}`)}}static initAclPermissionFromSDK(e,t,r){let i=this.parsePermissionDefinitionFile(e);i&&i.forEach(o=>{if(!Da(o))return;let s=o,a=Ad(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(_y(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||Ad(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||Ad(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:Kk(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let i=new Ra;i.permissionName=t;let o=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;i.permissionDisplayName=o;let s=Xk(r,this.ACL_SINCE_KEY);i.minSupportApiLevel=String(s),this.handleInsteadName(i,o),e.add(i)}static parsePermissionDefinitionFile(e){let t=Ce.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!xr.existsSync(t))return;let r;try{r=xr.readFileSync(t,"utf-8")}catch(s){kr(`failed to load permissionDefinitions.json: ${s}`);return}let i;try{let s=JSON.parse(r);if(!Da(s)){kr("json object is null");return}i=s}catch(s){kr(`failed to parse permissionDefinitions.json: ${s}`);return}let o=i[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(o)){kr("definePermissions is not an array");return}return o}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=Aa(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=Aa(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function ka(n,e){let t=new Set,r=new Set;sn.handleSpecificAclPermissions(),sn.initAclPermission(n,e);for(let i of n.profile.modules){let o=jy(i,n,e,r,Ta.join("src","main"));for(let a of o)t.add(a);let s=jy(i,n,e,r,Ta.join("src","ohosTest"));for(let a of s)t.add(a)}return Qk(r),t}function Qk(n){if(n.size>0)throw new Error(My.DUPLICATE_PERMISSION)}function jy(n,e,t,r,i){let o=tx(e.rootDir,n,i);if(o==null)return new Set;let s=[];for(let w of o){if(typeof w!="object"||w===null)continue;let b=ex(w,"name");b&&s.push(b)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=Ta.join(t.sdkPath,"default","sdk-pkg.json"),l=Ia(c),d=sn.getAclPermissionInfos(e),h=new Set(Array.from(d).filter(w=>{let b=Number(w.minSupportApiLevel);return Number.isFinite(b)&&b<=l}).map(w=>w.permissionName));for(let w of Array.from(a))h.has(w)||a.delete(w);return a}function ex(n,e){let t=n[e];return typeof t=="string"?t:""}function tx(n,e,t){let r=Ta.join(n,e.srcPath,t,"module.json5"),i=nx(r);if(i==null)return null;let o=rx(i,"module");return o==null?null:ix(o,"requestPermissions")}function nx(n){try{if(!Fy.existsSync(n))return null;let e=Fy.readFileSync(n,"utf-8");return Zk.parse(e)}catch{return null}}function rx(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return t!=null&&typeof t=="object"&&!Array.isArray(t)?t:null}function ix(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var Rd=class{verifyStorePassword(e,t){try{let r=an.readFileSync(e),i=$y.asn1.fromDer(r.toString("binary"));return $y.pkcs12.pkcs12FromAsn1(i,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=an.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(i=>this.formatFp(new xa.X509Certificate(i).fingerprint256));try{return[this.formatFp(new xa.X509Certificate(an.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let i=an.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let o of i)try{let s=new xa.X509Certificate(o);if(this.formatFp(s.fingerprint256)===t){let a=new Date(s.validTo);return isNaN(a.getTime())?null:a}}catch{}return null}formatFp(e){let t=e.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}};function sx(n){let e=an.readFileSync(n,"utf-8"),t=ax(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let i=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:Dd(i["bundle-name"]),expiryDate:cx(r?.validity?.["not-after"]),cerFingerprintInProfile:lx(Dd(i["development-certificate"])),deviceUdidsInProfile:dx(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:ux(r?.acls?.["allowed-acls"]),teamIdInProfile:Dd(i["developer-id"])}}function ax(n){let e=n.indexOf("{");if(e<0)return null;let t=0,r=-1,i=!1,o=!1;for(let s=e;s<n.length;s++){let a=n[s];if(i){o?o=!1:a==="\\"?o=!0:a==='"'&&(i=!1);continue}if(a==='"')i=!0;else if(a==="{")t++;else if(a==="}"&&(t--,t===0)){r=s;break}}return r<0?null:n.slice(e,r+1)}function cx(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function lx(n){if(!n)return null;try{let t=new xa.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function dx(n){if(!Array.isArray(n))return[];let e=[];for(let t of n)if(typeof t=="string"){let r=t.toUpperCase();e.includes(r)||e.push(r)}return e}function ux(n){if(!Array.isArray(n))return[];let e=[];for(let t of n)typeof t=="string"?e.push(t):t&&typeof t=="object"&&typeof t.name=="string"&&e.push(t.name);return[...new Set(e)].sort()}function Dd(n){return typeof n=="string"?n:null}var Qi=class n{static async shouldRegenerate(e,t){let r=await n.#e(e,t);return n.#t(r)??n.#n(r)??n.#r(r)??n.#i(r)??n.#o(r)??n.#s(r)??n.#a(r)??n.#c(r)??n.#l(r)??n.#d(r)??await n.#u(r)??n.#p()}static async#e(e,t){let r=e.force,i=e.teamId,o=e.productName??"default",s=U.discover(process.cwd()),a=s.rootDir,[c,l]=await Promise.all([px(o,a),mx(t.hdcPath)]),d=null;if(Uy(c).allExist)try{d=sx(c.profileFile)}catch{}return{force:r,teamId:i,productName:o,projectPath:a,materialPaths:c,bundleName:s.getBundleName(),deviceUdids:l,storePassword:await fx(a,o,c.storeFile),localAclPermissions:[...ka(s,t)].sort(),hapSignTool:new Rd,profileInfo:d}}static#t(e){return e.force?(m("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:Ne({force:!0})}):null}static#n(e){let t=Uy(e.materialPaths);return t.allExist?null:(m(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:Ne({allFilesExist:!1,missingFiles:t.missing})})}static#r(e){return(e.profileInfo?.rawContent??"").trim().length>0?null:(m("[reGenerateSign] profile content is empty"),{shouldRegenerate:!0,reason:"Profile file content is empty",checkDetails:Ne({allFilesExist:!0,profileContentNotEmpty:!1})})}static#i(e){let t=e.profileInfo?.expiryDate;return!t||t>=new Date?null:(m(`[reGenerateSign] profile expired at ${t.toISOString()}`),{shouldRegenerate:!0,reason:`Profile expired at ${t.toISOString()}`,checkDetails:Ne({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#o(e){let t=e.profileInfo?.bundleNameInProfile;return t&&t===e.bundleName?null:(m(`[reGenerateSign] bundleName mismatch \u2014 current=${e.bundleName}, profile=${t}`),{shouldRegenerate:!0,reason:`bundleName mismatch: current=${e.bundleName}, in profile=${t}`,checkDetails:Ne({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!1})})}static#s(e){let t=e.profileInfo?.teamIdInProfile;return t&&t===e.teamId?null:(m(`[reGenerateSign] teamId mismatch \u2014 current=${e.teamId}, profile=${t}`),{shouldRegenerate:!0,reason:`teamId mismatch: current=${e.teamId}, in profile=${t}`,checkDetails:Ne({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=gx(e.profileInfo?.deviceUdidsInProfile??[],e.deviceUdids);return t.allPresent?null:(m(`[reGenerateSign] missing device UDIDs: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Device UDID(s) not in profile: ${t.missing.join(", ")}`,checkDetails:Ne({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return yx(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(m("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:Ne({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!1})})}static#l(e){let t=e.hapSignTool.getLocalCerFingerprints(e.materialPaths.cerFile),r=e.profileInfo?.cerFingerprintInProfile;return r&&t.includes(r)?null:(m("[reGenerateSign] certificate mismatch"),{shouldRegenerate:!0,reason:"Certificate mismatch between profile and local .cer file",checkDetails:Ne({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!1})})}static#d(e){let t=e.profileInfo?.cerFingerprintInProfile,r=e.hapSignTool.getLocalCerExpiry(e.materialPaths.cerFile,t);return!r||r>=new Date?null:(m(`[reGenerateSign] local certificate expired at ${r.toISOString()}`),{shouldRegenerate:!0,reason:`Local certificate expired at ${r.toISOString()}`,checkDetails:Ne({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!1})})}static async#u(e){return e.storePassword?e.hapSignTool.verifyStorePassword(e.materialPaths.storeFile,e.storePassword)?null:(m("[reGenerateSign] keystore password verification failed"),{shouldRegenerate:!0,reason:"Keystore password verification failed (storeFile may be corrupted or password changed)",checkDetails:Ne({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})}):(m("[reGenerateSign] no stored keystore password"),{shouldRegenerate:!0,reason:"No stored keystore password available for verification",checkDetails:Ne({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})})}static#p(){return m("[reGenerateSign] all checks passed \u2014 skip regeneration"),{shouldRegenerate:!1,reason:"",checkDetails:Ne({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function px(n,e){let[t,r,i,o]=await Promise.all([me(n,e,"p12"),me(n,e,"csr"),me(n,e,"cer"),me(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:i,profileFile:o}}async function fx(n,e,t){let r=By.join(n,"build-profile.json5");if(!an.existsSync(r))return;let i;try{i=ox.parse(an.readFileSync(r,"utf-8"))}catch{return}let a=(i?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await on.decryptPassword(a,t)}catch{return}}async function mx(n){m(`Executing: ${n} list targets`);let{stdout:e}=await Hy(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
|
|
1388
|
+
`)){let o=i.trim();if(!o||o.startsWith("[Empty]"))continue;let s=o.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let r=[];for(let i of t)try{m(`Executing: ${n} -t ${i} shell bm get -u`);let{stdout:o}=await Hy(n,["-t",i,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),s=hx(o);s&&r.push(s)}catch{m(`[reGenerateSign] Failed to get UDID for ${i}, skipping`)}return r}function hx(n){let e=n.trim();if(!e)return null;let t=e.split(`
|
|
1389
|
+
`);for(let i=0;i<t.length-1;i++)if(t[i].includes("udid of current device is")){let s=t[i+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(s)return s[0].toUpperCase()}let r=e.match(/[A-Fa-f0-9]{64}/);return r?r[0].toUpperCase():null}function Uy(n){let e=[n.storeFile,n.csrFile,n.cerFile,n.profileFile],t=[];for(let r of e)an.existsSync(r)||t.push(r);return{allExist:t.length===0,missing:t}}function gx(n,e){let t=[];for(let r of e)n.includes(r)||t.push(r);return{allPresent:t.length===0,missing:t}}function yx(n,e){let t=[...n].sort(),r=[...e].sort();return t.length!==r.length?!1:t.every((i,o)=>i===r[o])}function Ne(n){let e={force:!1,allFilesExist:!1,missingFiles:[],profileContentNotEmpty:!1,profileNotExpired:!1,bundleNameMatched:!1,teamIdMatched:!1,allDevicesInProfile:!1,missingDeviceUdids:[],aclMatched:!1,cerMatched:!1,cerNotExpired:!1,storePasswordValid:!1};return n.force?{...e,force:!0}:{...e,...n,force:!1}}import{debuglog as Td}from"util";import{execa as kd}from"execa";async function Gy(n,e){let t=await Na(n);if(!t)throw new Error(v.DEVICE_LIST_EMPTY);let r=await Sx(e);if(t.length===0)for(let s of r)await wx(n,s.udid,s.deviceName);else for(let s of r)await vx(n,t,s.udid,s.deviceName);let o=(await Na(n)).map(s=>s.id);if(o.length===0)throw new Error(v.DEVICE_LIST_EMPTY);return o}async function wx(n,e,t){await qy(n,e,zy(t))}async function vx(n,e,t,r){for(let i=0;i<e.length;i++){if(t===e[i].udid)return;if(i===e.length-1){await qy(n,t,zy(r));return}}}function zy(n){switch(n){case"liteWearable":return"1";case"wearable":return"2";case"tv":return"3";default:return"4"}}async function Wy(n,e=1,t=100){let r=`${Y.BASE_URL}${Y.DEVICE_LIST_PATH}?encodeFlag=0&start=${e}&pageSize=${t}`,i=Yy(n),o=await N.get(r,{headers:i});if(!o)throw Td("query devices failed: response is null"),new Error(v.ERROR_WHILE_ADD_DEVICE);if(o.statusCode!==200)throw Vy(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.list)throw Td("query devices failed: response list is null"),new Error(s.ret?.msg||v.ERROR_WHILE_ADD_DEVICE);return{deviceList:s.list,total:s.totalCount||0}}function Vy(n,e,t){return n===rt.FORBIDDEN?e===le.OPENPROXY_BLOCKED_URL?new Error(v.ERR_CERT_NETWORK_ERROR):new Error(v.ERR_FORBIDDEN):n===rt.UNAUTHORIZED?new Error(v.ERR_UNAUTHORIZED):t.includes(le.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(v.DEVICE_LIMIT_REACHED):new Error(v.ERROR_WHILE_ADD_DEVICE)}async function Na(n){let t=await Wy(n,1,100);if(!t||!t.deviceList||t.deviceList.length===0)return[];let r=[...t.deviceList],i=t.total,o=Math.floor(i/100)+(i%100===0?0:1);for(let s=2;s<=o;s++){let a=await Wy(n,s,100);if(!a||!a.deviceList||a.deviceList.length===0)break;r.push(...a.deviceList)}return r}async function qy(n,e,t){let r=`${Y.BASE_URL}${Y.DEVICE_ADD_PATH}`,i=Yy(n),s={deviceName:`auto_sign_device_No.${Math.floor(Math.random()*3e3)}${Date.now()}`,udid:e,deviceType:t},a=await N.postAllowFailure(r,{headers:i,params:s});if(!a)throw Td("add device failed: response is null"),new Error(v.ERROR_WHILE_ADD_DEVICE);if(a.statusCode!==200)throw Vy(a.statusCode,a.statusText,a.data);let c=a.data,l=JSON.parse(a.data);if(!l||!l.ret||l.ret.code!==0)throw c.includes(le.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(v.DEVICE_LIMIT_REACHED):c.includes(le.DEVICE_NAME_REPEAT_CODE)?new Error(v.DEVICE_NAME_REPEAT):new Error(v.ERROR_WHILE_ADD_DEVICE)}function Yy(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}async function Sx(n){let{stdout:e}=await kd(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
|
|
1390
|
+
`)){let o=i.trim();if(!o||o.startsWith("[Empty]"))continue;let s=o.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let r=[];for(let i of t)try{let o=await bx(i,n),s=await Ex(i,n);o.length>0&&r.push({id:"",udid:o,deviceName:s})}catch{m(`Failed to get device info for ${i}, skipping`)}return r}async function bx(n,e){let{stdout:t}=await kd(e,["-t",n,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),r=t.trim();if(!r)return"";let i=r.split(`
|
|
1391
|
+
`);for(let s=0;s<i.length-1;s++)if(i[s].includes("udid of current device is")){let c=i[s+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(c)return c[0].toUpperCase()}let o=r.match(/[A-Fa-f0-9]{64}/);return o?o[0].toUpperCase():""}async function Ex(n,e){let{stdout:t}=await kd(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return Px(t)}function Px(n){let e=n.trim();return!e||e.includes("inaccessible")?"phone":n.includes("liteWearable")?"liteWearable":n.includes("wearable")?"wearable":n.includes("tv")?"tv":"phone"}import xn from"fs";import{createHash as Cx}from"crypto";import{debuglog as Tt}from"util";import{Buffer as Ky}from"buffer";import{createPublicKey as Ix,X509Certificate as xd}from"crypto";import{readFileSync as Ax}from"fs";import Nn from"node-forge";async function Xy(n,e){console.log("Start generating profile");let{productName:t,bundleName:r,projectPath:i,aclPermissionList:o,allDeviceIds:s,certIds:a,keyAlias:c,keyPwd:l}=e;if(s==null||s.length===0)throw new Error(v.DEVICE_LIST_EMPTY);let d=`${Y.BASE_URL}${Y.PROVISION_ADD_TEST_PATH}`,h=Dx(t,r),w=await Tx(n,d,a||[],r,s,h,o||[]);if(!w||!w.profileInfo||!w.profileInfo.provisionFileUrl)throw Tt("add provision failed, the provision file url is null"),new Error(v.ADD_PROFILE_FAIL);let b=w.profileInfo,he=(await Lx(n,b.provisionFileUrl)).urlList,kt=w.profileInfo.id;if(he&&he.length>0){let xt=await Dy(t,i),Nr=xt.profilePath;if(!await Ox(he,Nr))throw await Jy(n,kt),new Error(v.ERROR_WHILE_DOWNLOAD_PROFILE);if(await Jy(n,kt),xn.existsSync(xt.certPath)&&xn.existsSync(Nr)&&xn.existsSync(xt.p12Path)){let sw=xn.readFileSync(xt.certPath,"utf8"),aw=xn.readFileSync(Nr,"utf8");return Mx(aw,sw,xt.p12Path,c,l)||Nx(Nr),Nr}}throw new Error(v.ADD_PROFILE_FAIL)}function Dx(n,e){let t=n?`${n}_`:"";return`${Rx(`${t}${e}_${e}`)}`}function Rx(n){return Cx("sha256").update(n).digest("hex").substring(0,16)}async function Tx(n,e,t,r,i,o,s){kx(r);let a=Ld(n),c={certList:t,packageName:r,deviceList:i,provisionName:o};s.length&&(c.aclPermissionList=s);let l=await N.postAllowFailure(e,{headers:a,params:c});if(!l)throw Tt("add provision failed: response is null"),new Error(v.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw Nd(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw Tt(`add provision fail: ${l.data}`),xx(l.data,o),new Error(d.ret?.msg||v.ADD_PROFILE_FAIL);let h=d.provisionFileUrl;return{profileInfo:{id:d.id,name:o,provisionFileUrl:h}}}function Nd(n,e,t){return n===rt.FORBIDDEN?e===le.OPENPROXY_BLOCKED_URL?new Error(v.ERR_CERT_NETWORK_ERROR):new Error(v.ERR_FORBIDDEN):n===rt.UNAUTHORIZED?new Error(v.ERR_UNAUTHORIZED):t.includes(le.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(v.TEST_PROVISION_EXCEEDS_LIMIT):new Error(v.ADD_PROFILE_FAIL)}function kx(n){if(!n||n.trim().length===0)throw new Error(v.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!Pe.BUNDLE_NAME_REGEX.test(n))throw new Error(v.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function xx(n,e){if(n.includes(le.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(v.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(le.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(v.PROFILE_NAME_REPEAT)}async function Jy(n,e){if(!e||e.trim().length===0)return;let t=`${Y.BASE_URL}${Y.PROVISION_DELETE_PATH}?id=${e}`,r=await N.deleteAllowFailure(t,{headers:Ld(n)});if(r.statusCode!==200)throw Nd(r.statusCode,r.statusText,r.data);let i=JSON.parse(r.data);(!i||!i.ret||i.ret.code!==0)&&Tt(`delete provision failed: ${r.data}`)}function Nx(...n){for(let e of n)try{xn.existsSync(e)&&xn.unlinkSync(e)}catch(t){Tt(`delete local sign file error: ${t.message}`)}}async function Lx(n,e){let t=`${Y.BASE_URL}${Y.CERT_DOWNLOAD_URL_PATH}`,r=Ld(n),i={sourceUrls:e},o=await N.postAllowFailure(t,{headers:r,params:i});if(!o)throw Tt("get download list failed: response is null"),new Error(v.ADD_PROFILE_FAIL);if(o.statusCode!==200)throw Nd(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw Tt("download: The application does not exist"),new Error(s.ret?.msg||v.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function Ox(n,e){if(!n||n.length===0)return!1;let t=n[0].newUrl;return await Ki(t,e),!0}function Mx(n,e,t,r,i){return _x(n,e),r=r||Pe.TARGET_FRIENDLY_NAME,i=i||"",Fx(e,t,r,i),!0}function _x(n,e){if(e.lastIndexOf(Pe.CERT_BEGIN_HEADER)<0)throw new Error(v.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(Pe.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(v.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function Fx(n,e,t,r){let i=n.matchAll(Pe.CERTIFICATE_PATTERN_GLOBAL),o=[],s=new Date;for(let c of i)try{let l=c[0],d=jx(l),h=new Date(d.validFrom),w=new Date(d.validTo);if(s<h||s>w){let b=`Certificate is not valid, Valid from ${h} to ${w}`;throw console.warn(`checkCertificateInValidityPeriod: ${b}`),new Error(v.CERTIFICATE_HAS_EXPIRED)}o.push(d)}catch(l){throw console.warn(`checkCertificateInValidityPeriod\uFF1A ${l.message}`),new Error(v.CERTIFICATE_HAS_EXPIRED,{cause:l})}if(!o||o.length===0)throw new Error(v.CERTIFICATE_HAS_EXPIRED);if(!$x(e,t,r,o))throw new Error(v.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function jx(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new xd(t);let r=Ky.from(t,"base64");return new xd(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function Hx(n){if(n.cert){let e=Nn.pki.publicKeyToPem(n.cert.publicKey);return Ix(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=Nn.asn1.toDer(n.asn1).getBytes(),t=Ky.from(e,"binary");return new xd(t).publicKey.export({type:"spki",format:"der"})}catch(e){return Tt(`Failed to parse cert from asn1: ${e}`),null}return null}function $x(n,e,t,r){try{let i=Ax(n),o=Nn.asn1.fromDer(Nn.util.createBuffer(i)),c=Nn.pkcs12.pkcs12FromAsn1(o,t).getBags({bagType:Nn.pki.oids.certBag})[Nn.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let h=Hx(l);if(!h)continue;if(r.some(b=>{let L=b.publicKey.export({type:"spki",format:"der"});return h.equals(L)}))return!0}return!1}catch(i){let o=i instanceof Error?i.message:String(i);return Tt(`Failed to process P12 file: ${n}, error: ${o}`),!1}}function Ld(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var Qy="https://developer.huawei.com",Ux={"ohos.permission.SYSTEM_FLOAT_WINDOW":"/consumer/cn/doc/harmonyos-guides/window-pipwindow","ohos.permission.READ_CONTACTS":"/consumer/cn/doc/harmonyos-references/js-apis-contact#contactselectcontacts10","ohos.permission.READ_IMAGEVIDEO":"/consumer/cn/doc/harmonyos-guides/select-user-file#%E9%80%89%E6%8B%A9%E5%9B%BE%E7%89%87%E6%88%96%E8%A7%86%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.WRITE_IMAGEVIDEO":"/consumer/cn/doc/harmonyos-guides/savebutton","ohos.permission.READ_AUDIO":"/consumer/cn/doc/harmonyos-guides/select-user-file#%E9%80%89%E6%8B%A9%E9%9F%B3%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.WRITE_AUDIO":"/consumer/cn/doc/harmonyos-guides/save-user-file#%E4%BF%9D%E5%AD%98%E9%9F%B3%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.READ_PASTEBOARD":"/consumer/cn/doc/harmonyos-guides/pastebutton"},Bx="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function Wx(n){let e=Ux[n];return e?`${Qy}${e}`:void 0}function Gx(){return`${Qy}${Bx}`}var zx={"acl.can.apply.text":"Permission Application Scenarios","acl.permissions.warn":"Note: You are applying for restricted ACL permissions: {0} These permissions are subject to review together with your app release. For a faster review process, apply for the following permissions instead, if they are sufficient for your purposes: {1} {2}"};function Zy(n,e){return(zx[n]??n).replace(/\{(\d+)\}/g,(r,i)=>String(e[Number(i)]??""))}function Vx(n){return Array.from(n).join(", ")}function ew(n,e){if(n.size===0)return;let t=sn.getAclPermissionInfos(e),r=new Set;for(let h of t)n.has(h.permissionName)&&r.add(h);for(let h of r){let w=Wx(h.permissionName);w!=null&&(h.permissionHelpUrlKey=w)}let i=new Set;for(let h of r)i.add(h.permissionDisplayName);let o=new Set;for(let h of r)if(h.permissionHelpUrlKey!=null){let w=h.permissionInsteadName??h.permissionDisplayName;o.add(`${w} (${h.permissionHelpUrlKey})`)}let s=Gx(),a=Zy("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=o.size>0?Array.from(o).join(", ")+".":"",d=Zy("acl.permissions.warn",[Vx(i),l,c]);console.log(d)}var La=class{_project=null;get project(){if(!this._project)throw new Error("Project not initialized. Call checkProjectDir first.");return this._project}checkProjectDir(e){try{return this._project=U.discover(process.cwd()),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Project.discover() failed: ${t.message}`),e(z.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Product validation failed: ${r.message}`),t(`Product "${e}" not found.Check the product property in the build-profile.json5 file.`)}}checkBundleName(e,t){try{return this._project.getBundleName(),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] BundleName check failed: ${r.message}`),t(`bundleName was not found under product "${e}".Check the bundleName configuration.`)}}checkAtomicService(){return this._project.isAtomicService()?{passed:!1,message:z.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import qx from"fs";import tw from"path";var Oa=class{constructor(e){this.toolProvider=e}toolProvider;checkJava(e){try{return this.toolProvider.assertJava(),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Java check failed: ${t.message}`),e(z.JAVA_PLATFORM_UNSUPPORTED)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=tw.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");if(!qx.existsSync(r)){let i=tw.join("sdk","default","openharmony","toolchains","lib","hap_sign_tools.jar");return e(`hap_sign_tools.jar not found.Check whether ${i} exists.`)}return{passed:!0,message:""}}};var Ma=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await ne.getUserInfo()}catch(e){return m(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await ne.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(z.LOGIN_REQUIRED)}catch(t){return m(`[EnvCheck] Login check failed: ${t.message}`),e(z.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(z.TEAM_INFO_FAILED);try{if((await Ft()).teamList.length>0)return{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Team API error: ${r.message}`),e(z.TEAM_INFO_FAILED)}return m("[EnvCheck] No teams found for current user"),e(z.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(z.REALNAME_REQUIRED):t.isRealName!==!0?(m("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(z.REALNAME_REQUIRED)):{passed:!0,message:""}:e(z.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let i=await Ft();if(r=e??(i.teamList.length>0?i.teamList[0].id:t.userId)??"",!i.teamList.some(s=>s.id===r)){let s=`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`;return m(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(i){return m(`[EnvCheck] Team ID check failed: ${i.message}`),{passed:!1,message:`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`}}}async checkRegion(e){let t=await this.ensureUserInfo();return t?t.countryCode?t.countryCode!=="CN"?e(z.REGION_CHINA_ONLY):{passed:!0,message:""}:(m("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(z.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function Yx(n){try{let{teamList:e}=await Ft();if(e.length>0)return e[0].id}catch(e){m(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function Jx(n){let e=await ne.getUserInfo(),t=await ne.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await Yx(e.userId);if(!r)throw new Error("No team found");let i={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await Na(i)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var _a=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t){try{let r=await Jx(t);if(r.length>0)return m(`[EnvCheck] Scenario 4 Device check: ${r.length} device(s) found in AGC cloud, skipping local device check`),{passed:!0,message:""};m("[EnvCheck] Scenario 4 Device check: no cloud devices found, falling back to local hdc");let o=await Q.from(this.toolProvider).listDevices();return o.length===0?(m("[EnvCheck] Scenario 4 Device check: no local devices found"),e(z.DEVICE_MISSING)):o.some(a=>hn(a.serial))?{passed:!0,message:""}:(m("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(z.DEVICE_MISSING))}catch(r){return m(`[EnvCheck] Scenario 4 Device check failed: ${r.message}`),e(z.DEVICE_DETECT_FAILED)}}};var Fa=class{projectChecker=new La;toolchainChecker=null;authChecker=new Ma;deviceChecker=null;constructor(){}async preflight(e){let t=r=>this.blockingFail(r);return!(!await this.runAuthChain(e,t)||!await this.initToolchain()||!await this.runDeviceCheck(e,t)||!await this.runProjectChecks(e,t)||!await this.runAuxChecks(e))}async runAuthChain(e,t){let r=o=>(o.passed||this.fail(o),!0),i=[()=>this.authChecker.checkLogin(t),()=>this.authChecker.checkTeamInfo(t),()=>this.authChecker.checkRealname(t)];for(let o of i)if(!r(await o()))return!1;return!(e.teamId&&!r(await this.authChecker.checkTeamId(e.teamId)))}async initToolchain(){try{let e=await I.new();return this.toolchainChecker=new Oa(e),this.deviceChecker=new _a(e),!0}catch(e){throw m(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(z.TOOLCHAIN_INIT_FAILED,{cause:e})}}async runDeviceCheck(e,t){return(i=>i.passed?!0:(this.fail(i),!1))(await this.deviceChecker.checkDevice(t,e.teamId))}async runProjectChecks(e,t){let r=o=>o.passed?!0:(this.fail(o),!1);if(!r(this.projectChecker.checkProjectDir(t))||!r(this.projectChecker.checkAtomicService()))return!1;let i=[()=>this.projectChecker.checkProduct(e.productName,t),()=>this.projectChecker.checkBundleName(e.productName,t),()=>this.toolchainChecker.checkJava(t),()=>this.toolchainChecker.checkHapSignTools(t)];for(let o of i)if(!r(o()))return!1;return!0}async runAuxChecks(e){let t=r=>r.passed?!0:(this.fail(r),!1);return!e.teamId&&!t(await this.authChecker.checkTeamId(e.teamId))?!1:(await this.authChecker.checkRegion(r=>this.blockingFail(r)),!0)}blockingFail(e){return{passed:!1,message:e}}fail(e){throw m(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};function Zx(n){if(Md.existsSync(n)){let e=Md.readFileSync(n,"utf-8");return rw.parse(e)}return{app:{signingConfigs:[],products:[]}}}function Qx(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function eN(n){if(n.keyPwd===n.storePassword){let r=await on.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await on.encryptedPassword(n.keyPwd,n.p12FilePath),t=await on.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function tN(n,e,t){let r=nw.join(n,"build-profile.json5"),i=Zx(r);Qx(i);let o=t??"default",{keyPassword:s,storePassword:a}=await eN(e),c={name:o,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:it.signAlg,storeFile:e.p12FilePath,storePassword:a}},l=i.app?.signingConfigs?.findIndex(h=>h.name===o);l!==void 0&&l>=0?i.app.signingConfigs[l]=c:i.app.signingConfigs.push(c);let d=i.app?.products?.findIndex(h=>h.name===o);d!==void 0&&d>=0?i.app.products[d].signingConfig=o:i.app.products.push({name:o,signingConfig:o}),Md.writeFileSync(r,rw.stringify(i,null,2),"utf-8")}async function nN(n){let e=await ne.getUserInfo(),t=await ne.refreshToken();if(!e||!t)throw new Error("Failed to obtain login credentials. Run `devecocli login` again.");return{uid:e.userId??"",teamId:n.teamId??e.userId??"",accessToken:t.accessToken??""}}async function rN(n){let e=n.product||"default";await new Fa().preflight({productName:e,teamId:n.teamId}),console.log("Executing signature generate command");let r=await nN(n),i=await I.new(),{shouldRegenerate:o}=await Qi.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product},i);if(!o){console.log(Od("Signature generation completed successfully."));return}await iN(n,r,i),console.log(Od("Signature generation completed successfully."))}async function iN(n,e,t){let r=await bd(e,n.product),i=oN(n,e,r,t);i.allDeviceIds=await Gy(e,t.hdcPath),await Xy(e,i);let o=U.discover(process.cwd()).rootDir;await tN(o,r,n.product??"default"),console.log(Od(`Signing config written to ${nw.join(o,"build-profile.json5")}`))}function oN(n,e,t,r){let i=process.cwd(),o=U.discover(i),s=ka(o,r);return ew(s,o),{productName:n.product||"default",bundleName:o.getBundleName(),projectPath:o.rootDir,teamId:e.teamId,force:n.force||!1,aclPermissionList:[...s],certIds:[t.certId],keyAlias:t.keyAlias,keyPwd:t.keyPwd}}var iw=new Kx("signature").description("Generate application signature.");iw.command("generate").description("Automatically generate signing materials and write them to the project configuration.").option("--force","Force overwrite existing local signing materials.").option("--team-id <team-id>","Specify the team ID to use.").option("--product <product>","Specify the product. The default value is default.").action(async n=>{try{await rN(n)}catch(e){console.error(Xx(e.message)),process.exit(1)}});var ow=iw;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";sN();ee.name("devecocli").description("HarmonyOS application development command line tool").version("1.3.0-Test.7");ee.addCommand(Eu);ee.addCommand(Hu);ee.addCommand(Wu);ee.addCommand(tp);ee.addCommand(Rp);ee.addCommand(Vp);ee.addCommand(vf);ee.addCommand(Pf);ee.addCommand(Of);ee.addCommand(Bf);ee.addCommand(cm);ee.addCommand(vg);ee.addCommand(Wg);ee.addCommand(vy);ee.addCommand(ow);var _d=process.argv.slice(2);_d.length>=2&&_d[_d.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var cN=new Set(["update","auth"]);ee.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==ee;)t=t.parent;cN.has(t.name())||await I.checkVersion()});ee.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(aN(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
|