@deveco-test/hmos-deveco-cli 0.2.0 → 0.3.0-TD.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +65 -0
- package/SKILL.md +26 -21
- package/THIRD-PARTY-LICENSES +342 -3
- package/dist/cli.js +159 -103
- package/dist/internal/doc-init-background.js +8 -8
- package/index.zip +0 -0
- package/package.json +8 -2
- 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,60 +1,69 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{bootstrap as
|
|
3
|
-
`)}static parseDurationToSeconds(e,t="value"){let
|
|
4
|
-
`)}static resolveTimeBounds(e,t,r){let o=e?new Date(r.getTime()-e*1e3):null,i=t?new Date(r.getTime()-t*1e3):null;return o&&i?o<i?[o,i]:[i,o]:o?[o,r]:i?[null,i]:[null,null]}static isWithinBounds(e,t,r){let o=e.getTime(),i=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(i!==null&&o<i||s!==null&&o>s)}static extractTimestampFromLogLine(e,t){let r=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!r)return null;let o=t.getFullYear(),i=Number.parseInt(r[1],10)-1,s=Number.parseInt(r[2],10),a=Number.parseInt(r[3],10),c=Number.parseInt(r[4],10),l=Number.parseInt(r[5],10),u=r[6]??"0",h=Number.parseInt(u.padEnd(3,"0").slice(0,3),10),v=new Date(o,i,s,a,c,l,h);return v.getTime()>t.getTime()+1440*60*1e3&&v.setFullYear(o-1),v}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(r=>{let o=r.charCodeAt(0);return o<=n.ASCII_CONTROL_MAX||o===n.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let r=`'${e.replace(/'/g,"'\\''")}'`;return g(`quotePosixShellArg: ${e} -> ${r}`),r}static assertCrashFilename(e){if(!/^\w+-.+\d+-\d+$/.test(e))throw new Error(`Invalid crash log filename: ${JSON.stringify(e)}`)}static assertHilogLevel(e){if(!/^[DIWEF]$/.test(e))throw new Error(`Invalid log level: ${e}`)}static resolvePathWithinRoot(e,t){if($.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=$.resolve($.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=$.normalize(e),o=$.relative(r,t);if(o.split($.sep)[0]===".."||$.isAbsolute(o))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||$.isAbsolute(e)}static isPathContained(e,t){let r=$.resolve(t,e),o=$.relative(t,r);return n.isPathEscaping(o)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){if($.isAbsolute(e))return{contained:!1,reason:`Absolute path is not allowed: ${e}`};let r=n.isPathContained(e,t);if(!r.contained)return r;let o;try{o=Do.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let i=$.resolve(o,e),s;try{s=Do.realpathSync(i)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${i}`}}return n.isPathContained(s,o)}};var Ze=class n{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let r=n.tryLoadProjectProfile(t);if(r)return new n(t,r);let o=q.dirname(t);if(o===t)break;t=o}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=q.join(e,"build-profile.json5");if(!j.existsSync(t))return null;try{let r=j.readFileSync(t,"utf-8"),o=Re.parse(r);return o.app?o:null}catch(r){return console.error(`Error parsing ${t}:`,r),null}}getModuleType(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=P.resolvePathWithinRoot(this.rootDir,t.srcPath),o=q.join(r,"src","main","module.json5");if(!j.existsSync(o))return"entry";try{let i=j.readFileSync(o,"utf-8");return Re.parse(i)?.module?.type||"entry"}catch(i){return console.warn(`Warning: Failed to parse ${o}:`,i),"entry"}}getModuleProfile(e){let t=this.profile.modules.find(a=>a.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=P.resolvePathWithinRoot(this.rootDir,t.srcPath),o=q.join(r,"build-profile.json5");if(!j.existsSync(o))throw new Error(`Build profile for module '${e}' not found at ${o}.`);let i=j.readFileSync(o,"utf-8");return Re.parse(i)}getBundleName(){let e=q.join(this.rootDir,"AppScope","app.json5");if(j.existsSync(e))try{let t=j.readFileSync(e,"utf-8"),r=Re.parse(t);if(r?.app?.bundleName)return r.app.bundleName}catch(t){console.warn(`Warning: Failed to parse ${e}:`,t)}throw new Error("Could not find bundleName in AppScope/app.json5.")}getMainAbility(e,t){if(t)return t;let r=this.profile.modules.find(s=>s.name===e);if(!r)return"EntryAbility";let o=P.resolvePathWithinRoot(this.rootDir,r.srcPath),i=q.join(o,"src","main","module.json5");if(!j.existsSync(i))return"EntryAbility";try{let s=j.readFileSync(i,"utf-8"),c=Re.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let l=c.find(u=>u.name==="EntryAbility");return l?l.name:c[0].name}catch(s){return console.warn(`Warning: Failed to parse ${i}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new Error(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`);if(!this.profile.app.products?.some(r=>r.name===e)){let r=this.profile.app.products?.map(o=>o.name).join(", ")||"none";throw new Error(`Product '${e}' not found in project configuration. Available products: ${r}`)}}getModuleDependencies(e){let t=this.profile.modules.find(s=>s.name===e);if(!t)return[];let r=P.resolvePathWithinRoot(this.rootDir,t.srcPath),o=q.join(r,"oh-package.json5");if(!j.existsSync(o))return[];let i=[];try{let s=j.readFileSync(o,"utf-8"),c=Re.parse(s)?.dependencies||{};for(let l of Object.values(c)){if(typeof l!="string")continue;let u=l;if(!(u.startsWith("file:")||u.startsWith(".")||u.startsWith("..")))continue;u.startsWith("file:")&&(u=u.substring(5));let v=q.join(t.srcPath,u),D=P.resolvePathWithinRoot(this.rootDir,v),k=this.profile.modules.find(ne=>q.resolve(this.rootDir,ne.srcPath)===D);k&&i.push(k.name)}}catch{}return i}getModuleName(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)return e;let r=P.resolvePathWithinRoot(this.rootDir,t.srcPath),o=q.join(r,"src","main","module.json5");if(!j.existsSync(o))return e;try{let i=j.readFileSync(o,"utf-8");return Re.parse(i)?.module?.name||e}catch(i){return console.warn(`Warning: Failed to parse ${o}:`,i),e}}collectNonHarDependentModuleList(e){let t=[],r=[],o=new Set;for(r.push(e),o.add(e);r.length>0;){let i=r.shift();this.getModuleType(i)!=="har"&&t.push(i);let a=this.getModuleDependencies(i);for(let c of a)o.has(c)||(r.push(c),o.add(c))}return t}findArtifactPath(e,t,r,o="default"){this.validateProduct(o);let i=this.profile.modules.find(ne=>ne.name===e);if(!i)throw new Error(`Module '${e}' not found`);let a=this.getModuleType(e)==="shared",c=a?"hspName":"hapName",l=this.buildOutputPath(i.srcPath,o,["intermediates",a?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!j.existsSync(l))throw new Error(`Build metadata not found for module '${e}' at ${l}. Build the project first.`);let{packageName:u,isSigned:h}=this.parseOutputMetadata(l,c),v=u;if(!h){let ne=this.getSignedHapName(u,i.srcPath,o,t);ne&&(v=ne)}let D=a?"-signed.hsp":"-signed.hap";if(!r&&!v.endsWith(D))throw new Error(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`);let k=this.buildOutputPath(i.srcPath,o,["outputs",t,v]);if(!j.existsSync(k))throw new Error(`Generated package file not found in ${k}.`);return k}getSignedHapName(e,t,r,o){let i=null;if(e.endsWith("-unsigned.hap")?i=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(i=e.replace("-unsigned.hsp","-signed.hsp")),!i)return null;let s=this.buildOutputPath(t,r,["outputs",o,i]);return j.existsSync(s)?i:null}buildOutputPath(e,t,r){let o=P.resolvePathWithinRoot(this.rootDir,e),i=q.resolve(o,"build",t,...r);return P.ensurePathWithinRoot(this.rootDir,i)}parseOutputMetadata(e,t){let r=j.readFileSync(e,"utf-8"),o=Re.parse(r),i,s=!1;if(Array.isArray(o)){let a=o[0];a&&(i=a[t],s=a.isSigned===!0)}else o&&typeof o=="object"&&(i=o[t],s=o.isSigned===!0);if(!i)throw new Error(`Could not find ${t} in output_metadata.json at ${e}`);return this.validatePackageName(i),{packageName:i,isSigned:s}}validatePackageName(e){let t=q.basename(e);if(t!==e)throw new Error(`Invalid traversal name: '${e}'. It must contain path characters.`);if(!t.endsWith(".hap")&&!t.endsWith(".hsp"))throw new Error(`Invalid package name '${t}'.It must be a .hap or .hsp file.`)}};import{execFileSync as xo}from"child_process";import R,{existsSync as xs}from"fs";import*as E from"path";import*as W from"os";import bu from"regedit";import{join as ks}from"path";import{red as Su}from"colorette";import*as Es from"os";function I(){return Io()==="openharmony"}function Io(){return Es.platform()}var Co={HTTP_TIMEOUT_MS:2e4},Hn={USER_AGENT:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",ACCEPT_LANGUAGE:"zh-CN"};import{homedir as Me}from"os";import be from"path";import{xdgConfig as wu}from"xdg-basedir";var B={"trae-cn":be.join(Me(),".trae-cn"),opencode:be.join(wu,"opencode"),cursor:be.join(Me(),".cursor"),codebuddy:be.join(Me(),".codebuddy"),qoder:be.join(Me(),".qoder"),"claude-code":be.join(Me(),".claude"),codex:be.join(Me(),".codex"),bitfun:be.join(Me(),".bitfun"),opendesk:be.join(Me(),".opendesk")};import Oe from"path";var Ao="https://matrix.openharmony.cn",ce={TAGS_API_URL:`${Ao}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${Ao}/api/registry/skill/skills`,SKILL_API_BASE:`${Ao}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},Ds={"trae-cn":{path:Oe.join(B["trae-cn"],"skills"),displayName:"trae-cn"},opencode:{path:Oe.join(B.opencode,"skills"),displayName:"opencode"},cursor:{path:Oe.join(B.cursor,"skills"),displayName:"cursor"},codebuddy:{path:Oe.join(B.codebuddy,"skills"),displayName:"codebuddy"},qoder:{path:Oe.join(B.qoder,"skills"),displayName:"qoder"},"claude-code":{path:Oe.join(B["claude-code"],"skills"),projectPath:".claude/skills",displayName:"claude-code"},codex:{path:Oe.join(B.codex,"skills"),displayName:"codex"}},Is={opencode:{path:Oe.join(B.opencode,"skills"),displayName:"opencode"}};function Se(){return I()?Is:Ds}import{homedir as Wt}from"os";import re from"path";var fe="deveco-mcp";var Ne={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:re.join(B.opencode,"opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:re.join(process.platform==="win32"?re.join(process.env.APPDATA??re.join(Wt(),"AppData","Roaming"),"Trae CN","User"):re.join(Wt(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:re.join(B.cursor,"mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:re.join(B.codebuddy,"mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:re.join(process.platform==="win32"?re.join(process.env.APPDATA??re.join(Wt(),"AppData","Roaming"),"Qoder","SharedClientCache"):re.join(Wt(),"Library","Application Support","Qoder","SharedClientCache"),"mcp.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"standard"},"claude-code":{name:"claude-code",displayName:"Claude Code",supportsGlobal:!0,globalConfigPath:re.join(Wt(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:re.join(B.codex,"config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function As(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function Cs(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Ts(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function jn(n,e){return n.format==="opencode"?As(e):n.format==="claude-code"||n.format==="codex"?Cs(e):Ts(e)}var le={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var To="https://developer.huawei.com/consumer/cn/download/";var Rs="6.1.0",Pu=["sdk","default","openharmony","native","llvm","bin","clangd"],Fn=n=>new Promise((e,t)=>{bu.list(n,(r,o)=>{r?t(r):e(o)})}),_=class n{_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;_emulatorLauncherPath;_clangdPath;_lspServerPath;static _verifiedPaths=new Set;static _powerShellPath;static verifyAndCache(e){!e||e===""||I()||n._verifiedPaths.has(e)||(n.verifySignature(e),n._verifiedPaths.add(e))}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return n.verifyAndCache(this._nodePath),this._nodePath}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get javaPath(){return n.verifyAndCache(this._javaPath),this._javaPath}get sdkPath(){return this._sdkPath}get hdcPath(){return n.verifyAndCache(this._hdcPath),this._hdcPath}get emulatorPath(){return n.verifyAndCache(this._emulatorPath),this._emulatorPath}get emulatorLauncherPath(){return this._emulatorLauncherPath&&n.verifyAndCache(this._emulatorLauncherPath),this._emulatorLauncherPath}get clangdPath(){return n.verifyAndCache(this._clangdPath),this._clangdPath}get lspServerPath(){return n.verifyAndCache(this._lspServerPath),this._lspServerPath}constructor(e,t,r,o,i,s,a,c,l,u,h){this._devecoStudioPath=e,this._nodePath=t,this._ohpmJsPath=r,this._hvigorJsPath=o,this._javaPath=i,this._sdkPath=s,this._hdcPath=a,this._emulatorPath=c,this._emulatorLauncherPath=l,this._clangdPath=u,this._lspServerPath=h}static enforceStudioMinVersion(e){let t=n.parseProductInfoVersion(e);if(t===void 0)throw new Error(`Failed to determine DevEco Studio version at ${e}`);n.assertMinVersion(e,t)}static async checkVersion(){if(I())return;let e=await n.findDevEcoStudio();n.enforceStudioMinVersion(e)}static async new(e){if(I())return n.newForOpenHarmony();let t=e??await n.findDevEcoStudio(),{nodePath:r,ohpmJsPath:o,hvigorJsPath:i,javaPath:s,sdkPath:a,hdcPath:c,emulatorPath:l,clangdPath:u,lspServerPath:h}=n.resolveTools(t),v=n.getEmulatorExe(t);return new n(t,r,o,i,s,a,c,l,v??void 0,u,h)}static async newForOpenHarmony(){let e=process.env.COMMAND_LINE_TOOL_PATH;if(!e)throw new Error("COMMAND_LINE_TOOL_PATH environment variable is not set. ");let t=E.join(e,"node","bin","node"),r=E.join(e,"ohpm","bin","pm-cli.js"),o=E.join(e,"hvigor","bin","hvigorw.js");n.verifyTools(t,r,o);let i=E.join(e,"sdk"),s=E.join(e,"clangd","clangd"),a=E.join(e,"ace-server","out","index.js");if(!R.existsSync(s))throw new Error(`clangd not found at: ${s}`);if(!R.existsSync(a))throw new Error(`ace-server not found at: ${a}`);let c=n.resolveHdcPath(i,W.platform());return new n("",t,r,o,"",i,c,"",void 0,s,a)}static resolveLspServerPath(e){let t=W.platform();if(t==="linux")throw new Error("LSP server (ace-server) is not supported on Linux.");let r;if(t==="win32")r=E.join(e,"plugins","openharmony");else if(t==="darwin")r=E.join(e,"Contents","plugins","openharmony");else throw new Error(`LSP server (ace-server) is not supported on platform: ${t}`);let o=E.join(r,"ace-server","out","index.js");if(R.existsSync(o))return o;throw new Error(`LSP server (ace-server) not found at: ${o}`)}static devecoContentRootForClangd(e){return W.platform()==="darwin"&&e.endsWith(".app")?E.join(e,"Contents"):e}static clangdCandidatesFromDevecoHome(e){let t=new Set,r=[e,n.devecoContentRootForClangd(e)];for(let o of r){let i=E.join(o,...Pu);t.add(W.platform()==="win32"?i+".exe":i)}return[...t]}static resolveClangdPath(e){let t=n.clangdCandidatesFromDevecoHome(e);for(let r of t)if(R.existsSync(r))return r;throw new Error(`clangd executable not found. Searched in:
|
|
5
|
-
${t.
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
Searched locations:
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
`)}`)}static resolveEmulatorPath(e,t){let r;if(t==="win32")r=E.join(e,"tools","emulator","Emulator.exe");else if(t==="darwin")r=E.join(e,"Contents","tools","emulator","Emulator");else throw new Error("Linux is not fully supported yet");if(!R.existsSync(r))throw new Error(`Emulator executable not found at: ${r}`);return r}static verifyTools(e,t,r,o){if(!R.existsSync(e))throw new Error(`Node executable not found at: ${e}`);if(!R.existsSync(t))throw new Error(`ohpm js file not found at: ${t}`);if(!R.existsSync(r))throw new Error(`hvigor js file not found at: ${r}`);if(o&&!R.existsSync(o))throw new Error(`java executable not found at: ${o}`)}static getEmulatorExe(e){let t=W.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 xs(r)?r:void 0}static isValidApiLevel(e,t){let r=t??23;return Number.isInteger(e)&&e>=17&&e<=r}static parseApiLevelFromFile(e){if(R.existsSync(e))try{let t=R.readFileSync(e,"utf-8"),r=JSON.parse(t),o=r?.apiVersion??r?.data?.apiVersion;if(typeof o!="string"&&typeof o!="number")return;let i=Number(o);return Number.isInteger(i)&&i>=17?i:void 0}catch{return}}static detectFromSdkPkg(e){let t=E.join(e,"default","sdk-pkg.json");return n.parseApiLevelFromFile(t)}static detectFromOhUniPackage(e){let t=[E.join(e,"default","openharmony","toolchains","oh-uni-package.json"),E.join(e,"default","openharmony","native","oh-uni-package.json"),E.join(e,"default","openharmony","previewer","oh-uni-package.json")];for(let r of t){let o=n.parseApiLevelFromFile(r);if(o!==void 0)return o}}getMaxApiLevel(){let e=n.detectFromSdkPkg(this.sdkPath);if(e!==void 0)return e;let t=n.detectFromOhUniPackage(this.sdkPath);return t!==void 0?t:23}detectApiLevel(){return this.getMaxApiLevel()}static findPowerShellPath(){if(n._powerShellPath)return n._powerShellPath;if(W.platform()!=="win32")return n._powerShellPath="",n._powerShellPath;let e=E.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return xs(e)?(g(`[ToolProvider] Found PowerShell at: ${e}`),n._powerShellPath=e,e):(n._powerShellPath="",n._powerShellPath)}static verifySignature(e){if(!R.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=W.platform();if(n.isExecutableFile(e,t)){if(t==="win32"){if(!n.verifyWindowsSignature(e).signed)throw new Error(`The executable is not digitally signed: ${e}`)}else if(t==="darwin"&&!n.verifyMacSignature(e).signed)throw new Error(`The executable is not digitally signed: ${e}`)}}static isExecutableFile(e,t){if(t==="win32")return E.extname(e).toLowerCase()===".exe";if(t==="darwin")try{return R.accessSync(e,R.constants.X_OK),!0}catch{return!1}return!1}static createSignatureScript(){let e=R.mkdtempSync(E.join(W.tmpdir(),"deveco-verify-")),t=E.join(e,"Verify-Signature.ps1");return R.writeFileSync(t,"$env:PSModulePath = ($env:PSModulePath -split ';' | Where-Object { $_ -notmatch 'windowsapps' }) -join ';'; Get-AuthenticodeSignature -FilePath $args[0] | ConvertTo-Json -Depth 3 -Compress","utf-8"),{tmpDir:e,scriptPath:t}}static verifyWindowsSignature(e){let t=n.findPowerShellPath();if(!t)throw new Error("PowerShell application not found");let{tmpDir:r,scriptPath:o}=n.createSignatureScript();try{let i=xo(t,["-NoProfile","-ExecutionPolicy","Bypass","-File",o,e],{encoding:"utf-8",timeout:5e3,stdio:["pipe","pipe","ignore"]}),s=JSON.parse(i);return{signed:s?.Status===0,signer:s?.SignerCertificate?.Subject??void 0}}catch(i){return g(`[ToolProvider] verify Windows Signature, error msg: ${i}`),{signed:!0}}finally{try{R.rmSync(r,{recursive:!0,force:!0})}catch{}}}static verifyMacSignature(e){try{return xo("codesign",["-v",e],{encoding:"utf-8",timeout:5e3}),{signed:!0}}catch{return{signed:!1}}}};import{execa as Eu}from"execa";import*as pt from"path";import*as Ms from"os";var Pe=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let r={...process.env,DEVECO_SDK_HOME:e.sdkPath};if(e.javaPath){let o=pt.dirname(e.javaPath);r.PATH=`${o}${pt.delimiter}${process.env.PATH||""}`}I()&&(r.HVIGOR_USER_HOME=pt.join(Ms.homedir(),".hvigor")),this.env=r}async sync(e,t){let r=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(r)}async buildProduct(e,t){let r=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(r)}async buildModules(e,t,r,o){let i=[...Array.from(o),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(i)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];await this.runHvigor(e)}async stopDaemon(){I()||await this.runHvigor(["--stop-daemon"])}async runHvigor(e){I()&&(e=e.includes("--no-daemon")?e:["--no-daemon",...e]);let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];g(`Executing: ${t} ${r.join(" ")}`),await Eu(t,r,{cwd:this.projectRoot,env:this.env,stdout:"inherit",stderr:"inherit"})}};import{execa as Du}from"execa";var Le=class{toolProvider;projectRoot;constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=["--no-deprecation",this.toolProvider.ohpmJsPath,"install","--all"];g(`Executing: ${e} ${t.join(" ")}`),await Du(e,t,{cwd:this.projectRoot,stdout:"inherit",stderr:"inherit"})}};import{mkdir as Iu}from"fs/promises";import{dirname as Cu,resolve as Au}from"path";import{execa as Tu}from"execa";import{lock as ko,check as zb}from"proper-lockfile";function Ro(n){return Au(n,".hvigor",".build-lock")}function xu(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function Os(n){let e=Cu(Ro(n));if(await Iu(e,{recursive:!0}),process.platform==="win32")try{await Tu("attrib",["+h",e])}catch{}}async function ku(n,e){let t=new AbortController,r=xu(e);await Os(n);let o={lockfilePath:Ro(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await ko(n,{...o,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return r(),{release:await ko(n,{...o,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Xe(n,e,t){let{release:r,signal:o}=await ku(n,t);try{return await e(o)}finally{await r()}}async function Ns(n,e){let t=new AbortController;await Os(n);let r={lockfilePath:Ro(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},o;try{o=await ko(n,{...r,retries:0})}catch(i){if(i&&typeof i=="object"&&"code"in i&&i.code==="ELOCKED")return{acquired:!1};throw i}try{return{acquired:!0,result:await e(t.signal)}}finally{await o()}}import*as _e from"fs";import*as Qe from"path";import Ru from"json5";var Mu=1e3;function Bn(n){g(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=Qe.join(n,le.SYNC_OUTPUT_PATH);if(!_e.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return g(`[ProjectCheck] ${l.reason}`),l}let t=_e.statSync(e).mtimeMs;g(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Ou(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return g(`[ProjectCheck] ${l.reason}`),l}let o=Qe.join(n,le.OH_PACKAGE_JSON5),i=$n(o,t,"root");if(i.required)return g(`[ProjectCheck] Root check: ${i.reason}`),i;let s=Qe.join(n,le.BUILD_PROFILE_JSON5),a=$n(s,t,"build-profile");if(a.required)return g(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let u=Qe.join(n,l.srcPath,le.OH_PACKAGE_JSON5),h=$n(u,t,l.name);if(h.required)return g(`[ProjectCheck] Module '${l.name}' check: ${h.reason}`),h;let v=Qe.join(n,l.srcPath,le.BUILD_PROFILE_JSON5),D=$n(v,t,l.name);if(D.required)return g(`[ProjectCheck] Module '${l.name}' build-profile check: ${D.reason}`),D}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return g(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function $n(n,e,t){if(!_e.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=_e.statSync(n).mtimeMs;return r-e>Mu?{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 Ou(n){let e=Qe.join(n,le.BUILD_PROFILE_JSON5);try{let t=_e.readFileSync(e,"utf-8");if(!t.trim())return null;let r=Ru.parse(t);if(typeof r!="object"||r===null)return null;let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}function Lu(n,e){if(e.product&&n.validateProduct(e.product),e.buildMode&&!n.profile.app.buildModeSet.some(r=>r.name===e.buildMode))throw new Error(`Build mode '${e.buildMode}' not found in project build-profile.json5.`)}function _u(n,e){let t;if(e.modules&&e.modules.length>0)t=e.modules;else{let o=n.profile.modules,i=o.filter(s=>n.getModuleType(s.name)==="entry");if(o.length===1)t=[o[0].name];else if(i.length===1)t=[i[0].name];else throw i.length>1?new Error(`Multiple entry modules found (${i.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`):new Error(`No entry module found and multiple modules available (${o.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`)}let r=new Set;for(let o of t){let i=o.indexOf("@"),s=i!==-1?o.substring(0,i):o,a=i!==-1?o.substring(i+1):"default";r.add(`${s}@${a}`)}return Array.from(r)}function zt(n,e){let t=new Set;for(let r of e){let o=r.indexOf("@"),i=o!==-1?r.substring(0,o):r,s=n.getModuleType(i);s==="shared"?t.add("assembleHsp"):s==="har"?t.add("assembleHar"):t.add("assembleHap")}return t}function Ut(n,e){let t=e,r=`${n} failed`;console.error(Mo(r));let o=t.stdout||t.message;throw o&&console.error(o),t.stderr&&console.error(t.stderr),new Error(r,{cause:e})}async function qt(n,e,t,r,o,i){let s=Bn(i);console.log(`
|
|
15
|
-
|
|
16
|
-
|
|
2
|
+
var Iw=Object.defineProperty;var Aw=(n,e)=>{for(var t in e)Iw(n,t,{get:e[t],enumerable:!0})};import{bootstrap as FN}from"global-agent";import{program as ne}from"commander";import{red as jN}from"colorette";import{Command as bv}from"commander";import{green as sc,red as ac,yellow as cc}from"colorette";import Y from"fs";import*as ee from"path";import gt from"json5";import*as Ga from"fs";import*as oe from"path";function m(n){process.env.DEVECO_CLI_DEBUG&&console.log(`[DEBUG] ${n}`)}var E=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 assertBundleNameStrict(e){if(e.length<7||e.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${e.length}`);if(e.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let t=e.split(".");if(t.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let r=/^[a-zA-Z0-9_]+$/;for(let i=0;i<t.length;i++){let o=t[i];if(!r.test(o))throw new Error(`Segment "${o}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(i===0){if(!/^[a-zA-Z]/.test(o))throw new Error(`First segment "${o}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(o))throw new Error(`Segment "${o}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(o))throw new Error(`Segment "${o}" must end with a letter or digit.`)}}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(oe.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=oe.resolve(oe.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=oe.normalize(e),i=oe.relative(r,t);if(i.split(oe.sep)[0]===".."||oe.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||oe.isAbsolute(e)}static isPathContained(e,t){let r=oe.resolve(t,e),i=oe.relative(t,r);return n.isPathEscaping(i)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){if(oe.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=Ga.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=oe.resolve(i,e),s;try{s=Ga.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=ee.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=ee.join(e,"build-profile.json5");if(!Y.existsSync(t))return null;try{let r=Y.readFileSync(t,"utf-8"),i=gt.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=E.resolvePathWithinRoot(this.rootDir,t.srcPath),i=ee.join(r,"src","main","module.json5");if(!Y.existsSync(i))return"entry";try{let o=Y.readFileSync(i,"utf-8");return gt.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=E.resolvePathWithinRoot(this.rootDir,t.srcPath),i=ee.join(r,"build-profile.json5");if(!Y.existsSync(i))throw new Error(`Build profile for module '${e}' not found at ${i}.`);let o=Y.readFileSync(i,"utf-8");return gt.parse(o)}getBundleName(){let e=ee.join(this.rootDir,"AppScope","app.json5");if(Y.existsSync(e))try{let t=Y.readFileSync(e,"utf-8"),r=gt.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=ee.join(this.rootDir,"AppScope","app.json5");if(!Y.existsSync(e))return!1;try{let t=Y.readFileSync(e,"utf-8");return gt.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=E.resolvePathWithinRoot(this.rootDir,r.srcPath),o=ee.join(i,"src","main","module.json5");if(!Y.existsSync(o))return"EntryAbility";try{let s=Y.readFileSync(o,"utf-8"),c=gt.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=E.resolvePathWithinRoot(this.rootDir,t.srcPath),i=ee.join(r,"oh-package.json5");if(!Y.existsSync(i))return[];let o=[];try{let s=Y.readFileSync(i,"utf-8"),c=gt.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=ee.join(t.srcPath,d),S=E.resolvePathWithinRoot(this.rootDir,w),k=this.profile.modules.find(we=>ee.resolve(this.rootDir,we.srcPath)===S);k&&o.push(k.name)}}catch{}return o}getModuleName(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)return e;let r=E.resolvePathWithinRoot(this.rootDir,t.srcPath),i=ee.join(r,"src","main","module.json5");if(!Y.existsSync(i))return e;try{let o=Y.readFileSync(i,"utf-8");return gt.parse(o)?.module?.name||e}catch(o){return console.warn(`Warning: Failed to parse ${i}:`,o),e}}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(!Y.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 S=this.getSignedHapName(c,o.srcPath,i,t);S&&(d=S)}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(!Y.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=ee.isAbsolute(c)?c:this.buildOutputPath(i.srcPath,r,["outputs",t,c]);if(!Y.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 Y.existsSync(s)?o:null}buildOutputPath(e,t,r){let i=E.resolvePathWithinRoot(this.rootDir,e),o=ee.resolve(i,"build",t,...r);return E.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=Y.readFileSync(e,"utf-8"),i=gt.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=ee.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 lu}from"child_process";import B from"fs";import*as fe from"os";import*as v from"path";import eu from"fs";import*as uo from"os";import*as lo from"path";import Rw from"regedit";import{execFileSync as Dw}from"child_process";import Kd from"fs";import*as Xd from"os";import*as Va from"path";function co(n,e){let t=Va.join(n,"Contents","Info.plist");if(!Kd.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 Tw(n){let e=co(n,"CFBundleShortVersionString");if(!e)return co(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[co(n,"CFBundleVersion"),co(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 jr(n){if(Xd.platform()==="darwin")return Tw(n);let e=Va.join(n,"product-info.json");try{let t=JSON.parse(Kd.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}function Hr(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 kw(n){return n.filter(e=>{try{return eu.statSync(e).isDirectory()}catch{return!1}})}function xw(){let n=[];for(let e of[lo.join(uo.homedir(),"Applications"),"/Applications"])try{n.push(...eu.readdirSync(e).filter(t=>t.endsWith(".app")&&t.toLowerCase().includes("deveco")).map(t=>lo.join(e,t)))}catch{}return n}function Zd(n){return new Promise((e,t)=>Rw.list(n,(r,i)=>r?t(r):e(i)))}async function Qd(n,e,t){let i=((await Zd([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(i.length===0)return[];let o=await Zd(i);return i.flatMap(s=>{let a=o[s]?.values?.[t]?.value;return a?[a]:[]})}async function Nw(){let n=[lo.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 Qd(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 Qd(e,()=>!0,""))}catch{}return n}async function tu(){let n=uo.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"?xw():await Nw(),t=kw(e).flatMap(r=>{let i=jr(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)=>Hr(i.version,r.version)>0?i:r)}import*as nu from"fs";import*as Ee from"path";function $r(n,e){let t=Ee.relative(e,n);return t===""||!Ee.isAbsolute(t)&&!t.startsWith(`..${Ee.sep}`)&&t!==".."}function lt(n){let e=Ee.resolve(n),t=[],r=e;for(;;)try{let i=nu.realpathSync(r);return t.length===0?i:Ee.join(i,...t.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=Ee.dirname(r);if(o===r)return e;t.push(Ee.basename(r)),r=o}}function po(n,e){let t=lt(e),r=lt(n);return $r(r,t)?r:null}function fo(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function mo(n){let e=fo(n);if(!e)throw new Error("Path must not be empty.");return lt(e)}var Ur={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},ho={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 ve={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"},Ke={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"},gn={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},Br={baseUrl:Ke.LOGIN_URL,authUrl:Ke.AUTH_APPLY_PATH,tempTokenCheckUrl:Ke.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:Ke.JWT_TOKEN_CHECK_PATH,successRedirectUrl:Ke.LOGIN_SUCCESS_PATH,failedRedirectUrl:Ke.LOGIN_FAILED_PATH,logoutUrl:Ke.LOGOUT_PATH,agcTeamListUrl:Ke.AGC_TEAM_LIST_URL,appId:ve.APP_ID,timeout:Ur.LOGIN_TIMEOUT_MS,countryCode:"CN"};import{homedir as _t}from"os";import yt from"path";import{xdgConfig as Lw}from"xdg-basedir";var se={"trae-cn":yt.join(_t(),".trae-cn"),opencode:yt.join(Lw,"opencode"),cursor:yt.join(_t(),".cursor"),codebuddy:yt.join(_t(),".codebuddy"),qoder:yt.join(_t(),".qoder"),"claude-code":yt.join(_t(),".claude"),codex:yt.join(_t(),".codex"),bitfun:yt.join(_t(),".bitfun"),opendesk:yt.join(_t(),".opendesk")};import Ft from"path";import*as ru from"os";function b(){return qa()==="openharmony"}function qa(){return ru.platform()}var Ya="https://matrix.openharmony.cn",Xe={TAGS_API_URL:`${Ya}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${Ya}/api/registry/skill/skills`,SKILL_API_BASE:`${Ya}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},iu={"trae-cn":{path:Ft.join(se["trae-cn"],"skills"),displayName:"trae-cn"},opencode:{path:Ft.join(se.opencode,"skills"),displayName:"opencode"},cursor:{path:Ft.join(se.cursor,"skills"),displayName:"cursor"},codebuddy:{path:Ft.join(se.codebuddy,"skills"),displayName:"codebuddy"},qoder:{path:Ft.join(se.qoder,"skills"),displayName:"qoder"},"claude-code":{path:Ft.join(se["claude-code"],"skills"),projectPath:".claude/skills",displayName:"claude-code"},codex:{path:Ft.join(se.codex,"skills"),displayName:"codex"}},ou={opencode:{path:Ft.join(se.opencode,"skills"),displayName:"opencode"}};function wt(){return b()?ou:iu}import{homedir as Wr}from"os";import xe from"path";var dt="deveco-mcp";var jt={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:xe.join(se.opencode,"opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:xe.join(process.platform==="win32"?xe.join(process.env.APPDATA??xe.join(Wr(),"AppData","Roaming"),"Trae CN","User"):xe.join(Wr(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:xe.join(se.cursor,"mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:xe.join(se.codebuddy,"mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:xe.join(process.platform==="win32"?xe.join(process.env.APPDATA??xe.join(Wr(),"AppData","Roaming"),"Qoder","SharedClientCache"):xe.join(Wr(),"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:xe.join(Wr(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:xe.join(se.codex,"config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function au(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function su(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function cu(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function go(n,e){return n.format==="opencode"?au(e):n.format==="claude-code"||n.format==="codex"?su(e):cu(e)}var Ze={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var Ja="https://developer.huawei.com/consumer/cn/download/";var Ow=/^#\s*Version:\s*(\S+)/,Mw="26.0.0.810",_w=["sdk","default","openharmony","native","llvm","bin","clangd"];function Fw(n){try{let e=JSON.parse(B.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch{return}}function jw(n){let e=v.join(n,"default","openharmony");return[v.join(n,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>v.join(e,t,"oh-uni-package.json"))]}var A=class n{constructor(e,t,r,i,o,s,a,c,l,d,h="",w=""){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;this._clangdPath=h;this._lspServerPath=w}_sourceType;_toolchainRoot;_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;_clangdPath;_lspServerPath;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}get clangdPath(){return this.verify(this._clangdPath)}get lspServerPath(){return this.verify(this._lspServerPath)}verify(e){return e&&(n.verifiedPaths.has(e)||(n.verifySignature(e),n.verifiedPaths.add(e)),e)}assertJava(){if(!b()){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 Hr(e,t)}static async checkVersion(){if(b())return;let e=await n.resolveInstallSource();(e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)).assertVersion()}static async new(){if(b())return n.fromOpenHarmony();let e=await n.resolveInstallSource();return e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)}static fromCLT(e){let t=n.buildToolPaths(e,"clt");return n.assertBuiltPathsInsideRoot(e,t,!1),new n("clt",e,void 0,t.nodePath,t.ohpmJsPath,t.hvigorJsPath,n.resolveCltJava(!1),t.sdkPath,t.hdcPath,t.emulatorPath)}static fromIDE(e,t="studio"){let r=n.buildToolPaths(e,"studio");return n.assertBuiltPathsInsideRoot(e,r,!0),new n(t,e,e,r.nodePath,r.ohpmJsPath,r.hvigorJsPath,r.javaPath,r.sdkPath,r.hdcPath,r.emulatorPath,n.resolveClangdPath(e),n.resolveLspServerPath(e))}static fromOpenHarmony(){let e=process.env.COMMAND_LINE_TOOL_PATH;if(!e)throw new Error("COMMAND_LINE_TOOL_PATH environment variable is not set.");let t=n.buildOpenHarmonyToolPaths(e);n.assertBuiltPathsInsideRoot(e,t,!1);let r=v.join(e,"clangd","clangd"),i=v.join(e,"ace-server","out","index.js");return new n("clt",e,void 0,t.nodePath,t.ohpmJsPath,t.hvigorJsPath,"",t.sdkPath,t.hdcPath,t.emulatorPath,r,i)}static buildOpenHarmonyToolPaths(e){let t=v.join(e,"sdk");return{nodePath:v.join(e,"node","bin","node"),ohpmJsPath:v.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:v.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:t,hdcPath:v.join(t,"default","openharmony","toolchains","hdc"),emulatorPath:""}}static devecoContentRootForClangd(e){return fe.platform()==="darwin"&&e.endsWith(".app")?v.join(e,"Contents"):e}static clangdCandidatesFromDevecoHome(e){let t=new Set,r=[e,n.devecoContentRootForClangd(e)];for(let i of r){let o=v.join(i,..._w);t.add(fe.platform()==="win32"?o+".exe":o)}return[...t]}static resolveClangdPath(e){let t=n.clangdCandidatesFromDevecoHome(e);for(let r of t)if(B.existsSync(r))return r;return""}static resolveLspServerPath(e){let t=fe.platform(),r;if(t==="win32")r=v.join(e,"plugins","openharmony");else if(t==="darwin")r=v.join(e,"Contents","plugins","openharmony");else return"";let i=v.join(r,"ace-server","out","index.js");return B.existsSync(i)?i:""}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(jr(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(Hr(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
|
+
${Ja}`)}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=lt(e),s=lt(i);return n.assertInsideRoot(s,o,"codelinter"),s}static getCodelinterCandidates(e,t){if(t==="studio"){let r=fe.platform()==="darwin"?["Contents"]:[];return[v.join(e,...r,"plugins","codelinter","run","index.js"),v.join(e,...r,"plugins","codelinter","index.js"),v.join(e,...r,"tools","codelinter","bin","codelinter.js"),v.join(e,...r,"tools","codelinter","codelinter.js")]}return[v.join(e,"codelinter","index.js"),v.join(e,"codelinter","run","index.js"),v.join(e,"tool","codelinter","bin","codelinter.js"),v.join(e,"tool","codelinter","codelinter.js")]}static isValidRoot(e,t){if(!n.isDirectory(e))return!1;if(t==="clt")return B.existsSync(v.join(e,"version.txt"));let r=fe.platform()==="darwin"?v.join(e,"Contents"):e,i=fe.platform()==="darwin"?v.join(r,"Info.plist"):v.join(r,"product-info.json");if(!B.existsSync(i))return!1;let o=n.buildToolPaths(e,"studio");return[o.nodePath,o.ohpmJsPath,o.hvigorJsPath].every(B.existsSync)}static buildToolPaths(e,t){return t==="clt"?n.buildCltToolPaths(e):n.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=v.join(e,"sdk"),r=fe.platform()==="win32",i=r?".exe":"";return{nodePath:r?v.join(e,"tool","node","node.exe"):v.join(e,"tool","node","bin","node"),ohpmJsPath:v.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:v.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:t,hdcPath:v.join(t,"default","openharmony","toolchains",`hdc${i}`),emulatorPath:v.join(e,"emulator",r?"Emulator.exe":"Emulator")}}static buildStudioToolPaths(e){let t=fe.platform()==="darwin",r=fe.platform()==="win32",i=t?v.join(e,"Contents"):e,o=v.join(i,"tools"),s=v.join(i,"sdk"),a=r?".exe":"";return{nodePath:r?v.join(o,"node","node.exe"):v.join(o,"node","bin","node"),ohpmJsPath:v.join(o,"ohpm","bin","pm-cli.js"),hvigorJsPath:v.join(o,"hvigor","bin","hvigorw.js"),javaPath:r?v.join(e,"jbr","bin","java.exe"):t?v.join(i,"jbr","Contents","Home","bin","java"):v.join(i,"jbr","bin","java"),sdkPath:s,hdcPath:v.join(s,"default","openharmony","toolchains",`hdc${a}`),emulatorPath:v.join(o,"emulator",r?"Emulator.exe":"Emulator")}}static isFile(e){try{return B.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return B.existsSync(e)&&B.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 tu();return m(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,r){let i;try{i=mo(e)}catch(o){throw new Error(`Invalid ${r}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}return t==="studio"&&fe.platform()==="darwin"&&(i=n.normalizeMacStudioRoot(i)),n.isValidRoot(i,t)?i:n.throwInvalidSource(i,t,r,e)}static assertBuiltPathsInsideRoot(e,t,r){let i=lt(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)a&&n.assertInsideRoot(a,i,s)}static assertInsideRoot(e,t,r){if(po(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=`${v.sep}Contents`,r=v.normalize(e);return r.endsWith(t)?r.slice(0,-t.length):r}static readCltVersion(e){try{return B.readFileSync(v.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(Ow)?.[1]?.trim()).find(Boolean)}catch{return}}static resolveCltJava(e){let t=process.env.JAVA_HOME?.trim(),r=t&&(n.javaIn(v.join(t,"bin"))??n.javaIn(t)),i=(process.env.Path??process.env.PATH??"").split(v.delimiter).map(s=>n.javaIn(s.trim())).find(Boolean),o=r??i;if(o)return B.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(fe.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(r=>v.join(e,r)).find(B.existsSync)}getMaxApiLevel(){for(let e of jw(this.sdkPath)){let t=Fw(e);if(t!==void 0)return t}return 23}detectApiLevel(){return this.getMaxApiLevel()}_apiscanPaths;getApiscanPaths(){if(this._apiscanPaths)return this._apiscanPaths;let e=fe.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=v.join(this._devecoStudioPath,t,"plugins","harmony","arkanalyzer-apiscan"),i=v.join(r,"resources","apiChange"),o=v.join(r,"api-change-scan.js");if(!B.existsSync(i)||!B.existsSync(o)){let s=jr(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${Mw}. Upgrade before using 'check compat' at ${Ja}`)}return this._apiscanPaths={apiChangeDir:i,scriptPath:o},this._apiscanPaths}static verifySignature(e){if(!B.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=fe.platform();if(t==="linux"){n.assertExecutable(e);return}if(t==="win32"&&v.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(!B.statSync(e).isFile())throw new Error;B.accessSync(e,B.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=v.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return n.powerShellPath=B.existsSync(e)?e:"",n.powerShellPath&&(n.powerShellModulesPath=v.join(v.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=B.mkdtempSync(v.join(fe.tmpdir(),"deveco-verify-")),i=v.join(r,"Verify-Signature.ps1");B.writeFileSync(i,"Get-AuthenticodeSignature -FilePath $args[0] | ConvertTo-Json -Depth 3 -Compress","utf8");try{let o=lu(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{B.rmSync(r,{recursive:!0,force:!0})}}static verifyMacSignature(e){try{return lu("codesign",["-v",e],{encoding:"utf8",timeout:5e3,stdio:["ignore","ignore","ignore"]}),{signed:!0}}catch{return{signed:!1}}}};import{execa as Hw}from"execa";import*as yn from"path";import*as du from"os";var Qe=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let i={...process.env,DEVECO_SDK_HOME:e.sdkPath};if(e.javaPath){let o=yn.dirname(e.javaPath);i.PATH=`${o}${yn.delimiter}${process.env.PATH||""}`,e.sourceType==="clt"&&(i.JAVA_HOME=yn.dirname(o))}b()&&(i.HVIGOR_USER_HOME=yn.join(du.homedir(),".hvigor")),this.env=i}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(){b()||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){b()&&(e=e.includes("--no-daemon")?e:["--no-daemon",...e]);let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];m(`Executing: ${t} ${r.join(" ")}`);let i=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit";await Hw(t,r,{cwd:this.projectRoot,env:this.env,stdout:i,stderr:i})}};import{execa as $w}from"execa";var Ht=class{toolProvider;projectRoot;constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=["--no-deprecation",this.toolProvider.ohpmJsPath,"install","--all"];m(`Executing: ${e} ${t.join(" ")}`),await $w(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"})}};import{mkdir as Uw}from"fs/promises";import{dirname as Bw,resolve as Ww}from"path";import{execa as zw}from"execa";import{lock as Ka,check as SO}from"proper-lockfile";function Xa(n){return Ww(n,".hvigor",".build-lock")}function Gw(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function uu(n){let e=Bw(Xa(n));if(await Uw(e,{recursive:!0}),process.platform==="win32")try{await zw("attrib",["+h",e])}catch{}}async function Vw(n,e){let t=new AbortController,r=Gw(e);await uu(n);let i={lockfilePath:Xa(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await Ka(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 Ka(n,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function vt(n,e,t){let{release:r,signal:i}=await Vw(n,t);try{return await e(i)}finally{await r()}}async function yo(n,e){let t=new AbortController;await uu(n);let r={lockfilePath:Xa(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await Ka(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 $t from"fs";import*as wn from"path";import qw from"json5";var Yw=1e3;function vo(n){m(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=wn.join(n,Ze.SYNC_OUTPUT_PATH);if(!$t.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return m(`[ProjectCheck] ${l.reason}`),l}let t=$t.statSync(e).mtimeMs;m(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Jw(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return m(`[ProjectCheck] ${l.reason}`),l}let i=wn.join(n,Ze.OH_PACKAGE_JSON5),o=wo(i,t,"root");if(o.required)return m(`[ProjectCheck] Root check: ${o.reason}`),o;let s=wn.join(n,Ze.BUILD_PROFILE_JSON5),a=wo(s,t,"build-profile");if(a.required)return m(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let d=wn.join(n,l.srcPath,Ze.OH_PACKAGE_JSON5),h=wo(d,t,l.name);if(h.required)return m(`[ProjectCheck] Module '${l.name}' check: ${h.reason}`),h;let w=wn.join(n,l.srcPath,Ze.BUILD_PROFILE_JSON5),S=wo(w,t,l.name);if(S.required)return m(`[ProjectCheck] Module '${l.name}' build-profile check: ${S.reason}`),S}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return m(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function wo(n,e,t){if(!$t.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=$t.statSync(n).mtimeMs;return r-e>Yw?{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 Jw(n){let e=wn.join(n,Ze.BUILD_PROFILE_JSON5);try{let t=$t.readFileSync(e,"utf-8");if(!t.trim())return null;let r=qw.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 Le from"fs";import*as Bt from"path";import*as Su from"util";import*as M from"fs";import*as Io from"path";import X from"fs";import*as So from"os";import*as W from"path";import Kw from"json5";var pu=3;function bo(n){if(!X.existsSync(n)||!X.statSync(n).isDirectory())return!1;let e=X.existsSync(W.join(n,"build-profile.json5")),t=X.existsSync(W.join(n,"hvigorfile.js"))||X.existsSync(W.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=X.readFileSync(W.join(n,"build-profile.json5"),"utf-8");return Kw.parse(r).app!==void 0}catch{return!1}}function Za(n,e,t){if(e>=t)return null;let r=Xw(n),i=Zw(r);if(i)return i;for(let o of r){let s=Za(o,e+1,t);if(s)return s}return null}function Xw(n){try{let e=X.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(W.join(n,r.name));return t}catch{return[]}}function Zw(n){for(let e of n)if(bo(e))return e;return null}function St(n){if(!n||n.trim()==="")return null;let e=W.resolve(n),t;try{t=X.realpathSync(e)}catch{t=e}if(!X.existsSync(t))return null;if(bo(t))return t;let r=t;for(let i=1;i<=3;i++){let o=W.dirname(r);if(o===r)break;if(bo(o))return o;r=o}if(X.statSync(t).isDirectory()){let i=Za(t,0,pu);if(i)return i}return null}function Eo(n){if(!n||n.trim()==="")return null;let e=W.resolve(n),t;try{t=X.realpathSync(e)}catch{t=e}return!X.existsSync(t)||!X.statSync(t).isDirectory()?null:bo(t)?t:Za(t,0,pu)}var Qa=[b()?".bitfun":".idea",".deveco",b()?".cxx":"cxx","compile_commands.json"];function vn(n){return W.join(n,...Qa)}function fu(n){return new Promise(e=>setTimeout(e,n))}var Qw=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function Sn(n){let e=W.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&Qw.has(e)}function Po(n){return W.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function ae(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function ev(n){return ae(n)}function bn(n){let e=ev(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function Ut(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??W.join(So.homedir(),"AppData","Local");return W.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?W.join(So.homedir(),"Library","Logs","devecocli-mcp-server"):W.join(So.homedir(),".local","share","devecocli-mcp-server","logs")}function mu(n,e){let t=tv(e),r=nv(t,n);if(r!==null)return r;let i=Date.now(),s=`${n.replace(/:/g,"\\:")}=${i}`,a=rv(t,n,s);return iv(e,a),i}function tv(n){let e;try{e=X.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function nv(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 rv(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 iv(n,e){try{X.mkdirSync(W.dirname(n),{recursive:!0})}catch{}try{X.writeFileSync(n,e.join(`
|
|
9
|
+
`)+`
|
|
10
|
+
`,"utf8")}catch{}}function ec(n,e,t="[Cleanup]"){try{let r=W.dirname(n);if(!X.existsSync(r))return;let i=Date.now();for(let o of X.readdirSync(r,{withFileTypes:!0}))o.isDirectory()&&ov(W.join(r,o.name),i,e,t)}catch{}}function ov(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}`)}}var hu="mcp-server.log",sv="mcp-server",av={maxSize:10*1024*1024,maxFiles:4},tc=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={...av,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Ut(),this.currentLogFile=Io.join(this.logDir,hu),M.existsSync(this.logDir)||M.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 Io.join(this.logDir,`${sv}-${e}.log.${t}`)}fileExists(e){try{return M.accessSync(e,M.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=M.readdirSync(this.logDir),t=[];for(let i of e)if(i===hu||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=Io.join(this.logDir,i),s=M.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{M.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)&&M.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)&&M.renameSync(o,s)}let r=this.getRotatedFileName(e,1);M.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=M.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=M.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{M.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);M.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{M.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},je=null;function En(n=!1){je&&je.dispose(),je=new tc(n)}function gu(){je&&(je.dispose(),je=null)}function yu(){je&&je.flush()}function wu(){return je?.getLogFilePath()??null}function vu(){return je?.getLogDirectory()??null}function Co(){return je||En(!1),je}var g={debug:(n,...e)=>Co().debug(n,...e),info:(n,...e)=>Co().info(n,...e),warn:(n,...e)=>Co().warn(n,...e),error:(n,...e)=>Co().error(n,...e)};var nc="";function Do(n){if(!n||n==="auto"||n==="stdout"||n==="none"){nc="";return}nc=n}function bu(){return nc||(vu()??"")}function Ao(n,...e){if(e.length===0)return n;try{return Su.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] ${Ao(n,...e)}`)},warn(n,...e){g.warn(`[lsp] ${Ao(n,...e)}`)},error(n,...e){g.error(`[lsp] ${Ao(n,...e)}`)},debug(n,...e){g.debug(`[lsp] ${Ao(n,...e)}`)}};import*as zr from"fs";import*as Gr from"os";import*as Wn from"path";import cv 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"},T="2.0";var Eu=8192,rc=100,Pu=.03,Cu=.7,He=900*1e3,To="/data/app/sdk.org/sdk_1.0.0";function Ne(n){if(!zr.existsSync(n))return null;try{let e=zr.readFileSync(n,"utf-8");return e.trim()?cv.parse(e):null}catch{return null}}function Ro(n,e){let t=Math.floor(Gr.totalmem()/1048576),r=Math.floor(t*Cu),i,o;e!==void 0&&Number.isFinite(e)&&e>0?(i=e,o=`override(${e})`):(i=Eu,n>rc&&(i+=(n-rc)*Pu*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 et(n){if(n.startsWith("file:"))return n;try{let e=Wn.resolve(n),t=new URL(`file://${e}`).toString();if(Gr.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 zn(n){return n&&n.replace(/\\/g,"/")}function j(n){let e=Wn.normalize(n).replace(/\\/g,"/");if(Gr.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function Iu(n){return Wn.join(n,"build-profile.json5")}var bt=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=Iu(this.projectRoot);try{let t=Ne(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*as Au from"os";import*as Du from"path";import{spawn as lv}from"child_process";var dv=600*1e3;function uv(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 ko(n){return n.join("")}function pv(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 fv(n,e,t){return new Promise(r=>{let i=lv(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:o,stderr:s}=uv(i),a=setTimeout(()=>{i.kill();let c=[ko(o),ko(s)].filter(Boolean).join(`
|
|
14
|
+
`).trim();r({success:!1,output:`Build process timeout after 10 minutes.
|
|
15
|
+
Output so far:
|
|
16
|
+
`+c,exitCode:-1})},dv);i.on("close",(c,l)=>{clearTimeout(a);let d=[ko(o),ko(s)].filter(Boolean).join(`
|
|
17
|
+
`).trim()||"";r(pv(c,l,d))}),i.on("error",c=>{clearTimeout(a),r({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function ic(n,e,t,r,i){let o={...process.env,DEVECO_SDK_HOME:r};return b()&&(o.HVIGOR_USER_HOME=Du.join(Au.homedir(),".hvigor")),await fv([e,[t,...i]],n,o)}var mv=["--sync","-p","product=default","--analyze=normal","--parallel","--incremental","--no-daemon"];async function Tu(n,e){try{return(await ic(n,e.nodePath,e.hvigorJsPath,e.sdkPath,mv)).success}catch(t){return f.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}function hv(n){let e=Bt.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function gv(n,e){let t=Bt.join(n,e.name);return e.isDirectory()?e.name===".cxx"||Ru(t):hv(t)}function Ru(n){if(!Le.existsSync(n))return!1;try{return Le.readdirSync(n,{withFileTypes:!0}).some(t=>gv(n,t))}catch{}return!1}function Pn(n){let t=new bt(n).getAllModuleInfo(),r=[];for(let i of t){let o=E.resolvePathWithinRoot(n,i.srcPath);Ru(o)&&r.push(i)}return r}function yv(n){let e=[],r=new bt(n).getAllModuleInfo();for(let i of r){let o=E.resolvePathWithinRoot(n,i.srcPath),s=Bt.join(o,".cxx");Le.existsSync(s)&&ku(s,e)}return e}function ku(n,e){try{let t=Le.readdirSync(n,{withFileTypes:!0});for(let r of t){let i=Bt.join(n,r.name);r.isDirectory()?ku(i,e):r.name==="compile_commands.json"&&e.push(i)}}catch{}}function wv(n){let e=[];for(let t of n)try{let r=Le.readFileSync(t,"utf8"),i=JSON.parse(r);e.push(...i)}catch{}return e}function vv(n,e){let t=Bt.join(n,...Qa.slice(0,-1));Le.mkdirSync(t,{recursive:!0});let r=Bt.join(t,"compile_commands.json");Le.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function oc(n){let e=yv(n);if(e.length>0){let t=wv(e);vv(n,t),g.info(`[CppCompile] compile_commands.json generated, ${t.length} compile commands`)}else g.warn("[CppCompile] No compile_commands.json files found")}async function Sv(n,e,t){g.info(`[CppCompile] devecoPath: ${e.devecoStudioPath}, sdkPath: ${e.sdkPath}, nodePath: ${e.nodePath},hvigorJsPath:${e.hvigorJsPath}`);for(let r of t){let i=["--mode","module","-p",`module=${r.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"];g.info(`[CppCompile] Running compileNative for module: ${r.name}`);let o=await ic(n,e.nodePath,e.hvigorJsPath,e.sdkPath,i);o.success?g.info(`[CppCompile] compileNative ${r.name} succeeded`):g.warn(`[CppCompile] compileNative ${r.name} failed: ${o.output}`)}}async function xu(n,e){let t=Pn(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 Sv(n,e,t),oc(n)}function Ev(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 Pv(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 qr(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 Vr(n,e){let t=e,r=`${n} failed`;console.error(ac(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 Yr(n,e,t,r,i,o){let s=vo(o);console.log(`
|
|
18
|
+
[ohpm install] Running...`);try{await n.installAll()}catch(a){Vr("ohpm install",a)}if(s.required){console.log(`
|
|
19
|
+
[hvigor sync] Running...`);try{await e.sync(t,r)}catch(a){Vr("hvigor sync",a)}}else console.log(`
|
|
17
20
|
[hvigor sync] Skipped (configurations unchanged)`);console.log(`
|
|
18
|
-
[hvigor build] Running...`);try{
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
21
|
+
[hvigor build] Running...`);try{i.type==="product"?await e.buildProduct(t,r):await e.buildModules(t,r,i.modulesToBuild,i.moduleTasks)}catch(a){Vr("hvigor build",a)}Cv(o)}function Cv(n){try{if(Pn(n).length===0)return;oc(n),console.log(sc(`
|
|
22
|
+
Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(cc(`
|
|
23
|
+
Failed to merge compile_commands.json: ${e.message}`))}}var Nu=new bv("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(cc("Ensure the project source is trustworthy before proceeding."));let r=await A.new();r.assertJava(),Ev(t,n);let i=n.product||"default",o=n.buildMode||"debug",s;if(n.product&&!n.modules)s={type:"product"};else{let l=Pv(t,n),d=qr(t,l);s={type:"modules",modulesToBuild:l,moduleTasks:d}}let a=new Ht(r,t.rootDir),c=new Qe(r,t.rootDir);await vt(t.rootDir,async()=>Yr(a,c,i,o,s,t.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")}),console.log(`
|
|
24
|
+
`+sc("Build completed successfully"))}catch(e){console.error(ac(e.message)),process.exit(1)}});Nu.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{try{let n=process.cwd(),e=U.discover(n);console.warn(cc("Ensure the project source is trusted before proceeding."));let t=await A.new();t.assertJava();let r=new Qe(t,e.rootDir);await vt(e.rootDir,async()=>{console.log(`
|
|
25
|
+
[1/2] Running hvigor clean...`);try{await r.clean()}catch(i){Vr("hvigor clean",i)}console.log(`
|
|
26
|
+
[2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(i){Vr("hvigor --stop-daemon",i)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
|
|
27
|
+
`+sc("Clean completed successfully."))}catch(n){console.error(ac(n.message)),process.exit(1)}});var Lu=Nu;import{Command as hS}from"commander";import{green as Ku,red as gS,yellow as $o}from"colorette";import*as Uo from"path";import{randomUUID as Fv}from"crypto";import{execa as jv}from"execa";import{execa as _v}from"execa";import{execFile as Iv,spawn as Av}from"child_process";import{promisify as Dv}from"util";var Tv=Dv(Iv);function Ou(n,e,t){let i=n.replace(/\r\n/g,`
|
|
23
28
|
`).split(`
|
|
24
|
-
`),i
|
|
25
|
-
`)){let
|
|
26
|
-
`+
|
|
27
|
-
`)):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
|
|
28
|
-
`).map(t=>t.trim()).filter(t=>t.length>0&&t!=="[Empty]")}async isDevEcoStudioRunningViaHdc(e){return(await this.runHdc(["-t",e,"shell","ps -ef | grep com.huawei.devecostudio | grep -v grep"],!1)).trim().length>0}async launchPreview(e,t,r,o,i,s,a,c,l){let h=JSON.stringify({bundleName:t,abilityName:r,moduleName:s,productName:o,productType:i,subProductType:a,instanceId:c,launchDeviceIndex:l,launchFlag:"{}",isCustom:!1,nativeDebuggable:!1,appDebuggable:!1}).replace(/'/g,"'\\''"),v=`aa start -a DevEcoViewerAbility -b com.huawei.devecostudio -m DevEcoViewer --pi instanceId ${c} --ps paramJson '${h}'`;return await this.runHdc(["-t",e,"shell",v])}};import{execa as Ho}from"execa";import*as qs from"readline/promises";import{stdin as np,stdout as rp}from"process";import{green as ht,red as qn,yellow as jo}from"colorette";import zn from"fs";import*as Kt from"path";import op from"json5";var Zu=[{productIndex:0,productName:"Pura 90 Pro",productType:"phone",subProductType:"phone"},{productIndex:1,productName:"MatePad 11.5'S",productType:"tablet",subProductType:"tablet"},{productIndex:2,productName:"Mate X7",productType:"phone",subProductType:"foldable"},{productIndex:3,productName:"Pura X",productType:"phone",subProductType:"widefold"},{productIndex:4,productName:"Mate XT",productType:"phone",subProductType:"triplefold"}],Jt={productIndex:0,productName:"phone",productType:"phone",subProductType:"phone"};async function Xu(){return[]}async function Lo(){let n=await Xu();return n.length>0?n:Zu}function Un(n){return n.toLowerCase().replace(/[\s\W]+/g,"")}var Qu={phone:"Pura 90 Pro",tablet:"MatePad 11.5'S",pad:"MatePad 11.5'S",fold:"Mate X7",foldable:"Mate X7",widefold:"Pura X",wide:"Pura X",triplefold:"Mate XT",triple:"Mate XT",pura90:"Pura 90 Pro",pura90pro:"Pura 90 Pro",matepad:"MatePad 11.5'S",matex7:"Mate X7",purax:"Pura X",matext:"Mate XT"};function ep(n,e){let t=n.length,r=e.length;if(t===0)return r;if(r===0)return t;let o=new Array(r+1),i=new Array(r+1);for(let s=0;s<=r;s++)o[s]=s;for(let s=1;s<=t;s++){i[0]=s;for(let a=1;a<=r;a++){let c=n[s-1]===e[a-1]?0:1;i[a]=Math.min(o[a]+1,i[a-1]+1,o[a-1]+c)}for(let a=0;a<=r;a++)o[a]=i[a]}return o[r]}function tp(n,e){let t=n.map(i=>({spec:i,dist:ep(e,Un(i.productName))})),r=t.reduce((i,s)=>Math.min(i,s.dist),1/0);if(r>2)return;let o=t.filter(i=>i.dist===r);return o.length===1?{spec:o[0].spec,matchedName:o[0].spec.productName,fuzzy:!0,matchType:"fuzzy"}:{matchType:"none",ambiguous:o.map(i=>i.spec.productName)}}function _o(n,e){let t=Un(e);if(t.length===0)return{matchType:"none"};let r=n.find(a=>Un(a.productName)===t);if(r)return{spec:r,matchedName:r.productName,matchType:"exact"};let o=Qu[t];if(o){let a=n.find(c=>c.productName===o);if(a)return{spec:a,matchedName:a.productName,matchType:"alias"}}let i=n.filter(a=>{let c=Un(a.productName);return c.includes(t)||t.includes(c)});if(i.length===1)return{spec:i[0],matchedName:i[0].productName,matchType:"substring"};if(i.length>1)return{matchType:"none",ambiguous:i.map(a=>a.productName)};let s=tp(n,t);return s||{matchType:"none"}}async function ip(n){for(let e of n){let{stdout:t}=await Ho("tasklist",["/FI",`IMAGENAME eq ${e}`,"/FO","CSV","/NH"],{reject:!1});if(t.toLowerCase().includes(e.toLowerCase()))return!0}return!1}async function sp(){try{let n=Io();if(n==="win32")return ip(["devecostudio64.exe","devecostudio.exe"]);if(n==="darwin"){let{stdout:e}=await Ho("pgrep",["-x","DevEco Studio"],{reject:!1});return e.trim().length>0}if(n==="openharmony"||n==="linux"){let{stdout:e}=await Ho("pgrep",["-f","com.huawei.devecostudio"],{reject:!1});return e.trim().length>0}}catch{}return!1}async function ap(n,e){if(!I()){if(await sp()){console.log("DevEco Studio is already running.");return}throw new Error(`DevEco Studio is not running. The previewer requires DevEco Studio to be running.
|
|
29
|
+
`),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 Mu(n,e,t){let r=n.endsWith("\r")?n.slice(0,-1):n;r.length>0&&t.onData([r],e)}function Rv(n,e){return{stdout:n.stdoutChunks.join(""),stderr:n.stderrChunks.join(""),exitCode:e??-1}}function kv(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function xv(n,e,t,r,i){n.stdout?.on("data",o=>{let s=o.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=Ou(e.stdoutLineBuffer+s,"stdout",t)}),n.stderr?.on("data",o=>{let s=o.toString();e.stderrChunks.push(s),e.stderrLineBuffer=Ou(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,Mu(e.stdoutLineBuffer,"stdout",t),Mu(e.stderrLineBuffer,"stderr",t),t.onClose(o);let s=Rv(e,o);r(s)})}async function Jr(n,e=[],t={}){try{let{stdout:r,stderr:i}=await Tv(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 _u(n,e,t){return await new Promise((r,i)=>{let o=Av(n,e,{stdio:["inherit","pipe","pipe"]}),s=kv();xv(o,s,t,r,i)})}function Fu(n){let e=n.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var Nv=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],Lv=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function Gn(n){return n?Nv.some(e=>e.test(n))?"transient":Lv.some(e=>e.test(n))?"fatal":"ok":"ok"}var lc=[800,1500,2500];function Ov(n){return new Promise(e=>setTimeout(e,n))}async function Oe(n,e){let t=1+lc.length,r={stdout:"",stderr:"",exitCode:-1};for(let i=0;i<t;i++){if(r=await Jr(n,e),r.exitCode===0||Gn(r.stderr)!=="transient"||i>=t-1)return r;m(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${lc[i]}ms`),await Ov(lc[i])}return r}var ju=/^[\w.-]+$/;async function xo(n,e,t){if(!ju.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 Oe(n,r);if(i.exitCode!==0)return;let o=i.stdout.trim();if(!(!o||Gn(o)!=="ok"))return Fu(o)}var dc="__DEVECO_PARAM_DELIM__";function Mv(n,e){let t=new Map,r=n.split(dc);for(let i=0;i<e.length;i++){let o=(r[i]??"").trim();if(!o||Gn(o)!=="ok")continue;let s=Fu(o);s&&t.set(e[i],s)}return t}async function Vn(n,e,t){let r=t.filter(a=>ju.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 xo(n,e,r[0]);return c&&a.set(r[0],c),a}let i=r.map(a=>`param get ${a}`).join(`; echo ${dc}; `)+`; echo ${dc}`,o=await Oe(n,["-t",e,"shell",i]);if(o.exitCode===0){let a=Mv(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 xo(n,e,a);c&&s.set(a,c)}return s}function Cn(n){return n.startsWith("127.0.0.1:")}var Hu=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],Z=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(" ")}`),_v(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 Vn(this.hdcPath,e,[...Hu]);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:
|
|
31
|
+
`+o.map(s=>` - ${s.name} (${s.device.serial})`).join(`
|
|
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 Vn(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=b()?!1:Cn(e),r,i;try{let o=await Vn(this.hdcPath,e,[...Hu]);r=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:i}}};var In=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=Z.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;m(`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||""}}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/${Fv()}`;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 connectTarget(e){await this.runHdc(["tconn",e])}async disconnectTarget(e){await this.runHdc(["tconn",e,"-remove"],!1)}async listRawTargets(){return(await this.runHdc(["list","targets"],!1)).split(`
|
|
33
|
+
`).map(t=>t.trim()).filter(t=>t.length>0&&t!=="[Empty]")}async isDevEcoStudioRunningViaHdc(e){return(await this.runHdc(["-t",e,"shell","ps -ef | grep com.huawei.devecostudio | grep -v grep"],!1)).trim().length>0}async launchPreview(e,t,r,i,o,s,a,c,l){let h=JSON.stringify({bundleName:t,abilityName:r,moduleName:s,productName:i,productType:o,subProductType:a,instanceId:c,launchDeviceIndex:l,launchFlag:"{}",isCustom:!1,nativeDebuggable:!1,appDebuggable:!1}).replace(/'/g,"'\\''"),w=`aa start -a DevEcoViewerAbility -b com.huawei.devecostudio -m DevEcoViewer --pi instanceId ${c} --ps paramJson '${h}'`;return await this.runHdc(["-t",e,"shell",w])}async forceStopApp(e,t){let r=["-t",e,"shell","aa","force-stop",t];return await this.runHdc(r,!1)}};import uc from"fs";import*as pc from"path";function $u(n,e){if(!uc.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=uc.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=pc.resolve(e),o=new Set,s=[];for(let a of r){let c=pc.resolve(i,a),l=E.isPathContainedWithSymlink(a,i);if(!l.contained){if(E.isPathContained(a,i).contained&&!uc.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 fc from"fs";import Kr from"path";import{execa as Uv}from"execa";import Uu from"fs";import*as Bu from"path";import Hv from"json5";function $v(n,e){try{let r=Hv.parse(Uu.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 No(n,e){let t=Bu.join(n,"build-profile.json5");return Uu.existsSync(t)?$v(t,e)??e:e}async function Wu(n,e,t,r){let i=Kr.dirname(n.javaPath),o={...process.env,PATH:`${i}${Kr.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 Uv(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=>Wv(e,l,r))}function zu(n,e,t){let r=No(n,e);return Kr.join(n,r,"build",t,"outputs")}function Bv(n,e,t){return Kr.join(zu(n,e,t),`${e}-${t}-signed.hqf`)}function Wv(n,e,t){let r=zu(n,e,t),i=Bv(n,e,t);if(fc.existsSync(i))return i;let o=mc(r,"-signed.hqf")??mc(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 mc(n,e){if(!fc.existsSync(n))return null;for(let t of fc.readdirSync(n,{withFileTypes:!0})){let r=Kr.join(n,t.name);if(t.isDirectory()){let i=mc(r,e);if(i)return i}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import z from"fs";import*as x from"path";import hc from"json5";var Gu="default",Lo=class n{static writeChangedFileLists(e,t,r,i){let o=t||Gu,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||Gu,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(z.existsSync(s)||(z.mkdirSync(o,{recursive:!0}),z.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");z.existsSync(c)||(z.mkdirSync(a,{recursive:!0}),z.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=x.join(e,"build-profile.json5");if(!z.existsSync(t))return null;try{let r=z.readFileSync(t,"utf-8");return hc.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(!z.existsSync(r))return"entry";try{let i=z.readFileSync(r,"utf-8");return hc.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(!z.existsSync(r))return[];try{let i=z.readFileSync(r,"utf-8"),o=hc.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);z.existsSync(l)||z.mkdirSync(l,{recursive:!0}),z.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),m(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!z.existsSync(e))return[];try{let t=z.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,r,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(Je=>n.resolveRelativePathForPatch(Je,d)),w=n.mergeStrings(l.modifiedFiles,h),S=n.mergePatchResources(l.rawFile,o),k=n.mergePatchResources(l.resFile,s),we=x.dirname(c);z.existsSync(we)||z.mkdirSync(we,{recursive:!0}),z.writeFileSync(c,JSON.stringify({resources:{resFile:k,rawFile:S},modifiedFiles:w}),"utf-8"),m(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!z.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=z.readFileSync(e,"utf-8"),r=JSON.parse(t);return{modifiedFiles:r?.modifiedFiles||[],rawFile:r?.resources?.rawFile||[],resFile:r?.resources?.resFile||[]}}catch{return{modifiedFiles:[],rawFile:[],resFile:[]}}}static resolveRelativePathForPatch(e,t){return 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 zv from"fs";import{randomUUID as Gv}from"crypto";import{execa as Vv}from"execa";var Oo=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!zv.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}let o=`/data/local/tmp/${Gv()}`,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 Vv(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}};var qv="6.1.1",Mo=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}toolProvider;projectRoot;async execute(e){await vt(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(qv);let t=$u(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=Lo.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 Wu(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 Oo(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 In(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 Vu from"fs";import*as F from"path";var _o=class n{static generate(e,t,r,i){let o=No(e,t),s=F.join(e,o),a=F.join(s,"build","config"),c=n.buildConfig(e,s,r,i);Vu.mkdirSync(a,{recursive:!0}),Vu.writeFileSync(F.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=F.dirname(i.nodePath)+F.sep,s=F.join(t,"build",r),a=F.join(s,"intermediates"),c=F.join(a,"loader_out",r),l=F.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:F.join(e,"build-profile.json5"),localPropertiesPath:F.join(e,"local.properties"),appResource:F.join(l,"ResourceTable.txt"),cachePath:F.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:F.join(a,"loader",r,"loader.json"),aceModuleJsonPath:F.join(l,"module.json"),aceSoPath:F.join(c,"nativeDependencies.txt"),aceModuleRoot:F.join(t,"src","main","ets"),aceModuleBuild:F.join(c,"ets"),aceProfilePath:F.join(l,"resources","base","profile"),aceSuperVisualPath:F.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:F.join(c,"ets"),changedFileList:F.join(a,"patch","default","changedFileList.json"),patchAbcPath:F.join(a,"patch","default","ets"),removeChangedFileListInSdk:"true"}}}};import{execa as wc}from"execa";import*as qu from"readline/promises";import{stdin as Qv,stdout as eS}from"process";import{green as qn,red as Ho,yellow as vc}from"colorette";import jo from"fs";import*as Zr from"path";import tS from"json5";var Yv=[{productIndex:0,productName:"Pura 90 Pro",productType:"phone",subProductType:"phone"},{productIndex:1,productName:"MatePad 11.5'S",productType:"tablet",subProductType:"tablet"},{productIndex:2,productName:"Mate X7",productType:"phone",subProductType:"foldable"},{productIndex:3,productName:"Pura X",productType:"phone",subProductType:"widefold"},{productIndex:4,productName:"Mate XT",productType:"phone",subProductType:"triplefold"}],Xr={productIndex:0,productName:"phone",productType:"phone",subProductType:"phone"};async function Jv(){return[]}async function gc(){let n=await Jv();return n.length>0?n:Yv}function Fo(n){return n.toLowerCase().replace(/[\s\W]+/g,"")}var Kv={phone:"Pura 90 Pro",tablet:"MatePad 11.5'S",pad:"MatePad 11.5'S",fold:"Mate X7",foldable:"Mate X7",widefold:"Pura X",wide:"Pura X",triplefold:"Mate XT",triple:"Mate XT",pura90:"Pura 90 Pro",pura90pro:"Pura 90 Pro",matepad:"MatePad 11.5'S",matex7:"Mate X7",purax:"Pura X",matext:"Mate XT"};function Xv(n,e){let t=n.length,r=e.length;if(t===0)return r;if(r===0)return t;let i=new Array(r+1),o=new Array(r+1);for(let s=0;s<=r;s++)i[s]=s;for(let s=1;s<=t;s++){o[0]=s;for(let a=1;a<=r;a++){let c=n[s-1]===e[a-1]?0:1;o[a]=Math.min(i[a]+1,o[a-1]+1,i[a-1]+c)}for(let a=0;a<=r;a++)i[a]=o[a]}return i[r]}function Zv(n,e){let t=n.map(o=>({spec:o,dist:Xv(e,Fo(o.productName))})),r=t.reduce((o,s)=>Math.min(o,s.dist),1/0);if(r>2)return;let i=t.filter(o=>o.dist===r);return i.length===1?{spec:i[0].spec,matchedName:i[0].spec.productName,fuzzy:!0,matchType:"fuzzy"}:{matchType:"none",ambiguous:i.map(o=>o.spec.productName)}}function yc(n,e){let t=Fo(e);if(t.length===0)return{matchType:"none"};let r=n.find(a=>Fo(a.productName)===t);if(r)return{spec:r,matchedName:r.productName,matchType:"exact"};let i=Kv[t];if(i){let a=n.find(c=>c.productName===i);if(a)return{spec:a,matchedName:a.productName,matchType:"alias"}}let o=n.filter(a=>{let c=Fo(a.productName);return c.includes(t)||t.includes(c)});if(o.length===1)return{spec:o[0],matchedName:o[0].productName,matchType:"substring"};if(o.length>1)return{matchType:"none",ambiguous:o.map(a=>a.productName)};let s=Zv(n,t);return s||{matchType:"none"}}async function nS(n){for(let e of n){let{stdout:t}=await wc("tasklist",["/FI",`IMAGENAME eq ${e}`,"/FO","CSV","/NH"],{reject:!1});if(t.toLowerCase().includes(e.toLowerCase()))return!0}return!1}async function rS(){try{let n=qa();if(n==="win32")return nS(["devecostudio64.exe","devecostudio.exe"]);if(n==="darwin"){let{stdout:e}=await wc("pgrep",["-x","DevEco Studio"],{reject:!1});return e.trim().length>0}if(n==="openharmony"||n==="linux"){let{stdout:e}=await wc("pgrep",["-f","com.huawei.devecostudio"],{reject:!1});return e.trim().length>0}}catch{}return!1}async function iS(n,e){if(!b()){if(await rS()){console.log("DevEco Studio is already running.");return}throw new Error(`DevEco Studio is not running. The previewer requires DevEco Studio to be running.
|
|
29
34
|
Please start DevEco Studio manually, then retry.`)}if(!n||!e)throw new Error("Internal error: hdcAdapter and targetDeviceId are required for IDE detection on HarmonyOS.");if(await n.isDevEcoStudioRunningViaHdc(e)){console.log("DevEco Studio is already running.");return}throw new Error(`DevEco Studio is not running. The previewer requires DevEco Studio to be running.
|
|
30
|
-
Please start DevEco Studio manually, then retry.`)}async function
|
|
35
|
+
Please start DevEco Studio manually, then retry.`)}async function Yu(n){if(!n)return!1;let e=n.split(",").map(i=>i.trim()).filter(i=>i.length>0);if(e.length===0)return!1;let t=await gc(),r=t.length>0?t:[Xr];return e.every(i=>yc(r,i).spec!==void 0)}function oS(n,e){if(!n)return[e[0]||Xr];let t=n.split(",").map(o=>o.trim()).filter(o=>o.length>0);if(t.length===0)return[e[0]||Xr];let r=[],i=[];for(let o of t){let s=yc(e,o);if(s.spec)r.push(s.spec),s.matchType==="fuzzy"?console.warn(vc(` [fuzzy] "${o}" \u2192 ${s.matchedName}`)):(s.matchType==="alias"||s.matchType==="substring")&&console.log(` [${s.matchType}] "${o}" \u2192 ${s.matchedName}`);else{if(s.ambiguous&&s.ambiguous.length>0)throw new Error(`Ambiguous device name "${o}". Candidates:
|
|
31
36
|
`+s.ambiguous.map(a=>` - ${a}`).join(`
|
|
32
37
|
`)+`
|
|
33
|
-
Please specify a more precise name.`);
|
|
34
|
-
Available: ${
|
|
38
|
+
Please specify a more precise name.`);i.push(o)}}if(i.length>0){let o=e.map(s=>s.productName).join(", ");throw new Error(`Device type(s) not found: ${i.join(", ")}
|
|
39
|
+
Available: ${o}`)}return sS(r)}function sS(n){let e=new Set,t=[];for(let r of n)e.has(r.productName)||(e.add(r.productName),t.push(r));return t}async function aS(n){if(!process.stdin.isTTY)return;console.log(""),console.log("No device connected. To connect to this HarmonyOS device:"),console.log(' 1. Open "Settings \u2192 System \u2192 Developer options \u2192 Wireless debugging"'),console.log(" 2. Enable it and note the port number shown"),console.log(" 3. Enter the port below (or set DEVECO_HDC_PORT env var)"),console.log("");let e=qu.createInterface({input:Qv,output:eS});try{let t=await e.question("Wireless debugging port: ");if(t.trim()){let r=`127.0.0.1:${t.trim()}`;return await n.connectTarget(r),console.log(qn(`Connected to local device: ${r}`)),r}}catch{}finally{e.close()}}async function cS(n,e){if(e){let o=e.includes(":")?e:`127.0.0.1:${e}`;return await n.connectTarget(o),console.log(`Connected to local device: ${o}`),o}let t=process.env.DEVECO_HDC_PORT;if(t){let o=`127.0.0.1:${t}`;try{return await n.connectTarget(o),console.log(`Connected to local device via DEVECO_HDC_PORT: ${o}`),o}catch{console.warn(vc(`DEVECO_HDC_PORT=${t} but connect failed, trying other methods...`))}}let r=await n.listRawTargets();if(r.length>0){let o=r[0];return m(`[preview] Found existing target: ${o}`),o}let i=await aS(n);if(i)return i;throw new Error(`Cannot connect to local HarmonyOS device.
|
|
35
40
|
Please either:
|
|
36
41
|
1. Run with --device 127.0.0.1:<port>, or
|
|
37
42
|
2. Set DEVECO_HDC_PORT env var, or
|
|
38
|
-
3. Open wireless debugging in system settings first.`)}async function
|
|
39
|
-
`))}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let
|
|
40
|
-
[multi-preview] Building with multiAppMode (appClone) for multi-instance preview...`);let
|
|
41
|
-
Launching DevEco Studio previewer on ${n}...`),console.log(` bundleName : ${e}`),console.log(` abilityName : ${t}`),console.log(` moduleName : ${r}`),console.log(` instanceId : ${
|
|
42
|
-
[${l+1}/${e.length}] Launching ${
|
|
43
|
-
`+"\u2500".repeat(50));let e=n.filter(r=>r.success).length,t=n.length-e;console.log(`Previewer launch summary: ${
|
|
44
|
-
`))}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let
|
|
43
|
+
3. Open wireless debugging in system settings first.`)}async function lS(n,e){let t=await n.listDevices();if(t.length===0)throw new Error(b()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device.");if(!e&&t.length>1){let i=await n.listDevicesWithName();throw new Error("Multiple devices found. Please specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+i.map(o=>` - ${o.name} (${o.serial})`).join(`
|
|
44
|
+
`))}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 dS(n){if(!jo.existsSync(n))throw new Error(`app.json5 not found at ${n}`);let e=jo.readFileSync(n,"utf8"),t=tS.parse(e);return t.app?.multiAppMode?(console.log("[multi-preview] app.json5 already has multiAppMode, skipping injection."),()=>{}):(t.app||(t.app={}),t.app.multiAppMode={multiAppModeType:"appClone",maxCount:5},jo.writeFileSync(n,JSON.stringify(t,null,2),"utf8"),console.log(`[multi-preview] Injected multiAppMode into ${Zr.basename(n)}`),()=>{jo.writeFileSync(n,e,"utf8"),console.log(`[multi-preview] Restored original ${Zr.basename(n)}`)})}async function uS(n,e,t,r,i,o){let s=Zr.join(e.rootDir,"AppScope","app.json5"),a=dS(s);try{let c=n.product||"default",l=n.buildMode||"debug",d="default",h=i.includes("127.0.0.1")||i.includes("localhost");console.log(`
|
|
45
|
+
[multi-preview] Building with multiAppMode (appClone) for multi-instance preview...`);let w=new Ht(t,e.rootDir),S=new Qe(t,e.rootDir),we=e.collectNonHarDependentModuleList(o).map(Jd=>`${Jd}@${d}`),Je=qr(e,we),ke={type:"modules",modulesToBuild:we,moduleTasks:Je};await vt(e.rootDir,async()=>{await Yr(w,S,c,l,ke,e.rootDir)},()=>console.log("Another build is already running. Waiting...")),console.log(qn("[multi-preview] Build completed."));let ht=e.findArtifactPath(o,d,h,c);console.log(`[multi-preview] Installing multiAppMode hap to ${i}...`),await r.installApp(i,[ht]),console.log(qn("[multi-preview] Installed multiAppMode hap."))}finally{a()}}function pS(n,e,t,r,i,o,s){console.log(`
|
|
46
|
+
Launching DevEco Studio previewer on ${n}...`),console.log(` bundleName : ${e}`),console.log(` abilityName : ${t}`),console.log(` moduleName : ${r}`),console.log(` instanceId : ${i}`),console.log(` mode : ${o?"multi":"single"}`),console.log(` previewers : ${s.map(a=>a.productName).join(", ")}`)}async function fS(n,e,t,r,i,o,s,a){let c=[];for(let l=0;l<e.length;l++){let d=e[l],h=t?l:-1;console.log(`
|
|
47
|
+
[${l+1}/${e.length}] Launching ${d.productName} (${d.productType}/${d.subProductType})...`);try{let w=await n.launchPreview(r,i,o,d.productName,d.productType,s,d.subProductType,a,h),S=/start ability successfully/i.test(w);c.push({name:d.productName,success:S,output:w}),S?console.log(qn(` \u2713 ${d.productName}: ${w.trim()}`)):console.error(Ho(` \u2717 ${d.productName}: ${w.trim()}`))}catch(w){let S=w.message;c.push({name:d.productName,success:!1,output:S}),console.error(Ho(` \u2717 ${d.productName}: ${S}`))}}return c}function mS(n){console.log(`
|
|
48
|
+
`+"\u2500".repeat(50));let e=n.filter(r=>r.success).length,t=n.length-e;console.log(`Previewer launch summary: ${qn(String(e))} succeeded, ${t>0?Ho(String(t)):"0"} failed.`);for(let r of n){let i=r.success?qn("\u2713"):Ho("\u2717");console.log(` ${i} ${r.name}`)}return t===0}async function Ju(n,e,t,r,i,o){let s=await gc(),a=s.length>0?s:[Xr],c=oS(n.device,a),l=c.length>1,d;if(b()){let ke=(await r.listRawTargets()).find(ht=>ht.includes("127.0.0.1:"));ke?(d=ke,console.log(`Using self-connected device: ${d}`)):(console.warn(vc("hdc \u672A\u81EA\u8054\u5230\u672C\u673A\u8BBE\u5907(\u9700\u8981 127.0.0.1:<port>)\u3002\u6B63\u5728\u5C1D\u8BD5\u81EA\u52A8\u8FDE\u63A5...")),d=await cS(r,void 0))}else d=await lS(i,void 0);l&&await uS(n,e,t,r,d,o),await iS(r,d);let h=e.getBundleName(),w=e.getMainAbility(o,n.ability),S=e.getModuleName(o),k=process.pid;pS(d,h,w,S,k,l,c);let we=await fS(r,c,l,d,h,w,S,k);return mS(we)}function yS(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 Xu(n,e){let t=await n.listDevices();if(t.length===0)throw new Error(b()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device.");if(!e&&t.length>1){let 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(`
|
|
49
|
+
`))}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 wS(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>...].
|
|
45
50
|
Available runnable modules:
|
|
46
51
|
`+t.map(r=>` - ${r.name}`).join(`
|
|
47
|
-
`))}function
|
|
48
|
-
Installing artifacts to device ${e}...`),await n.installApp(e,r),
|
|
52
|
+
`))}function vS(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 SS(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(`
|
|
53
|
+
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(Ku(`
|
|
49
54
|
Application '${t}': ${s}`))}else console.log(`
|
|
50
|
-
Application '${t}' installed successfully (no ability to launch).`)}var
|
|
51
|
-
`+
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
`).
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
55
|
+
Application '${t}' installed successfully (no ability to launch).`)}var Sc=new hS("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");b()||Sc.option("--apply <fileName>","Quick-apply changed files via quickfix (incremental hqf) and restart. <fileName> under project .hvigor/");Sc.action(async n=>{try{await CS(n)}catch(e){console.error(gS(e.message)),process.exit(1)}});async function bS(n,e,t,r,i){let o=new Ht(e,n.rootDir),s=new Qe(e,n.rootDir),a=new Set,c=new Set;for(let{moduleName:w,targetName:S}of t)for(let k of n.collectNonHarDependentModuleList(w))a.add(`${k}@${S}`),c.add(k);let l=[...a],d=qr(n,l),h={type:"modules",modulesToBuild:l,moduleTasks:d};for(let w of c)_o.generate(n.rootDir,w,r,e);await vt(n.rootDir,()=>Yr(o,s,r,i,h,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion...")),console.log(`
|
|
56
|
+
`+Ku("Build completed successfully."))}async function ES(n,e,t,r,i){let o=new In(t),s=Z.from(t),a=r[0]?.moduleName||i[0];await Ju(n,e,t,o,s,a)}function PS(n,e){for(let{moduleName:t}of e){let r=n.getModuleType(t);if(r!=="entry"&&r!=="feature"&&r!=="shared")throw new Error(`Module '${t}' '${r}' is not runnable. Specify an entry or feature module.`)}}async function CS(n){let e=U.discover(process.cwd());console.warn($o("Ensure the project source is trusted before proceeding."));let t=await A.new();if(n.skipBuild||t.assertJava(),n.apply){await AS(n,e,t);return}await Zu(n,e,t)}function IS(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 Zu(n,e,t){let r=wS(e,n.module),i=r.map(yS);if(await Yu(n.device)){await ES(n,e,t,i,r);return}PS(e,i);let o=new In(t),s=Z.from(t),a=await Xu(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 bS(e,t,i,l,d);let h=IS(e,i,c,l),w=e.getBundleName(),S=vS(e,i,n.ability);await SS(o,a,w,h,S,!!n.uninstall)}async function AS(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(Uo.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let i=Uo.join(e.rootDir,".hvigor",r),o=Z.from(t),s=await Xu(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 Mo(t,e.rootDir);try{await h.execute({applyFile:i,productName:a,targetDeviceId:s,bundleName:c,abilityName:d}),console.log($o("[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($o(`[Apply] \u5931\u8D25\uFF1A${w.message}`)),console.warn($o("[Apply] \u81EA\u52A8\u56DE\u9000\u5230\u5168\u91CF devecocli run..."))}await Zu(n,e,t)}var Qu=Sc;import{Command as DS}from"commander";import{green as ep,red as tp,cyan as bc}from"colorette";import{execa as np}from"execa";function TS(){return"beta"}function RS(){return"@deveco-test/hmos-deveco-cli"}function kS(){return"0.3.0-TD.1.1"}var xS=new DS("update").description("Update deveco-cli to latest").action(async()=>{let n=RS(),e=kS(),t=TS();console.log(bc("Checking for updates..."));try{let{stdout:r}=await np("npm",["view",n,`dist-tags.${t}`]),i=r.trim();if(!i||i===e){console.log(ep(`
|
|
57
|
+
${n} is already up to date (v${e}, tag: ${t})`));return}console.log(bc(`
|
|
58
|
+
New version found: ${i} (current: ${e})`)),console.log(bc(`Updating ${n}...`)),await np("npm",["install","-g",`${n}@${t}`],{stdio:"inherit"}),console.log(`
|
|
59
|
+
`+ep(`${n} updated successfully to version ${i}.`))}catch(r){let i=r;console.error(tp(`Failed to update ${n}`)),i.message&&console.error(tp(i.message)),process.exit(1)}}),rp=xS;import{Command as ab}from"commander";import{execa as Wo}from"execa";function me(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as NS}from"child_process";var LS=2500;function OS(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 MS(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,LS);n.once("error",d=>c(d.message)),OS(n,l,s,a,c,o)}function ip(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)),MS(s,o,r,i)})}import*as Yn from"path";function _S(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 FS(n){let e=n.instancePath?.trim();if(e)return Yn.dirname(Yn.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?Yn.dirname(Yn.normalize(t)).replace(/\\/g,"/"):""}function jS(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function op(n,e){return e?[...n,"-bootmode",e]:n}function HS(n,e,t){let r=[op(["-start",n],t)],i=FS(e);if(i)for(let o of jS(e.imageRoot))r.push(op(["-hvd",n,"-path",i,...o],t));return _S(r)}async function sp(n,e,t,r){let i=new Error("No start strategy ran"),o=HS(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 Ec(n){return(await Z.withHdcPath(n).listDevices()).map(t=>t.serial).filter(Cn)}async function Pc(n){let e=await Ec(n);return e.length===0?[]:(await Promise.all(e.map(r=>xo(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function ap(n,e){return(await Pc(n)).includes(e)}import*as Kn from"path";import{existsSync as $S,statSync as US}from"fs";function Jn(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function BS(n){let e=Jn(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 WS(n){return Jn(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function zS(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=Kn.dirname(Kn.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let i=Kn.join(t,r.name);$S(i)&&US(i).isDirectory()&&(r.instancePath=i.replace(/\\/g,"/"))}}function GS(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=WS(t),i=Jn(t,["deviceType","DeviceType","devicetype"]),o=Jn(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:BS(t),path:Jn(t,["path","Path","hvdPath","hvd_path"]),imageRoot:Jn(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 VS(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 cp(n){let t=GS(n)??VS(n);return zS(t),t}function Cc(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function qS(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function YS(n){if(!qS(n))return null;let e=Cc(n,["osVersion","OsVersion","OSVersion"]),t=Cc(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=Cc(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function Bo(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=YS(i);o&&r.push(o)}return r}catch{return[]}}function lp(n){let t=Bo(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var dp=/no images are available/i,JS="7.0.0",KS={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 tt(n){return n.normalize("NFKC").trim().toLowerCase()}function XS(n,e){let t=n.deviceType?.trim(),r=t?KS[tt(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 ZS(n){let e=n.message||"";return dp.test(e)}function QS(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function Qr(n,e){return`${n} ${e.join(" ")}`.trim()}function eb(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 Xn=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: ${Qr(this.emulatorPath,e)}`),Wo(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return ip(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return cp(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let r of t)r.name&&r.deviceType&&e.set(me(r.name),r.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),r=me(e),i=t.find(a=>me(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 sp(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.
|
|
60
|
+
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:ap(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=me(e),i=t.find(a=>me(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"&&XS(i,t.state);let o=this.buildControlArgs(i.name,t);m(`[EmulatorManager] control ${eb(t)} -> ${Qr(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: ${Qr(this.emulatorPath,t)}`);let{stdout:r,stderr:i,exitCode:o}=await Wo(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(`
|
|
61
|
+
`).trim(),a=QS(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(A.compareVersion(a,JS)<0)throw new Error(`Emulator scene control commands require Emulator 7.0 or later. Current Emulator version is ${a}. Please upgrade DevEco Studio or the Emulator SDK.`);n.supportedControlPaths.add(e)}buildControlArgs(e,t){let r=["-instance",e],{type:i}=t;switch(i){case"shake":return[...r,"-shake"];case"power":return[...r,"-power"];case"rotation":return[...r,"-rotation",t.direction];case"volume":return[...r,"-volume",t.direction];case"folded-state":return[...r,"-foldedState",t.state];case"battery":return[...r,"-battery",String(t.level)];case"battery-status":return[...r,"-batteryStatus",String(t.status)];case"gps":return[...r,"-gps",`-${t.key}`,t.value];case"outdoor-running":return[...r,"-outdoorRunning"];case"outdoor-cycling":return[...r,"-outdoorCycling"];case"driving-navigation":return[...r,"-drivingNavigation"];case"sensor":return[...r,"-sensor",`-${t.key}`,String(t.value)];default:throw new Error(`Unsupported emulator control action type: ${i}`)}}async executeEmulatorInherit(e){m(`Executing: ${Qr(this.emulatorPath,e)}`);let{exitCode:t}=await Wo(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(!ZS(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 lp(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}
|
|
62
|
+
`:"";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=Bo(t),i=tt(e.deviceType),o=tt(e.osVersion);return r.filter(s=>tt(s.deviceType)===i&&(tt(s.osVersion)===o||tt(s.softwareVersion)===o))}async hasDownloadedSystemImage(e,t){let r=await this.listEmulatorImages({downloaded:!0}),i=Bo(r),o=tt(t),s=e?.trim()?tt(e):void 0;return i.some(a=>tt(a.osVersion)===o||tt(a.softwareVersion)===o?s===void 0?!0:tt(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:[dp]})}async runEmulatorChecked(e,t){m(`Executing: ${Qr(this.emulatorPath,e)}`);let{stdout:r,stderr:i,exitCode:o}=await Wo(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(`
|
|
63
|
+
`).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=me(e),o=r.find(s=>me(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(`
|
|
64
|
+
`)}),!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=>me(a.name)===e))return!0;await new Promise(a=>setTimeout(a,r))}return!1}async deleteVirtualDevice(e){let t=await this.listEmulators(),r=me(e),i=t.find(s=>me(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}
|
|
65
|
+
The device may be running.`);return await this.runEmulatorChecked(["-delete",o,"-force"],{printOutputOnSuccess:!1}),o}};import{red as Ac,yellow as fp,gray as mp}from"colorette";import cb from"ora";import{red as tb}from"colorette";function zo(n,e){n?n.fail(e):console.error(tb(e)),process.exit(1)}import{green as nb}from"colorette";var rb=[[4352,4447],[9001,9002],[11904,42191],[43360,43388],[44032,55203],[63744,64255],[65040,65049],[65072,65135],[65281,65376],[65504,65510],[127744,129535],[131072,173791],[173824,177983],[177984,178207],[178208,183983],[183984,191456]],ib=[[0,31],[127,159],[768,879],[6832,6911],[7616,7679],[8203,8207],[8400,8447],[65024,65039],[65056,65071],[8205,8205]],ob=new RegExp("\x1B\\[([0-9;]*)[a-zA-Z]","g");function up(n,e){for(let[t,r]of e)if(n>=t&&n<=r)return!0;return!1}function Ic(n){let e=n.replace(ob,""),t=0,r=0;for(;r<e.length;){let i=e.codePointAt(r);if(i===void 0)break;up(i,ib)||(up(i,rb)?t+=2:t+=1),r+=i>65535?2:1}return t}function pp(n,e){let t=Ic(n);return n+" ".repeat(Math.max(0,e-t))}function sb(n,e){return n.map((t,r)=>{let i=Ic(t);for(let o of e){let s=o.cells[r]??"";i=Math.max(i,Ic(s))}return i})}function Et(n,e){let t=sb(n,e),r=[];r.push(n.map((i,o)=>pp(i,t[o])).join(" ")),r.push(t.map(i=>"-".repeat(i)).join(" "));for(let i of e){let o=i.cells.map((s,a)=>pp(s??"",t[a])).join(" ").trimEnd();r.push(i.highlight?nb(o):o)}return r.join(`
|
|
66
|
+
`)}function lb(n,e){if(e.size!==0)for(let t of n){if(!t.isEmulator||!t.name)continue;let r=e.get(me(t.name));r&&(t.deviceType=r)}}var db=["Name","Serial","Kind","Device Type"];function ub(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function pb(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function fb(){console.log(fp(" No active devices.")),console.log(mp(b()?" Connect a USB device with debugging enabled.":" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function mb(n){let t=[...n].sort(pb).map(ub);console.log(Et(db,t))}async function hb(n,e){if(b()||!n.some(i=>i.isEmulator)||!e.emulatorPath)return;let r=await Xn.from(e).getDeviceTypeByName();lb(n,r)}async function gb(n,e,t){try{let r=await n.getConnectedEntries();await hb(r,e),t?.stop(),r.length===0?fb():mb(r)}catch(r){zo(t,`Failed to list devices: ${r.message}`)}}async function yb(n,e){let t=await n.listDevices();if(!(t.length<2)){console.error(Ac("Multiple devices connected. Specify a device with:"));for(let r of t){let i=await n.getDeviceName(r.serial);console.error(mp(` ${e} -t ${r.serial} # ${i}`))}process.exit(1)}}async function wb(n,e){try{e||await yb(n,"devecocli device view");let t=await n.listDevices(),r=await n.getDeviceInfo(t,e);r||(console.log(fp("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(Ac(`Failed to show device details: ${t.message}`)),process.exit(1)}}async function hp(){try{let n=await A.new();return{manager:Z.from(n),toolProvider:n}}catch(n){console.error(Ac(`Failed to initialize device manager: ${n.message}`)),process.exit(1);return}}var Dc=new ab("device").description("Manage connected devices");Dc.command("list").description("List all connected devices").action(async()=>{let{manager:n,toolProvider:e}=await hp(),t=cb({text:"Querying connected devices\u2026",color:"cyan"}).start();await gb(n,e,t)});Dc.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").action(async n=>{let{manager:e}=await hp();await wb(e,n.target)});var gp=Dc;import{Argument as Oc,Command as Mc,Option as ri}from"commander";import{green as ii,cyan as Qn,red as Se,yellow as ut,gray as ni}from"colorette";import Ob from"ora";import vb from"readline/promises";import{execa as wp}from"execa";import*as Wt from"fs/promises";import*as Rc from"os";import*as An from"path";var Tc=`1/4:\r
|
|
58
67
|
---------------------------------------\r
|
|
59
68
|
Statement About HarmonyOS and Privacy\r
|
|
60
69
|
\r
|
|
@@ -1224,61 +1233,72 @@ Part I: Chinese mainland.\r
|
|
|
1224
1233
|
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
|
|
1225
1234
|
\r
|
|
1226
1235
|
Part III: Other countries and regions.\r
|
|
1227
|
-
---------------------------------------\r`;var
|
|
1228
|
-
`),
|
|
1229
|
-
`)}function
|
|
1230
|
-
${t}.`);return
|
|
1231
|
-
`,"utf8"),!0}catch{}return!1}async function
|
|
1236
|
+
---------------------------------------\r`;var Sb=new Set,Go=new Map,kc="HarmonyOS_Software_Service_Agreement",vp=["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(`
|
|
1237
|
+
`),Sp=vp,xc="HarmonyOS_SDK_Agreement";function bp(n,e){return`${n}\0${e}`}function Ep(){Sb.clear(),Go.clear()}var bb=vp,$e=class extends Error{constructor(e=bb){super(e),this.name="EmulatorLicenseBlockedError"}};function Pp(n,e){return[n??"",e??""].join(`
|
|
1238
|
+
`)}function Cp(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 Eb(n){return`Emulator${n.trim()}`}function Ip(n){let e=Eb(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 An.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return An.join(Rc.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||An.join(Rc.homedir(),".cache");return An.join(t,"Huawei",e,".emu_config")}async function Pb(n,e,t){let r=bp(n,e),i=Go.get(r);if(i!==void 0)return i;let o=await wp(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=Pp(o.stdout,o.stderr).trim();if(o.exitCode!==0||!s)throw new $e(t);return Go.set(r,s),s}function Cb(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function Ib(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 Ab(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=Cb(e.slice(r+1).trim());return{key:i,entry:{value:o,delimiter:t}}}}function Db(n){let e={};for(let t of n.split(/\r?\n/)){let r=Ab(t);r&&(e[r.key]=r.entry)}return e}function Tb(n){let e=n.trim();if(!e)return{};let t=Ib(e);return t||Db(n)}function Rb(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function Ap(n,e,t,r){let i=await Pb(n,e,r),o=Cp(i);if(!o)throw new $e(r);let s=Ip(o),a;try{a=await Wt.readFile(s,"utf8")}catch(d){throw d.code==="ENOENT"?new $e(r):d}let l=Tb(a)[t];if(!l)throw new $e(r);if(l.delimiter==="=")throw new $e(r);if(!Rb(l.value))throw new $e(r)}async function Nc(n,e){await Ap(n,e,kc,Sp)}async function Lc(n,e){await Ap(n,e,xc,Sp)}async function kb(n,e){let t=await wp(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),r=Pp(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=bp(n,e);return Go.set(i,r),r}async function Dp(n,e){let t=await kb(n,e),r=Cp(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
|
|
1239
|
+
${t}.`);return Ip(r)}function yp(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function xb(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[kc]="agree",r[xc]="agree",await Wt.writeFile(n,`${JSON.stringify(r,null,2)}
|
|
1240
|
+
`,"utf8"),!0}catch{}return!1}async function Nb(n,e){let t=kc,r=xc,i=[{k:t,re:new RegExp(`^\\s*${yp(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${yp(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 Wt.writeFile(n,s.join(`
|
|
1232
1241
|
`)+(s.length>0?`
|
|
1233
|
-
`:""),"utf8")}async function Am(n){await He.mkdir(et.dirname(n),{recursive:!0});let e="";try{e=await He.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await Im(n,e,t)||await Cm(n,e)}async function wa(n,e){return console.log(qo),0}var Tm="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function ba(n,e){if(console.log(qo),!process.stdin.isTTY||!process.stdout.isTTY)return console.error("`devecocli emulator license accept` requires an interactive terminal."),1;let r=um.createInterface({input:process.stdin,output:process.stdout}),o;try{o=await r.question(Tm)}finally{r.close()}let i=o.trim().toLowerCase();if(i!=="y"&&i!=="yes")return 1;try{let s=await Dm(n,e);await Am(s),mm()}catch(s){return console.error(s.message),1}return 0}var km=["ohos.qemu.hvd.name","const.product.name","const.product.model"];function Rm(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 Mm(n){let e=n.trim();if(!e)throw new Error("--os-version must not be empty.");if(/^\d+$/.test(e))throw new Error(`--os-version "${n}" is invalid. use the full image label, e.g. HarmonyOS 5.1.1(19).`);if(!/^HarmonyOS\s+/i.test(e))throw/^HarmonyOS$/i.test(e)?new Error('--os-version is incomplete (only "HarmonyOS"). On PowerShell/cmd, quote the full label, e.g. --os-version "HarmonyOS 6.0.1(21)".'):new Error(`Invalid --os-version "${n}". It must start with "HarmonyOS " (e.g. "HarmonyOS 5.1.1(19)").`)}function Om(n,e){let t=o=>o.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(ge("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(ge("Run `devecocli emulator image download ...` followed by `devecocli emulator image list` and then copy an `osVersion` string exactly.")),new Error("No downloaded osVersion values parsed; cannot validate --os-version.");if(!e.some(o=>t(o)===r)){console.error(Q("--os-version does not match any downloaded image (exact string required).")),console.log(ge("Use one of these --os-version values:"));for(let o of e)console.log(` ${o}`);throw new Error(`No downloaded image matches --os-version "${n}".`)}}var Nm=["Name","Status","Serial","Device Type","OS Version"];function Lm(n,e,t){return{cells:[n.name,t?"running":"stopped",e??"-",n.deviceType??"-",n.osVersion??"-"],highlight:t}}async function _m(n,e){let t=await Promise.all(e.map(async r=>{let o=await ft(n,r,km);return[r,o]}));return new Map(t)}async function Hm(n){let e=await Fo(n),t=await _m(n,e);return{serials:e,params:t}}function jm(n,e,t,r,o){if(e)for(let i of["const.product.name","const.product.model"]){let s=e.get(i);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),o.set(s,n);let c=r.indexOf(n);c!==-1&&r.splice(c,1);return}}function Fm(n,e,t){let r=new Map,o=new Map,i=[...n],s=[...t];for(let a of n){let c=e.get(a),l=c?.get("ohos.qemu.hvd.name");l&&o.set(l,a),t.length>0&&jm(a,c,s,i,r)}for(let a=0;a<s.length&&a<i.length;a++)r.set(s[a],i[a]);return{productSerialMap:r,hvdSerialMap:o}}function $m(n,e,t){let r=n.map(o=>({emu:o,serial:e.get(o.name)??t.get(o.name),effectiveRunning:o.isRunning===!0||t.has(o.name)}));return r.sort((o,i)=>o.effectiveRunning!==i.effectiveRunning?o.effectiveRunning?-1:1:o.emu.name.localeCompare(i.emu.name)),r.map(o=>Lm(o.emu,o.serial,o.effectiveRunning))}async function Bm(n,e,t){try{let[r,o]=await Promise.all([n.listEmulators(),Hm(e)]);if(r.length===0){t?.stop(),console.log(ge(" No emulator instances found."));return}let i=r.filter(l=>l.isRunning).map(l=>l.name),{productSerialMap:s,hvdSerialMap:a}=Fm(o.serials,o.params,i);t?.stop();let c=$m(r,s,a);console.log(Zt(Nm,c))}catch(r){Gn(t,`Failed to list emulators: ${r.message}`)}}function Ea(n,e,t){let r=!1;for(let o=0;o<n.length;o++){let i=n[o];if(i.status!=="rejected")continue;r=!0;let s=i.reason;console.error(Q(`Failed to ${t} emulator "${e[o]}": ${s.message}`)),s.stdout&&console.error(Qt(s.stdout)),s.stderr&&console.error(Qt(s.stderr))}return r}var Wm=2e3,Um=6e4;async function zm(n,e){let t=V(e);return(await $o(n)).some(o=>V(o)===t)}async function Da(n,e,t,r=Um,o=Wm){let i=Date.now()+r;for(;Date.now()<i;){if(await zm(n,e)===t)return!0;await new Promise(a=>setTimeout(a,o))}return!1}async function qm(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(ge(`Emulator "${t}" is already running.`));return}console.log(St(`Starting emulator "${t}"...`));let o=await Da(e,t,!0);console.log(o?Jn(`Emulator "${t}" started successfully.`):ge(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function Vm(n,e,t){let r=await Promise.allSettled(t.map(i=>qm(n,e,i)));Ea(r,t,"start")&&process.exit(1)}async function Gm(n,e){let t=e.trim();if(!Gt(t))return t;let r=await K.withHdcPath(n).getDeviceName(t);if(r===t)throw new Error(`Cannot resolve a running emulator with serial "${t}". Use \`devecocli emulator list\` or pass the emulator name instead.`);return r}async function Ym(n,e,t){let r=await Gm(e,t);if(console.log(St(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(ge(`Emulator "${r}" is already stopped.`));return}let i=await Da(e,r,!1);console.log(i?Jn(`Emulator "${r}" stopped successfully.`):ge(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function Jm(n,e,t){let r=await Promise.allSettled(t.map(i=>Ym(n,e,i)));Ea(r,t,"stop")&&process.exit(1)}async function ye(){try{let n=await _.new();return{manager:wt.from(n),toolProvider:n}}catch(n){console.error(Q(`Failed to initialize emulator: ${n.message}`)),process.exit(1);return}}var je=new Jo("emulator").description("Manage emulator instances"),Km=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Kn(n){let e=new Pa("--device-type <type>","Emulator device type").choices([...Km]);return n?e.makeOptionMandatory():e}function bt(n,e){for(let t of e)if(t in n)return n[t]}function Xt(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function Sa(n){let e=Xt(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var Zm=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],Xm="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function Ia(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function Ca(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let o=r,i=Xt(bt(o,["osVersion","OsVersion","OSVersion","os_version"])),s=Xt(bt(o,["deviceType","DeviceType","device_type"])),a=Sa(bt(o,["downloaded","Downloaded","isDownloaded"])),c=Xt(bt(o,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=Xt(bt(o,["releaseType","ReleaseType","release_type"])),u=Sa(bt(o,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[i,s,c,l,u,a],highlight:e&&a==="true"})}return t}function Qm(n){let e=n.trim();if(!e)return!0;let t=Ia(e);return t===null?!1:t.length===0?!0:Ca(t,!0).length===0}function ef(n,e){let t=n.trim();if(!t)return"";let r=Ia(t);if(!r)return n.trimEnd();let o=Ca(r,e);return Zt(Zm,o)}var Zn=new Jo("image").description("HarmonyOS emulator system images (download, list, remove)");Zn.command("download").description("Download system image").addOption(Kn(!1)).option("--os-version <version>","Example: HarmonyOS 5.1.1(19) or HarmonyOS 6.0.1(21) (required)").option("--force","Overwrite an existing image").action(async n=>{let{manager:e,toolProvider:t}=await ye();try{await va(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof de&&(console.error(Q(r.message)),process.exit(1)),r}n.deviceType?.trim()||(console.error(Q("Error: missing required option '--device-type <type>'")),process.exit(1)),n.osVersion?.trim()||(console.error(Q("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(Q(`Failed to download system image: ${r.message}`)),process.exit(1)}});Zn.command("remove").description("Remove a downloaded system image").addOption(Kn(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let{manager:e}=await ye();try{await e.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})}catch(t){console.error(Q(`Failed to remove system image: ${t.message}`)),process.exit(1)}});Zn.command("list").description("List system images").addOption(Kn(!1)).option("--all","List all images (local and remote)").addOption(new Pa("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await ye();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if(Qm(r)){console.log(ge(Xm));return}if(n.format==="json"){console.log(r.trimEnd());return}let o=ef(r,n.all===!0);console.log(o)}catch(t){console.error(Q(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});je.addCommand(Zn);var Ko=new Jo("license").description("local emulator license");Ko.command("view").description("Review agreement text(read-only)").action(async()=>{let{toolProvider:n}=await ye(),e=await wa(n.emulatorPath,n.sdkPath);process.exit(e)});Ko.command("accept").description("Review and accept agreements").action(async()=>{let{toolProvider:n}=await ye(),e=await ba(n.emulatorPath,n.sdkPath);process.exit(e)});je.addCommand(Ko);je.command("list").description("List all emulator instances").action(async()=>{let{manager:n,toolProvider:e}=await ye(),t=xm({text:"Listing emulators\u2026",color:"cyan"}).start();await Bm(n,e.hdcPath,t)});je.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await ye();try{await ya(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof de&&(console.error(Q(r.message)),process.exit(1)),r}n?.length||(console.error(Q("Error: missing required argument 'names'")),process.exit(1)),await Vm(e,t.hdcPath,n)});je.command("stop <names...>").description("Stop one or more emulator instances (by name or serial,e.g.,127.0.0.1:<port>)").action(async n=>{let{manager:e,toolProvider:t}=await ye();n?.length||(console.error(Q("Error: missing required argument 'names'")),process.exit(1)),await Jm(e,t.hdcPath,n)});var Aa=je.command("create <name>").description("Create a local emulator by running emulator -create <name> \u2026. --os-version must match a downloaded image from `emulator image list`.").addOption(Kn(!0)).requiredOption("--os-version <version>",'Downloaded image label. which will be quoted in PowerShell (e.g. "HarmonyOS 6.0.1(21)") or be used in the format --os-version="\u2026";For details, run`devecocli emulator image list`.').option("--force","Overwrite if supported");Aa.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
${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)}},Fe=new Zo;var Ra=["DevEco"];async function Xn(){let n=await Fe.get(ce.TAGS_API_URL),t=Qn(n,"Tags API").data.skill.filter(r=>r.name==="HMOS");if(t.length===0)throw new Error("No HMOS tag found.");return t.map(r=>r.id)}async function rf(n){let e=[],t=ce.DEFAULT_PAGE_SIZE,r=1;for(;;){let o=await Fe.post(ce.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:r,pageSize:t,tagIds:[n]}}),i=Qn(o,"Skills API");if(e.push(...i.data.list),i.data.list.length<t)break;r++}return e}async function Xo(n){let e=new Map,t=n.map(o=>rf(o)),r=await Promise.all(t);for(let o of r)for(let i of o)e.has(i.id)||e.set(i.id,i);return Array.from(e.values()).filter(o=>o.tags?.every(i=>!Ra.includes(i.name)))}async function of(n,e){let t=await Fe.post(ce.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:ce.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return Qn(t,"Skills API").data.list}async function Qo(n,e){let t=new Map,r=e.map(i=>of(n,i)),o=await Promise.all(r);for(let i of o)for(let s of i)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(i=>i.tags?.every(s=>!Ra.includes(s.name)))}function Ma(n){let e=[],t=Se();for(let[,r]of Object.entries(t)){let o=ka.join(r.path,n);xa.existsSync(o)&&e.push(r.displayName)}return e.sort()}function Qn(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=Fe.parseJson(n);if(t.code!==ce.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Oa(n){let e=`${ce.SKILL_API_BASE}/${n}/checksum`,t=await Fe.get(e);return Qn(t,"Checksum API").data}import sf from"adm-zip";import af from"crypto";import La from"fs";import H from"path";import{fileURLToPath as cf}from"url";import{red as lf}from"colorette";var Ee=La.promises;function ei(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function Na(n,e){let t=H.resolve(e),r=H.resolve(n),o=H.relative(r,t);if(o.startsWith("..")||H.isAbsolute(o))throw new Error(`Path traversal detected: ${e}.`)}function ti(n){return H.isAbsolute(n)?n:H.resolve(process.cwd(),n)}function df(n){return af.createHash("sha256").update(n).digest("hex")}async function uf(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=df(n),o=e.sha256.toLowerCase();if(r!==o)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function _a(n){let e=`${ce.SKILL_API_BASE}/${n}/install?format=zip`,t=await Fe.getBinary(e),r=await Oa(n);return await uf(t,r),t}async function pf(n,e,t){ei(t);let r=new sf(n),o=r.getEntries();try{await Ee.stat(e)}catch{await Ee.mkdir(e,{recursive:!0})}let i=H.join(e,t);Na(e,i);for(let s of o){let a=H.join(i,s.entryName);Na(i,a)}r.extractAllTo(i,!0)}async function ni(n){let e=Se();if(!e[n])throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(e).join(", ")}`);let r=B[n];try{return await Ee.access(r),!0}catch{return!1}}function ri(n){return Se()[n].path}function oi(n,e){let r=Se()[e],o="projectPath"in r?r.projectPath:H.join("."+e,"skills");return H.join(n,o)}async function mf(n,e,t){ei(e);let r=H.join(n,e);try{if(await Ee.access(r),t)await Ee.rm(r,{recursive:!0,force:!0});else return console.log(`Skill ${e} exists in ${n}.`),{skillDir:r,shouldSkip:!0}}catch{}return{skillDir:r,shouldSkip:!1}}async function ii(n,e,t){await pf(n,e,t),console.log(`Skill ${t} installed to ${H.join(e,t)}.`)}async function si(n,e,t){let r=H.join(e,t);await Ee.mkdir(r,{recursive:!0});let o=H.join(r,H.basename(n));await Ee.copyFile(n,o),console.log(`Skill ${t} installed to ${r}.`)}function Ha(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(lf(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function Pt(n,e,t,r){try{let o=await e(),{shouldSkip:i}=await mf(o,n,r);return i?{success:!0,skipped:!0}:(await t(o),{success:!0})}catch(o){return Ha(n,o,"Installation failed")}}async function ai(n,e){try{ei(n);let t=await e(),r=H.join(t,n);try{await Ee.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await Ee.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return Ha(n,t,"Removal failed")}}async function ja(n,e,t,r=!1){return Pt(n,()=>ri(e),o=>ii(t,o,n),r)}async function Fa(n,e,t,r=!1){return Pt(n,()=>t,o=>ii(e,o,n),r)}async function $a(n,e,t,r,o=!1){return Pt(n,()=>oi(t,r),i=>ii(e,i,n),o)}async function Ba(n,e,t,r=!1){return Pt(n,()=>ri(t),o=>si(e,o,n),r)}async function Wa(n,e,t,r,o=!1){return Pt(n,()=>oi(t,r),i=>si(e,i,n),o)}async function Ua(n,e,t,r=!1){return Pt(n,()=>t,o=>si(e,o,n),r)}async function za(n,e){return ai(n,()=>ri(e))}async function qa(n,e){return ai(n,()=>e)}async function Va(n,e,t){return ai(n,()=>oi(e,t))}function Ga(){let e=H.dirname(cf(import.meta.url));for(;;){let t=H.join(e,"SKILL.md");if(La.existsSync(t))return t;let r=H.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import Ya from"fs";import{cyan as ff}from"colorette";async function en(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await ni(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function tn(){let n=[],e=Se();for(let t of Object.keys(e))await ni(t)&&n.push(t);return n}function nn(n){let e=n.filter(o=>o.success&&!o.skipped).length,t=n.filter(o=>o.skipped).length,r=n.filter(o=>!o.success).length;console.log(),console.log(ff("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function $e(n,e,t){if(!Ya.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!Ya.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function rn(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?ti(n):void 0,resolvedProject:e?ti(e):void 0}}async function er(n,e,t){let r=[],o=[],i;if(e?i=e:t&&n.agent?o=(await en(n.agent)).map(a=>({project:t,agent:a})):t?o=(await tn()).map(a=>({project:t,agent:a})):n.agent?r=await en(n.agent):r=await tn(),!i&&r.length===0&&o.length===0)throw new Error("No agents found. Install an AI agent (opencode, etc.) or use `--path` for a custom location.");return{agents:r,projectAgents:o,customPath:i}}async function vf(n){let e=await Xn();if(n.all)return(await Xo(e)).map(r=>r.enName);{let r=(await Qo(n.skill,e)).find(o=>o.enName===n.skill);if(!r)throw new Error(`Skill "${n.skill}" not found`);return[r.enName]}}async function wf(n,e,t,r){let o=[];if(t.customPath){let i=await Fa(n,e,t.customPath,r);return o.push(i),o}for(let i of t.agents){let s=await ja(n,i,e,r);o.push(s)}for(let{project:i,agent:s}of t.projectAgents){let a=await $a(n,e,i,s,r);o.push(a)}return o}function bf(n){if(n.all&&n.skill)throw new Error("`--all` and `--skill` cannot be specified together.");if(!n.all&&!n.skill)throw new Error("Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=rn(n.path,n.project,n.agent);return t&&$e(t,"Project directory",n.force),e&&$e(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}async function Sf(n,e,t){let r=await er(n,e,t);return{skillNames:await vf(n),targets:r}}async function Pf(n){try{let e=await _a(n);return{name:n,buffer:e,success:!0}}catch(e){let t=e instanceof Error?e.message:"unknown error";return{name:n,error:t,success:!1}}}async function Ef(n,e,t,r){let o=[],i=n.length,s=yf(5),a=n.map(c=>s(()=>Pf(c)));for(let c=0;c<n.length;c++){let l=n[c],u=i>1?` (${c+1}/${i})`:"";r.start(`Installing ${l}${u}...`);let h=await a[c];if(!h.success){r.fail(),console.log(on(`${l}: Download failed - ${h.error}`)),o.push({success:!1});continue}r.stop();let v=await wf(l,h.buffer,e,t);o.push(...v)}return o}async function Df(n){let e=new tt;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=bf(n),{skillNames:o,targets:i}=await Sf(n,t,r),s=await Ef(o,i,n.force||!1,e);e.stop(),nn(s)}catch(t){throw e.stop(),t}}function If(n){let{resolvedPath:e,resolvedProject:t}=rn(n.path,n.project,n.agent);return t&&$e(t,"Project directory"),e&&$e(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function Cf(n,e){let t=new tt;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:o}=If(e);t.stop();let i=await Af(e,n,r,o);t.stop(),nn(i)}catch(r){throw t.stop(),r}}function Ja(n,e=""){if(n.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function tr(n,e){let t=[];for(let r of e){let o=r.type==="agent"?await za(n,r.agent):await Va(n,r.project,r.agent);t.push(o)}return t}async function Af(n,e,t,r){if(t)return[await qa(e,t)];if(r&&n.agent){let a=(await en(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return tr(e,a)}if(r){let s=await tn();Ja(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return tr(e,a)}if(n.agent){let a=(await en(n.agent)).map(c=>({type:"agent",agent:c}));return tr(e,a)}let o=await tn();Ja(o,"or use --path for a custom location.");let i=o.map(s=>({type:"agent",agent:s}));return tr(e,i)}var sn=new hf("skills").description("Manage HarmonyOS skills");sn.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async n=>{let e=new tt;try{e.start("Fetching skills...");let t=await Xn(),r=await Xo(t);if(r.length===0){e.stop(),console.log(Za("No skills available."));return}e.succeed(`Fetched ${r.length} skills`);for(let o of r)if(n.long){console.log(Ka(o.enName)),console.log(Xa(o.description));let i=Ma(o.enName);i.length>0&&console.log(gf(`Installed for: ${i.join(", ")}`)),console.log()}else console.log(o.enName)}catch(t){e.stop(),console.error(on(t.message)),process.exit(1)}});sn.command("find <keyword>").description("Search skills by keyword").action(async n=>{let e=new tt;try{e.start("Searching skills...");let t=await Xn(),r=await Qo(n,t);if(r.length===0){console.log(Za(`No skills found matching '${n}'.`)),e.stop();return}e.succeed(`Found ${r.length} skills.`);for(let o of r)console.log(Ka(o.enName)),console.log(Xa(o.description)),console.log()}catch(t){e.stop(),console.error(on(t.message)),process.exit(1)}});sn.command("add").description("Install skills to AI agents").option("--all","Install all available skills").option("--agent <agents>","Target agents, comma-separated; Omit to install to all available agents.").option("--skill <skill-name>","Name of the skill to install").option("-f, --force","Overwrite an existing skill installation").option("--project <path>","Project root directory for skill installation").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").action(async n=>{try{await Df(n)}catch(e){console.error(on(e.message)),process.exit(1)}});sn.command("remove").description("Remove an installed skill from AI agents").requiredOption("--skill <skill-name>","Name of the skill to remove").option("--agent <agents>","Target agents, comma-separated.Omit to remove from all available agents").option("--project <path>","Project root directory for skill removal").option("--path <path>","Path for skill removal").action(async n=>{try{await Cf(n.skill,n)}catch(e){console.error(on(e.message)),process.exit(1)}});var Qa=sn;import{Command as xf,InvalidArgumentError as nc}from"commander";import{cyan as nr}from"colorette";function nt(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=mt(t);return r==="transient"?new Error(`${e}: Device communication channel unavailable. Retry in a few seconds.`):r==="fatal"?new Error(`${e}: ${t.trim()}`):null}var ci=[800,1500,2500];function Tf(n){return new Promise(e=>setTimeout(e,n))}function ec(){return I()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device."}var rr=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=K.from(e)}createFollowLineHandler(){return(e,t)=>{if(t==="stderr"){for(let r of e)console.error(r);return}for(let r of e)console.log(r)}}findDeviceByArg(e,t){return e.find(r=>r.serial===t||r.name===t)}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
|
|
1239
|
-
|
|
1242
|
+
`:""),"utf8")}async function Tp(n){await Wt.mkdir(An.dirname(n),{recursive:!0});let e="";try{e=await Wt.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await xb(n,e,t)||await Nb(n,e)}async function Rp(n,e){return console.log(Tc),0}var Lb="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function kp(n,e){try{return await Nc(n,e),await Lc(n,e),!0}catch(t){if(t instanceof $e)return!1;throw t}}async function xp(n,e){if(await kp(n,e))return console.log("Emulator license agreements are already accepted."),0;if(console.log(Tc),!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=vb.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await r.question(Lb)}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 Dp(n,e);await Tp(s),Ep()}catch(s){return console.error(s.message),1}return console.log("Emulator license agreements accepted."),0}async function Np(n,e){if(await kp(n,e))return console.log("Emulator license agreements are already accepted."),0;try{let t=await Dp(n,e);await Tp(t),Ep()}catch(t){return console.error(t.message),1}return console.log("Emulator license agreements accepted."),0}var Mb=["ohos.qemu.hvd.name","const.product.name","const.product.model"],Lp=["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"],_b=`
|
|
1243
|
+
Folded state scene mappings:
|
|
1244
|
+
foldableFold (3):
|
|
1245
|
+
open Fully expanded state
|
|
1246
|
+
half-open Semi-folded state
|
|
1247
|
+
close Fully folded state
|
|
1248
|
+
|
|
1249
|
+
2in1foldableFold (4):
|
|
1250
|
+
open Landscape unfolded state
|
|
1251
|
+
vertical-open Portrait unfolded state
|
|
1252
|
+
half-open Semi-folded state
|
|
1253
|
+
close Magnetic attachment state
|
|
1254
|
+
|
|
1255
|
+
tripleFold (9):
|
|
1256
|
+
single
|
|
1257
|
+
double
|
|
1258
|
+
triple
|
|
1259
|
+
left-folded-right-half-folded
|
|
1260
|
+
left-half-folded-right-expanded
|
|
1261
|
+
left-expanded-right-folded
|
|
1262
|
+
left-half-folded-right-folded
|
|
1263
|
+
left-expanded-right-half-folded
|
|
1264
|
+
left-half-folded-right-half-folded
|
|
1265
|
+
`;function Fb(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function jb(n){let e=n.trim();if(!Lp.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${Lp.join(", ")}`);return e}function Mp(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 _p(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&&!Hb(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 Hb(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function $b(n,e,t,r,i){return Number(_p(n,e,t,r,i))}function Ub(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 Bb(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 Wb(n,e){let t=i=>i.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(ut("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(ut("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(Se("--os-version does not match any downloaded image (exact string required).")),console.log(ut("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 zb=["Name","Status","Serial","Device Type","OS Version"];function Gb(n,e,t){return{cells:[n.name,t?"running":"stopped",e??"-",n.deviceType??"-",n.osVersion??"-"],highlight:t}}async function Vb(n,e){let t=await Promise.all(e.map(async r=>{let i=await Vn(n,r,Mb);return[r,i]}));return new Map(t)}async function qb(n){let e=await Ec(n),t=await Vb(n,e);return{serials:e,params:t}}function Yb(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 Jb(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&&Yb(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 Kb(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=>Gb(i.emu,i.serial,i.effectiveRunning))}async function Xb(n,e,t){try{let[r,i]=await Promise.all([n.listEmulators(),qb(e)]);if(r.length===0){t?.stop(),console.log(ut(" No emulator instances found."));return}let o=r.filter(l=>l.isRunning).map(l=>l.name),{productSerialMap:s,hvdSerialMap:a}=Jb(i.serials,i.params,o);t?.stop();let c=Kb(r,s,a);console.log(Et(zb,c))}catch(r){zo(t,`Failed to list emulators: ${r.message}`)}}function Fp(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(Se(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(ni(s.stdout)),s.stderr&&console.error(ni(s.stderr))}return r}var Zb=2e3,Qb=6e4;async function eE(n,e){let t=me(e);return(await Pc(n)).some(i=>me(i)===t)}async function jp(n,e,t,r=Qb,i=Zb){let o=Date.now()+r;for(;Date.now()<o;){if(await eE(n,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}async function tE(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(ut(`Emulator "${t}" is already running.`));return}console.log(Qn(`Starting emulator "${t}"...`));let i=await jp(e,t,!0);console.log(i?ii(`Emulator "${t}" started successfully.`):ut(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function nE(n,e,t){let r=await Promise.allSettled(t.map(o=>tE(n,e,o)));Fp(r,t,"start")&&process.exit(1)}async function Hp(n,e){let t=e.trim();if(!Cn(t))return t;let r=await Z.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 rE(n,e,t){let r=await Hp(e,t);if(console.log(Qn(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(ut(`Emulator "${r}" is already stopped.`));return}let o=await jp(e,r,!1);console.log(o?ii(`Emulator "${r}" stopped successfully.`):ut(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function iE(n,e,t){let r=await Promise.allSettled(t.map(o=>rE(n,e,o)));Fp(r,t,"stop")&&process.exit(1)}async function Ue(){try{let n=await A.new();return{manager:Xn.from(n),toolProvider:n}}catch(n){console.error(Se(`Failed to initialize emulator: ${n.message}`)),process.exit(1);return}}async function Pt(n,e){try{let t=Fb(n.target),r=e(),{manager:i,toolProvider:o}=await Ue(),s=await Hp(o.hdcPath,t);await i.controlEmulator(s,r),console.log(ii(`Emulator "${t}" operation completed.`))}catch(t){let r=n.target?.trim()||"<unknown>";console.error(Se(`Failed to operate emulator "${r}": ${t.message}`)),process.exit(1)}}function oE(n){let e=[];return Vo(e,"longitude",n.longitude,-180,180,8),Vo(e,"latitude",n.latitude,-90,90,8),Vo(e,"altitude",n.altitude,-1e4,1e4,2),Vo(e,"bearing",n.direction,0,359.99,2,"--direction"),_c(e,"Specify one geolocation option.")}function sE(n){let e=[];return ei(e,"light",n.lightIntensity,0,1e5,!1,"--light-intensity"),ei(e,"humidity",n.humidity,0,100,!1),ei(e,"temperature",n.temperature,-273.1,100,!1),ei(e,"steps",n.steps,0,1e4,!0),ei(e,"heartrate",n.heartrate,0,255,!0),_c(e,"Specify one sensor option.")}function _c(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 Vo(n,e,t,r,i,o,s=`--${e}`){t!==void 0&&n.push({type:"gps",key:e,value:_p(s,t,r,i,o)})}function ei(n,e,t,r,i,o,s=`--${e}`){if(t===void 0)return;let a=o?Mp(s,t,r,i):$b(s,t,r,i,1);n.push({type:"sensor",key:e,value:a})}function aE(n){let e=[];return n.level!==void 0&&e.push({type:"battery",level:Mp("--level",n.level,1,100)}),n.status!==void 0&&e.push({type:"battery-status",status:n.status==="charging"?1:0}),_c(e,"Specify --level or --status.")}var ce=new Mc("emulator").description("Manage emulator instances"),cE=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function qo(n){let e=new ri("--device-type <type>","Emulator device type").choices([...cE]);return n?e.makeOptionMandatory():e}function Zn(n,e){for(let t of e)if(t in n)return n[t]}function ti(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function Op(n){let e=ti(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var lE=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],dE="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function $p(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function Up(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let i=r,o=ti(Zn(i,["osVersion","OsVersion","OSVersion","os_version"])),s=ti(Zn(i,["deviceType","DeviceType","device_type"])),a=Op(Zn(i,["downloaded","Downloaded","isDownloaded"])),c=ti(Zn(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=ti(Zn(i,["releaseType","ReleaseType","release_type"])),d=Op(Zn(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,l,d,a],highlight:e&&a==="true"})}return t}function uE(n){let e=n.trim();if(!e)return!0;let t=$p(e);return t===null?!1:t.length===0?!0:Up(t,!0).length===0}function pE(n,e){let t=n.trim();if(!t)return"";let r=$p(t);if(!r)return n.trimEnd();let i=Up(r,e);return Et(lE,i)}var Yo=new Mc("image").description("HarmonyOS emulator system images (download, list, remove)");Yo.command("download").description("Download system image").addOption(qo(!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 Ue();try{await Lc(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof $e&&(console.error(Se(r.message)),process.exit(1)),r}n.deviceType?.trim()||(console.error(Se("Error: missing required option '--device-type <type>'")),process.exit(1)),n.osVersion?.trim()||(console.error(Se("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(Se(`Failed to download system image: ${r.message}`)),process.exit(1)}});Yo.command("remove").description("Remove a downloaded system image").addOption(qo(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let{manager:e}=await Ue();try{await e.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})}catch(t){console.error(Se(`Failed to remove system image: ${t.message}`)),process.exit(1)}});Yo.command("list").description("List system images").addOption(qo(!1)).option("--all","List all images (local and remote)").addOption(new ri("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await Ue();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if(uE(r)){console.log(ut(dE));return}if(n.format==="json"){console.log(r.trimEnd());return}let i=pE(r,n.all===!0);console.log(i)}catch(t){console.error(Se(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});ce.addCommand(Yo);var Jo=new Mc("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");Jo.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let{toolProvider:n}=await Ue(),e=await Rp(n.emulatorPath,n.sdkPath);process.exit(e)});Jo.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let{toolProvider:n}=await Ue(),e=await Np(n.emulatorPath,n.sdkPath);process.exit(e)});Jo.action(async()=>{let{toolProvider:n}=await Ue(),e=await xp(n.emulatorPath,n.sdkPath);process.exit(e)});ce.addCommand(Jo);ce.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Pt(n,()=>({type:"shake"})));ce.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Pt(n,()=>({type:"power"})));ce.command("rotate").description("Rotate emulator").addOption(new ri("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Oc("<direction>").choices(["left","right"])).action((n,e)=>Pt(e,()=>({type:"rotation",direction:n})));ce.command("volume").description("Change volume").addOption(new ri("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Oc("<direction>").choices(["up","down"])).action((n,e)=>Pt(e,()=>({type:"volume",direction:n})));ce.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",_b).action((n,e)=>Pt(e,()=>({type:"folded-state",state:jb(n)})));ce.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 ri("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>Pt(n,()=>aE(n)));ce.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=>Pt(n,()=>oE(n)));ce.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new Oc("<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 Pt(e,()=>t[n])});ce.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=>Pt(n,()=>sE(n)));ce.command("list").description("List all emulator instances").action(async()=>{let{manager:n,toolProvider:e}=await Ue(),t=Ob({text:"Listing emulators\u2026",color:"cyan"}).start();await Xb(n,e.hdcPath,t)});ce.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await Ue();try{await Nc(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof $e&&(console.error(Se(r.message)),process.exit(1)),r}n?.length||(console.error(Se("Error: missing required argument 'names'")),process.exit(1)),await nE(e,t.hdcPath,n)});ce.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 Ue();n?.length||(console.error(Se("Error: missing required argument 'names'")),process.exit(1)),await iE(e,t.hdcPath,n)});var Bp=ce.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(qo(!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");Bp.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
|
|
1266
|
+
${ut("Tip: ")}${ni("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
|
|
1267
|
+
${Qn('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
|
|
1268
|
+
${Qn('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
|
|
1269
|
+
`)}});Bp.action(async(n,e)=>{try{Ub(n),Bb(e.osVersion);let{manager:t}=await Ue(),r=await t.listDownloadedImageOsVersions();Wb(e.osVersion,r),console.log(Qn(`Creating emulator "${n}"...`)),await t.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(ii(`Emulator "${n}" created successfully.`))}catch(t){console.error(Se(`${t.message}`)),process.exit(1)}});ce.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let{manager:e}=await Ue();console.log(Qn(`Deleting emulator "${n}"...`));try{let t=await e.deleteVirtualDevice(n);console.log(ii(`Emulator "${t}" deleted successfully.`))}catch(t){let r=t;console.error(Se(r.message)),r.stdout&&console.error(ni(r.stdout)),r.stderr&&console.error(ni(r.stderr)),process.exit(1)}});var Wp=ce;import{Command as kE}from"commander";import{cyan as We}from"colorette";import*as df from"readline";import*as af from"crypto";import*as zp from"http";import*as Gp from"crypto";import{URL as fE}from"url";var Ko=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=zp.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 fE(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&&Gp.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 Ce from"fs";import*as tr from"path";import{homedir as SE}from"os";var Ct={};Aw(Ct,{LocalCrypto:()=>Ct,decryptForLocalStorage:()=>yE,decryptForLocalStorageFromDirectory:()=>wE,encryptForLocalStorage:()=>gE,isEncryptedBlob:()=>vE});import*as G from"fs";import*as Dn from"path";import*as Pe from"crypto";import{homedir as Vp}from"os";var oi=gn.ALGORITHM,qp=gn.IV_LENGTH,si=gn.KEY_LENGTH,ai=gn.KEY_LENGTH,ci=gn.KEK_VERSIONS,Fc=process.env.DEVECO_CLI_DATA_DIR||Dn.join(Vp(),ve.CONFIG_DIR_NAME,ve.APP_NAME),jc=Dn.join(Vp(),".local","share",ve.APP_NAME,"keys"),er=Dn.join(Fc,ve.KEY_FILE_NAME);function Hc(n){return Dn.join(jc,`${n}.bin`)}function Yp(){G.existsSync(Fc)||G.mkdirSync(Fc,{recursive:!0,mode:448}),G.existsSync(jc)||G.mkdirSync(jc,{recursive:!0,mode:448})}function Jp(){Yp();for(let n of ci){let e=Hc(n);G.existsSync(e)||G.writeFileSync(e,Pe.randomBytes(si),{mode:384})}}function Kp(n){Jp();let e=Hc(n),t=G.readFileSync(e);if(t.length===si)return t;let r=Pe.randomBytes(si);return G.writeFileSync(e,r,{mode:384}),r}function $c(n,e){let t=Pe.randomBytes(qp),r=Kp(e),i=Pe.createCipheriv(oi,r,t),o=Buffer.concat([i.update(n),i.final()]),s=i.getAuthTag();return{version:1,algorithm:oi,kekId:e,encryptedDek:o.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function Xp(n,e){return Zp(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function Zp(n,e,t,r){let i=Pe.createDecipheriv(oi,e,Buffer.from(t,"base64"));return i.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([i.update(n),i.final()])}function Qp(n,e){return Zp(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function mE(){if(Jp(),G.existsSync(er))return;let n=Pe.randomBytes(ai),e=$c(n,ci[0]);G.writeFileSync(er,JSON.stringify(e,null,2),{mode:384})}function ef(){mE();let n=JSON.parse(G.readFileSync(er,"utf8")),e=Xp(n,Kp(n.kekId));if(e.length===ai)return e;let t=Pe.randomBytes(ai),r=$c(t,ci[0]);return G.writeFileSync(er,JSON.stringify(r,null,2),{mode:384}),t}function hE(){Yp();for(let t of ci){let r=Hc(t);G.existsSync(r)||G.writeFileSync(r,Pe.randomBytes(si),{mode:384})}if(G.existsSync(er))return;let n=Pe.randomBytes(ai),e=$c(n,ci[0]);G.writeFileSync(er,JSON.stringify(e,null,2),{mode:384})}function gE(n){let e=ef(),t=Pe.randomBytes(qp),r=Pe.createCipheriv(oi,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o=r.getAuthTag();return{version:1,algorithm:oi,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:o.toString("base64"),timeStamp:Date.now()}}function yE(n){try{return Qp(n,ef())}catch{throw hE(),new Error("Failed to decrypt local ciphertext")}}function wE(n,e){let t=Dn.join(e,ve.KEY_FILE_NAME),r=JSON.parse(G.readFileSync(t,"utf8")),i=Dn.join(e,"keys",`${r.kekId}.bin`),o=G.readFileSync(i);if(o.length!==si)throw new Error("Invalid external root key");let s=Xp(r,o);if(s.length!==ai)throw new Error("Invalid external data encryption key");return Qp(n,s)}function vE(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 Xo=class{tokenFilePath;constructor(e){let t=e||process.env.DEVECO_CLI_DATA_DIR||tr.join(SE(),ve.CONFIG_DIR_NAME,ve.APP_NAME);this.tokenFilePath=tr.join(t,ve.TOKEN_FILE_NAME)}ensureConfigDir(){let e=tr.dirname(this.tokenFilePath);Ce.existsSync(e)||Ce.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=Ct.encryptForLocalStorage(e);this.ensureConfigDir(),Ce.writeFileSync(this.tokenFilePath,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return(await this.resolveJwtToken())?.token??null}async resolveJwtToken(){let e=this.loadDevecoCodeToken();if(e)return{token:e,source:"deveco-code"};let t=await this.loadLocalJwtToken();return t?{token:t,source:"deveco-cli"}:null}loadDevecoCodeToken(){if(process.env.DEVECO_CLI_AUTH_SOURCE!=="deveco-code")return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;try{let t=tr.join(e,ve.TOKEN_FILE_NAME);if(!Ce.existsSync(t))return null;let r=JSON.parse(Ce.readFileSync(t,"utf8"));return Ct.isEncryptedBlob(r)?Ct.decryptForLocalStorageFromDirectory(r,e):null}catch{return null}}async loadLocalJwtToken(){try{if(!Ce.existsSync(this.tokenFilePath))return null;let e=JSON.parse(Ce.readFileSync(this.tokenFilePath,"utf8"));return Ct.isEncryptedBlob(e)?Ct.decryptForLocalStorage(e):null}catch{return await this.clearToken(),null}}async clearToken(){try{Ce.existsSync(this.tokenFilePath)&&Ce.unlinkSync(this.tokenFilePath)}catch(e){throw new Error("Failed to clear token",{cause:e})}}},Be=new Xo;var pt={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},li={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},Zo={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},bE={[pt.CHINA]:li.CHINA,[pt.RUSSIA]:li.RUSSIA,[pt.EUROPE]:li.EUROPE,[pt.SINGAPORE]:li.CHINA},EE={[Zo.CHINA]:pt.CHINA,[Zo.SINGAPORE]:pt.SINGAPORE,[Zo.EUROPE]:pt.EUROPE,[Zo.RUSSIA]:pt.RUSSIA};function tf(n){return bE[n]??li.CHINA}function nf(n){return EE[n]??pt.CHINA}function Qo(n,e){return n?.toUpperCase()===pt.CHINA?Ke.CN_LOGIN_URL:e}import{exec as PE}from"child_process";import{promisify as CE}from"util";var IE=CE(PE);async function rf(n){let e=process.platform,t;switch(e){case"win32":t=`start "" "${n}"`;break;case"darwin":t=`open "${n}"`;break;case"openharmony":console.log("\u65E0\u6CD5\u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668\uFF0C\u8BF7\u624B\u52A8\u590D\u5236\u4EE5\u4E0B\u767B\u5F55\u94FE\u63A5\u5230\u6D4F\u89C8\u5668\u6253\u5F00\uFF1A"),console.log(n);return;default:t=`xdg-open "${n}"`;break}try{await IE(t)}catch(r){throw new Error("Failed to open browser",{cause:r})}}import AE from"axios";var Uc=class{client;constructor(){let e={timeout:Ur.HTTP_TIMEOUT_MS,headers:{"User-Agent":ho.USER_AGENT,"accept-language":ho.ACCEPT_LANGUAGE},transformResponse:[t=>t],proxy:!1};this.client=AE.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}
|
|
1270
|
+
${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 Uc;var Bc=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 Be.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}}},di=new Bc;function of(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 sf(n){let e=n.split(".");return e.length===3&&e.every(t=>t.length>0)}var Wc=class{async getJwtToken(e,t,r,i,o){let s=e.split("&")[0],a=nf(t),c=r(),l={tempToken:s,site:a,version:ve.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(!sf(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=of(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:tf(r.userInfo.nationalCode),isRealName:String(r.userInfo.realName)==="true"}}},es=new Wc;var ts=class{config;server=null;constructor(e){this.config={...Br,...e}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}async login(){try{let e=this.generateClientSecret();this.server=new Ko(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 es.getJwtToken(t.tempToken,t.siteId,()=>this.getRegionalizedBaseUrl(),this.config.tempTokenCheckUrl,this.config.appId),i=await es.getUserInfoFromJwt(r,o=>di.checkJwtToken(o,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl));return await Be.saveJwtToken(r),i}finally{this.server&&(await this.server.stop(),this.server=null)}}async isLoggedIn(){let e=await Be.resolveJwtToken();return e==null?!1:(await di.checkJwtToken(e.token,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)).status?!0:(e.source==="deveco-cli"&&await Be.clearToken(),!1)}async logout(){let e=await Be.resolveJwtToken();if(e==null)return!1;if(e.source==="deveco-code")throw new Error("Login is managed by deveco-code. Log out from deveco-code instead.");let r=`${this.getRegionalizedBaseUrl()}/${this.config.logoutUrl}?jwtToken=${e.token}`;try{await N.post(r,{timeout:5e3})}finally{await Be.clearToken()}return!0}async getUserInfo(){let e=await Be.loadJwtToken();return e?es.getUserInfoFromJwt(e,t=>di.checkJwtToken(t,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)):null}generateClientSecret(){return af.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 rf(i)}async refreshToken(){return di.refreshToken(()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)}},re=new ts;import cf from"axios";var TE="No JWT in local storage. Run `devecocli auth login` first.";function RE(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 ns=class{config;constructor(e){this.config={...Br,...e}}updateConfig(e){this.config={...this.config,...e}}async listTeams(){let e=await Be.loadJwtToken();if(!e)throw new Error(TE);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=RE(i);return{userId:r??"",teamList:o}}async fetchTeamList(e,t){let r=this.config.agcTeamListUrl;m(`Executing: GET ${r}`);let i;try{i=await cf.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 cf.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)}},lf=new ns;async function zt(){return lf.listTeams()}function xE(n){if(n.length===0)return We("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(`
|
|
1271
|
+
`)}function NE(){return new Promise(n=>{let e=df.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}var ui=new kE("auth").description("Authentication commands (login, logout, status, team)");ui.command("login").description("Log in to your Huawei Developer account").action(async()=>{try{if(await re.isLoggedIn()){let t=await re.getUserInfo();if(t){console.log(We(`Already logged in, User Name:${t.userName}`));return}}console.log(We("Starting login process...")),console.log(We("Press Enter to open browser for login...")),await NE();let e=await re.login();console.log(We(`Login successful. Logged in as ${e.userName}.`))}catch(n){throw new Error("Login failed",{cause:n})}});ui.command("logout").description("Log out of your Huawei Developer account").action(async()=>{try{let n=await re.logout();console.log(n?We("Logout successful"):We("Already logged out."))}catch(n){throw new Error("Logout failed",{cause:n})}});ui.command("status").description("Show the currently logged-in user").action(async()=>{try{if(!await re.isLoggedIn()){console.log(We("Not logged in"));return}let e=await re.getUserInfo();if(!e){console.log(We("Not logged in"));return}console.log(We(`Current user: ${e.userName}`))}catch{console.log(We("Not logged in"))}});var LE=ui.command("team").description("Team-related commands");LE.command("list").description("List team accounts the current user has joined").option("--json","output as JSON",!1).action(async n=>{try{if(!await re.isLoggedIn()){console.log(We("Please run `devecocli auth login` first."));return}let t=await zt();if(n.json){console.log(JSON.stringify(t,null,2));return}console.log(xE(t.teamList))}catch(e){throw new Error("Failed to list teams",{cause:e})}});var uf=ui;import{Command as VE}from"commander";import{green as qE,red as gi,cyan as Lf,yellow as Of,dim as Mf}from"colorette";import YE from"p-limit";import OE from"ora";var nt=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=OE(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 pf from"fs";import*as ff from"path";var mf=["DevEco"];async function rs(){let n=await N.get(Xe.TAGS_API_URL),t=is(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 ME(n){let e=[],t=Xe.DEFAULT_PAGE_SIZE,r=1;for(;;){let i=await N.post(Xe.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:r,pageSize:t,tagIds:[n]}}),o=is(i,"Skills API");if(e.push(...o.data.list),o.data.list.length<t)break;r++}return e}async function zc(n){let e=new Map,t=n.map(i=>ME(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=>!mf.includes(o.name)))}async function _E(n,e){let t=await N.post(Xe.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:Xe.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return is(t,"Skills API").data.list}async function Gc(n,e){let t=new Map,r=e.map(o=>_E(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=>!mf.includes(s.name)))}function hf(n){let e=[],t=wt();for(let[,r]of Object.entries(t)){let i=ff.join(r.path,n);pf.existsSync(i)&&e.push(r.displayName)}return e.sort()}function is(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=N.parseJson(n);if(t.code!==Xe.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function gf(n){let e=`${Xe.SKILL_API_BASE}/${n}/checksum`,t=await N.get(e);return is(t,"Checksum API").data}import FE from"adm-zip";import jE from"crypto";import wf from"fs";import te from"path";import{fileURLToPath as HE}from"url";import{red as $E}from"colorette";var It=wf.promises;function Vc(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function yf(n,e){let t=te.resolve(e),r=te.resolve(n),i=te.relative(r,t);if(i.startsWith("..")||te.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function qc(n){return te.isAbsolute(n)?n:te.resolve(process.cwd(),n)}function UE(n){return jE.createHash("sha256").update(n).digest("hex")}async function BE(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=UE(n),i=e.sha256.toLowerCase();if(r!==i)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function vf(n){let e=`${Xe.SKILL_API_BASE}/${n}/install?format=zip`,t=await N.getBinary(e),r=await gf(n);return await BE(t,r),t}async function WE(n,e,t){Vc(t);let r=new FE(n),i=r.getEntries();try{await It.stat(e)}catch{await It.mkdir(e,{recursive:!0})}let o=te.join(e,t);yf(e,o);for(let s of i){let a=te.join(o,s.entryName);yf(o,a)}r.extractAllTo(o,!0)}async function Yc(n){let e=wt();if(!e[n])throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(e).join(", ")}`);let r=se[n];try{return await It.access(r),!0}catch{return!1}}function Jc(n){return wt()[n].path}function Kc(n,e){let r=wt()[e],i="projectPath"in r?r.projectPath:te.join("."+e,"skills");return te.join(n,i)}async function zE(n,e,t){Vc(e);let r=te.join(n,e);try{if(await It.access(r),t)await It.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 Xc(n,e,t){await WE(n,e,t),console.log(`Skill ${t} installed to ${te.join(e,t)}.`)}async function Zc(n,e,t){let r=te.join(e,t);await It.mkdir(r,{recursive:!0});let i=te.join(r,te.basename(n));await It.copyFile(n,i),console.log(`Skill ${t} installed to ${r}.`)}function Sf(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log($E(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function nr(n,e,t,r){try{let i=await e(),{shouldSkip:o}=await zE(i,n,r);return o?{success:!0,skipped:!0}:(await t(i),{success:!0})}catch(i){return Sf(n,i,"Installation failed")}}async function Qc(n,e){try{Vc(n);let t=await e(),r=te.join(t,n);try{await It.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await It.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return Sf(n,t,"Removal failed")}}async function bf(n,e,t,r=!1){return nr(n,()=>Jc(e),i=>Xc(t,i,n),r)}async function Ef(n,e,t,r=!1){return nr(n,()=>t,i=>Xc(e,i,n),r)}async function Pf(n,e,t,r,i=!1){return nr(n,()=>Kc(t,r),o=>Xc(e,o,n),i)}async function Cf(n,e,t,r=!1){return nr(n,()=>Jc(t),i=>Zc(e,i,n),r)}async function If(n,e,t,r,i=!1){return nr(n,()=>Kc(t,r),o=>Zc(e,o,n),i)}async function Af(n,e,t,r=!1){return nr(n,()=>t,i=>Zc(e,i,n),r)}async function Df(n,e){return Qc(n,()=>Jc(e))}async function Tf(n,e){return Qc(n,()=>e)}async function Rf(n,e,t){return Qc(n,()=>Kc(e,t))}function kf(){let e=te.dirname(HE(import.meta.url));for(;;){let t=te.join(e,"SKILL.md");if(wf.existsSync(t))return t;let r=te.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import xf from"fs";import{cyan as GE}from"colorette";async function pi(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await Yc(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function fi(){let n=[],e=wt();for(let t of Object.keys(e))await Yc(t)&&n.push(t);return n}function mi(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(GE("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function Gt(n,e,t){if(!xf.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!xf.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function hi(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?qc(n):void 0,resolvedProject:e?qc(e):void 0}}async function os(n,e,t){let r=[],i=[],o;if(e?o=e:t&&n.agent?i=(await pi(n.agent)).map(a=>({project:t,agent:a})):t?i=(await fi()).map(a=>({project:t,agent:a})):n.agent?r=await pi(n.agent):r=await fi(),!o&&r.length===0&&i.length===0)throw new Error("No agents found. Install an AI agent (opencode, etc.) or use `--path` for a custom location.");return{agents:r,projectAgents:i,customPath:o}}async function JE(n){let e=await rs();if(n.all)return(await zc(e)).map(r=>r.enName);{let r=(await Gc(n.skill,e)).find(i=>i.enName===n.skill);if(!r)throw new Error(`Skill "${n.skill}" not found`);return[r.enName]}}async function KE(n,e,t,r){let i=[];if(t.customPath){let o=await Ef(n,e,t.customPath,r);return i.push(o),i}for(let o of t.agents){let s=await bf(n,o,e,r);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await Pf(n,e,o,s,r);i.push(a)}return i}function XE(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}=hi(n.path,n.project,n.agent);return t&&Gt(t,"Project directory",n.force),e&&Gt(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}async function ZE(n,e,t){let r=await os(n,e,t);return{skillNames:await JE(n),targets:r}}async function QE(n,e,t,r){let i=[],o=n.length,s=YE(5),a=n.map(c=>s(()=>eP(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(gi(`${l}: Download failed - ${h.error}`)),i.push({success:!1});continue}r.stop();let w=await KE(l,h.buffer,e,t);i.push(...w)}return i}async function eP(n){try{let e=await vf(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 tP(n){let e=new nt;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=XE(n),{skillNames:i,targets:o}=await ZE(n,t,r),s=await QE(i,o,n.force||!1,e);e.stop(),mi(s)}catch(t){throw e.stop(),t}}function nP(n){let{resolvedPath:e,resolvedProject:t}=hi(n.path,n.project,n.agent);return t&&Gt(t,"Project directory"),e&&Gt(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function rP(n,e){let t=new nt;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:i}=nP(e);t.stop();let o=await iP(e,n,r,i);t.stop(),mi(o)}catch(r){throw t.stop(),r}}function Nf(n,e=""){if(n.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function ss(n,e){let t=[];for(let r of e){let i=r.type==="agent"?await Df(n,r.agent):await Rf(n,r.project,r.agent);t.push(i)}return t}async function iP(n,e,t,r){if(t)return[await Tf(e,t)];if(r&&n.agent){let a=(await pi(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return ss(e,a)}if(r){let s=await fi();Nf(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return ss(e,a)}if(n.agent){let a=(await pi(n.agent)).map(c=>({type:"agent",agent:c}));return ss(e,a)}let i=await fi();Nf(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return ss(e,o)}var yi=new VE("skills").description("Manage HarmonyOS skills");yi.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 nt;try{e.start("Fetching skills...");let t=await rs(),r=await zc(t);if(r.length===0){e.stop(),console.log(Of("No skills available."));return}e.succeed(`Fetched ${r.length} skills`);for(let i of r)if(n.long){console.log(Lf(i.enName)),console.log(Mf(i.description));let o=hf(i.enName);o.length>0&&console.log(qE(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName)}catch(t){e.stop(),console.error(gi(t.message)),process.exit(1)}});yi.command("find <keyword>").description("Search skills by keyword").action(async n=>{let e=new nt;try{e.start("Searching skills...");let t=await rs(),r=await Gc(n,t);if(r.length===0){console.log(Of(`No skills found matching '${n}'.`)),e.stop();return}e.succeed(`Found ${r.length} skills.`);for(let i of r)console.log(Lf(i.enName)),console.log(Mf(i.description)),console.log()}catch(t){e.stop(),console.error(gi(t.message)),process.exit(1)}});yi.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 tP(n)}catch(e){console.error(gi(e.message)),process.exit(1)}});yi.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 rP(n.skill,n)}catch(e){console.error(gi(e.message)),process.exit(1)}});var _f=yi;import{Command as sP,InvalidArgumentError as cs}from"commander";import{cyan as as}from"colorette";function Tn(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=Gn(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 el=[800,1500,2500];function oP(n){return new Promise(e=>setTimeout(e,n))}function Ff(){return b()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device."}var rr=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=Z.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(`
|
|
1272
|
+
`)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let i=t[0];return m(as(`Using device serial: ${i}`)),i}if(e&&t.includes(e))return m(as(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let i=this.findDeviceByArg(r,e);if(i)return m(as(`Using device: ${i.name} (${i.serial})`)),i.serial;let o=this.formatConnectedDeviceList(r);throw new Error(`Device '${e}' not found.
|
|
1240
1273
|
Available devices:
|
|
1241
|
-
${
|
|
1242
|
-
${
|
|
1243
|
-
`).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return P.assertCrashFilename(r),!0}catch{return!1}}).filter(r=>t?r.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){g(`Fetching latest crash log file: ${r}`);let o=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];g(`Executing command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log streaming read"),s=nt(i,"Failed to fetch crash log content");if(s)throw s;return i.exitCode!==0&&i.stderr&&console.error(`Warning: Failed to fetch crash logs: ${i.stderr}`),i.stdout+i.stderr}};import{cyan as li,red as rc}from"colorette";import kf from"ora";function Rf(n){try{return P.parsePositiveInteger(n,"tail")}catch{throw new nc("`tail` must be a positive integer.")}}function tc(n,e){try{return P.parseDurationToSeconds(n,e)}catch{throw new nc(`${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 Mf(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.");P.assertRelativeTimeRange(n.from,n.to)}async function Of(n,e,t,r,o){return t.crash?await n.getCrashLog(e,t.bundleName):await n.getHilog(e,{level:t.level,bundleName:t.bundleName,keyword:t.keyword,isFollow:!!t.follow,tail:t.tail,fromSeconds:r,toSeconds:o})}function Nf(n,e,t,r){let o=P.filterLogsByRelativeWindow(n,t,r);return e.tail?P.getLastLines(o,e.tail):o}var Lf=new xf("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(rc(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=>tc(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>tc(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await _f(n)});async function _f(n){let e=kf({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),Mf(n);let r=n.from,o=n.to,i=await _.new(),s=new rr(i),a=await s.selectDevice(n.device);a||(t(),process.exit(1)),g(li(`deviceId: ${a}`)),g(li(`type: ${n.crash?"Crash logs":"Common logs"}`)),g(li("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await Of(s,a,n,r,o);t(),n.crash&&c&&(c=Nf(c,n,r,o)),c&&console.log(c)}catch(r){t(),console.error(rc(r.message)),process.exit(1)}}var oc=Lf;import cn from"path";import De from"fs";import pi from"process";import uc from"os";import{Command as Jf}from"commander";import{green as cc,red as di,cyan as Kf,yellow as ui}from"colorette";import F from"fs-extra";import M from"path";import*as ic from"os";import{fileURLToPath as Hf}from"url";var jf={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"}},Ff=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function $f(){let n=import.meta.url,e=Hf(n);if(e.includes("dist")){let i=M.dirname(e),s=M.dirname(i);return M.join(s,"templates","application")}let t=M.dirname(e),r=M.dirname(t),o=M.dirname(r);return M.join(o,"templates","application")}function sc(n,e){F.mkdirSync(e,{recursive:!0});for(let t of F.readdirSync(n,{withFileTypes:!0})){let r=M.join(n,t.name),o=M.join(e,t.name);if(t.isDirectory()){sc(r,o);continue}F.existsSync(o)||(F.mkdirSync(M.dirname(o),{recursive:!0}),F.copyFileSync(r,o))}}function an(n,e){let t=F.readFileSync(n,"utf-8"),r=t;for(let[o,i]of e)r=r.replaceAll(o,i);r!==t&&F.writeFileSync(n,r,"utf-8")}function Bf(n,e){if(e===22)return;let t=jf[e];t&&(an(M.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),an(M.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),an(M.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function Wf(n){return Ff.filter(t=>!F.existsSync(M.join(n,t))).length===0}function Uf(){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 zf(n){return ic.platform()==="darwin"?M.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):M.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function qf(n,e){let t=zf(e);if(!F.existsSync(t))return!1;let r=[["AppScope/resources/base/media/background.png","AppScope/resources/base/media/background.png"],["AppScope/resources/base/media/foreground.png","AppScope/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/background.png"],["entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/startIcon.png","entry/src/main/resources/base/media/startIcon.png"]];for(let[o,i]of r){let s=M.join(t,o),a=M.join(n,i);F.existsSync(s)&&(F.mkdirSync(M.dirname(a),{recursive:!0}),F.copyFileSync(s,a))}return!0}function Vf(n){let e=Uf(),t=["AppScope/resources/base/media/background.png","AppScope/resources/base/media/foreground.png","entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/startIcon.png"];for(let r of t){let o=M.join(n,r);F.mkdirSync(M.dirname(o),{recursive:!0}),F.writeFileSync(o,e)}}function Gf(n,e){e&&qf(n,e)||Vf(n)}function Yf(n){let e=[M.join(n,"gitignore.txt"),M.join(n,"entry","gitignore.txt")];for(let t of e)F.existsSync(t)&&F.renameSync(t,t.replace(/\/gitignore\.txt$/,"/.gitignore"))}function ac(n,e,t,r,o){let i=$f();if(!F.existsSync(i))throw new Error(`Template directory not found: ${i}`);F.mkdirSync(n,{recursive:!0}),sc(i,n),Yf(n),Gf(n,o),an(M.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),an(M.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),Bf(n,r);let s=Wf(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function Zf(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 Xf(n){if(n.length<7||n.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${n.length}`);if(n.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let e=n.split(".");if(e.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let t=/^[a-zA-Z0-9_]+$/;for(let r=0;r<e.length;r++){let o=e[r];if(!t.test(o))throw new Error(`Segment "${o}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(r===0){if(!/^[a-zA-Z]/.test(o))throw new Error(`First segment "${o}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(o))throw new Error(`Segment "${o}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(o))throw new Error(`Segment "${o}" must end with a letter or digit.`)}}function pc(n){if(uc.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function lc(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=uc.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(n)){let i=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new Error(`Project path can only contain ${i}.`)}let r=pc(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 Qf(n){let e=n,t=cn.parse(n).root;for(;e!==t;){if(De.existsSync(e))return e;e=cn.dirname(e)}return De.existsSync(t)?t:null}function dc(n){let e=Qf(n);if(!e)throw new Error(`No existing parent directory found for '${n}'. Cannot create project directory.`);try{De.accessSync(e,De.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=cn.join(e,`.deveco_write_test_${Date.now()}`);try{De.writeFileSync(t,"test"),De.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function eh(n){return`com.example.${n.toLowerCase()}`}function th(n,e){if(e){let o=pc(e),i=cn.resolve(o);if(De.existsSync(i)){if(De.readdirSync(i).length>0)throw new Error(`Directory '${i}' is not empty. Cannot create project here.`)}else dc(i);return i}let t=pi.cwd(),r=cn.join(t,n);if(De.existsSync(r))throw new Error(`Directory '${r}' already exists. Cannot create project here.`);return dc(r),r}function nh(n,e){let t=e?.getMaxApiLevel(),r=23;if(n.apiLevel){let o=Number(n.apiLevel);if(!Number.isInteger(o)||o<17)throw new Error(`Invalid API version ${n.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(o>t)throw new Error(`Invalid API version ${n.apiLevel}. Your SDK supports API version 17-${t}`)}else if(o>r){let i=I()?"commandLineTools":"DevEco Studio";throw new Error(`Invalid API version ${n.apiLevel}. Without ${i}, supported range is API version 17-${r}`)}return o}return t!==void 0?t:23}async function rh(){try{return await _.new()}catch(n){let e=n,t=I()?"Toolchain not found":"DevEco Studio not found";console.error(ui(`${t}: ${e.message}`)),I()?console.log(ui("Please install commandLineTools. Use placeholder API level instead.")):console.log(ui("Use placeholder API level instead."));return}}var oh=new Jf("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(di("Error: --app-name is required")),pi.exit(1));let e=n.appName;Zf(e);let t=n.bundleName||eh(e);Xf(t),n.projectPath&&lc(n.projectPath);let r=th(e,n.projectPath);lc(r),console.log(Kf("Initializing project...")),console.log(`Project path: ${r}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let o=await rh(),i=nh(n,o);console.log(`API level: ${i}`);let s=o?.devecoStudioPath,a=ac(r,e,t,i,s);console.log(`
|
|
1244
|
-
`+
|
|
1245
|
-
Failed to create project.`)),console.error(
|
|
1246
|
-
`)+`
|
|
1247
|
-
`,"utf8")}catch{}}function wi(n,e,t="[Cleanup]"){try{let r=L.dirname(n);if(!U.existsSync(r))return;let o=Date.now();for(let i of U.readdirSync(r,{withFileTypes:!0}))i.isDirectory()&&Th(L.join(r,i.name),o,e,t)}catch{}}function Th(n,e,t,r){try{let{mtimeMs:o}=U.statSync(n);if(e-o<=t)return;U.rmSync(n,{recursive:!0,force:!0});let i=Math.floor((e-o)/1e3);console.error(`${r} Removed expired dir (age ${Math.floor(i/86400)}d ${Math.floor(i%86400/3600)}h): ${n}`)}catch(o){console.error(`${r} Failed to remove expired dir ${n}: ${o}`)}}import*as T from"fs";import*as ur from"path";var Ac="mcp-server.log",xh="mcp-server",kh={maxSize:10*1024*1024,maxFiles:4},bi=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={...kh,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=lr(),this.currentLogFile=ur.join(this.logDir,Ac),T.existsSync(this.logDir)||T.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${o}`}getRotatedFileName(e,t){return ur.join(this.logDir,`${xh}-${e}.log.${t}`)}fileExists(e){try{return T.accessSync(e,T.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=T.readdirSync(this.logDir),t=[];for(let o of e)if(o===Ac||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(o)){let i=ur.join(this.logDir,o),s=T.statSync(i);t.push({name:o,mtime:s.mtime,path:i})}t.sort((o,i)=>i.mtime.getTime()-o.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let o=r;o<t.length;o++)try{T.unlinkSync(t[o].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&T.unlinkSync(t);for(let o=this.rotationOptions.maxFiles-1;o>=1;o--){let i=this.getRotatedFileName(e,o),s=this.getRotatedFileName(e,o+1);this.fileExists(i)&&T.renameSync(i,s)}let r=this.getRotatedFileName(e,1);T.renameSync(this.currentLogFile,r),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let e=T.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=T.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{T.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...r){if(this.mode==="silent"||n.LEVEL_ORDER[e]<n.LEVEL_ORDER[this.minLevel])return;let o=r.map(c=>typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),i=o?`${t} ${o}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] ${i}
|
|
1248
|
-
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);T.writeSync(this.fd,c),this.checkRotation(c.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{T.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},ie=null;function Si(n=!1){ie&&ie.dispose(),ie=new bi(n)}function Tc(){ie&&(ie.dispose(),ie=null)}function xc(){ie&&ie.flush()}function kc(){return ie?.getLogFilePath()??null}function Rc(){return ie?.getLogDirectory()??null}function dr(){return ie||Si(!1),ie}var f={debug:(n,...e)=>dr().debug(n,...e),info:(n,...e)=>dr().info(n,...e),warn:(n,...e)=>dr().warn(n,...e),error:(n,...e)=>dr().error(n,...e)};function Mc(n){return"method"in n&&!("id"in n)}import{spawn as Oh}from"child_process";import{EventEmitter as Nh}from"events";import*as It from"fs";import*as Bc from"path";import*as Oc from"util";var Pi="";function Nc(n){if(!n||n==="auto"||n==="stdout"||n==="none"){Pi="";return}Pi=n}function Lc(){return Pi||(Rc()??"")}function pr(n,...e){if(e.length===0)return n;try{return Oc.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var d={info(n,...e){f.info(`[lsp] ${pr(n,...e)}`)},warn(n,...e){f.warn(`[lsp] ${pr(n,...e)}`)},error(n,...e){f.error(`[lsp] ${pr(n,...e)}`)},debug(n,...e){f.debug(`[lsp] ${pr(n,...e)}`)}};import*as pn from"fs";import*as mn from"os";import*as Dt from"path";import Mh from"json5";var Rh={EXIT:"exit",INITIALIZED:"initialized",ON_DID_CHANGE_PACKAGE_DEPENDENCIES:"aceProject/onDidChangePackageDependencies",ON_ASYNC_DID_OPEN:"aceProject/onAsyncDidOpen",ON_ASYNC_DID_CHANGE:"aceProject/onAsyncDidChange",DID_CLOSE:"textDocument/didClose",ON_ASYNC_HOVER:"aceProject/onAsyncHover",ON_ASYNC_DEFINITION:"aceProject/onAsyncDefinition",ON_ASYNC_FIND_USAGES:"aceProject/onAsyncFindUsages"},mr={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",DEFINITION:"textDocument/definition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles"},b={...Rh,...mr},O="2.0",se={EXIT:"exit",INITIALIZED:"initialized",EMPTY:"empty",ON_DID_CHANGE_PACKAGE_DEPENDENCIES:"onDidChangePackageDependencies",ON_ASYNC_DID_OPEN:"onAsyncDidOpen",ON_ASYNC_DID_CHANGE:"onAsyncDidChange",DID_CLOSE:"didClose",ON_ASYNC_HOVER:"onAsyncHover",ON_ASYNC_DEFINITION:"onAsyncDefinition",ON_ASYNC_FIND_USAGES:"onAsyncFindUsages"};var _c=8192,Ei=100,Hc=.03,jc=.7,un=900*1e3;function oe(n){if(!pn.existsSync(n))return null;try{let e=pn.readFileSync(n,"utf-8");return e.trim()?Mh.parse(e):null}catch{return null}}function Fc(n,e){let t=Math.floor(mn.totalmem()/1048576),r=Math.floor(t*jc),o,i;e!==void 0&&Number.isFinite(e)&&e>0?(o=e,i=`override(${e})`):(o=_c,n>Ei&&(o+=(n-Ei)*Hc*1024),i=`formula(moduleCount=${n})`);let s=r>0&&o>r;s&&(o=r);let a=Math.round(o);return d.info(`[computeLspServerMaxSize] source=${i}, physicalTotal=${t}MB, physicalCap(70%)=${r}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function Ce(n){try{let e=Dt.resolve(n),t=new URL(`file://${e}`).toString();if(mn.platform()==="win32"){let r=t.match(/^file:\/\/\/([A-Za-z]):/);if(r){let o=r[1].toUpperCase(),i=t.substring(`file:///${r[1]}:`.length);t=`file:///${o}%3A${i}`}}return t}catch{return n}}function fr(n){return n&&n.replace(/\\/g,"/")}function G(n){let e=Dt.normalize(n).replace(/\\/g,"/");if(mn.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function $c(n){return Dt.join(n,"build-profile.json5")}var hr=class extends Nh{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;ensureDirectories(){let t=Bc.join(this.config.logPath,"lspLog");return It.existsSync(t)||It.mkdirSync(t,{recursive:!0}),It.existsSync(this.config.indexingDataLocation)||It.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let r=this.ensureDirectories();d.info(`[LspClient] serverMaxSize=${t}MB`);let o=G(r),i=["--expose-gc",`--max-old-space-size=${t}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${o}`,this.config.serverPath,"--stdio",`--logger-path=${o}`,"--logger-level=TRACE"];d.info(`[LspClient] Starting process: node ${i.join(" ")}`);let s=this.config.nodePath;d.info(`[LspClient] nodePath: ${s}`),this.process=Oh(s,i,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0}),this.process.stdout?.on("data",a=>{this.handleData(a)}),this.process.stderr?.on("data",a=>{let c=a.toString("utf8").trim();d.error(`[LspClient] stderr: ${c}`),this.isClosing||this.emit("error",new Error(`[LspClient] stderr: ${c}`))}),this.process.on("exit",a=>{d.info(`[LSP EXIT] code=${a}`),this.isClosing||this.emit("error",new Error(`LSP process exited with code ${a}`))}),await new Promise(a=>setTimeout(a,500)),d.info("[LspClient] start lsp process success")}sendRaw(t,r){if(!this.process?.stdin?.writable){d.warn("[LspClient] Cannot send message, stdin not writable");return}d.info(`[LspClient] send message: ${r}`);let o=this.buildLspMessage(t);this.process.stdin.write(o,"utf8")}send(t,r,o){let i={jsonrpc:"2.0",method:t,params:r};o!==void 0&&(i.id=o),this.sendRaw(JSON.stringify(i),t)}buildLspMessage(t){return`Content-Length: ${Buffer.from(t,"utf8").length}\r
|
|
1274
|
+
${o}`)}if(r.length===1){let i=r[0];return m(as(`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(Ff());return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error(Ff());return e}async getPidForBundle(e,t,r){m(`Retrieving PID for bundle ${r}`),E.assertBundleNameStrict(r);let i=await Oe(e,["-t",t,"shell","pidof",r]),o=Tn(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 Oe(e,["-t",t,"shell","hilog","-G",r]),o=Tn(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&&(E.assertHilogToken(e.tag,"tag"),r.push("-T",e.tag)),e.level&&(E.assertHilogLevel(e.level),r.push("-L",e.level)),e.domain&&(E.assertHilogToken(e.domain,"domain"),r.push("-D",e.domain)),t&&r.push("-P",t),e.keyword&&(E.assertHilogKeyword(e.keyword),r.push("-e",E.quotePosixShellArg(e.keyword))),r.join(" ")}async followHilog(e,t,r,i,o){let a=await _u(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+el.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||Gn(a.stderr)!=="transient"||c>=s-1)return a;m(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${el[c]}ms`),await oP(el[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=Tn(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=E.filterLogsByRelativeWindow(c.stdout||c.stderr,r.fromSeconds,r.toSeconds);d=E.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=Tn(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=E.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return d=E.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=Tn(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=Tn(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:
|
|
1275
|
+
${o.stdout}`),this.parseCrashLogFilenames(o.stdout,r)}parseCrashLogFilenames(e,t){return e.split(`
|
|
1276
|
+
`).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return E.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=Tn(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 tl,red as Hf}from"colorette";import aP from"ora";function cP(n){try{return E.parsePositiveInteger(n,"tail")}catch{throw new cs("`tail` must be a positive integer.")}}function jf(n,e){try{return E.parseDurationToSeconds(n,e)}catch{throw new cs(`${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 lP(n){try{return E.assertHilogLevel(n),n}catch{throw new cs("`level` must be one of: D, I, W, E, F.")}}function dP(n){try{return E.assertBundleNameStrict(n),n}catch(e){throw new cs(e.message)}}function uP(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.");E.assertRelativeTimeRange(n.from,n.to)}async function pP(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 fP(n,e,t,r){let i=E.filterLogsByRelativeWindow(n,t,r);return e.tail?E.getLastLines(i,e.tail):i}var mP=new sP("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(Hf(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",lP).option("--bundle-name <bundle-name>","Filter by application bundle name",dP).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",cP).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>jf(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>jf(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await hP(n)});async function hP(n){let e=aP({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),uP(n);let r=n.from,i=n.to,o=await A.new(),s=new rr(o),a=await s.selectDevice(n.device);a||(t(),process.exit(1)),m(tl(`deviceId: ${a}`)),m(tl(`type: ${n.crash?"Crash logs":"Common logs"}`)),m(tl("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await pP(s,a,n,r,i);t(),n.crash&&c&&(c=fP(c,n,r,i)),c&&console.log(c)}catch(r){t(),console.error(Hf(r.message)),process.exit(1)}}var $f=mP;import vi from"path";import At from"fs";import il from"process";import Yf from"os";import{Command as TP}from"commander";import{green as Gf,red as nl,cyan as RP,yellow as rl}from"colorette";import ie from"fs-extra";import _ from"path";import*as Bf from"os";import{fileURLToPath as gP}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"}},yP=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function wP(){let n=import.meta.url,e=gP(n);if(e.includes("dist")){let o=_.dirname(e),s=_.dirname(o);return _.join(s,"templates","application")}let t=_.dirname(e),r=_.dirname(t),i=_.dirname(r);return _.join(i,"templates","application")}function Wf(n,e){ie.mkdirSync(e,{recursive:!0});for(let t of ie.readdirSync(n,{withFileTypes:!0})){let r=_.join(n,t.name),i=_.join(e,t.name);if(t.isDirectory()){Wf(r,i);continue}ie.existsSync(i)||(ie.mkdirSync(_.dirname(i),{recursive:!0}),ie.copyFileSync(r,i))}}function wi(n,e){let t=ie.readFileSync(n,"utf-8"),r=t;for(let[i,o]of e)r=r.replaceAll(i,o);r!==t&&ie.writeFileSync(n,r,"utf-8")}function vP(n){if(Uf[n])return Uf[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function SP(n,e){if(e===22)return;let t=vP(e);t&&(wi(_.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),wi(_.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),wi(_.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function bP(n){return yP.filter(t=>!ie.existsSync(_.join(n,t))).length===0}function EP(){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 PP(n){return Bf.platform()==="darwin"?_.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):_.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function CP(n,e){let t=PP(e);if(!ie.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=_.join(t,i),a=_.join(n,o);ie.existsSync(s)&&(ie.mkdirSync(_.dirname(a),{recursive:!0}),ie.copyFileSync(s,a))}return!0}function IP(n){let e=EP(),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=_.join(n,r);ie.mkdirSync(_.dirname(i),{recursive:!0}),ie.writeFileSync(i,e)}}function AP(n,e){e&&CP(n,e)||IP(n)}function DP(n){let e=[_.join(n,"gitignore.txt"),_.join(n,"entry","gitignore.txt")];for(let t of e)if(ie.existsSync(t)){let r=_.dirname(t);ie.renameSync(t,_.join(r,".gitignore"))}}function zf(n,e,t,r,i){let o=wP();if(!ie.existsSync(o))throw new Error(`Template directory not found: ${o}`);ie.mkdirSync(n,{recursive:!0}),Wf(o,n),DP(n),AP(n,i),wi(_.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),wi(_.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),SP(n,r);let s=bP(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function kP(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 Jf(n){if(Yf.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function Vf(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=Yf.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=Jf(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 xP(n){let e=n,t=vi.parse(n).root;for(;e!==t;){if(At.existsSync(e))return e;e=vi.dirname(e)}return At.existsSync(t)?t:null}function qf(n){let e=xP(n);if(!e)throw new Error(`No existing parent directory found for '${n}'. Cannot create project directory.`);try{At.accessSync(e,At.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=vi.join(e,`.deveco_write_test_${Date.now()}`);try{At.writeFileSync(t,"test"),At.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function NP(n){return`com.example.${n.toLowerCase()}`}function LP(n,e){if(e){let i=Jf(e),o=vi.resolve(i);if(At.existsSync(o)){if(At.readdirSync(o).length>0)throw new Error(`Directory '${o}' is not empty. Cannot create project here.`)}else qf(o);return o}let t=il.cwd(),r=vi.join(t,n);if(At.existsSync(r))throw new Error(`Directory '${r}' already exists. Cannot create project here.`);return qf(r),r}function OP(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){let o=b()?"commandLineTools":"DevEco Studio";throw new Error(`Invalid API version ${n.apiLevel}. Without ${o}, supported range is API version 17-${r}`)}return i}return t!==void 0?t:23}async function MP(){try{return await A.new()}catch(n){let e=n,t=b()?"Toolchain not found":"DevEco Studio not found";console.error(rl(`${t}: ${e.message}`)),b()?console.log(rl("Please install commandLineTools. Use placeholder API level instead.")):console.log(rl("Use placeholder API level instead."));return}}var _P=new TP("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(nl("Error: --app-name is required")),il.exit(1));let e=n.appName;kP(e);let t=n.bundleName||NP(e);E.assertBundleNameStrict(t),n.projectPath&&Vf(n.projectPath);let r=LP(e,n.projectPath);Vf(r),console.log(RP("Initializing project...")),console.log(`Project path: ${r}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let i=await MP(),o=OP(n,i);console.log(`API level: ${o}`);let s=i?.devecoStudioPath,a=zf(r,e,t,o,s);console.log(`
|
|
1277
|
+
`+Gf("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(Gf("Template integrity check passed."))}catch(e){let t=e;console.error(nl(`
|
|
1278
|
+
Failed to create project.`)),console.error(nl(t.message)),il.exit(1)}}),Kf=_P;import{Command as WP}from"commander";import{red as zP,cyan as rm}from"colorette";import FP from"fs";import ls from"path";import{cyan as jP}from"colorette";import*as ds from"smol-toml";var ir=FP.promises;async function HP(n){try{let e=await ir.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 $P(n){try{let e=await ir.readFile(n,"utf8");return e.trim()===""?{}:ds.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 UP(n,e){let t=ls.dirname(n);await ir.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await ir.writeFile(n,r,"utf8")}async function BP(n,e){let t=ls.dirname(n);await ir.mkdir(t,{recursive:!0});let r=ds.stringify(e);await ir.writeFile(n,r,"utf8")}function Xf(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function Zf(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 Qf(n,e){return n.format==="codex"?$P(e):HP(e)}async function em(n,e,t){return n.format==="codex"?BP(e,t):UP(e,t)}async function tm(n,e,t=!1){let r=jt[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(jt).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 Qf(r,r.globalConfigPath);if(Xf(i,r.mcpServersKey,dt)&&!t)return console.log(`MCP server ${dt} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let o=go(r,void 0);return Zf(i,r.mcpServersKey,dt,o,t),await em(r,r.globalConfigPath,i),console.log(`MCP server ${dt} 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 ol(n,e,t=!1){let r=jt[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(jt).join(", ")}`};let i=ls.isAbsolute(r.projectConfigPath)?r.projectConfigPath:ls.join(e,r.projectConfigPath);try{let o=await Qf(r,i);if(Xf(o,r.mcpServersKey,dt)&&!t)return console.log(`MCP server ${dt} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:n,installType:"project"};let s=go(r,e);return Zf(o,r.mcpServersKey,dt,s,t),await em(r,i,o),console.log(`MCP server ${dt} 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 nm(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(jP("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 sl="deveco-cli";async function GP(n,e,t){if(n.customPath)return[await Af(sl,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>If(sl,e,s,a,t.force)),...n.agents.map(s=>()=>Cf(sl,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 VP(n,e,t){let r=[];for(let{project:i,agent:o}of n.projectAgents){let s=await ol(o,i,t);r.push(s)}for(let i of n.agents){let o=await ol(i,e,t);r.push(o)}return r}async function qP(n,e){let t=[];for(let r of n){if(!jt[r])continue;let o=await tm(r,process.cwd(),e);t.push(o)}return t}async function YP(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 VP(s,e,r):await qP(s.agents,r);a.length>0&&(console.log(rm("MCP Configuration:")),nm(a))}async function JP(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}=hi(n.path,n.project,n.agent);t&&Gt(t,"Project directory",n.force),e&&Gt(e,"Directory",n.force);let r=await os(n,e,t);if(n.mcp){await YP(r,t,n);return}let i=kf(),o=await GP(r,i,n);console.log(),o.length>0&&(console.log(rm("Skill Installation:")),mi(o))}var KP=new WP("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 JP(n)}catch(e){console.error(zP(e.message)),process.exit(1)}}),im=KP;import{Command as BC}from"commander";import{McpServer as DC}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as TC}from"@modelcontextprotocol/sdk/server/stdio.js";import*as Zt from"path";import*as vm from"fs";import{z as he}from"zod";var us=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 al(){return new us}import*as Ie from"fs";import*as le from"path";import{z as ll}from"zod";function om(n){return"method"in n&&!("id"in n)}import{spawn as XP}from"child_process";import{EventEmitter as ZP}from"events";import*as or from"fs";import*as sm from"path";var Vt=class extends ZP{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;ensureDirectories(){let t=sm.join(this.config.logPath,"lspLog");return or.existsSync(t)||or.mkdirSync(t,{recursive:!0}),or.existsSync(this.config.indexingDataLocation)||or.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let r=this.ensureDirectories();f.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"];f.info(`[LspClient] Starting process: node ${o.join(" ")}`);let s=this.config.nodePath;f.info(`[LspClient] nodePath: ${s}`),this.process=XP(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
|
|
1249
1279
|
\r
|
|
1250
1280
|
${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this.buffer.indexOf(`\r
|
|
1251
1281
|
\r
|
|
1252
|
-
`);if(r===-1)break;let i=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!i){d.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(i[1],10),a=r+4,c=a+s;if(this.buffer.length<c)break;let l=this.buffer.slice(a,c).toString("utf8"),u=this.recoverFramedJson(l);if(u&&u.rest.length>0){d.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${l.length}, restLen=${u.rest.length}`),this.emit("message",u.json),this.buffer=Buffer.concat([Buffer.from(u.rest,"utf8"),this.buffer.slice(c)]);continue}this.emit("message",l),this.buffer=this.buffer.slice(c)}}waitForExitOrTimeout(t){let r=this.process;return!r||r.exitCode!==null||r.signalCode!==null?Promise.resolve():new Promise(o=>{let i=!1,s=()=>{i||(i=!0,clearTimeout(c),r.off("exit",a),o())},a=()=>s();r.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let r=t.search(/\S/);if(r<0||t[r]!=="{"&&t[r]!=="[")return null;let o=0,i=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(i){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(i=!1);continue}if(c==='"'){i=!0;continue}if(c==="{"||c==="["){o++;continue}if((c==="}"||c==="]")&&(o--,o===0)){let l=t.slice(r,a+1),u=t.slice(a+1);return{json:l,rest:u}}}return null}stop(){this.isClosing=!0;let t=this.process;if(!t)return;if(this.process=null,t.exitCode===null&&t.signalCode===null)try{t.kill()}catch{}}};var gr=class{callbacks=new Map;timeouts=new Map;register(e,t){this.callbacks.set(e,t)}emit(e,t,r){d.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let o=this.callbacks.get(e);o&&(o(t,r),this.callbacks.delete(e))}registerTimeout(e,t,r,o){this.timeouts.has(e)&&clearTimeout(this.timeouts.get(e));let i=setTimeout(()=>{d.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`),o(),this.timeouts.delete(e)},r);this.timeouts.set(e,i)}clearTimeout(e){let t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e))}deleteCallback(e){this.callbacks.delete(e)}hasCallback(e){return this.callbacks.has(e)}clear(e){this.clearTimeout(e),this.callbacks.delete(e)}};var yr=class{uri;messages=[];receivedTypes=new Set;uniqueMessages=new Set;isFromEditor=!1;constructor(e){this.uri=e}setReceivedType(e){this.receivedTypes.add(e)}addMessage(e,t){this.receivedTypes.add(e);let r=`${e}:${t}`;if(this.uniqueMessages.has(r)){d.info(`[Diagnostic] addMessage: duplicate message=${r}`);return}this.uniqueMessages.add(r),this.messages.push(new Di(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)}},Di=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var vr=class{map=new Map;register(e,t){let r=this.map.get(e);r||(r=new Set,this.map.set(e,r)),r.add(t)}unregister(e,t){let r=this.map.get(e);r&&(t!==void 0?r.delete(t):r.clear(),r.size===0&&this.map.delete(e))}invoke(e,...t){let r=this.map.get(e);if(r)for(let o of r)try{o(...t)}catch(i){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,i)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function y(n){return typeof n=="object"&&n!==null}function Ii(n){return Array.isArray(n)&&n.every(e=>typeof e=="string")}function Lh(n){if(!y(n))return!1;let e=n.textDocument;return y(e)&&typeof e.uri=="string"}function _h(n){return y(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function Hh(n){return y(n)&&typeof n.moduleName=="string"&&typeof n.current=="number"&&typeof n.total=="number"?`indexing module '${n.moduleName}', ${n.current} of total ${n.total} modules`:`params=${JSON.stringify(n??null)}`}var wr=class n{client;isInitialized=!1;stopOnce=null;callbacks=new vr;requestCallbacks=new gr;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;static EXPECTED_DIAGNOSTIC_TYPES=new Set([1e3,2e3,3e3,3001]);constructor(e){this.client=new hr(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{d.info("[ClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.EXIT,params:{}}),se.EXIT),d.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),d.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(b.BROADCAST),this.callbacks.register(b.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(b.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(b.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(b.INDEXING_PROGRESS_UPDATE,e)}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}sendInitialize(e,t){this.client.send("initialize",e,t)}sendInitialized(e){this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.INITIALIZED,params:{editors:e}}),se.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:O,id:0,result:{}}),se.EMPTY)}sendAsyncRequest(e,t,r,o){if(!y(t)){d.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!Lh(t)){d.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof r!="number"){d.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(r)}`);return}let i=t.textDocument.uri,s=Ce(i);t.textDocument.uri=s,delete t.requestId;let a=o??e;d.info(`[LSP] sendAsyncRequest ${a}, filePath: ${i}`),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:e,params:{params:t,requestId:r}}),a)}onDidChangeWatchedFiles(e){if(d.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let r of e){if(!_h(r)){d.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),b.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!y(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){d.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;d.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),se.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let o=Ce(t);e.textDocument.uri=o,d.info(`[LSP] onAsyncOpenFile, uri: ${o}`);let i=this.diagnosticMap.get(o);i||(i=new yr(o),this.diagnosticMap.set(o,i),this.registerDiagnosticTimeout(o,mr.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(i.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),se.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=Ce(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,mr.PUBLISH_DIAGNOSTICS)),d.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),se.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=Ce(e);d.info(`[LSP] didClose, uri: ${r}`);let o=this.diagnosticMap.get(r);if(!t&&(!o||o.isFromEditor)){d.info(`[LSP] closeFile skip, !diagnostic: ${!o}, isFromEditor: ${o?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.DID_CLOSE,params:{textDocument:{uri:r}}}),se.DID_CLOSE)}getDiagnosticMessage(e){let t=Ce(e),r=this.diagnosticMap.get(t);return r?r.getMessages():[]}clear(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){try{let t=JSON.parse(e);this.handleLspMessage(t)}catch(t){let r=t instanceof Error?t.message:String(t);d.error(`[LSP] JSON parse error: ${r}, raw: ${e}`)}}handleError(e){let t=this.getPendingDiagnosticUris();if(t.length>0){let r=JSON.stringify({message:e.message,severity:"Error",severityStr:"Error"});for(let o of t)this.finalizeDiagnostic(o,b.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:O,method:b.ARKTS_ERROR,params:{message:e.message}})}handleLspMessage(e){let t=e.method;t!==void 0&&(!this.isInitialized&&this.handlePreInitMessage(t,e)||this.handlePostInitMessage(t,e))}handlePreInitMessage(e,t){switch(e){case b.MODULE_INIT_FINISH:return d.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(b.MODULE_INIT_FINISH),this.callbacks.unregister(b.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case b.INDEXING_PROGRESS_UPDATE:return d.info(`[LSP] onIndexingProgressUpdate: ${Hh(t.params)}`),this.callbacks.invoke(b.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case b.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case b.ON_PACKAGE_CHANGE_FINISH:d.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case b.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case b.ON_ASYNC_HOVER:this.handleAsyncResponse(t,b.HOVER);return;case b.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,b.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case b.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,b.REFERENCES);return;default:d.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){d.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;y(t)&&y(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){d.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,r={jsonrpc:O,method:b.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){d.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(r);return}if(!(t.length>0&&t[0]===!0)){d.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(r);return}d.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){d.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let r=e.params;if(!y(r)){d.warn("[LSP] aceProject/onAsyncHover message invalid");return}let o=r.requestId;if(typeof o!="number"){d.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(o,t,r)}handleForceOpenFile(e){if(!e){d.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,b.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){d.info("[LSP] publishDiagnostics uri is null");return}let r=e.version??-1;if(r===-1)return;let o=this.diagnosticMap.get(t);if(!o){d.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let i=e.diagnostics||[];i.length!==0?i.forEach(s=>{this.normalizeDiagnostic(s),o.addMessage(r,JSON.stringify(s))}):o.setReceivedType(r),o.hasReceivedAllTypes(n.EXPECTED_DIAGNOSTIC_TYPES)&&this.finalizeDiagnostic(t,b.PUBLISH_DIAGNOSTICS,o.getMessages())}normalizeDiagnostic(e){if(delete e.source,e.severity!==void 0){let t=typeof e.severity=="number"?e.severity:parseInt(e.severity),r={1:"Error",2:"Warning",3:"Information",4:"Hint"};e.severityStr=r[t]||"Unknown",e.severity=e.severityStr}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let r=e[t];r&&typeof r.line=="number"&&(r.line=r.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,n.DIAGNOSTIC_TIMEOUT_MS,()=>{let r=this.diagnosticMap.get(e),o=r?r.getMessages():[];this.finalizeDiagnostic(e,t,o,o.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,o){let i={uri:e,diagnostics:r,...o?{errorMessage:o}:{}};this.requestCallbacks.emit(e,t,i),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import Ci from"path";import*as Cr from"path";var br=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var Sr=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var Pr=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var Er=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Dr=class{typeSetting=new Pr;parameterNames=new Er};var Ir=class{constructor(e,t,r,o){this.rootUri=e;this.lspServerWorkspacePath=G(Cr.dirname(t)),this.indexingDataLocation=G(o),this.loggerPath=G(Cr.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new br;gutterIconsSetting=new Sr;inlayHintsSetting=new Dr;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Wc from"path";var fn=class{productName="default";buildModeName="debug";targetName="default";arkTSVersion="1.1";resourceDirectories=[];targetESVersion="ES2021";maxFlowDepth=2e3;caseSensitiveCheck=!0;tsImportSendable=!1;compatibleSdkVersionStage="";useNormalizedOHMUrl=!0;reExportCheckMode="noCheck";skipOhModulesLint=!1;byteCodeHar=!0;obfuscationRuleOptionsEnable=!1;enableStrictCheckOHModules=!1;sourceRoots=[];constructor(e){e&&this.resourceDirectories.push(G(Wc.join(e,"src","main","resources")))}};var jh="OS",Ct=class{deviceType=[5];aceLoaderPath;modulePath;jsComponentType="declarative";sdkJsPath;compatibleSdkVersion;compatibleSdkLevel;compileSdkLevel;compileSdkVersion="6.0.1.112";compileSdkType="Release";syscap={NDeviceSysCaps:[],addedSysCaps:[]};apiType="stageMode";hosSdkPath;runtimeOs=`Harmony${jh}`;moduleName;moduleType;compileMode="jsbundle";crossPlatform=!1;ignoreCrossPlatform=!1;packageManagerType="ohpm";permissions=[];testPermissions=[];buildProfileParam;appParam={bundleType:"app"};packageName;projectType="OHOS";projectName;moduleDependencies;moduleJsonParam=null;globalDeclarationFiles=[];constructor(e){e?(this.modulePath=e,this.buildProfileParam=new fn(e)):this.buildProfileParam=new fn}toString(){return JSON.stringify(this)}};var At=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as ae from"path";import*as kt from"fs";var Ar=class{modulePath;dependencies={};dynamicDependencies={}};var ot=class{registryType;resolved;name;version;type;constructor(e){let t=typeof e=="object"&&e!==null?e:{};this.name=typeof t.name=="string"?t.name:"",this.version=typeof t.version=="string"?t.version:"",typeof t.registryType=="string"?this.registryType=t.registryType:this.registryType=typeof t.path=="string"?"local":"ohpm",typeof t.resolved=="string"?this.resolved=t.resolved:typeof t.storePath=="string"?this.resolved=t.storePath:this.resolved="",this.type=typeof t.type=="string"?t.type:void 0}};var Tt=class{constructor(e,t,r){this.projectPath=e;this.moduleName=t;this.modulePath=r}projectPath;moduleName;modulePath;dependencies=[];devDependencies=[];dynamicDependencies=[];finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[]};import*as Ae from"path";import*as Tr from"fs";var xt=class{name="";version="";storePath="";dependencyPath="";path=""};var A={HVIGOR_CACHE:".hvigor",DEPENDENCY:"dependencyMap",JSON5:".json5",KEY_DEPENDENCY:"dependencies",KEY_DYNAMIC_DEPENDENCY:"dynamicDependencies",KEY_DEV_DEPENDENCY:"devDependencies",OH_MODULES_PATH:"oh_modules",OHPM_PATH:".ohpm",LOCK_JSON5_FILE:"lock.json5",OH_PACKAGE_JSON5:le.OH_PACKAGE_JSON5},hn=`${A.HVIGOR_CACHE}/${A.DEPENDENCY}`,it=`${A.DEPENDENCY}${A.JSON5}`,RC=le.SYNC_OUTPUT_PATH;var gn=class n{dependencyPath;modulePath;projectPath;static FILE_DEPENDENCY_PREFIX="file:";static PARAMETER_PREFIX="@param:";fileSpecPattern;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;static PACKAGE_JSON_PARSER_MAP=new Map;dependencies=[];devDependencies=[];dynamicDependencies=[];static getInstance(e,t,r){let o=this.PACKAGE_JSON_PARSER_MAP.get(e);return o||(o=new n(e,t,r),this.PACKAGE_JSON_PARSER_MAP.set(e,o)),o}constructor(e,t,r){this.dependencyPath=e,this.modulePath=t,this.projectPath=r,this.fileSpecPattern=n.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=Ae.join(this.dependencyPath,A.OH_PACKAGE_JSON5),r=oe(t);r&&(this.dependencies=this.getDependencyList(r,A.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(r,A.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(r,A.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let r=[];if(!y(e))return r;let o=e[t];if(!y(o))return r;for(let[i,s]of Object.entries(o)){if(typeof s!="string"){d.error(`${i} package dependency value is not String ${t}`);continue}let a=new xt;a.name=i;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(n.PARAMETER_PREFIX)||this.parseDependencyPath(i,c,a,!1),r.push(a)}return r}parseDependencyPath(e,t,r,o){if(!(!e||!t))try{let i=Ae.normalize(Ae.join(this.modulePath,A.OH_MODULES_PATH,e));if(!(t.startsWith(n.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){r.dependencyPath=i;return}if(r.path=t,this.fileNameForOhpm.test(t)){r.dependencyPath=i;return}let s=t;if(t.startsWith(n.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(n.FILE_DEPENDENCY_PREFIX.length)),Ae.isAbsolute(s)){r.dependencyPath=i;return}if(!o){let a=Ae.resolve(this.modulePath,s);i=P.ensurePathWithinRoot(this.projectPath,a)}Tr.existsSync(i)&&Tr.statSync(i).isDirectory()&&(r.dependencyPath=i)}catch(i){d.error("parser dependency path is invalid",i)}}};import*as yn from"fs";import*as vn from"path";import Fh from"json5";var xr=class n{projectPath;static FILE_DEPENDENCY_PREFIX="file:";fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[];storePathMap=new Map;lockFileCache=null;lockFileParsed=!1;constructor(e=""){this.projectPath=e}parseDependencies(e){if(!this.ensureLockFileParsed())return!1;let t=this.lockFileCache;return this.extractDependencies(t.modules,t.storePathMap,e),!0}ensureLockFileParsed(){if(this.lockFileParsed)return this.lockFileCache!==null;this.lockFileParsed=!0;let e=this.getLockFilePath(),t=this.readLockFile(e);if(!t)return!1;let r=this.validateLockFile(t);return r.valid?(this.lockFileCache={modules:r.modules,storePathMap:this.parseStorePathMap(r.packages)},!0):!1}getLockFilePath(){return vn.join(this.projectPath,A.OH_MODULES_PATH,A.OHPM_PATH,A.LOCK_JSON5_FILE)}readLockFile(e){if(!yn.existsSync(e))return d.error("lock file does not exist"),this.clearDependencies(),null;try{let t=yn.readFileSync(e,"utf8"),r=Fh.parse(t);return r||(d.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return d.error("Error parsing lock.json5:",t),this.clearDependencies(),null}}validateLockFile(e){if(!y(e))return d.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return d.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let r=e.packages;return r?{valid:!0,modules:t,packages:r}:(d.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,r){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,A.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,A.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,A.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!y(e))return t;for(let[r,o]of Object.entries(e)){if(!y(o)){d.error(`${r} value is not json object`);continue}typeof o.storePath=="string"&&t.set(r,o.storePath)}return t}getDependencyList(e,t,r){if(!y(e))return[];for(let[o,i]of Object.entries(e))if(y(i)){let s=typeof i.name=="string"?i.name:"";if(r==="."&&s===""||s===r)return this.getFinalDependencyList(e,t,o)}return[]}getFinalDependencyList(e,t,r){let o=e[r];if(!y(o))return d.error("moduleJsonObject is null"),[];let i=[],s=o[t];if(!y(s))return[];for(let[a,c]of Object.entries(s)){if(!y(c))continue;let l=typeof c.specifier=="string"?c.specifier:"",u=typeof c.version=="string"?c.version:"",h=new xt;h.name=a,h.version=u.startsWith(n.FILE_DEPENDENCY_PREFIX)?u.substring(n.FILE_DEPENDENCY_PREFIX.length):u,this.parseDependencyPath(h,r,a,l,u);let v=`${a}@${u}`;this.storePathMap.has(v)&&(h.storePath=this.storePathMap.get(v)||""),i.push(h)}return i}parseDependencyPath(e,t,r,o,i){let s=P.resolvePathWithinRoot(this.projectPath,vn.join(t,A.OH_MODULES_PATH,r));try{let a=i.startsWith(n.FILE_DEPENDENCY_PREFIX)?i.substring(n.FILE_DEPENDENCY_PREFIX.length):i,c=vn.isAbsolute(a)?P.ensurePathWithinRoot(this.projectPath,a):P.resolvePathWithinRoot(this.projectPath,a);yn.existsSync(c)?(e.path=o,e.dependencyPath=this.fileNameForOhpm.test(i)?s:c):e.dependencyPath=s}catch(a){d.error("Invalid dependency path in lock.json5",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};var st=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=$c(this.projectRoot);try{let t=oe(e);if(typeof t!="object"||t===null)return[];let r=t.modules;return Array.isArray(r)?r.filter(o=>{if(typeof o!="object"||o===null)return!1;let i=o;return typeof i.name=="string"&&typeof i.srcPath=="string"}):[]}catch(t){return d.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};function Uc(n){return y(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var wn=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new st(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=ae.join(t,hn),o=ae.join(r,it);if(!kt.existsSync(r)||!kt.existsSync(o)){let c="Dependency map or JSON not found";return d.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let i=new Tt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(r,i),this.parseLockJson(i);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return d.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:c}}let a=Date.now();for(let c=0;c<s.length;c++){let l=s[c];Uc(l)&&(this.parseSingleModule(l,r,i,e),(c+1)%100===0&&d.info(`[Parser] getAllDependencyMap progress: ${c+1}/${s.length} (${Date.now()-a}ms)`))}return d.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-a}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],r=this.projectPath,o=ae.join(r,hn),i=ae.join(o,it);if(!kt.existsSync(o)||!kt.existsSync(i))return d.warn("[Parser] Dependency map or JSON not found."),t;let s=e&&e.length>0?new Set(e.map(l=>l.trim()).filter(Boolean)):null,a=new Tt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(o,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return d.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let l of c){if(!Uc(l))continue;let u=l.name;if(s&&!s.has(u))continue;let h=P.resolvePathWithinRoot(this.projectPath,l.srcPath),v=ae.join(o,u),D=G(h),k=this.buildModuleDependencies(u,D,v,a);k.moduleName=u,t.push(k)}return t}parseSingleModule(e,t,r,o){let i=e.name,s=P.resolvePathWithinRoot(this.projectPath,e.srcPath),a=ae.join(t,i),c=G(s),l=new Ct(c),u=this.buildModuleDependencies(i,c,a,r);this.parseModuleJson5(c,l);let h=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=i,l.moduleType=i,l.packageName=i,l.moduleDependencies=u,l.moduleJsonParam=new At(h),o.push(l)}buildModuleDependencies(e,t,r,o){let i=new Tt(this.projectPath,e,t);gn.getInstance(r,t,this.projectPath).parseDependency(i),this.parseLockJson(i),i.finalDependencies.push(...o.finalDependencies),i.finalDevDependencies.push(...o.finalDevDependencies),i.finalDynamicDependencies.push(...o.finalDynamicDependencies),i.finalDependencies.push(...i.finalDevDependencies);let a=new Ar;return a.modulePath=t,this.toModuleDependencies(i,a),a}toModuleDependencies(e,t){let r={},o={};for(let i of e.finalDependencies)r[i.name]=new ot(i);for(let i of e.finalDynamicDependencies)o[i.name]=new ot(i);t.dependencies=r,t.dynamicDependencies=o}parseProjectDependencies(e,t){let r=ae.join(e,A.OH_PACKAGE_JSON5);if(!kt.existsSync(r))return;gn.getInstance(e,this.projectPath,this.projectPath).parseDependency(t)}parseLockJson(e){let t=this.getLockJson5Parser();t.parseDependencies(e.moduleName)?(e.finalDependencies=t.finalDependencies,e.finalDevDependencies=t.finalDevDependencies,e.finalDynamicDependencies=t.finalDynamicDependencies):(e.finalDependencies=e.dependencies,e.finalDevDependencies=e.devDependencies,e.finalDynamicDependencies=e.dynamicDependencies)}getLockJson5Parser(){return this.lockJson5Parser||(this.lockJson5Parser=new xr(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=ae.join(e,"src","main","module.json5"),o=oe(r);if(!y(o)||!y(o.module))return;let i=o.module;t.permissions=this.parseRequestPermissions(i),t.deviceType=this.parseDeviceTypes(i)}parseRequestPermissions(e){let t=[];if(y(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)y(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=ae.join(e,"src","main","resources","base","profile","main_pages.json"),r=oe(t);return!y(r)||!Array.isArray(r.src)?[]:r.src.filter(o=>typeof o=="string")}parseSdkJson(e){let t=this.getSdkPkg();!y(t)||!y(t.data)||(typeof t.data.apiVersion=="string"&&(e.compileSdkLevel=t.data.apiVersion),typeof t.data.releaseType=="string"&&(e.compileSdkType=t.data.releaseType),typeof t.data.version=="string"&&(e.compileSdkVersion=t.data.version))}getSdkPkg(){if(this.sdkPkgCache===void 0){let e=ae.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=oe(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!y(t)||!y(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!y(r)||typeof r.compatibleSdkVersion!="string")return;let[o,i]=this.parseBySplit(r.compatibleSdkVersion);e.compatibleSdkVersion=o,e.compatibleSdkLevel=i}getBuildProfile(){if(this.buildProfileCache===void 0){let e=ae.join(this.projectPath,"build-profile.json5");this.buildProfileCache=oe(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,""];let r=e.substring(0,t),o=e.substring(t+1,e.length-1);return[r,o]}parseDeviceTypes(e){return!y(e)||!Array.isArray(e.deviceTypes)?[]:e.deviceTypes.filter(t=>typeof t=="string").map(t=>this.getDeviceType(t))}getDeviceType(e){return{liteWearable:1,wearable:2,tv:3,car:4,phone:5,default:5,smartVision:6,tablet:7,router:8,pc:9,"2in1":10}[e]||0}};var kr=class{constructor(e=[]){this.valueSet=e}valueSet};var Rt=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var zc=(w=>(w[w.File=1]="File",w[w.Module=2]="Module",w[w.Namespace=3]="Namespace",w[w.Package=4]="Package",w[w.Class=5]="Class",w[w.Method=6]="Method",w[w.Property=7]="Property",w[w.Field=8]="Field",w[w.Constructor=9]="Constructor",w[w.Enum=10]="Enum",w[w.Interface=11]="Interface",w[w.Function=12]="Function",w[w.Variable=13]="Variable",w[w.Constant=14]="Constant",w[w.String=15]="String",w[w.Number=16]="Number",w[w.Boolean=17]="Boolean",w[w.Array=18]="Array",w[w.Object=19]="Object",w[w.Key=20]="Key",w[w.Null=21]="Null",w[w.EnumMember=22]="EnumMember",w[w.Struct=23]="Struct",w[w.Event=24]="Event",w[w.Operator=25]="Operator",w[w.TypeParameter=26]="TypeParameter",w))(zc||{}),qc=()=>Object.values(zc).filter(n=>typeof n=="number");var Rr=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Mr=class{applyEdit=!0;workspaceEdit=new Rr;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new kr(qc());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Rt;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Or=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Nr=class{constructor(e=[]){this.valueSet=e}valueSet};var Lr=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var Vc=(S=>(S[S.Text=1]="Text",S[S.Method=2]="Method",S[S.Function=3]="Function",S[S.Constructor=4]="Constructor",S[S.Field=5]="Field",S[S.Variable=6]="Variable",S[S.Class=7]="Class",S[S.Interface=8]="Interface",S[S.Module=9]="Module",S[S.Property=10]="Property",S[S.Unit=11]="Unit",S[S.Value=12]="Value",S[S.Enum=13]="Enum",S[S.Keyword=14]="Keyword",S[S.Snippet=15]="Snippet",S[S.Color=16]="Color",S[S.File=17]="File",S[S.Reference=18]="Reference",S[S.Folder=19]="Folder",S[S.EnumMember=20]="EnumMember",S[S.Constant=21]="Constant",S[S.Struct=22]="Struct",S[S.Event=23]="Event",S[S.Operator=24]="Operator",S[S.TypeParameter=25]="TypeParameter",S))(Vc||{}),Gc=()=>Object.values(Vc).filter(n=>typeof n=="number");var _r=class{completionItemKind=new Nr(Gc());completionItem=new Lr;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Hr=class{synchronization=new Or;completion=new _r;hover={contentFormat:{},dynamicRegistration:{}};signatureHelp={signatureInformation:{},contextSupport:{},dynamicRegistration:{}};references={dynamicRegistration:{}};documentHighlight={dynamicRegistration:!0};documentSymbol=null;formatting={dynamicRegistration:{}};rangeFormatting={dynamicRegistration:{}};onTypeFormatting={dynamicRegistration:{}};declaration={};definition={linkSupport:{},dynamicRegistration:{}};codeLens=null;documentLink={tooltipSupport:{},dynamicRegistration:{}};colorProvider=null;rename={prepareSupport:!0,prepareSupportDefaultBehavior:null,honorsChangeAnnotations:null,dynamicRegistrationSupport:null};publishDiagnostics=null;foldingRage=null;typeHierarchy=null;callHierarchy={dynamicRegistration:{}};selectionRange=null;semanticTokens=new Rt;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var jr=class{workspace=new Mr;textDocument=new Hr;notebookDocument=null;window=null;general=null;experimental=null};var Fr=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};function Mt(n){return y(n)?typeof n.line=="number"&&typeof n.character=="number":!1}function Yc(n){return y(n)?typeof n.uri=="string"&&typeof n.text=="string"&&typeof n.languageId=="string"&&typeof n.version=="number":!1}function Jc(n){if(!y(n)||typeof n.text!="string")return!1;let e=n.range;return y(e)?Mt(e.start)&&Mt(e.end):!1}var $r=class{messageHandle;serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}sdkPath;rootUri;nodeMaxOldSpaceSize;nodePath;constructor(e){this.sdkPath=e.sdkPath,this.rootUri=e.workspaceRoot,this.nodeMaxOldSpaceSize=e.nodeMaxOldSpaceSize,this.nodePath=e.nodePath,this.serverPath=e.arktsLangServerPath,this.logPath=Lc(),this.indexLogPath=e.indexLogPath||this.logPath,this.messageHandle=new wr({serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath,nodePath:this.nodePath}),this.messageHandle.setBroadcastToClients(t=>this.onLspMessage(t))}async start(e,t){let r=!1;try{d.info(`serverPath: ${this.serverPath}`),d.info(`rootUri: ${this.rootUri}`),d.info(`sdkPath: ${this.sdkPath}`),d.info(`logPath: ${this.logPath}`);let o=Ce(this.rootUri),i=new Ir(o,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new wn(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),i.modules=s;let l=Fc(s.length,this.nodeMaxOldSpaceSize);await this.messageHandle.start(l),this.currentParams=new Fr(o,i,new jr),this.messageHandle.sendInitialize(this.currentParams,1),this.messageHandle.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:O,method:b.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((u,h)=>{this.messageHandle.onIndexingProgressUpdate(h),this.messageHandle.onInitializationCompleted(u)},"LSP initialization",un),this.messageHandle.sendInitialized(e),r=!0}catch(o){this.lastStartErrorMessage=o instanceof Error?o.message:String(o),d.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(r)}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){let t=Ce(e);this.messageHandle.registerRequestCallback(t,(r,o)=>{let i=y(o)?o:{};d.info(`[LSP] onDiagnosticCompleted called, filePath: ${e}`);let s={jsonrpc:O,method:r,params:{uri:typeof i.uri=="string"?i.uri:t,diagnostics:Array.isArray(i.diagnostics)?i.diagnostics.filter(a=>typeof a=="string"):[],...typeof i.errorMessage=="string"?{errorMessage:i.errorMessage}:{}}};this.onLspMessage(s)})}registerRequestCallback(e,t){this.messageHandle.registerRequestCallback(t,(r,o)=>{d.info(`[LSP] onRequestCompleted called, requestId: ${t}, method: ${r}`);let i={jsonrpc:O,id:e,result:y(o)?o.result:void 0};this.onLspMessage(i)})}reloadDependenciesOnly(e){let t=e?.fullReload??!1,r=new wn(this.rootUri,this.sdkPath),o=this.getModuleModelsByName();if(t){d.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let l=r.getDependenciesOnly();this.markDependencyTypesIncremental(l);let u=this.mergeDepsOnlyIntoModuleList(l,o);return this.applyModuleModelsUpdate(u),d.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${u.length}`),this.lastDepsOnlyForDiff=l,l}let i=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(i.length===0&&s.size===0)return d.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];d.info(`[LspServerProxy] Module-level deps changed, parsing: [${i.join(", ")}]`);let a=r.getDependenciesOnly(i);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),d.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),r=new Map(this.lastDepsOnlyForDiff.map(o=>[o.moduleName??"",o]));for(let o of e){let i=o.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(i,t,r),c=o.dependencies??{},l=o.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(u,h)=>{(o.dependencies??={})[u]=this.makeDeleteEntry(u,h)}),this.markAddAndDeleteInDeps(a,l,(u,h)=>{(o.dynamicDependencies??={})[u]=this.makeDeleteEntry(u,h)})}}getOldDepsForModule(e,t,r){let o=t.get(e),i=o?.moduleDependencies?.dependencies??{},s=o?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(i).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(i=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:i,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let o of Object.keys(t))o in e||(t[o].type="add");for(let o of Object.keys(e))o in t||r(o,e[o])}makeDeleteEntry(e,t){return new ot({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Ct(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new At([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let o of e){let i=o.moduleName??"",s=t.get(i);s?(s.modulePath=o.modulePath,s.moduleDependencies=o):s=this.createMinimalModelFromDepsItem(o),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let o=new Map(r.map(s=>[s.moduleName??"",s])),i=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=o.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,o.delete(a)),i.push(s)}for(let[,s]of o)i.push(this.createMinimalModelFromDepsItem(s));return i}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=fr(Ci.join(t,"default/openharmony/ets/build-tools/ets-loader")),o=fr(Ci.join(t,"default/openharmony/ets/api")),i=fr(Ci.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=o,s.hosSdkPath=i}sendRequest(e){switch(e.method){case b.HOVER:this.handleHoverRequest(e);break;case b.DEFINITION:this.handleDefinitionRequest(e);break;case b.REFERENCES:this.handleReferencesRequest(e);break;default:d.warn(`Unhandled LSP request: ${e.method}`)}}handleHoverRequest(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/hover, params missing or not an object");return}let{textDocument:r,position:o,requestId:i}=t;if(!y(r)||typeof r.uri!="string"||!Mt(o)){d.error("Invalid client textDocument/hover, malformed or missing required parameters");return}if(typeof i!="number"){d.error("Invalid client textDocument/hover, requestId missing or not a number");return}this.registerRequestCallback(e.id,i),this.messageHandle.sendAsyncRequest(b.ON_ASYNC_HOVER,t,i,se.ON_ASYNC_HOVER)}handleDefinitionRequest(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/definition, params missing or not an object");return}let{textDocument:r,position:o}=t;if(!y(r)||typeof r.uri!="string"||!Mt(o)){d.error("Invalid client textDocument/definition, malformed or missing required parameters");return}let i=this.resolveRequestId(t.requestId,e.id);if(!Number.isFinite(i)){d.error("Invalid client textDocument/definition, requestId missing or not a valid number");return}this.registerRequestCallback(e.id,i),this.messageHandle.sendAsyncRequest(b.ON_ASYNC_DEFINITION,t,i,se.ON_ASYNC_DEFINITION)}handleReferencesRequest(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/references, params missing or not an object");return}let{textDocument:r,position:o}=t;if(!y(r)||typeof r.uri!="string"||!Mt(o)){d.error("Invalid client textDocument/references, malformed or missing required parameters");return}let i=this.resolveRequestId(t.requestId,e.id);if(!Number.isFinite(i)){d.error("Invalid client textDocument/references, requestId missing or not a valid number");return}this.registerRequestCallback(e.id,i),this.messageHandle.sendAsyncRequest(b.ON_ASYNC_FIND_USAGES,t,i,se.ON_ASYNC_FIND_USAGES)}resolveRequestId(e,t){let r=e??t;return typeof r=="number"?r:Number(r)}sendNotification(e){if(!Mc(e)){d.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case b.DID_OPEN:this.handleDidOpenNotification(e);break;case b.DID_CHANGE:this.handleDidChangeNotification(e);break;case b.DID_CLOSE:this.handleDidCloseNotification(e);break;case b.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:this.handleDidChangePackageDependencies(e);break;case b.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;default:d.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/didOpen, params missing or not an object");return}let{textDocument:r,editorFiles:o}=t;if(!Yc(r)||!Ii(o)){d.error("Invalid client textDocument/didOpen, malformed or missing required parameters");return}let s={isFromEditor:typeof t.isFromEditor=="boolean"?t.isFromEditor:!1,editorFiles:o,textDocument:r};this.registerDiagnosticCallback(r.uri),this.messageHandle.onAsyncOpenFile(s)}handleDidChangeNotification(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/didChange, params missing or not an object");return}let{textDocument:r,contentChanges:o}=t;if(!y(r)||typeof r.uri!="string"||typeof r.version!="number"){d.error("Invalid client textDocument/didChange, malformed or missing required parameters");return}if(!Array.isArray(o)||!o.every(Jc)){d.error("Invalid client textDocument/didChange, contentChanges invalid");return}let i=r.uri,s=r.version;this.registerDiagnosticCallback(i),this.messageHandle.onAsyncDidChange({uri:i,version:s,contentChanges:o})}handleDidCloseNotification(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/didClose, params missing or not an object");return}let{textDocument:r}=t;if(!y(r)||typeof r.uri!="string"){d.error("Invalid client textDocument/didClose, malformed or missing required parameters");return}let o=typeof t.isManual=="boolean"?t.isManual:!1;this.messageHandle.closeFile(r.uri,o)}handleDidChangePackageDependencies(e){let t=e.params;if(!y(t)){d.error("Invalid client aceProject/onDidChangePakcageDependencies, params missing or not an object");return}let{moduleSet:r}=t;if(!Array.isArray(r)||r.length===0){d.error("Invalid client aceProject/onDidChangePakcageDependencies, malformed or missing required parameters");return}this.messageHandle.sendModuleDependencyUpdate(t)}handleDidChangeWatchedFiles(e){let t=e.params;if(!y(t)){d.error("Invalid client workspace/didChangeWatchedFiles, params missing or not an object");return}let{changes:r}=t;if(!Array.isArray(r)){d.error("Invalid client workspace/didChangeWatchedFiles, malformed or missing required parameters");return}this.messageHandle.onDidChangeWatchedFiles(r)}withResettableTimeout(e,t,r){return new Promise((o,i)=>{let s,a=()=>{s=setTimeout(()=>{i(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),o()},c)})}async dispose(){await this.messageHandle.stop()}};import*as Te from"fs";import*as Be from"path";import{createHash as $h}from"crypto";import{EventEmitter as Bh}from"events";var Br=class extends Bh{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r}projectRoot;watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),r=new Set(this.watchers.keys());for(let o of t)r.has(o)||this.watchFile(o);for(let o of r)t.has(o)||(this.unwatchFile(o),d.info(`[ConfigFileWatcher] Stopped watching: ${o}`));d.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!Te.existsSync(t)){d.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Te.watch(t,r=>{r==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",r=>{d.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${r.message}`)}),d.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(r){d.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${r instanceof Error?r.message:String(r)}`)}}emitModuleAddedEvents(t,r){for(let o of t){let i=P.resolvePathWithinRoot(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:i,relativePath:o.srcPath,timestamp:r,moduleName:o.name})}}emitModuleRemovedEvents(t,r){for(let o of t){let i=P.resolvePathWithinRoot(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:i,relativePath:o.srcPath,timestamp:r,removedModuleName:o.name})}}emitModuleRenamedEvents(t,r){for(let o of t){let i=P.resolvePathWithinRoot(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:i,relativePath:o.after.srcPath,timestamp:r,moduleName:o.after.name,removedModuleName:o.before.name})}}emitModuleMovedEvents(t,r){for(let o of t){let i=P.resolvePathWithinRoot(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:i,relativePath:o.after.srcPath,timestamp:r,moduleName:o.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let r=Date.now();this.emitModuleAddedEvents(t.added,r),this.emitModuleRemovedEvents(t.removed,r),this.emitModuleRenamedEvents(t.renamed,r),this.emitModuleMovedEvents(t.moved,r)}onBuildProfileChanged(){let t="__build_profile__",r=this.debounceTimers.get(t);r&&clearTimeout(r);let o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(i);if(s===this.lastModulesSnapshot){d.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,i);this.lastModules=i,this.lastModulesSnapshot=s,d.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,o)}computeModulesSnapshot(t){return t.map(o=>`${o.name}::${o.srcPath}`).sort().join("|")}diffModules(t,r){let o=this.buildModuleMatchState(r),i={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,o),this.matchRenamedModules(t,o,i),this.matchMovedModules(t,o,i),this.collectRemovedModules(t,o,i),this.collectAddedModules(r,o,i),i}buildModuleMatchState(t){let r=new Map,o=new Map;for(let i of t)r.set(i.srcPath,i),o.set(i.name,i);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:o}}matchExactModules(t,r){for(let o of t){let i=r.newBySrc.get(o.srcPath);i&&i.name===o.name&&(r.matchedOld.add(o),r.matchedNew.add(i))}}matchRenamedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newBySrc.get(i.srcPath);s&&!r.matchedNew.has(s)&&s.name!==i.name&&(o.renamed.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}matchMovedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newByName.get(i.name);s&&!r.matchedNew.has(s)&&s.srcPath!==i.srcPath&&(o.moved.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}collectRemovedModules(t,r,o){for(let i of t)r.matchedOld.has(i)||o.removed.push(i)}collectAddedModules(t,r,o){for(let i of t)r.matchedNew.has(i)||o.added.push(i)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=oe(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return d.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=Be.join(this.projectRoot,A.OH_PACKAGE_JSON5);Te.existsSync(r)&&t.push(r);let o=this.parseModulesFromBuildProfile();for(let i of o){let s=P.resolvePathWithinRoot(this.projectRoot,i.srcPath),a=Be.join(s,A.OH_PACKAGE_JSON5);Te.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Be.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Te.readFileSync(t,"utf-8");return $h("sha256").update(r).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let r=this.computeFileHash(t);r&&this.contentHashes.set(t,r);let o=Te.watch(t,i=>{i==="change"&&this.onFileChanged(t)});o.on("error",i=>{d.error(`[ConfigFileWatcher] Watch error for ${t}: ${i.message}`)}),this.watchers.set(t,o)}catch(r){d.error(`[ConfigFileWatcher] Failed to watch ${t}: ${r instanceof Error?r.message:String(r)}`)}}unwatchFile(t){let r=this.watchers.get(t);r&&(r.close(),this.watchers.delete(t)),this.contentHashes.delete(t);let o=this.debounceTimers.get(t);o&&(clearTimeout(o),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.computeFileHash(t);if(!i){d.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===i){d.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,i),d.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:Be.basename(t),relativePath:Be.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,o)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),d.info("[ConfigFileWatcher] All watchers stopped")}};import*as We from"fs";import*as ue from"path";import{createHash as Wh}from"crypto";import{EventEmitter as Uh}from"events";var Wr=class extends Uh{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=ue.join(t,hn)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!We.existsSync(this.depMapDir)){d.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=We.watch(this.depMapDir,{recursive:!0},(t,r)=>this.onDirEvent(t,r)),this.dirWatcher.on("error",t=>{d.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){d.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),d.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return G(ue.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let o=r.replace(/\\/g,"/"),i;if(o===A.OH_PACKAGE_JSON5)i="root-oh-package";else if(o===it)i="dep-map-json";else{let a=o.match(/^([^/]+)\/oh-package\.json5$/);i=a?`module:${a[1]}`:""}if(!i)return;let s=ue.join(this.depMapDir,r);We.existsSync(s)&&this.scheduleDebouncedFullScan()}stop(){this.dirWatcher&&(this.dirWatcher.close(),this.dirWatcher=null),this.fullScanTimer&&(clearTimeout(this.fullScanTimer),this.fullScanTimer=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.coalesceTimer&&(clearTimeout(this.coalesceTimer),this.coalesceTimer=null),this.pendingTags=[],this.pendingRenames=[],this.contentHashes.clear(),this.initialScanDone=!1,d.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=ue.join(this.depMapDir,A.OH_PACKAGE_JSON5),r=ue.join(this.depMapDir,it),o=this.parseModulesFromDepMap(),i=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...o.map(s=>({path:ue.join(this.depMapDir,s.name,A.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of i){if(!We.existsSync(s))continue;let c=this.canonicalPath(s),l=this.computeFileHash(s);if(!l)continue;let u=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,l);continue}u!==l&&(this.contentHashes.set(c,l),d.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=ue.join(this.depMapDir,it);try{let r=oe(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return d.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${r instanceof Error?r.message:String(r)}`),[]}}scheduleCoalescedReload(t){this.pendingTags.push(t),t==="dep-map-json"&&this.applyDepMapJsonDiff(),this.coalesceTimer&&clearTimeout(this.coalesceTimer),this.coalesceTimer=setTimeout(()=>{this.coalesceTimer=null,this.flushPendingReload()},this.coalesceMs)}collectPendingState(){let t=this.pendingTags,r=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:r}}processTagsIntoSets(t,r,o,i){for(let s of t)s.startsWith("module:")?(o.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(o.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(i.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,o,i,s){for(let a of t)s.push(a.info),o.add(a.info.newName),i.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let o=new Set;for(let i of t)i.startsWith("dep-added:")&&o.add(i.substring(10));for(let i of r)o.add(i.info.newName);return o}emitIncrementalReload(t,r,o,i,s){d.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...o].join(",")}], added=[${[...i].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...o],addedModuleNames:[...i],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:r}=this.collectPendingState();if(t.length===0&&r.length===0)return;if(d.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${r.length}`),t.includes("root-oh-package")){d.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let o=new Set,i=new Set,s=new Set,a=[];this.processTagsIntoSets(t,o,i,s),this.processRenameEntries(r,o,i,s,a);for(let l of i)s.delete(l);if(i.size===0&&s.size===0&&a.length===0){d.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(o,i,s,c,a)}normalizeSrcPath(t){return G(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(i=>[i.name,i])),o=new Map(t.map(i=>[this.normalizeSrcPath(i.srcPath),i]));return{byName:r,bySrcPath:o}}detectModuleRenames(t,r,o,i){for(let[s,a]of t){let c=r.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),o.add(a.name),i.add(c.name);let l=ue.join(this.depMapDir,a.name,A.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(l)),d.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,r,o,i){for(let[s,a]of t){if(o.has(s))continue;let c=r.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),o.add(s),i.add(s),d.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,o){for(let[i]of t)o.has(i)||r.has(i)||(this.pendingTags.push(`dep-added:${i}`),o.add(i))}detectRemovedModules(t,r,o){for(let[i]of t)if(!o.has(i)&&!r.has(i)){this.pendingTags.push(`dep-removed:${i}`),o.add(i);let s=ue.join(this.depMapDir,i,A.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(o=>o.startsWith("dep-")),r=this.pendingRenames.map(o=>`${o.kind}(${o.info.oldName}\u2192${o.info.newName})`);d.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:o}=this.buildModuleLookupMaps(this.lastModules),{byName:i,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(o,s,a,c),this.detectModuleMoves(r,i,a,c),this.detectAddedModules(i,r,c),this.detectRemovedModules(r,i,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=We.readFileSync(t,"utf-8");return Wh("sha256").update(r).digest("hex")}catch{return null}}};import*as Kc from"os";import*as Zc from"path";import{spawn as zh}from"child_process";var qh=600*1e3;function Vh(n){let e=[],t=[];return n.stdout?.on("data",r=>{e.push(r.toString())}),n.stderr?.on("data",r=>{t.push(r.toString())}),{stdout:e,stderr:t}}function Ur(n){return n.join("")}function Gh(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
`).trim();r({success:!1,output:`Build process timeout after 10 minutes.
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
`).trim()||"";r(Gh(c,l,u))}),o.on("error",c=>{clearTimeout(a),r({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function Ai(n,e,t,r,o){let i={...process.env,DEVECO_SDK_HOME:r};return I()&&(i.HVIGOR_USER_HOME=Zc.join(Kc.homedir(),".hvigor")),await Yh([e,[t,...o]],n,i)}var Jh=["--sync","-p","product=default","--analyze=normal","--parallel","--incremental","--no-daemon"];async function Xc(n,e){try{return(await Ai(n,e.nodePath,e.hvigorJsPath,e.sdkPath,Jh)).success}catch(t){return d.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}import{spawn as Kh}from"child_process";var Zh=["install","--all"];async function Xh(n,e,t,r){return new Promise(o=>{let i=Kh(n,e,{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";i.stdout?.on("data",c=>{s+=c.toString()}),i.stderr?.on("data",c=>{a+=c.toString()}),i.on("close",c=>{let l=[s,a].filter(Boolean).join(`
|
|
1259
|
-
`);o({exitCode:c??-1,output:l})}),i.on("error",c=>{let l=[s,a].filter(Boolean).join(`
|
|
1260
|
-
`);o({exitCode:-1,output:l+`
|
|
1261
|
-
`+c.message})})})}function Qh(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>d.info("[ohpm] %s",e))}async function Qc(n,e){try{let{exitCode:t,output:r}=await Xh(e.nodePath,[e.ohpmJsPath,...Zh],n,e.sdkPath);return Qh(r),t===0?(d.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(d.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",t),d.error("ohpm \u8F93\u51FA: %s",r),!1)}catch(t){return d.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var el={UNINITIALIZED:-32099,UNKNOWN:-32e3},bn=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,el.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,el.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var Ot=class{config;lspProxy=null;configWatcher=null;depMapWatcher=null;isInitialized=!1;lastEditorOpenFiles=[];onMessage=()=>{};onConfigChanged=null;disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}async start(e=[]){this.lastEditorOpenFiles=e,this.startConfigWatcher(),this.startLspProxy(e)}sendNotification(e){if(!this.lspProxy){d.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){d.warn("[ArktsLspManager] sendRequest before LSP ready, dropped");return}this.lspProxy.sendRequest(e)}static async handleSyncProject(e,t,r){if(d.info("[ArktsLspManager] Received arkts/syncProject"),!e)return d.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let o=r?.skipHvigorSync===!0,i=await Ns(e,async()=>await Qc(e,t)?o?(d.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await Xc(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 i.acquired?i.result:(d.info("[ArktsLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){try{this.configWatcher?.stop()}catch(e){d.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){d.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){d.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new $r(this.config);t.setOnMessage(r=>this.handleLspMessage(r)),t.start(e,r=>this.handleLspInitialized(r)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)d.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:O,method:b.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();d.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?bn.uninitialized(t):bn.unknown();this.onMessage({jsonrpc:O,method:b.ARKTS_INITIALIZATION_FAILED,params:r.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(d.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:O,method:b.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Br(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Wr(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){d.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let r=this.lspProxy.reloadDependenciesOnly(e).map(o=>({modulePath:o.modulePath??"",dependencies:o.dependencies??{},dynamicDependencies:o.dynamicDependencies??{}}));this.lspProxy.sendNotification({jsonrpc:O,method:b.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT,params:{moduleSet:r}}),this.onMessage({jsonrpc:O,method:b.ARKTS_SYNC_COMPLETED,params:{success:!0}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){d.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var eg=120*1e3,tg=10080*60*1e3,ng=7200*60*1e3,Nt=class{manager=null;diagnosticWaiters=new Map;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;toolProvider;nodeMaxOldSpaceSize;onConfigChangedCallback=null;constructor(e,t,r){this.projectPath=e,this.toolProvider=t,this.nodeMaxOldSpaceSize=r}setOnConfigChanged(e){this.onConfigChangedCallback=e}static getToolDefinition(){return{name:"check_ets_files",description:"\u5BF9\u4F20\u5165\u7684ets\u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5(ArkTS-Check)\u5E76\u5B9E\u65F6\u8FD4\u56DE\u8BCA\u65AD\u4FE1\u606F\u3002",inputSchema:Ti.object({files:Ti.array(Ti.string()).describe('\u5F85\u68C0\u67E5\u7684 ETS \u6587\u4EF6\u8DEF\u5F84\u5217\u8868\uFF0C\u683C\u5F0F\u4E3A ["file1.ets","file2.ets",...]')})}}isInitializing(){return this.initializing}isInitialized(){return this.initialized}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initializing=!0,this.initPromise=this.doInitialize().then(()=>{this.initialized=!0}).finally(()=>{this.initializing=!1}),await this.initPromise}}async doInitialize(){let{harmonyRoot:e,devecoStudioPath:t,arktsLangServerPath:r}=this.resolveProjectAndDeveco(),o=ve(e),{logPath:i,indexPath:s}=this.getLogAndIndexPath(o);setImmediate(()=>{wi(s,tg,"[ArkTS-Check]"),wi(i,ng,"[ArkTS-Check]")}),Nc(i);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a;f.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${c??"undefined \u2192 dynamic formula applies"}`);let l=this.toolProvider.sdkPath;f.info(`ArktsCheck devecoStudioPath: ${t}, sdkPath: ${l}`),this.manager=new Ot({sdkPath:l,arktsLangServerPath:r,workspaceRoot:G(o),indexLogPath:s,nodeMaxOldSpaceSize:c,nodePath:this.toolProvider.nodePath}),this.manager.setOnMessage(u=>this.handleLspMessage(u)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((u,h)=>{this.initResolve=u,this.initReject=h,this.armInitTimer(un),this.manager.start([]).catch(v=>{let D=v instanceof Error?v:new Error(String(v));this.failInit(D)})})}resolveProjectAndDeveco(){let e=Ie(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.toolProvider.devecoStudioPath??"";f.debug(`DevEco Studio installation path: ${t}`);let r=this.toolProvider.lspServerPath;if(!r)throw new Error("arkts-lang-server path not found");return{harmonyRoot:e,devecoStudioPath:t,arktsLangServerPath:r}}armInitTimer(e){this.initDeadlineTimer&&clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=setTimeout(()=>{let t=this.initReject;this.clearInitHandlers(),t?.(new Error("LSP initialize timeout"))},e)}clearInitHandlers(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async checkFile(e){this.initialized||await this.initialize();let t=ln(rt(e)),r=vi(e),o=await xe.promises.readFile(e,"utf8"),s=`deveco.apptool.${we.extname(e).replace(/^\./,"")||"plaintext"}`,a=new Promise((l,u)=>{let h=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&u(new Error("Wait for diagnostics timeout"))},eg);this.diagnosticWaiters.set(t,{resolve:l,reject:u,timer:h})}),c={textDocument:{uri:r,text:o,languageId:s,version:o.length},editorFiles:[r],isFromEditor:!1};f.debug(`textDocument/didOpen uri=${r} content_len=${o.length}`),this.sendNotification("textDocument/didOpen",c);try{return await a}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:r},isManual:!1})}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],r=[],o=this.collectValidFiles(e.files,t);return o.length===0?{content:[{type:"text",text:t.length>0?t.join(`
|
|
1262
|
-
`):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],isError:!0}:(await this.runDiagnosticsForFiles(o,t,r),this.formatCallResult(t,r))}buildNotReadyResponse(){return{content:[{type:"text",text:this.initializing?"LSP \u6B63\u5728\u521D\u59CB\u5316\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5":this.projectPath?"LSP\u672A\u521D\u59CB\u5316":"\u6CA1\u6709\u914D\u7F6E\u5DE5\u7A0B\u8DEF\u5F84\uFF0C\u8BF7\u914D\u7F6EPROJECT_PATH\u53C2\u6570"}],isError:!0}}collectValidFiles(e,t){let r=this.projectPath,o=[];for(let i of e){let s=we.isAbsolute(i)?i:we.join(r,i);if(!xe.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${i}`);continue}if(!xe.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${i}`);continue}if(!s.endsWith(".ets")){t.push(`\u4E0D\u662F .ets \u6587\u4EF6: ${i}`);continue}o.push(s)}return o}async runDiagnosticsForFiles(e,t,r){for(let o of e){await Ec(500);try{let i=await this.checkFile(o);r.push(rg(o,i))}catch(i){t.push(`${o} => wait for diagnostics failed: ${i.message}`)}}}formatCallResult(e,t){let r=[];e.length>0&&r.push(e.join(`
|
|
1282
|
+
`);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 qt=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 ps=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var sr=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 D(n){return typeof n=="object"&&n!==null}var am=20*1e3,QP=30*1e3,fs=class{client;nextRequestId=1;stopOnce=null;callbacks=new sr;requestCallbacks=new qt;diagnosticMap=new Map;initProgressReset=null;constructor(e){this.client=new Vt(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,He);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 ps(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=QP){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){D(e)&&this.broadcastToClients({jsonrpc:T,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,am,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${am}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:T,method:y.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var ms=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 cl(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)}},cl=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var eC={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"},tC={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"},R={...eC,...tC},Yt={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"},cm=new Set([1e3,2e3,3e3,3001]);function nC(n){if(!D(n))return!1;let e=n.textDocument;return D(e)&&typeof e.uri=="string"}function rC(n){return D(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function iC(n){return D(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 hs=class n{client;isInitialized=!1;stopOnce=null;callbacks=new sr;requestCallbacks=new qt;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;constructor(e){this.client=new Vt(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:T,method:R.EXIT,params:{}}),Yt.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(R.BROADCAST),this.callbacks.register(R.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(R.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(R.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(R.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:T,method:R.INITIALIZED,params:{editors:e}}),Yt.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:T,id:0,result:{}}),Yt.EMPTY)}sendAsyncRequest(e,t,r,i){if(!D(t)){f.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!nC(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=et(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:T,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(!rC(r)){f.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:T,method:R.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),R.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!D(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:T,method:R.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),Yt.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let i=et(t);e.textDocument.uri=i,f.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new ms(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,R.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:R.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),Yt.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=et(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,R.PUBLISH_DIAGNOSTICS)),f.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:R.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),Yt.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=et(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:T,method:R.DID_CLOSE,params:{textDocument:{uri:r}}}),Yt.DID_CLOSE)}getDiagnosticMessage(e){let t=et(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,R.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:T,method:R.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 R.MODULE_INIT_FINISH:return f.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(R.MODULE_INIT_FINISH),this.callbacks.unregister(R.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case R.INDEXING_PROGRESS_UPDATE:return f.info(`[LSP] onIndexingProgressUpdate: ${iC(t.params)}`),this.callbacks.invoke(R.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case R.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case R.ON_PACKAGE_CHANGE_FINISH:f.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case R.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case R.ON_ASYNC_HOVER:this.handleAsyncResponse(t,R.HOVER);return;case R.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,R.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case R.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,R.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;D(t)&&D(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:T,method:R.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(!D(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,R.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(cm)&&this.finalizeDiagnostic(t,R.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 Ii from"path";import*as Es from"path";var gs=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var ys=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var ws=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var vs=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Ss=class{typeSetting=new ws;parameterNames=new vs};var bs=class{constructor(e,t,r,i){this.rootUri=e;this.lspServerWorkspacePath=j(Es.dirname(t)),this.indexingDataLocation=j(i),this.loggerPath=j(Es.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new gs;gutterIconsSetting=new ys;inlayHintsSetting=new Ss;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as lm from"path";var Si=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(lm.join(e,"src","main","resources")))}};var oC="OS",ar=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${oC}`;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 Si(e)):this.buildProfileParam=new Si}toString(){return JSON.stringify(this)}};var cr=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as ze from"path";import*as ur from"fs";var Ps=class{modulePath;dependencies={};dynamicDependencies={}};var Rn=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 lr=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 Dt from"path";import*as Cs from"fs";var dr=class{name="";version="";storePath="";dependencyPath="";path=""};var L={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:Ze.OH_PACKAGE_JSON5},bi=`${L.HVIGOR_CACHE}/${L.DEPENDENCY}`,kn=`${L.DEPENDENCY}${L.JSON5}`,zU=Ze.SYNC_OUTPUT_PATH;var Ei=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=Dt.join(this.dependencyPath,L.OH_PACKAGE_JSON5),r=Ne(t);r&&(this.dependencies=this.getDependencyList(r,L.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(r,L.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(r,L.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let r=[];if(!D(e))return r;let i=e[t];if(!D(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 dr;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=Dt.normalize(Dt.join(this.modulePath,L.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)),Dt.isAbsolute(s)){r.dependencyPath=o;return}if(!i){let a=Dt.resolve(this.modulePath,s);o=E.ensurePathWithinRoot(this.projectPath,a)}Cs.existsSync(o)&&Cs.statSync(o).isDirectory()&&(r.dependencyPath=o)}catch(o){f.error("parser dependency path is invalid",o)}}};import*as Pi from"fs";import*as Ci from"path";import sC from"json5";var Is=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 Ci.join(this.projectPath,L.OH_MODULES_PATH,L.OHPM_PATH,L.LOCK_JSON5_FILE)}readLockFile(e){if(!Pi.existsSync(e))return f.error("lock file does not exist"),this.clearDependencies(),null;try{let t=Pi.readFileSync(e,"utf8"),r=sC.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(!D(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,L.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,L.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,L.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!D(e))return t;for(let[r,i]of Object.entries(e)){if(!D(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(!D(e))return[];for(let[i,o]of Object.entries(e))if(D(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(!D(i))return f.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!D(s))return[];for(let[a,c]of Object.entries(s)){if(!D(c))continue;let l=typeof c.specifier=="string"?c.specifier:"",d=typeof c.version=="string"?c.version:"",h=new dr;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=E.resolvePathWithinRoot(this.projectPath,Ci.join(t,L.OH_MODULES_PATH,r));try{let a=o.startsWith(n.FILE_DEPENDENCY_PREFIX)?o.substring(n.FILE_DEPENDENCY_PREFIX.length):o,c=Ci.isAbsolute(a)?E.ensurePathWithinRoot(this.projectPath,a):E.resolvePathWithinRoot(this.projectPath,a);Pi.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 dm(n){return D(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var xn=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new bt(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=ze.join(t,bi),i=ze.join(r,kn);if(!ur.existsSync(r)||!ur.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 lr(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];dm(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=ze.join(r,bi),o=ze.join(i,kn);if(!ur.existsSync(i)||!ur.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 lr(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(!dm(l))continue;let d=l.name;if(s&&!s.has(d))continue;let h=E.resolvePathWithinRoot(this.projectPath,l.srcPath),w=ze.join(i,d),S=j(h),k=this.buildModuleDependencies(d,S,w,a);k.moduleName=d,t.push(k)}return t}parseSingleModule(e,t,r,i){let o=e.name,s=E.resolvePathWithinRoot(this.projectPath,e.srcPath),a=ze.join(t,o),c=j(s),l=new ar(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 cr(h),i.push(l)}buildModuleDependencies(e,t,r,i){let o=new lr(this.projectPath,e,t);Ei.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 Ps;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 Rn(o);for(let o of e.finalDynamicDependencies)i[o.name]=new Rn(o);t.dependencies=r,t.dynamicDependencies=i}parseProjectDependencies(e,t){let r=ze.join(e,L.OH_PACKAGE_JSON5);if(!ur.existsSync(r))return;Ei.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 Is(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=ze.join(e,"src","main","module.json5"),i=Ne(r);if(!D(i)||!D(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(D(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)D(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=ze.join(e,"src","main","resources","base","profile","main_pages.json"),r=Ne(t);return!D(r)||!Array.isArray(r.src)?[]:r.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!D(t)||!D(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=ze.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=Ne(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!D(t)||!D(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!D(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=ze.join(this.projectPath,"build-profile.json5");this.buildProfileCache=Ne(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!D(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 As=class{constructor(e=[]){this.valueSet=e}valueSet};var pr=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var um=(C=>(C[C.File=1]="File",C[C.Module=2]="Module",C[C.Namespace=3]="Namespace",C[C.Package=4]="Package",C[C.Class=5]="Class",C[C.Method=6]="Method",C[C.Property=7]="Property",C[C.Field=8]="Field",C[C.Constructor=9]="Constructor",C[C.Enum=10]="Enum",C[C.Interface=11]="Interface",C[C.Function=12]="Function",C[C.Variable=13]="Variable",C[C.Constant=14]="Constant",C[C.String=15]="String",C[C.Number=16]="Number",C[C.Boolean=17]="Boolean",C[C.Array=18]="Array",C[C.Object=19]="Object",C[C.Key=20]="Key",C[C.Null=21]="Null",C[C.EnumMember=22]="EnumMember",C[C.Struct=23]="Struct",C[C.Event=24]="Event",C[C.Operator=25]="Operator",C[C.TypeParameter=26]="TypeParameter",C))(um||{}),pm=()=>Object.values(um).filter(n=>typeof n=="number");var Ds=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Ts=class{applyEdit=!0;workspaceEdit=new Ds;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new As(pm());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new pr;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Rs=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var ks=class{constructor(e=[]){this.valueSet=e}valueSet};var xs=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var fm=(I=>(I[I.Text=1]="Text",I[I.Method=2]="Method",I[I.Function=3]="Function",I[I.Constructor=4]="Constructor",I[I.Field=5]="Field",I[I.Variable=6]="Variable",I[I.Class=7]="Class",I[I.Interface=8]="Interface",I[I.Module=9]="Module",I[I.Property=10]="Property",I[I.Unit=11]="Unit",I[I.Value=12]="Value",I[I.Enum=13]="Enum",I[I.Keyword=14]="Keyword",I[I.Snippet=15]="Snippet",I[I.Color=16]="Color",I[I.File=17]="File",I[I.Reference=18]="Reference",I[I.Folder=19]="Folder",I[I.EnumMember=20]="EnumMember",I[I.Constant=21]="Constant",I[I.Struct=22]="Struct",I[I.Event=23]="Event",I[I.Operator=24]="Operator",I[I.TypeParameter=25]="TypeParameter",I))(fm||{}),mm=()=>Object.values(fm).filter(n=>typeof n=="number");var Ns=class{completionItemKind=new ks(mm());completionItem=new xs;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Ls=class{synchronization=new Rs;completion=new Ns;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 pr;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var Os=class{workspace=new Ts;textDocument=new Ls;notebookDocument=null;window=null;general=null;experimental=null};var Ms=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var _s=class{messageHandle;get stdHandle(){return this.messageHandle}get legacyHandle(){return this.messageHandle}onAsyncOpenFile(e){this.legacyHandle.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.legacyHandle.closeFile(e,t)}serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];sdkPath;rootUri;nodeMaxOldSpaceSize;nodePath;useStandardProtocol;get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}constructor(e){this.sdkPath=e.sdkPath,this.rootUri=e.workspaceRoot,this.nodeMaxOldSpaceSize=e.nodeMaxOldSpaceSize,this.nodePath=e.nodePath,this.useStandardProtocol=e.useStandardProtocol,this.serverPath=e.useStandardProtocol?Ii.resolve(Ii.dirname(e.arktsLangServerPath),"standardIndex","index.js"):e.arktsLangServerPath,this.logPath=bu(),this.indexLogPath=e.indexLogPath||this.logPath;let t={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath,nodePath:this.nodePath};this.messageHandle=e.useStandardProtocol?new fs(t):new hs(t),this.messageHandle.setBroadcastToClients(r=>this.onLspMessage(r))}async start(e,t){let r=!1;try{f.info(`serverPath: ${this.serverPath}`),f.info(`rootUri: ${this.rootUri}`),f.info(`sdkPath: ${this.sdkPath}`),f.info(`logPath: ${this.logPath}`);let i=et(this.rootUri),o=new bs(i,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new xn(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),o.modules=s;let l=Ro(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new Ms(i,o,new Os),this.useStandardProtocol){let d=this.messageHandle;await d.sendInitializeResettable(this.currentParams,He),f.info("[LSP] initialize response received"),d.broadcastToClients({jsonrpc:T,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:T,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((i,o)=>{r.onIndexingProgressUpdate(o),r.onInitializationCompleted(i)},"LSP initialization",He),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=D(r)?r:{};f.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let o={jsonrpc:T,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 xn(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 Rn({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new ar(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new cr([]),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=zn(Ii.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=zn(Ii.join(t,"default/openharmony/ets/api")),o=zn(Ii.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:T,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:T,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:T,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:T,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:T,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:T,id:e.id,error:{code:-32603,message:t.message}}));break;default:f.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!om(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 Tt from"fs";import*as Jt from"path";import{createHash as cC}from"crypto";import{EventEmitter as lC}from"events";var Fs=class extends lC{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(!Tt.existsSync(t)){f.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Tt.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=E.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=E.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=E.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=E.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=Ne(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=Jt.join(this.projectRoot,L.OH_PACKAGE_JSON5);Tt.existsSync(r)&&t.push(r);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=E.resolvePathWithinRoot(this.projectRoot,o.srcPath),a=Jt.join(s,L.OH_PACKAGE_JSON5);Tt.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Jt.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Tt.readFileSync(t,"utf-8");return cC("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=Tt.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:Jt.basename(t),relativePath:Jt.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 Kt from"fs";import*as rt from"path";import{createHash as dC}from"crypto";import{EventEmitter as uC}from"events";var js=class extends uC{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=rt.join(t,bi)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!Kt.existsSync(this.depMapDir)){f.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=Kt.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 j(rt.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let i=r.replace(/\\/g,"/"),o;if(i===L.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===kn)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=rt.join(this.depMapDir,r);Kt.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=rt.join(this.depMapDir,L.OH_PACKAGE_JSON5),r=rt.join(this.depMapDir,kn),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...i.map(s=>({path:rt.join(this.depMapDir,s.name,L.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!Kt.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=rt.join(this.depMapDir,kn);try{let r=Ne(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 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=rt.join(this.depMapDir,a.name,L.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=rt.join(this.depMapDir,o,L.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=Kt.readFileSync(t,"utf-8");return dC("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as pC}from"child_process";var fC=["install","--all"];async function mC(n,e,t,r){return new Promise(i=>{let o=pC(n,e,{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(`
|
|
1283
|
+
`);i({exitCode:c??-1,output:l})}),o.on("error",c=>{let l=[s,a].filter(Boolean).join(`
|
|
1284
|
+
`);i({exitCode:-1,output:l+`
|
|
1285
|
+
`+c.message})})})}function hC(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>f.info("[ohpm] %s",e))}async function hm(n,e){try{let{exitCode:t,output:r}=await mC(e.nodePath,[e.ohpmJsPath,...fC],n,e.sdkPath);return hC(r),t===0?(f.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(f.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",t),f.error("ohpm \u8F93\u51FA: %s",r),!1)}catch(t){return f.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var gm={UNINITIALIZED:-32099,UNKNOWN:-32e3},Ai=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,gm.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,gm.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var fr=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)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 yo(e,async()=>await hm(e,t)?i?(f.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await Tu(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 _s(this.config);t.setOnMessage(r=>this.handleLspMessage(r)),t.start(e,r=>this.handleLspInitialized(r)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)f.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:T,method:y.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();f.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?Ai.uninitialized(t):Ai.unknown();this.onMessage({jsonrpc:T,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:T,method:y.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Fs(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new js(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:T,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 gC=10080*60*1e3,yC=7200*60*1e3,wC=120*1e3,mr=class n{manager=null;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;toolProvider;nodeMaxOldSpaceSize;onConfigChangedCallback=null;useStandardProtocol=!0;diagnosticWaiters=new Map;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION,completion:y.COMPLETION,signatureHelp:y.SIGNATURE_HELP,documentHighlight:y.DOCUMENT_HIGHLIGHT};constructor(e,t,r){this.projectPath=e,this.toolProvider=t,this.nodeMaxOldSpaceSize=r}setOnConfigChanged(e){this.onConfigChangedCallback=e}static getToolDefinition(){return{name:"check_ets_files",description:"\u5BF9\u4F20\u5165\u7684ets\u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5(ArkTS-Check)\u5E76\u5B9E\u65F6\u8FD4\u56DE\u8BCA\u65AD\u4FE1\u606F\u3002",inputSchema:ll.object({files:ll.array(ll.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=ae(e),{logPath:s,indexPath:a}=this.getLogAndIndexPath(o);setImmediate(()=>{ec(a,gC,"[ArkTS-Check]"),ec(s,yC,"[ArkTS-Check]")}),Do(s);let c=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,l=Number.isNaN(c)?void 0:c;g.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${l??"undefined \u2192 dynamic formula applies"}`);let d=this.toolProvider.sdkPath;g.info(`ArktsCheck devecoStudioPath: ${t}, sdkPath: ${d}`),this.manager=new fr({sdkPath:d,arktsLangServerPath:r,workspaceRoot:j(o),indexLogPath:a,nodeMaxOldSpaceSize:l,nodePath:this.toolProvider.nodePath,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(He),this.manager.start([]).catch(S=>{let k=S instanceof Error?S:new Error(String(S));this.failInit(k)})})}resolveProjectAndDeveco(){let e=St(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.toolProvider.devecoStudioPath??"";g.debug(`DevEco Studio installation path: ${t}`);let r=this.toolProvider.lspServerPath;if(!r)throw new Error("arkts-lang-server path not found");let i=le.resolve(le.dirname(r),"standardIndex","index.js"),o=Ie.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=bn(e),i=await Ie.promises.readFile(e,"utf8"),s=`deveco.apptool.${le.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 vC(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"))},wC);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(`
|
|
1286
|
+
`):"\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 Ie.promises.readFile(t,"utf8")).split(`
|
|
1287
|
+
`).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=bn(e),i=await Ie.promises.readFile(e,"utf8"),s=`deveco.apptool.${le.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=le.isAbsolute(e)?e:le.join(this.projectPath,e);return!Ie.existsSync(t)||!Ie.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=le.isAbsolute(o)?o:le.join(r,o);if(!Ie.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!Ie.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 fu(500);try{let o=await this.checkFile(i);r.push(SC(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(`
|
|
1263
1288
|
`)),t.length>0&&r.push(t.join(`
|
|
1264
|
-
`));let
|
|
1265
|
-
`).trim(),
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
`);if(t<0)return;let r=this.clangdBuffer.slice(0,t).toString("ascii"),o=/content-length:\s*(\d+)/i.exec(r);if(!o){this.clangdBuffer=this.clangdBuffer.slice(t+4);continue}let i=parseInt(o[1],10),s=t+4+i;if(this.clangdBuffer.length<s)return;let a=this.clangdBuffer.slice(t+4,s).toString("utf8");this.clangdBuffer=this.clangdBuffer.slice(s);try{let c=JSON.parse(a);this.dispatchMessage(c)}catch(c){f.error(`[CppCheck] Failed to parse C++ LSP JSON message: ${c}`)}}}dispatchMessage(e){if(typeof e.id=="number"){let t=this.pendingRequests.get(e.id);t&&(this.pendingRequests.delete(e.id),clearTimeout(t.timer),e.error?t.reject(new Error(e.error.message??JSON.stringify(e.error))):t.resolve(e.result??null));return}if(e.method==="textDocument/publishDiagnostics"&&e.params){let t=e.params,r=t.uri;if(!r)return;let o=cg(r),i=this.diagnosticWaiters.get(o);if(i){this.diagnosticWaiters.delete(o),clearTimeout(i.timer);let s=Array.isArray(t.diagnostics)?t.diagnostics:[];f.info(`[CppCheck] Received C++ diagnostics for ${o} (${s.length} entries)`),i.resolve(s)}}}failAll(e){for(let[,t]of this.pendingRequests)clearTimeout(t.timer),t.reject(e);this.pendingRequests.clear();for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear()}async acquireFileCheckLock(){let e=this.fileCheckLock,t;return this.fileCheckLock=new Promise(r=>{t=r}),await e,t}};function cg(n){try{let e=new URL(n);if(e.protocol==="file:"){let t=decodeURIComponent(e.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(t)&&(t=t.slice(1)),rt(t)}}catch{}return n}function lg(n){let e=Z.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function dg(n,e){let t=Z.join(n,e.name);return e.isDirectory()?e.name===".cxx"||nl(t):lg(t)}function nl(n){if(!C.existsSync(n))return!1;try{return C.readdirSync(n,{withFileTypes:!0}).some(t=>dg(n,t))}catch{}return!1}function rl(n){let t=new st(n).getAllModuleInfo(),r=[];for(let o of t){let i=P.resolvePathWithinRoot(n,o.srcPath);nl(i)&&r.push(o)}return r}function ug(n){let e=[],r=new st(n).getAllModuleInfo();for(let o of r){let i=P.resolvePathWithinRoot(n,o.srcPath),s=Z.join(i,".cxx");C.existsSync(s)&&ol(s,e)}return e}function ol(n,e){try{let t=C.readdirSync(n,{withFileTypes:!0});for(let r of t){let o=Z.join(n,r.name);r.isDirectory()?ol(o,e):r.name==="compile_commands.json"&&e.push(o)}}catch{}}function pg(n){let e=[];for(let t of n)try{let r=C.readFileSync(t,"utf8"),o=JSON.parse(r);e.push(...o)}catch{}return e}function mg(n,e){let t=Z.join(n,...yi.slice(0,-1));C.mkdirSync(t,{recursive:!0});let r=Z.join(t,"compile_commands.json");C.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function fg(n){let e=ug(n);if(e.length>0){let t=pg(e);mg(n,t),f.info(`[CppCheck] compile_commands.json \u5DF2\u751F\u6210\uFF0C\u5171 ${t.length} \u6761\u7F16\u8BD1\u547D\u4EE4`)}else f.warn("[CppCheck] \u672A\u627E\u5230\u4EFB\u4F55 compile_commands.json \u6587\u4EF6")}var ki="/data/app/sdk.org/sdk_1.0.0";function hg(n,e){if(!I())return;let t=dn(n);if(!C.existsSync(t))return;let r=C.readFileSync(t,"utf8");if(!r.includes(ki))return;let o=r.replaceAll(ki,e);C.writeFileSync(t,o,"utf8"),f.info(`[CppCheck] Patched SDK path in compile_commands.json: ${ki} -> ${e}`)}function gg(n){let e=new Set;for(let t of n)if(t.file)try{e.add(C.realpathSync(t.file))}catch{e.add(t.file)}return e}function yg(n,e){try{let t=C.realpathSync(n);if(!e.has(t))return f.info(`[CppCheck] File not covered by compile_commands.json: ${n}`),!1}catch{}return!0}function vg(n,e){if(!C.existsSync(n))return!1;try{let t=C.readFileSync(n,"utf8"),r=JSON.parse(t),o=gg(r);for(let i of e)if(!yg(i,o))return!1;return!0}catch(t){return f.warn(`[CppCheck] Failed to read/parse compile_commands.json: ${t}`),!1}}async function wg(n,e,t=""){let r=Sg(n),o=t?` (${t})`:"";f.info(`[CppCheck] Running compileNative for module: ${n.name}${o}`);let i=await e(r);i.success?f.info(`[CppCheck] compileNative ${n.name} \u6210\u529F`):f.warn(`[CppCheck] compileNative ${n.name} \u5931\u8D25: ${i.output}`)}async function bg(n,e,t){let r=t.sdkPath,o=t.nodePath,i=t.hvigorJsPath;f.info(`CppCheck devecoStudioPath: ${t?.devecoStudioPath}, sdkPath: ${r}, nodePath: ${o}, hvigorPath: ${i}`);let s=async a=>Ai(n,o,i,r,a);for(let a of e)await wg(a,s)}function Sg(n){return["--mode","module","-p",`module=${n.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"]}async function Pg(n,e){let t=rl(n);if(t.length===0){f.info("[CppCheck] \u672A\u53D1\u73B0\u542BC++\u7684\u6A21\u5757\uFF0C\u8DF3\u8FC7\u521D\u59CB\u5316");return}f.info(`[CppCheck] \u53D1\u73B0 ${t.length} \u4E2A\u542BC++\u7684\u6A21\u5757: ${t.map(r=>r.name).join(", ")}`),await bg(n,t,e),fg(n)}var Lt=class{projectPath;toolProvider;clangdProcess=null;client=null;initializedProjectPath=null;initializing=!1;initPromise=null;pollHandle=null;backendReady=!1;constructor(e,t){this.projectPath=e,this.toolProvider=t}static getToolDefinition(){return{name:"check_cpp_files",description:"\u5BF9\u4F20\u5165\u7684 C/C++ \u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5\u5E76\u8FD4\u56DE clangd \u8BCA\u65AD\u4FE1\u606F\u3002",inputSchema:xi.object({files:xi.array(xi.string()).describe('\u5F85\u68C0\u67E5\u7684 C/C++ \u6587\u4EF6\u8DEF\u5F84\u5217\u8868\uFF0C\u683C\u5F0F\u4E3A ["file1.cpp","file2.hpp",...]')})}}isInitializing(){return this.initializing}isInitialized(){return this.client!==null&&this.initializedProjectPath!==null}async handleCall(e){let t=[],r=[],o=this.collectValidFiles(e.files,t);if(o.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
|
|
1270
|
-
`)
|
|
1271
|
-
`)}],isError:!0}}
|
|
1272
|
-
`),e.join(`
|
|
1273
|
-
`)].filter(i=>i.trim().length>0).join(`
|
|
1274
|
-
`).trim()}],isError:r}}async ensureInitializedWithFiles(e){let t=ve(this.projectPath),r=this.prepareCppCheck(t,e);if(hg(t,this.toolProvider.sdkPath),r)this.client&&this.initializedProjectPath&&(f.info("[CppCheck] Re-initializing C++ project due to file changes"),await this.shutdown()),await Pg(t,this.toolProvider);else if(this.client&&this.initializedProjectPath){let o=ve(this.projectPath);if(this.initializedProjectPath===o)return this.client;await this.shutdown()}return this.doEnsureInitialized()}prepareCppCheck(e,t){let r=dn(e);return C.existsSync(r)?rl(e).length===0?(f.info("[CppCheck] No cpp modules found, no initialization needed"),!1):vg(r,t)?(f.info("[CppCheck] All files covered, no initialization needed"),!1):(f.info("[CppCheck] Files not fully covered by compile_commands.json, needs initialization"),!0):(f.info("[CppCheck] compile_commands.json not found, needs initialization"),!0)}async doEnsureInitialized(){if(this.initPromise&&(await this.initPromise,this.client))return this.client;if(this.initializing=!0,this.initPromise=this.doInitialize().finally(()=>{this.initializing=!1,this.initPromise=null}),await this.initPromise,!this.client)throw new Error("C++ LSP failed to initialize");return this.client}async doInitialize(){let e=this.resolveProjectRoot();this.client=new Ri,await this.client.initialize(e),this.initializedProjectPath=e,f.info(`[CppCheck] Client initialized in wrapper mode for workspace: ${e}`),this.startPollingForClangd(e)}resolveProjectRoot(){let e=Ie(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);return this.projectPath=e,ve(e)}startPollingForClangd(e){let t=dn(e);if(C.existsSync(t)){f.info("[CppCheck] compile_commands.json found, spawning clangd immediately"),this.spawnAndConnectClangd(e).catch(r=>{f.error(`[CppCheck] Immediate clangd spawn failed: ${r}`)});return}f.info("[CppCheck] compile_commands.json not found, starting poll..."),this.pollHandle=setInterval(()=>{if(!this.client||this.client.isClosed()||this.backendReady){this.stopPolling();return}C.existsSync(t)&&(this.stopPolling(),f.info("[CppCheck] compile_commands.json found via poll, spawning clangd..."),this.spawnAndConnectClangd(e).catch(r=>{f.error(`[CppCheck] Clangd spawn from poll failed: ${r}`)}))},ag)}stopPolling(){this.pollHandle&&(clearInterval(this.pollHandle),this.pollHandle=null)}async spawnAndConnectClangd(e){let{clangdPath:t,compileCommandsDir:r}=this.resolveClangdPaths(e);f.info(`[CppCheck] Starting clangd for workspace: ${e} (clangd=${t})`);let o=this.spawnClangd(t,e,r);this.clangdProcess=o;try{await this.client.connectClangdProcess(o.stdin,o.stdout),this.backendReady=!0,f.info(`[CppCheck] clangd connected for workspace: ${e}`)}catch(i){if(f.error(`[CppCheck] Failed to connect clangd: ${i}`),this.clangdProcess&&!this.clangdProcess.killed){try{this.clangdProcess.kill()}catch{}this.clangdProcess=null}throw i}}resolveClangdPaths(e){let t=this.toolProvider.clangdPath;if(!t)throw new Error("clangd executable not found");let r=dn(e),o=Z.dirname(r);return{clangdPath:t,compileCommandsDir:o}}spawnClangd(e,t,r){let o=og(e,[`--compile-commands-dir=${r}`],{cwd:t,stdio:["pipe","pipe","pipe"]});if(!o.stdin||!o.stdout||!o.stderr)throw new Error("Failed to start clangd: stdio not available");return o.stderr.on("data",i=>{let s=i.toString("utf8").trimEnd();s&&f.warn(`[CppLsp stderr] ${s}`)}),o.on("exit",(i,s)=>{f.warn(`[CppCheck] clangd exited code=${i} signal=${s??"null"}`),this.clangdProcess===o&&(this.clangdProcess=null,this.backendReady=!1)}),o.on("error",i=>{f.error(`[CppCheck] clangd spawn error: ${i}`)}),o}collectValidFiles(e,t){let r=this.projectPath,o=[];for(let i of e){let s=Z.isAbsolute(i)?i:Z.join(r,i);if(!C.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${i}`);continue}if(!C.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${i}`);continue}if(!cr(s)){t.push(`\u4E0D\u662F\u53D7\u652F\u6301\u7684 C/C++ \u6587\u4EF6: ${i}`);continue}try{o.push(C.realpathSync(s))}catch{o.push(s)}}return o}async shutdown(){this.stopPolling();let e=this.client,t=this.clangdProcess;if(this.client=null,this.clangdProcess=null,this.initializedProjectPath=null,this.backendReady=!1,e)try{await e.close()}catch(r){f.warn(`[CppCheck] client.close() failed: ${r}`)}if(t&&!t.killed)try{t.kill()}catch(r){f.warn(`[CppCheck] failed to kill clangd: ${r}`)}}};function il(n){let e=Bn(n);return d.info(`[SyncGuard] ${e.reason}`),e}var al=(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))(al||{}),Oi=3,sl=600*1e3,zr=class{server;toolRouter;config;arktsCheckTool=null;cppCheckTool=null;projectState=0;workspaceRoot="";initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;toolProvider;constructor(e){this.config=e,this.toolProvider=e.toolProvider,Si(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),f.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",f.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,f.info(`Constructor: using configured path as startPath: '${t}'`));let o=Ie(t);f.info(`Constructor: findHarmonyProject('${t}') => ${o??"null"}`),this.config.projectPath=o??void 0,this.server=new Eg({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=hi(),this.registerTools()}getToolProvider(){return this.toolProvider}registerTools(){this.toolRouter.add({name:"check",description:"Perform static syntax analysis on HarmonyOS project source files and return structured diagnostics. Supported languages: ArkTS and C/C++.",inputSchema:Mi.object({files:Mi.array(Mi.string()).min(1).describe("List of source file paths to check, relative to the project root. Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}validateContainment(e){let t=this.config.projectPath;if(t){let o=[];for(let i of e){let s=P.isPathContainedWithSymlink(i,t);s.contained||(f.warn(`Containment check failed: ${s.reason}`),o.push(s.reason))}return o.length>0?{content:[{type:"text",text:o.join(`
|
|
1275
|
-
`)}],isError:!0}:null}let r=e.filter(o=>qr.isAbsolute(o));return r.length>0?(f.warn(`Absolute paths rejected (no project root): ${r.join(", ")}`),{content:[{type:"text",text:r.map(o=>`Absolute path is not allowed: ${o}`).join(`
|
|
1276
|
-
`)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(h=>typeof h=="string"):[];if(t.length===0)return f.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};let r=this.validateContainment(t);if(r)return r;let{etsFiles:o,cppFiles:i,unsupported:s}=Ig(t);s.length>0&&f.warn(`Unsupported file types in check request: ${s.join(", ")}`);let a=s.map(h=>`Unsupported file type: ${h} (only .ets and C/C++ source/header files are supported)`),c=[];o.length>0&&this.mergeCheckResult(await this.callArktsCheck(o),a,c),i.length>0&&this.mergeCheckResult(await this.callCppCheck(i),a,c);let l=a.length>0;return{content:[{type:"text",text:[c.join(`
|
|
1289
|
+
`));let i=r.join(`
|
|
1290
|
+
`).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(He),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=le.join(Ut(),"ArkTSCheck"),r=le.join(t,"mapping-config.properties"),i=mu(e,r),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=le.join(t,"lsp-log",String(i),o),a=le.join(t,"lsp-index",String(i));return Ie.mkdirSync(s,{recursive:!0}),Ie.mkdirSync(a,{recursive:!0}),{logPath:ae(s),indexPath:ae(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function vC(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 SC(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 Me from"fs";import*as $s from"path";import{z as dl}from"zod";function hr(){return{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}function Hs(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 bC=500,gr=class{manager;toolProvider;constructor(e,t){this.manager=e,this.toolProvider=t}static getToolDefinition(){return{name:"check_cpp_files",description:"Perform static syntax checks on the provided C/C++ files and return clangd diagnostics.",inputSchema:dl.object({files:dl.array(dl.string()).describe('List of C/C++ file paths to check, format: ["file1.cpp","file2.hpp",...]')})}}async handleCall(e){if(!this.manager.ready)return hr();let t=[],r=[],i=this.collectValidFiles(e.files,t);if(i.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
|
|
1291
|
+
`):"No valid C/C++ files"}],isError:!0};this.patchSdkPathInCompileCommands(this.manager.projectRoot,this.toolProvider.sdkPath);for(let c of i){await PC(bC);try{let l=await this.checkFile(c);r.push(EC(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(`
|
|
1292
|
+
`)),r.length>0&&s.push(r.join(`
|
|
1293
|
+
`));let a=s.join(`
|
|
1294
|
+
`).trim();return!o&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:o}}patchSdkPathInCompileCommands(e,t){if(!b())return;let r=vn(e);if(!Me.existsSync(r))return;let i=Me.readFileSync(r,"utf8");if(!i.includes(To))return;let o=i.replaceAll(To,t);Me.writeFileSync(r,o,"utf8"),f.info(`[CppCheck] Patched SDK path in compile_commands.json: ${To} -> ${t}`)}async checkFile(e){let t=bn(e),r=await Me.promises.readFile(e,"utf8"),i=Po(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=$s.isAbsolute(o)?o:$s.join(r,o);if(!Me.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!Me.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!Sn(s)){t.push(`Not a supported C/C++ file: ${o}`);continue}try{i.push(Me.realpathSync(s))}catch{i.push(s)}}return i}};function EC(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 PC(n){return new Promise(e=>setTimeout(e,n))}import*as wr from"fs";import*as Us from"path";var yr=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 hr();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 Hs(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 hr();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 Hs("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return hr();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 Hs("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=bn(e),i=await wr.promises.readFile(e,"utf8"),o=Po(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=Us.isAbsolute(e)?e:Us.join(this.manager.projectRoot,e);return!wr.existsSync(t)||!wr.statSync(t).isFile()||!Sn(t)?null:t}};import{spawn as CC}from"child_process";import*as Ws from"fs";import*as ym from"path";var IC=30*1e3,AC=30*1e3,Bs=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new qt;diagnosticWaiters=new Map;lastStartErrorMessage=null;onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}async start(e){let t=!1;try{f.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),f.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),f.info(`[ClangdLspProxy] compileCommandsDir: ${this.config.compileCommandsDir}`),this.ensureLogDir(),this.clangdProcess=this.spawnClangd();let r={serverPath:"",logPath:this.config.logPath,indexingDataLocation:this.config.logPath,cwd:this.config.workspaceRoot,nodePath:this.config.nodePath};this.client=new Vt(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,He),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}`))},AC);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=${j(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];f.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=CC(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=zn(this.config.workspaceRoot),t=et(e),r=ym.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"0.3.0-TD.1.1"},rootPath:e,rootUri:t,workspaceFolders:[{uri:t,name:r}],capabilities:this.buildClientCapabilities(),initializationOptions:null}}buildClientCapabilities(){return{textDocument:{synchronization:{didOpen:!0,didChange:!0,didClose:!0,willSave:!1,save:!1},publishDiagnostics:{relatedInformation:!0,versionSupport:!1,tagSupport:{valueSet:[1,2]}},hover:{contentFormat:["markdown","plaintext"]},completion:{contextSupport:!1,completionItemKind:{valueSet:[]}},signatureHelp:{signatureInformation:{documentationFormat:["markdown","plaintext"]}},references:{},declaration:{linkSupport:!0},definition:{linkSupport:!0},implementation:{linkSupport:!0},documentSymbol:{hierarchicalDocumentSymbolSupport:!0,symbolKind:{valueSet:[]}},callHierarchy:{dynamicRegistration:!1}},workspace:{symbol:{symbolKind:{valueSet:[]}},configuration:!1,didChangeWatchedFiles:{dynamicRegistration:!1}}}}sendLspRequest(e,t,r=IC){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:T,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:T,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:T,method:y.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{Ws.existsSync(this.config.logPath)||Ws.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)),et(r)}}catch{}return e}};import*as Di from"path";import*as ul from"fs";var Ti=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)return f.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or devecoPath is empty"),{status:"failed",reason:"workspaceRoot or devecoPath is empty"};if(Pn(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let i=await yo(e,async()=>{try{return await xu(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(He);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=St(this.config.workspaceRoot);this.resolvedRoot=e?ae(e):ae(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();Do(t);let r=this.config.toolProvider.clangdPath;if(!r){let s="clangd executable not found inside DevEco Studio SDK";f.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let i=Di.dirname(vn(this.resolvedRoot));try{ul.mkdirSync(i,{recursive:!0})}catch(s){f.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}f.info(`[ClangdLspManager] clangdPath: ${r}`),f.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),f.info(`[ClangdLspManager] compileCommandsDir: ${i}`);let o=new Bs({clangdPath:r,workspaceRoot:this.resolvedRoot,compileCommandsDir:i,logPath:t,nodePath:this.config.toolProvider.nodePath});o.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=o,o.start(s=>this.handleProxyInitialized(s)).catch(s=>{let a=s instanceof Error?s:new Error(String(s));this.handleProxyInitialized(!1,a.message)})}handleProxyInitialized=(e,t)=>{if(this.clearInitTimer(),e){this.isInitialized=!0,f.info("[ClangdLspManager] clangd initialized");let r=this.initResolve;this.clearInitHandlers(),r?.()}else{let r=t??this.proxy?.consumeStartErrorMessage()??"unknown error";f.error(`[ClangdLspManager] clangd initialization failed: ${r}`),this.isInitialized=!1,this.proxy=null;let 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=Di.join(Ut(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=Di.join(e,"lsp-log",t);return ul.mkdirSync(r,{recursive:!0}),ae(r)}catch{return"auto"}}};function wm(n){let e=vo(n);return f.info(`[SyncGuard] ${e.reason}`),e}var fl=(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))(fl||{}),Sm=(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))(Sm||{}),Xt=3,pl=600*1e3,zs=class{server;toolRouter;config;arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;standardProtocolAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;constructor(e){this.config=e,En(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=St(t);g.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0,this.server=new DC({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=al(),this.standardProtocolAvailable=this.detectStandardProtocolAvailable(),this.registerTools()}registerTools(){this.registerCheckTool(),b()||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:he.object({files:he.array(he.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=he.object({file:he.string().describe("Source file path, relative to the project root. Supports .ets (ArkTS) and C/C++ extensions."),line:he.number().describe("Line number (0-based)"),character:he.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature: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:he.object({query:he.string().describe("Symbol name (or partial) to search for")})},async e=>this.handleWorkspaceSymbolCall(e)),this.toolRouter.add({name:"documentSymbol",description:"Get the symbol tree (functions, classes, variables with ranges) of an ArkTS (.ets) or C/C++ file. Useful for file overview, structured code breakdown, and large file slicing.",inputSchema:he.object({file:he.string().describe("Source file path, relative to the project root. Supports .ets and C/C++ extensions.")})},async e=>this.handleDocumentSymbolCall(e))}registerCallHierarchyTool(){this.toolRouter.add({name:"callHierarchy",description:'Query call hierarchy for a function at the given position. Use direction "incoming" to find callers, "outgoing" to find callees. ArkTS supports both directions; C/C++ (clangd) supports incoming only.',inputSchema:he.object({file:he.string().describe("Source file path, relative to the project root. Supports .ets and C/C++ extensions."),line:he.number().describe("Line number (0-based)"),character:he.number().describe("Character offset in the line (0-based)"),direction:he.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.config.toolProvider.lspServerPath;if(!e)return g.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=Zt.join(Zt.dirname(e),"standardIndex","index.js"),r=vm.existsSync(t);return g.info(`ArktsCheck protocol: ${r?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${r})`),r}catch(e){return g.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}validateContainment(e){let t=this.config.projectPath;if(t){let i=[];for(let o of e){let s=E.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(`
|
|
1295
|
+
`)}],isError:!0}:null}let r=e.filter(i=>Zt.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(`
|
|
1296
|
+
`)}],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}=RC(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(`
|
|
1277
1297
|
`),a.join(`
|
|
1278
1298
|
`)].filter(h=>h.trim().length>0).join(`
|
|
1279
|
-
`).trim()||"No diagnostics collected"}],isError:l}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return f.warn(`ArkTS check rejected: project is ${al[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return f.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e});default:return{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],isError:!0}}}async handleIdleCheck(){if(this.ensureProjectReady(),this.config.projectPath){let e,t;return this.syncSkippedDueToLock?(e=`Another build process is running, sync deferred (waiting ${this.syncSkipStartedAt>0?Math.round((Date.now()-this.syncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,t="lock contention",this.syncSkippedDueToLock=!1):this.configChangedTriggeredResync?(e="Config file changed, resyncing project, please retry in 10 seconds",t="config changed",this.configChangedTriggeredResync=!1):(e="HarmonyOS project detected, syncing, please retry in 10 seconds",t="initial"),f.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(f.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(f.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=Oi?(f.error(`Init retry limit reached (${this.initRetryCount}/${Oi}), will not auto-retry`),{content:[{type:"text",text:"Project initialization failed multiple times. Please check project configuration and restart the MCP Server."}],isError:!0}):(f.info(`Error check: auto-retrying (${this.initRetryCount}/${Oi})`),this.ensureProjectReady(),{content:[{type:"text",text:"Project initialization failed, auto-retrying, please retry in 10 seconds"}],isError:!0})}async callCppCheck(e){if(!this.cppCheckTool){let t=this.config.projectPath?"C++ LSP is not ready, please retry later":"Project path is not configured. Set the PROJECT_PATH parameter or open a project in DevEco Studio.";return f.warn(`C++ check rejected: ${t}, files: ${e.join(", ")}`),{content:[{type:"text",text:t}],isError:!0}}return this.cppCheckTool.handleCall({files:e})}mergeCheckResult(e,t,r){let o=e.content.map(i=>i.text).filter(i=>i&&i.trim().length>0).join(`
|
|
1280
|
-
`);o&&(e.isError?t.push(o):r.push(o))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{f.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool&&(this.cppCheckTool.shutdown().catch(t=>{f.warn("Failed to shutdown CppCheckTool during setProjectPath:",t)}),this.cppCheckTool=null),this.initPromise?(this.needsReinit=!0,f.info("Project path changed while init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{f.warn("Failed to re-init project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new Dg;if(await this.server.connect(e),f.info("devecocli-mcp-server started"),!this.config.debug){let t=kc();t&&f.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=Ie(t);r?(f.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):f.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?f.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):f.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{f.warn("Background project init failed:",t)}),this.initializeCppCheck()}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return f.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return f.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){f.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,f.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{f.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{f.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}initializeCppCheck(){let e=this.config.projectPath;if(!e){f.warn("C++ LSP initialization skipped: project path is not configured");return}this.cppCheckTool=new Lt(e,this.toolProvider),f.info("CppCheckTool created (lazy initialization)")}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{f.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?Ie(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=Ie(this.originalProjectPath),t&&f.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&await this.ensureProjectSynced()){this.projectState=3,this.arktsCheckTool=new Nt(this.config.projectPath,this.toolProvider,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{f.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,f.info("Project fully initialized, check tool is available")}catch(e){f.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=il(e),r=!t.required;return f.info(`Sync check: skipHvigor=${r}, reason=${t.reason}`),this.runSync(e,{skipHvigorSync:r})}async runSync(e,t){this.projectState=2,f.info("Starting project sync...");let r=await Ot.handleSyncProject(e,this.toolProvider,t);switch(r.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let o=Date.now()-this.syncSkipStartedAt,i=Math.round(o/1e3);return o>=sl?(f.error(`Sync skipped for ${i}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(f.warn(`Sync skipped: ${r.reason}, resetting to IDLE for retry (elapsed ${i}s / ${sl/1e3}s)`),this.projectState=0,!1)}case"failed":return f.error(`Project sync failed: ${r.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:{let o=r;return f.error(`Unknown sync result status: ${JSON.stringify(o)}`),this.projectState=5,!1}}}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppCheckTool&&await this.cppCheckTool.shutdown();try{await this.server.close()}catch(e){f.warn("Failed to close MCP server connection:",e)}f.info("devecocli-mcp-server stopped"),xc(),Tc()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function Ig(n){let e=[],t=[],r=[];for(let o of n)qr.extname(o).toLowerCase()===".ets"?e.push(o):cr(o)?t.push(o):r.push(o);return{etsFiles:e,cppFiles:t,unsupported:r}}function Ni(n){return new zr(n)}async function Ag(){let n=process.env.PROJECT_PATH||"",e=process.env.DEVECO_PATH,t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=process.env.DEBUG==="true"||process.env.DEBUG==="1",o=await _.new(e),s=Ni({toolProvider:o,projectPath:n,nodeMaxOldSpaceSize:t,debug:r}),a=async()=>{await s.shutdown(),process.exit(0)};process.once("SIGINT",a),process.once("SIGTERM",a),process.platform==="win32"&&process.once("SIGBREAK",a);try{await s.start()}catch(c){console.error("Failed to start MCP server:",c),process.exit(1)}}var cl=new Cg("serve").description("Host bundled auxiliary protocol servers");cl.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await Ag()});var ll=cl;import{Command as Iw,InvalidArgumentError as Ss}from"commander";import{red as So,dim as Cw}from"colorette";import*as z from"fs";import*as Bt from"path";import lw from"adm-zip";import dw from"proper-lockfile";import hu from"ora";import*as pe from"fs";import*as Dn from"path";var Ue=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],at={"harmonyos-guides":"\u5F00\u53D1\u6307\u5357","harmonyos-references":"API\u53C2\u8003","best-practices":"\u6700\u4F73\u5B9E\u8DF5","harmonyos-faqs":"FAQ","harmonyos-releases":"\u7248\u672C\u8BF4\u660E","harmonyos-roadmap":"\u53D8\u66F4\u9884\u544A"};var Vr="1.9.1",hk=48*1024*1024,dl=280,ul=6,pl=100,ml=3,fl=28,Li=10,hl=/API参考|APIReference/i,Sn=200,gl=12,yl=4,_i=8,vl=6,Gr=700,Hi=250,ji=400,wl=1320,bl=120,Sl=450,Pl=250,El=500,Dl=480,Il=80,Cl=200,Al=60,Tl=200,xl=40,kl=200,Rl=200,Ml=40,_t=500,Ol=Object.fromEntries(Ue.map((n,e)=>[at[n],e])),ze=Object.fromEntries(Ue.map((n,e)=>[n,e]));import*as _l from"fs";import*as x from"path";import{fileURLToPath as Hl}from"url";import*as Yr from"path";import{homedir as Tg}from"os";var xg="deveco-cli";function Ll(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function kg(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&Ll(n)!==""}function Nl(){return Yr.join(Tg(),".local","share",xg)}function Jr(n){let e=Kr();return kg()?[`Data directory (DEVECO_CLI_DATA_DIR): ${e}`,"If you changed this in System Environment Variables, open a new terminal and retry.",`Log file: ${n}`]:[`Data directory (default): ${e}`,"To use a custom location, set DEVECO_CLI_DATA_DIR and open a new terminal.",`Log file: ${n}`]}function Kr(){let n=process.env.DEVECO_CLI_DATA_DIR;if(n===void 0||n==="")return Nl();let e=Ll(n);return e?Yr.resolve(e):Nl()}var Rg="docs";function Zr(){return x.join(Kr(),Rg)}function X(){return x.join(Zr(),".index")}function jl(){return x.join(X(),"build.lock")}function Fi(){return x.join(X(),"build-status.json")}function Xr(){return x.join(X(),"build-meta.json")}function Pn(){return x.join(X(),"search.db")}function Ht(){return x.join(X(),".tmp")}function Mg(){return x.join(Kr(),"logs")}function jt(){return x.join(Mg(),"doc-init.log")}function Og(n,e){let t=e;for(;!t.endsWith(`${x.sep}dist`)&&t!==x.dirname(t);)t=x.dirname(t);return t}function Fl(n,e){return x.dirname(Og(n,e))}function Ng(){let n=Hl(import.meta.url),e=x.dirname(n);return n.includes(`${x.sep}dist${x.sep}`)?Fl(n,e):x.join(e,"..","..","..")}function Lg(...n){let e=Hl(import.meta.url),t=x.dirname(e);return e.includes(`${x.sep}dist${x.sep}`)?[x.join(Fl(e,t),...n)]:[x.join(t,"..","..","..",...n)]}function $l(...n){for(let e of Lg(...n))if(_l.existsSync(e))return e;return null}function qe(){return $l("docs.zip")}function $i(){return $l("index.zip")}function Bl(){return x.join(Ng(),"index","data")}import*as ke from"fs";import*as ct from"path";var lt=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Qr=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function Wl(n){return n instanceof Qr}var Bi=null;function Wi(n){Bi=n}function Ui(){if(Bi)return Bi;let n=X();if(lt.every(o=>ke.existsSync(ct.join(n,o))))return n;let t=Bl();if(lt.every(o=>ke.existsSync(ct.join(t,o))))return t;throw new Qr("Lexicon files not found. Install the documentation index first (index.zip).")}function Ul(){Ui()}function dt(n){let e=ct.join(Ui(),n);return ke.readFileSync(e,"utf-8")}function zl(n,e){return ke.readFileSync(ct.join(e,n),"utf-8")}async function ql(n,e=Ui()){await ke.promises.mkdir(n,{recursive:!0});for(let t of lt){let r=ct.join(e,t),o=ct.join(n,t);await ke.promises.copyFile(r,o)}}import*as eo from"fs";import*as Vl from"path";import*as Gl from"yauzl";var En=null;function _g(n){return new Promise((e,t)=>{Gl.open(n,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(r,o)=>{if(r||!o){t(r??new Error(`Failed to open zip: ${n}`));return}e(o)})})}function Hg(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function jg(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",o=>{let i=Hg(o);i.endsWith("/")||e.set(i,o),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function Fg(){En?.zipfile.close(),En=null}async function $g(n){let e=Vl.resolve(n),t=await eo.promises.stat(e),r=En;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;Fg();let o=await _g(e),i=await jg(o);return En={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:o,entries:i,readChain:Promise.resolve()},En}function Bg(n,e){return new Promise((t,r)=>{n.openReadStream(e,(o,i)=>{if(o||!i){r(o??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];i.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),i.on("end",()=>{t(Buffer.concat(s))}),i.on("error",r)})})}async function Wg(n,e){let t=n.readChain,r;n.readChain=new Promise(o=>{r=o}),await t;try{return await Bg(n.zipfile,e)}finally{r()}}function Ug(n){let e=n.replace(/\\/g,"/").replace(/\.md$/,"");return[`docs/${e}.md`,`${e}.md`,`docs/${e}`,e]}function zg(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function Yl(n){let e=qe();if(!e)throw new Error("docs.zip not found");let t=await $g(e),r=zg(t.entries,Ug(n));if(!r)throw new Error(`Document not found: ${n}`);return(await Wg(t,r)).toString("utf-8")}function zi(){let n=qe();return n!==null&&eo.existsSync(n)}import*as Y from"fs";import*as Ve from"path";import Jl from"adm-zip";var Kl=["search.db","build-meta.json",...lt],qg=["corpus.json","corpus-offsets.json","orama.dpack"];async function Vg(n){for(let e of qg)await Y.promises.rm(Ve.join(n,e),{force:!0})}async function Gg(n){let e=await Y.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await Y.promises.rm(Ve.join(n,t.name),{recursive:!0,force:!0})}function Yg(n){let t=new Jl(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 Jg(n){let e=X();await Y.promises.mkdir(e,{recursive:!0});for(let t of Kl){let r=Ve.join(e,t);await Y.promises.rm(r,{force:!0}),await Y.promises.rename(Ve.join(n,t),r)}await Vg(e),await Y.promises.rm(Ht(),{recursive:!0,force:!0})}function qi(){let n=$i();return n!==null&&Y.existsSync(n)}async function Zl(n){let e=$i();if(!e)throw new Error("index.zip not found");let t=Yg(e);if(t.docsZipSha256!==n)throw new Error("Bundled index.zip does not match docs.zip. Rebuild index.zip with npm run build:index.");if(t.segmentCount<=0)throw new Error("Bundled index.zip is empty");let r=Ht();await Y.promises.rm(r,{recursive:!0,force:!0}),await Y.promises.mkdir(r,{recursive:!0});let o=new Jl(e);for(let s of Kl){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await Y.promises.writeFile(Ve.join(r,s),a.getData())}let i=JSON.parse(await Y.promises.readFile(Ve.join(r,"build-meta.json"),"utf-8"));if(!Y.existsSync(Ve.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await Jg(r),await Y.promises.mkdir(Zr(),{recursive:!0}),await Gg(Zr()),i}import{createHash as Xl}from"crypto";import*as Ql from"fs";async function to(n){return new Promise((e,t)=>{let r=Xl("sha256"),o=Ql.createReadStream(n);o.on("data",i=>r.update(i)),o.on("error",t),o.on("end",()=>e(r.digest("hex")))})}function ed(n){return Xl("sha256").update(n,"utf8").digest("hex")}var Vi=null;function Kg(){let n=dt("harmonyos-synonyms.json");return JSON.parse(n)}function Zg(n){let e=new Map;for(let t of n){let r=t.map(o=>o.trim()).filter(Boolean);for(let o of r){let i=r.filter(s=>s!==o);e.set(o.toLowerCase(),i),o!==o.toLowerCase()&&e.set(o,i)}}return e}function Xg(){let n=Zg(Kg()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function Qg(){return Vi||(Vi=Xg()),Vi}function Gi(n,e){let t=Qg(),r=n.split(/\s+/).filter(Boolean),o=new Set,i=Number.isFinite(e)?e:r.length;for(let s=0;s<r.length&&o.size<i;s+=1){let a=r[s];o.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(o.size>=i)break;o.add(l)}}return[...o].join(" ")}function td(n,e){let t=e?zl(n,e):dt(n);return ed(t)}function no(n){return td("harmonyos-synonyms.json",n)}function ro(n){return td("harmonyos-terms.txt",n)}var ey={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function oo(){try{let n=await pe.promises.readFile(Fi(),"utf-8");return JSON.parse(n)}catch{return{...ey}}}async function Yi(n){let e=Fi();await pe.promises.mkdir(Dn.dirname(e),{recursive:!0}),await pe.promises.writeFile(e,JSON.stringify(n,null,2))}function nd(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 Ge(n){let t={...await oo(),...n,updatedAt:Date.now()};return await Yi(t),t}async function Ji(){let n=qe();return n?to(n):null}async function Ki(){try{let n=await pe.promises.readFile(Xr(),"utf-8");return JSON.parse(n)}catch{return null}}async function Zi(n=!1){if(n)return"no-index";let e=await Ki();if(!e||e.segmentCount===0)return"no-index";let t=await Ji();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==Vr?"engine-upgraded":e.termsHash!==ro()?"terms-changed":e.synonymsHash!==no()?"synonyms-changed":null}function In(){if(!zi()||!pe.existsSync(Pn())||!pe.existsSync(Xr()))return!1;let n=Dn.dirname(Pn());if(!lt.every(e=>pe.existsSync(Dn.join(n,e))))return!1;try{let e=pe.readFileSync(Xr(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function Xi(n=!1){return n?!0:zi()?In()?await Zi()!==null:!0:!1}async function rd(){let n=await oo();return["installing","indexing","persisting"].includes(n.state)}import*as J from"fs";import*as cu from"os";import*as ee from"path";var od=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),Qi=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),id=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"]),sd=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 ty=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,ny=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,ry=/[A-Z][a-zA-Z0-9]{2,}/g,oy=/@[A-Z][a-zA-Z0-9]*/g,iy=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,ad=6,sy=/^[a-z][a-z0-9]{2,}$/,ay=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,cy=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,ly=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,dy=/^[A-Z][a-zA-Z0-9]+$/;function uy(n){return`"${n.replace(/"/g,'""')}"`}function An(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(uy).join(` ${e} `)}function Cn(n){return An(n,"OR")}function cd(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?Cn([...t,...r]):`(${Cn(t)}) AND (${Cn(r)})`}function Tn(n){return cy.test(n)}function ld(n){return ly.test(n)&&n.length>=ad}function py(n){return dy.test(n)}function xn(n){return Tn(n)||ld(n)||py(n)}function my(n){let e=n.trim().toLowerCase();return sd.has(e)?!1:od.has(e)}function fy(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function io(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function es(n){return[...n.matchAll(ty)].map(e=>e[0])}function ts(n,e=ad){let t=[];for(let r of n.matchAll(ny))r[0].length>=e&&t.push(r[0]);return t}function Ft(n){return n.filter(e=>{let t=e.toLowerCase();return!n.some(r=>{if(r===e)return!1;let o=r.toLowerCase();return o.length>t.length&&o.endsWith(t)&&t.length>=4})})}function me(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function hy(n){let e=new Set;me(e,n);let t=io(n);return t&&me(e,t),Ft([...e])}function so(n){if(Tn(n))return hy(n);let e=new Set;return me(e,n),Ft([...e])}function ao(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(ay);if(!t)return null;let r=t[1].toLowerCase(),o=t[2].toLowerCase();if(!sy.test(r)||id.has(r)||!my(o))return null;let i=fy(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function ns(n){let e=ao(n.trim());return!e||e.second!=="manager"?null:e}function gy(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function dd(n){let e=n.trim(),t=ns(e);if(t&&Qi.has(t.first))return!0;if(ld(e)){let r=gy(e);return r!==null&&Qi.has(r)}return!1}function rs(n,e,t){let r=t.toLowerCase(),o=new RegExp(`@ohos\\.[^\\s(]*${t}`,"i");for(let i of[n,e])if(i&&(i.toLowerCase().includes(r)||o.test(i)))return!0;return!1}function os(n){let e=n.trim();if(xn(e))return so(e);let t=new Set;for(let r of es(n)){me(t,r);let o=io(r);o&&me(t,o)}for(let r of ts(n))me(t,r);for(let r of n.matchAll(oy))t.add(r[0]);for(let r of n.matchAll(iy))t.add(r[0]);for(let r of n.matchAll(ry))r[0].length>=4&&t.add(r[0]);return Ft([...t])}function ud(n){let e=n.trim();if(xn(e))return so(e);let t=new Set,r=ao(e);r&&me(t,r.camelCase);for(let o of os(e))t.add(o);for(let o of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let i=o[0];i!==i.toLowerCase()&&t.add(i)}return Ft([...t])}function pd(n){return xn(n)}var N={pureApiSymbol:/^[A-Z][a-zA-Z0-9]+$/,stageModelExact:/^Stage\s*模型$/i,stageModelEnglishExact:/^stage\s+model$/i,stageModel:/Stage\s*模型/i,stageModelEntryPage:/Stage\s*模型.*EntryAbility.*(页面|新页面)/,declarePermissionBoost:/声明.*权限|应用权限.*声明|如何声明应用权限/,declarePermissionCatalog:/如何声明应用权限/,declarePermissionTokens:/如何声明应用权限|声明应用权限/,uiAbilityLifecycleBoost:/UIAbility.*生命周期|生命周期.*UIAbility|UIAblity/i,uiAbilityLifecycleCatalog:/UIAblity.*生命周期|UIAbility.*生命周期/i,entryAbilityPage:/EntryAbility.*(页面|启动|跳转|新页面)/,stateDecoratorBoost:/@State|@Prop|@Link|@Provide|@Consume/,stateDecoratorCatalog:/@State\s*装饰器|@Prop\s*装饰器|@Link\s*装饰器/,stateManagement:/状态管理原理/,routerRoute:/Router\s+路由/,dialogPopupExact:/^Dialog\s+弹窗$/,dialogPopupBoost:/Dialog\s+弹窗/};function md(n){return N.pureApiSymbol.test(n.trim())}function kn(n){let e=n.trim();return N.stageModelExact.test(e)||N.stageModelEnglishExact.test(e)}function fd(n){let e=[];return kn(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),N.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),N.stageModelEntryPage.test(n)&&e.push("\u9875\u9762\u8DEF\u7531","pushUrl"),/UIAblity|UIAbility/.test(n)&&/生命周期/.test(n)&&e.push("UIAbility\u7EC4\u4EF6\u751F\u547D\u5468\u671F"),e}function hd(n){return kn(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var yy=[{matches:n=>N.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>kn(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!kn(n)&&N.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>N.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>N.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>N.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>N.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>N.routerRoute.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:1.4},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]},{matches:n=>N.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function vy(n,e){for(let{catalog:t,multiplier:r}of e){let o=ze[t];n.set(o,(n.get(o)??1)*r)}}function gd(n,e){for(let t of yy)t.matches(n)&&vy(e,t.weights)}function yd(n,e){if(e!==void 0)return!1;let t=n.trim();return Tn(t)||N.pureApiSymbol.test(t)||dd(t)}function vd(n){let e=n.trim();if(Tn(e)||N.pureApiSymbol.test(e))return"harmonyos-references";if(kn(e)||N.uiAbilityLifecycleCatalog.test(e)||N.stateDecoratorCatalog.test(e)||N.stateManagement.test(e)||N.declarePermissionCatalog.test(e)||N.stageModelEntryPage.test(e)||N.routerRoute.test(e)||N.dialogPopupExact.test(e))return"harmonyos-guides"}var co=null,ss=null,as=null,wd=!1,is=null;function wy(){if(co)return co;let n=dt("harmonyos-stopwords.txt");return co=new Set(n.split(`
|
|
1281
|
-
`).map(e=>e.trim()).filter(Boolean)),
|
|
1299
|
+
`).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 ${fl[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}/${Xt})`;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}/${Xt})`;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 ${fl[this.projectState]}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return g.warn(`ArkTS ${e} rejected: LSP is initializing`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return t();default:return g.error(`ArkTS ${e}: unknown project state ${this.projectState}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],isError:!0}}}async handleIdleCheck(){if(this.ensureProjectReady(),this.config.projectPath){let e,t;return this.syncSkippedDueToLock?(e=`Another build process is running, sync deferred (waiting ${this.syncSkipStartedAt>0?Math.round((Date.now()-this.syncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,t="lock contention",this.syncSkippedDueToLock=!1):this.configChangedTriggeredResync?(e="Config file changed, resyncing project, please retry in 10 seconds",t="config changed",this.configChangedTriggeredResync=!1):(e="HarmonyOS project detected, syncing, please retry in 10 seconds",t="initial"),g.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(g.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(g.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=Xt?(g.error(`Init retry limit reached (${this.initRetryCount}/${Xt}), 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}/${Xt})`),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 ${Sm[this.cppProjectState]}`),{content:[{type:"text",text:"C++ project is syncing (compileNative), please retry in 25 seconds"}],isError:!0};case 3:return g.warn(`C++ ${e} rejected: clangd is initializing`),{content:[{type:"text",text:"C++ LSP (clangd) is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleCppErrorCheck();case 4:return this.cppHasNoCppCode?{content:[{type:"text",text:"No C++ code in this project"}],isError:!0}:this.cppLspManager?.ready?t():{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0};default:return g.error(`C++ ${e}: unknown C++ project state ${this.cppProjectState}`),{content:[{type:"text",text:`Unknown C++ project state: ${this.cppProjectState}`}],isError:!0}}}async routeLspRequest(e,t,r){return e.endsWith(".ets")?this.routeArktsRequest(t,r):Sn(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>=Xt?(g.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${Xt}), 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}/${Xt})`),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(`
|
|
1300
|
+
`);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 TC;if(await this.server.connect(e),g.info("devecocli-mcp-server started"),!this.config.debug){let t=wu();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=St(t);r?(g.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):g.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?g.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):g.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{g.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return g.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return g.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){g.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,g.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{g.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{g.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{g.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?St(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=St(this.originalProjectPath),t&&g.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&await this.ensureProjectSynced()){this.ensureCppProjectReady().catch(e=>{g.warn("Background C++ project init failed:",e)}),this.projectState=3,this.arktsCheckTool=new mr(this.config.projectPath,this.config.toolProvider,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{g.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,g.info("Project fully initialized, check tool is available")}catch(e){g.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=wm(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 fr.handleSyncProject(e,this.config.toolProvider,t);switch(r.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let i=Date.now()-this.syncSkipStartedAt,o=Math.round(i/1e3);return i>=pl?(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 / ${pl/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=Pn(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 Ti({workspaceRoot:e,toolProvider:this.config.toolProvider});try{await this.cppLspManager.start(),this.cppCheckTool=new gr(this.cppLspManager,this.config.toolProvider),this.cppLspTool=new yr(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,g.info("[Cpp] C++ project fully initialized, C++ tools are available")}catch(r){g.error("[Cpp] C++ LSP initialization failed:",r),this.cppLspManager&&this.cppLspManager.dispose().catch(()=>{}),this.cppLspManager=null,this.cppCheckTool=null,this.cppLspTool=null,this.cppInitRetryCount++,this.cppProjectState=5}}}async runSyncCpp(e){this.cppProjectState=2,g.info("[Cpp] Starting C++ project sync (compileNative)...");let t=await Ti.handleSyncCppProject(e,this.config.toolProvider);switch(t.status){case"success":return this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,!0;case"skipped":{this.cppSyncSkippedDueToLock=!0,this.cppSyncSkipStartedAt===0&&(this.cppSyncSkipStartedAt=Date.now());let r=Date.now()-this.cppSyncSkipStartedAt,i=Math.round(r/1e3);return r>=pl?(g.error(`[Cpp] C++ sync skipped for ${i}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(g.warn(`[Cpp] C++ sync skipped: ${t.reason}, resetting to IDLE_CPP for retry (elapsed ${i}s)`),this.cppProjectState=0,!1)}case"failed":return g.error(`[Cpp] C++ project sync failed: ${t.reason}`),this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitRetryCount++,this.cppProjectState=5,!1}return!1}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppLspManager&&await this.cppLspManager.dispose(),this.cppCheckTool=null,this.cppLspTool=null;try{await this.server.close()}catch(e){g.warn("Failed to close MCP server connection:",e)}g.info("devecocli-mcp-server stopped"),yu(),gu()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function RC(n){let e=[],t=[],r=[];for(let i of n)Zt.extname(i).toLowerCase()===".ets"?e.push(i):Sn(i)?t.push(i):r.push(i);return{etsFiles:e,cppFiles:t,unsupported:r}}function ml(n){return new zs(n)}import*as hl from"fs";import*as Qt from"path";import{spawn as kC}from"child_process";async function bm(n){En(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:i,serverMaxSize:o}=await xC(n),s=OC(e,t,r,i,o);g.info("ace-server started, bridging stdio (initialize is left to the client)"),_C(s)}async function xC(n){let e=await A.new();b()||e.require({clt:!1});let t;if(n.projectPath)t=ae(Qt.resolve(n.projectPath)),g.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let c=Eo(process.cwd());t=ae(c??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=ae(process.cwd()),g.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,i=e.lspServerPath;i||(g.error("ace-server not found in DevEco Studio installation."),process.exit(1));let o=Qt.resolve(Qt.dirname(i),"standardIndex","index.js"),s=Qt.join(Ut(),"lsp-server",String(Date.now()));hl.mkdirSync(s,{recursive:!0});let a=NC(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 NC(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=LC(n,e),s=Ro(o,i);return g.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${o}, override=${i??"none"})`),s}function LC(n,e){try{let t=[];return new xn(n,e).getAllDependencyMap(t).status==="OK"?t.length:new bt(n).getAllModuleInfo().length}catch{return 0}}function OC(n,e,t,r,i){let o=Qt.join(e,"lspLog");hl.mkdirSync(o,{recursive:!0});let s=MC(n,o,t,r,i),a=process.execPath??"node";return g.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),kC(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function MC(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 _C(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 Em from"fs";import*as Nn from"path";import{spawn as FC}from"child_process";async function Pm(n){En(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await jC(n),i=Nn.join(t,"compile_commands.json");Em.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=HC(e,t,r);g.info("clangd started, bridging stdio (initialize is left to the client)"),UC(o)}async function jC(n){let e=await A.new(),t;if(n.projectPath)t=ae(Nn.resolve(n.projectPath)),g.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let s=Eo(process.cwd());t=ae(s??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${s??"null, fallback to cwd"}`)}else t=ae(Nn.resolve(process.cwd())),g.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.clangdPath;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=vn(t),o=Nn.dirname(i);return g.info(`projectPath=${t}, clangdPath=${r}, compileCommandsDir=${o}`),{projectPath:t,clangdPath:r,compileCommandsDir:o}}function HC(n,e,t){let r=$C(e);return g.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),FC(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function $C(n){return[`--compile-commands-dir=${j(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 WC(){let n=process.env.PROJECT_PATH||"",e=process.env.NODE_MAX_OLD_SPACE_SIZE,t=process.env.DEBUG==="true"||process.env.DEBUG==="1",r=await A.new();b()||r.require({clt:!1});let o=ml({toolProvider:r,projectPath:n,nodeMaxOldSpaceSize:e,debug:t}),s=async()=>{await o.shutdown(),process.exit(0)};process.once("SIGINT",s),process.once("SIGTERM",s),process.platform==="win32"&&process.once("SIGBREAK",s);try{await o.start()}catch(a){console.error("Failed to start MCP server:",a),process.exit(1)}}var gl=new BC("serve").description("Host bundled auxiliary protocol servers");gl.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await WC()});b()||gl.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 bm({projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await Pm({projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var Cm=gl;import{Command as GD,InvalidArgumentError as sd}from"commander";import{red as wa,dim as VD}from"colorette";import*as Q from"fs";import*as ft from"path";import RD from"adm-zip";import kD from"proper-lockfile";import Ng from"ora";import*as it from"fs";import*as ji from"path";var en=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],Ln={"harmonyos-guides":"\u5F00\u53D1\u6307\u5357","harmonyos-references":"API\u53C2\u8003","best-practices":"\u6700\u4F73\u5B9E\u8DF5","harmonyos-faqs":"FAQ","harmonyos-releases":"\u7248\u672C\u8BF4\u660E","harmonyos-roadmap":"\u53D8\u66F4\u9884\u544A"};var vr="1.9.1",pG=48*1024*1024,Im=280,Am=6,Dm=100,Tm=3,Rm=28,yl=10,km=/API参考|APIReference/i,Ri=200,xm=12,Nm=4,wl=8,Lm=6,Gs=700,vl=250,Sl=400,Om=1320,Mm=120,_m=450,Fm=250,jm=500,Hm=480,$m=80,Um=200,Bm=60,Wm=200,zm=40,Gm=200,Vm=200,qm=40,Sr=500,Ym=Object.fromEntries(en.map((n,e)=>[Ln[n],e])),tn=Object.fromEntries(en.map((n,e)=>[n,e]));import*as ki from"fs";import*as O from"path";import{fileURLToPath as Zm}from"url";import*as nn from"fs";import*as Jm from"path";import{homedir as zC}from"os";var GC="deveco-cli",bl,On=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function VC(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&fo(n)!==""}function Km(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":fo(n))||Jm.join(zC(),".local","share",GC);try{return mo(t)}catch(r){throw new On(r instanceof Error?r.message:String(r))}}async function Xm(){let n=Km();await nn.promises.mkdir(n,{recursive:!0});let e;try{e=await nn.promises.realpath(n)}catch(r){throw new On(`DEVECO_CLI_DATA_DIR is not usable: ${r instanceof Error?r.message:String(r)}`)}if(!(await nn.promises.stat(e)).isDirectory())throw new On("DEVECO_CLI_DATA_DIR must be a writable directory.");return bl=e,e}function Vs(n){let e=br();return VC()?[`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 br(){if(bl!==void 0)return bl;let n=Km();try{if(nn.existsSync(n))return nn.realpathSync(n)}catch{}return n}var qC="docs";function Er(){return O.join(br(),qC)}function J(){return O.join(Er(),".index")}function qs(){return O.join(J(),"build.lock")}function xi(){return O.join(J(),"build-status.json")}function Pr(){return O.join(J(),"build-meta.json")}function Mn(){return O.join(J(),"search.db")}function Ni(){return O.join(J(),"sqlite-backend.json")}function Li(){return O.join(J(),"jieba-backend.json")}function Rt(){return O.join(J(),".tmp")}function YC(){return O.join(br(),"logs")}function Cr(){return O.join(YC(),"doc-init.log")}function JC(n,e){let t=e;for(;!t.endsWith(`${O.sep}dist`)&&t!==O.dirname(t);)t=O.dirname(t);return t}function Qm(n,e){return O.dirname(JC(n,e))}function eh(){let n=Zm(import.meta.url),e=O.dirname(n);return n.includes(`${O.sep}dist${O.sep}`)?Qm(n,e):O.join(e,"..","..","..")}function KC(...n){let e=Zm(import.meta.url),t=O.dirname(e);return e.includes(`${O.sep}dist${O.sep}`)?[O.join(Qm(e,t),...n)]:[O.join(t,"..","..","..",...n)]}function th(...n){let e=eh(),t=ki.realpathSync(e);for(let r of KC(...n))try{let i=ki.lstatSync(r);if(i.isSymbolicLink()||!i.isFile())throw new Error(`Unsafe documentation package asset: ${n.join("/")} must be a regular file.`);let o=ki.realpathSync(r);if(!$r(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 rn(){return th("docs.zip")}function El(){return th("index.zip")}function nh(){return O.join(eh(),"index","data")}import*as kt from"fs";import*as _n from"path";var xt=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Ys=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function rh(n){return n instanceof Ys}var Pl=null;function Cl(n){Pl=n}function Il(){if(Pl)return Pl;let n=J();if(xt.every(i=>kt.existsSync(_n.join(n,i))))return n;let t=nh();if(xt.every(i=>kt.existsSync(_n.join(t,i))))return t;throw new Ys("Lexicon files not found. Install the documentation index first (index.zip).")}function ih(){Il()}function Fn(n){let e=_n.join(Il(),n);return kt.readFileSync(e,"utf-8")}function oh(n,e){return kt.readFileSync(_n.join(e,n),"utf-8")}async function sh(n,e=Il()){await kt.promises.mkdir(n,{recursive:!0});for(let t of xt){let r=_n.join(e,t),i=_n.join(n,t);await kt.promises.copyFile(r,i)}}import*as Js from"fs";import*as ah from"path";import*as ch from"yauzl";var Oi=null;function XC(n){return new Promise((e,t)=>{ch.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 ZC(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function QC(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",i=>{let o=ZC(i);o.endsWith("/")||e.set(o,i),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function eI(){Oi?.zipfile.close(),Oi=null}async function tI(n){let e=ah.resolve(n),t=await Js.promises.stat(e),r=Oi;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;eI();let i=await XC(e),o=await QC(i);return Oi={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:i,entries:o,readChain:Promise.resolve()},Oi}function nI(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 rI(n,e){let t=n.readChain,r;n.readChain=new Promise(i=>{r=i}),await t;try{return await nI(n.zipfile,e)}finally{r()}}function iI(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 oI(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function lh(n){let e=rn();if(!e)throw new Error("docs.zip not found");let t=await tI(e),r=oI(t.entries,iI(n));if(!r)throw new Error(`Document not found: ${n}`);return(await rI(t,r)).toString("utf-8")}function Al(){let n=rn();return n!==null&&Js.existsSync(n)}import*as de from"fs";import*as Nt from"path";import dh from"adm-zip";import*as Mi from"fs";import*as Xs from"path";var Ks=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function _i(n){return n instanceof On||n instanceof Ks||n instanceof Error&&(n.name==="CliDataDirError"||n.name==="DocPathSafetyError")}function Rl(n){return new Ks(n)}function sI(){return lt(br())}function Tl(n,e,t){let r=po(n,e);if(r===null)throw Rl(`${t} resolves outside the data directory.`);return r}async function Dl(n,e){await Mi.promises.mkdir(n,{recursive:!0});let t=Tl(n,e,"directory");if(!(await Mi.promises.stat(t)).isDirectory())throw Rl("path must be a directory.")}function Fi(n){let e=sI();try{let t=Tl(n,e,"file");if(!Mi.statSync(t).isFile())throw Rl("path must be a regular file.")}catch(t){if(t.code==="ENOENT"){Tl(Xs.dirname(n),e,"file parent");return}throw t}}async function Ir(n={}){let e=n.mode??"write",t=await Xm();await Dl(Er(),t),await Dl(J(),t),e==="write"&&await Dl(Rt(),t);for(let r of[Mn(),Pr(),xi(),qs(),Li(),Ni(),...xt.map(i=>Xs.join(J(),i))])Fi(r)}var kl=["search.db","build-meta.json",...xt],aI=["corpus.json","corpus-offsets.json","orama.dpack"];async function cI(n){for(let e of aI)await de.promises.rm(Nt.join(n,e),{force:!0})}async function lI(n){let e=await de.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await de.promises.rm(Nt.join(n,t.name),{recursive:!0,force:!0})}function uh(n){let t=new dh(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 dI(n){let e=J();await de.promises.mkdir(e,{recursive:!0});for(let t of kl){let r=Nt.join(e,t);await de.promises.rm(r,{force:!0}),await de.promises.rename(Nt.join(n,t),r)}await cI(e),await de.promises.rm(Rt(),{recursive:!0,force:!0})}function ph(n){let e=El();if(!e)return!1;try{let t=uh(e);return t.indexVersion===vr&&t.docsZipSha256===n&&t.segmentCount>0}catch{return!1}}async function fh(n){await Ir({mode:"write"});let e=El();if(!e)throw new Error("index.zip not found");let t=uh(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=Rt();await de.promises.rm(r,{recursive:!0,force:!0}),await de.promises.mkdir(r,{recursive:!0});let i=new dh(e);for(let s of kl){let a=i.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await de.promises.writeFile(Nt.join(r,s),a.getData())}let o=JSON.parse(await de.promises.readFile(Nt.join(r,"build-meta.json"),"utf-8"));if(!de.existsSync(Nt.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await dI(r),await de.promises.mkdir(Er(),{recursive:!0}),await lI(Er()),o}async function mh(){await de.promises.rm(Rt(),{recursive:!0,force:!0});let n=J();for(let e of kl)await de.promises.rm(Nt.join(n,e),{force:!0})}import{createHash as hh}from"crypto";import*as gh from"fs";async function Zs(n){return new Promise((e,t)=>{let r=hh("sha256"),i=gh.createReadStream(n);i.on("data",o=>r.update(o)),i.on("error",t),i.on("end",()=>e(r.digest("hex")))})}function yh(n){return hh("sha256").update(n,"utf8").digest("hex")}var xl=null;function uI(){let n=Fn("harmonyos-synonyms.json");return JSON.parse(n)}function pI(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 fI(){let n=pI(uI()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function mI(){return xl||(xl=fI()),xl}function Nl(n,e){let t=mI(),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 wh(n,e){let t=e?oh(n,e):Fn(n);return yh(t)}function Qs(n){return wh("harmonyos-synonyms.json",n)}function ea(n){return wh("harmonyos-terms.txt",n)}var hI={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function ta(){try{let n=await it.promises.readFile(xi(),"utf-8");return JSON.parse(n)}catch{return{...hI}}}async function Ll(n){let e=xi();await it.promises.mkdir(ji.dirname(e),{recursive:!0}),await it.promises.writeFile(e,JSON.stringify(n,null,2))}function vh(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 on(n){let t={...await ta(),...n,updatedAt:Date.now()};return await Ll(t),t}async function Ol(){let n=rn();return n?Zs(n):null}async function Ml(){try{let n=await it.promises.readFile(Pr(),"utf-8");return JSON.parse(n)}catch{return null}}async function na(n=!1){if(n)return"no-index";let e=await Ml();if(!e||e.segmentCount===0)return"no-index";let t=await Ol();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==vr?"engine-upgraded":e.termsHash!==ea()?"terms-changed":e.synonymsHash!==Qs()?"synonyms-changed":null}function Hi(){if(!Al()||!it.existsSync(Mn())||!it.existsSync(Pr()))return!1;let n=ji.dirname(Mn());if(!xt.every(e=>it.existsSync(ji.join(n,e))))return!1;try{let e=it.readFileSync(Pr(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function _l(n=!1){return n?!0:Al()?Hi()?await na()!==null:!0:!1}async function Sh(){let n=await ta();return["installing","indexing","persisting"].includes(n.state)}import*as ge from"fs";import*as Ig from"os";import*as Ae from"path";var bh=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),Fl=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),Eh=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"]),Ph=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 gI=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,yI=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,wI=/[A-Z][a-zA-Z0-9]{2,}/g,vI=/@[A-Z][a-zA-Z0-9]*/g,SI=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,Ch=6,bI=/^[a-z][a-z0-9]{2,}$/,EI=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,PI=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,CI=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,II=/^[A-Z][a-zA-Z0-9]+$/;function AI(n){return`"${n.replace(/"/g,'""')}"`}function Ui(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(AI).join(` ${e} `)}function $i(n){return Ui(n,"OR")}function Ih(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?$i([...t,...r]):`(${$i(t)}) AND (${$i(r)})`}function Bi(n){return PI.test(n)}function Ah(n){return CI.test(n)&&n.length>=Ch}function DI(n){return II.test(n)}function Wi(n){return Bi(n)||Ah(n)||DI(n)}function TI(n){let e=n.trim().toLowerCase();return Ph.has(e)?!1:bh.has(e)}function RI(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function ra(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function jl(n){return[...n.matchAll(gI)].map(e=>e[0])}function Hl(n,e=Ch){let t=[];for(let r of n.matchAll(yI))r[0].length>=e&&t.push(r[0]);return t}function Ar(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 ot(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function kI(n){let e=new Set;ot(e,n);let t=ra(n);return t&&ot(e,t),Ar([...e])}function ia(n){if(Bi(n))return kI(n);let e=new Set;return ot(e,n),Ar([...e])}function oa(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(EI);if(!t)return null;let r=t[1].toLowerCase(),i=t[2].toLowerCase();if(!bI.test(r)||Eh.has(r)||!TI(i))return null;let o=RI(r,i);return{first:r,second:i,camelCase:o,lower:o.toLowerCase()}}function $l(n){let e=oa(n.trim());return!e||e.second!=="manager"?null:e}function xI(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function Dh(n){let e=n.trim(),t=$l(e);if(t&&Fl.has(t.first))return!0;if(Ah(e)){let r=xI(e);return r!==null&&Fl.has(r)}return!1}function Ul(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 Bl(n){let e=n.trim();if(Wi(e))return ia(e);let t=new Set;for(let r of jl(n)){ot(t,r);let i=ra(r);i&&ot(t,i)}for(let r of Hl(n))ot(t,r);for(let r of n.matchAll(vI))t.add(r[0]);for(let r of n.matchAll(SI))t.add(r[0]);for(let r of n.matchAll(wI))r[0].length>=4&&t.add(r[0]);return Ar([...t])}function Th(n){let e=n.trim();if(Wi(e))return ia(e);let t=new Set,r=oa(e);r&&ot(t,r.camelCase);for(let i of Bl(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 Ar([...t])}function Rh(n){return Wi(n)}var V={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 kh(n){return V.pureApiSymbol.test(n.trim())}function zi(n){let e=n.trim();return V.stageModelExact.test(e)||V.stageModelEnglishExact.test(e)}function xh(n){let e=[];return zi(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),V.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),V.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 Nh(n){return zi(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=>V.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>zi(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!zi(n)&&V.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>V.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>V.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>V.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>V.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>V.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=>V.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function LI(n,e){for(let{catalog:t,multiplier:r}of e){let i=tn[t];n.set(i,(n.get(i)??1)*r)}}function Lh(n,e){for(let t of NI)t.matches(n)&&LI(e,t.weights)}function Oh(n,e){if(e!==void 0)return!1;let t=n.trim();return Bi(t)||V.pureApiSymbol.test(t)||Dh(t)}function Mh(n){let e=n.trim();if(Bi(e)||V.pureApiSymbol.test(e))return"harmonyos-references";if(zi(e)||V.uiAbilityLifecycleCatalog.test(e)||V.stateDecoratorCatalog.test(e)||V.stateManagement.test(e)||V.declarePermissionCatalog.test(e)||V.stageModelEntryPage.test(e)||V.routerRoute.test(e)||V.dialogPopupExact.test(e))return"harmonyos-guides"}import*as Dr from"fs";import*as Fh from"path";var sa=null,Wl=null,zl=null;function OI(){return Dr.existsSync(Li())}function MI(n){let e=Li(),t={backend:"jieba-wasm",reason:"native-jieba-load-failed",message:n,createdAt:new Date().toISOString()};Dr.mkdirSync(Fh.dirname(e),{recursive:!0}),Fi(e),Dr.writeFileSync(e,JSON.stringify(t,null,2))}function _I(){if(sa)return sa;let n=Fn("harmonyos-stopwords.txt");return sa=new Set(n.split(`
|
|
1301
|
+
`).map(e=>e.trim()).filter(Boolean)),sa}function FI(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 jh(n){let e=_I(),t=[];for(let r of FI(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 Hh(n){let{dict:e}=await import("@node-rs/jieba/dict.js"),t=n.withDict(e),r=Fn("harmonyos-terms.txt");return t.loadDict(Buffer.from(r,"utf-8")),t}async function jI(){let{Jieba:n}=await import("@node-rs/jieba");return Hh(n)}async function _h(){let{Jieba:n}=await import("@node-rs/jieba-wasm32-wasi");return Hh(n)}async function HI(){let n=await import("jieba-wasm"),e=Fn("harmonyos-terms.txt");return n.with_dict(e),{cut:n.cut,cutForSearch:n.cut_for_search}}async function $I(){if(b())return HI();if(OI())return _h();try{let e=await jI();return m("doc-index: using @node-rs/jieba backend"),e}catch(e){let t=e instanceof Error?e.message:String(e);MI(t),m(`doc-index: @node-rs/jieba unavailable (${t}); falling back to wasm32-wasi`)}let n=await _h();return m("doc-index: using @node-rs/jieba-wasm32-wasi backend"),n}async function sn(){return Wl||(zl||(zl=$I().then(n=>(Wl=n,n))),zl)}async function UI(n){let e=await sn();return jh(e.cutForSearch(n,!0))}async function $h(n){let e=await sn();return jh(e.cut(n,!0))}async function aa(n,e){let t=n.trim();if(!t||e<=0)return"";let r=(await UI(t)).join(" ");return r.length<=e?r:r.slice(0,e)}async function BI(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 ca(n){let e=!!n.sectionTitle.trim(),t=n.titleTokens.trim(),r=e?Hm:Om,i=e?Um:_m,o=e?await BI(n.apiSymbols,i):await aa(n.apiSymbols.join(" "),i),a=(await Promise.all([aa(t,e?$m:Mm),Promise.resolve(o),aa(n.headingsText,e?Bm:Fm),aa(n.bodySample,e?Wm:jm)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}function WI(n){return n.join(" ").replace(/\s+/g," ").trim().slice(0,Ri)}function Gl(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>=xm))break}return r}function zI(n){return n.length>=2&&n.length<=Nm}function GI(n,e){let t=Nl(n,wl),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=Gl(i,o);return{rawQuery:n,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:Ih(i,o)}}function VI(n,e){let t=Gl(ia(e),[]);return{rawQuery:n,expandedQuery:n,tokens:t,preferAnd:!1,ftsMatch:$i(t)}}async function Uh(n){let e=WI(n),t=e.trim(),r=Nh(t);if(r)return{rawQuery:e,expandedQuery:r.expandedQuery,tokens:r.tokens,preferAnd:!1};let i=oa(t);if(i)return GI(e,i);if(Wi(t))return VI(e,t);let o=xh(e),s=[...Bl(e),...o],c=Rh(t)?e:Nl(e,wl),l=await $h(c),d=Gl(s,l);return{rawQuery:e,expandedQuery:c,tokens:d,preferAnd:o.length===0&&zI(d)}}var Bh=["harmonyos-releases","harmonyos-roadmap"],qI=new Set(Bh.map(n=>tn[n])),YI=Bh.map(n=>`${Ln[n]}/`);function JI(n){return qI.has(n)}function KI(n){return YI.some(e=>n.startsWith(e))}function Wh(n){let e=[],t=[];for(let r of n)JI(r.catalog_id)?t.push(r):e.push(r);return[...e,...t]}function zh(n){let e=[],t=[];for(let r of n)KI(r.documentId)?t.push(r):e.push(r);return[...e,...t]}var XI=[{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 Gi(n,e,t){let r=tn[e];n.set(r,(n.get(r)??1)*t)}function ZI(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)){Gi(e,"harmonyos-guides",1.45),Gi(e,"harmonyos-references",1.35);return}(i||o)&&Gi(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&Gi(e,"harmonyos-references",1.75)}function Gh(n){let e=new Map,t=n.trim();if(!t)return e;let r=kh(t);ZI(t,e),Lh(t,e);for(let i of XI)i.pattern.test(t)&&(i.skipForPureApiSymbol&&r||Gi(e,i.catalog,i.multiplier));return e}function Vh(n){return Mh(n)}import*as Rr from"fs";import*as eg from"path";var QI=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function qh(n,e){let t=-1;for(let r of QI){let i=n.lastIndexOf(r);i>t&&(t=i)}return t>=e?t:-1}function Yh(n,e){let t=n.trim();if(t.length<=e)return{text:t,excerptTruncated:!1};let r=t.slice(0,e),i=qh(r,e-20),o=i>=0?i:e;return{text:t.slice(0,o).trimEnd(),excerptTruncated:!0}}function Jh(n,e,t={}){let{maxLen:r=Vm,contextChars:i=qm,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(Je=>Je.trim()).filter(Boolean),c=0;for(let Je of a){let ke=s.toLowerCase().indexOf(Je.toLowerCase());if(ke>=0){c=ke;break}}let l=Math.max(0,c-i),d=Math.min(s.length,l+r),h=s.slice(l,d),w=qh(h,r-25);w>=0&&(d=l+w);let S=s.slice(l,d).trim(),k=l>0?"...":"",we=d<s.length||o?"...":"";return`${k}${S}${we}`}var eA=`
|
|
1282
1302
|
SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
|
|
1283
1303
|
d.catalog_id, bm25(segments_fts) AS bm25
|
|
1284
1304
|
FROM segments_fts
|
|
@@ -1287,7 +1307,7 @@ Output so far:
|
|
|
1287
1307
|
WHERE segments_fts MATCH ?
|
|
1288
1308
|
ORDER BY bm25(segments_fts)
|
|
1289
1309
|
LIMIT ?
|
|
1290
|
-
`,
|
|
1310
|
+
`,tA=`
|
|
1291
1311
|
SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
|
|
1292
1312
|
d.catalog_id, bm25(segments_fts) AS bm25
|
|
1293
1313
|
FROM segments_fts
|
|
@@ -1296,7 +1316,7 @@ Output so far:
|
|
|
1296
1316
|
WHERE segments_fts MATCH ? AND d.catalog_id = ?
|
|
1297
1317
|
ORDER BY bm25(segments_fts)
|
|
1298
1318
|
LIMIT ?
|
|
1299
|
-
`,
|
|
1319
|
+
`,nA=3.5,rA=1.4,iA=4,oA=1.8,sA=1.35,aA=3.5,cA=1.8,lA=120,Kh=6;function ql(n){return n.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function dA(n){return n.split(/[^\p{L}\p{N}@.]+/u).map(ql).filter(e=>e.length>=2)}function uA(n,e){return e.length>1&&e.every(t=>n.includes(t))}function pA(n){return/^[a-z0-9]{1,4}$/.test(n.trim().toLowerCase())}function fA(n,e){return n===e?aA:n.startsWith(e)||n.includes(`@ohos.${e}`)?cA:1}function mA(n,e){let t=ql(e);if(t.length<2)return 1;let r=ql(n.doc_title);if(pA(e))return fA(r,t);if(r.includes(t))return iA;if(t.length>=Kh&&r.includes(t.slice(0,Kh)))return oA;let i=dA(e);return uA(r,i)?sA:1}function hA(n,e){return e<=1?n:n<0?n*e:n/e}function la(n,e,t,r){let i=n.bm25/(e.get(n.catalog_id)??1);return i=hA(i,mA(n,t)),r&&Ul(n.doc_title,n.section_title,r)&&(i/=nA,n.catalog_id===tn["harmonyos-references"]&&(i/=rA)),i}function Vl(n,e,t,r){return n.reduce((i,o)=>la(o,e,t,r)<la(i,e,t,r)?o:i)}function gA(n,e){return e.some(t=>n.section_title.includes(t)||n.doc_title.includes(t))}function yA(n,e,t,r,i){if(i){let o=n.filter(s=>Ul(s.doc_title,s.section_title,i));if(o.length>0)return Vl(o,t,r,i)}if(e.length>0){let o=n.filter(s=>gA(s,e));if(o.length>0)return Vl(o,t,r,i)}return Vl(n,t,r,i)}function Xh(n,e,t,r,i){let o=Gh(e),s=Th(e),c=$l(e)?.camelCase,l=new Map;for(let S of n){let k=l.get(S.document_id)??[];k.push(S),l.set(S.document_id,k)}let d=[];for(let S of l.values())d.push(yA(S,s,o,t,c));let h=d.sort((S,k)=>la(S,o,t,c)-la(k,o,t,c));return(i?Wh(h):h).slice(0,r)}function da(n,e,t,r,i,o){let s=e?tn[e]:void 0,a=Math.max(t,t*Lm,lA),c=s===void 0?n.all(eA,r,a):n.all(tA,r,s,a);return(s===void 0?Xh(c,o,i,t,!0):Xh(c,o,i,t,!1)).map(d=>({title:d.doc_title,documentId:d.document_id,sectionTitle:d.section_title||void 0,snippet:Jh(d.lead_text,i,{excerptTruncated:!!d.excerpt_truncated})}))}var ua=`
|
|
1300
1320
|
CREATE TABLE documents (
|
|
1301
1321
|
id INTEGER PRIMARY KEY,
|
|
1302
1322
|
document_id TEXT NOT NULL UNIQUE,
|
|
@@ -1334,18 +1354,54 @@ CREATE TRIGGER segments_au AFTER UPDATE ON segments BEGIN
|
|
|
1334
1354
|
END;
|
|
1335
1355
|
|
|
1336
1356
|
CREATE INDEX segments_doc_id_idx ON segments(doc_id);
|
|
1337
|
-
`;var
|
|
1357
|
+
`;var Tr=null,Yl=null;function wA(){Tr?.close(),Tr=null,Yl=null}function vA(n,e){if(Tr&&Yl===e)return Tr;Tr?.close();let t=new n(e,{readonly:!0,fileMustExist:!0});return Tr=t,Yl=e,t.pragma("mmap_size = 268435456"),t.pragma("cache_size = -8000"),t.pragma("query_only = ON"),t}function SA(n,e){let t=new n(e);return t.pragma("journal_mode = OFF"),t.pragma("synchronous = OFF"),t.pragma("temp_store = MEMORY"),t.exec(ua),t}function bA(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(`
|
|
1338
1358
|
INSERT INTO documents(document_id, catalog_id, doc_title)
|
|
1339
1359
|
VALUES (?, ?, ?)
|
|
1340
|
-
`).run(t.documentId,t.catalogId,t.docTitle),c=Number(a.lastInsertRowid);return e.set(t.documentId,c),c}async function
|
|
1360
|
+
`).run(t.documentId,t.catalogId,t.docTitle),c=Number(a.lastInsertRowid);return e.set(t.documentId,c),c}async function EA(n,e,t,r){await sn();let i=SA(n,e),o=new Map,s=i.prepare(`
|
|
1341
1361
|
INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated)
|
|
1342
1362
|
VALUES (?, ?, ?, ?, ?)
|
|
1343
|
-
`),a=t.length;for(let c=0;c<a;c+=_t){let l=t.slice(c,c+_t),u=await Promise.all(l.map(async v=>({source:v,searchText:await uo(v)})));o.transaction(v=>{for(let D of v){let k=rv(o,i,D.source);s.run(k,D.source.sectionTitle,D.source.leadText,D.searchText,D.source.excerptTruncated?1:0)}})(u),await r?.(Math.min(c+l.length,a),a)}o.exec("ANALYZE"),o.exec("VACUUM"),o.close()}function iv(n,e,t,r,o,i,s){let a=tv(n,e);return mo({all(c,...l){return a.prepare(c).all(...l)}},t,r,o,i,s)}async function Od(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:ev,buildSearchIndex:(t,r,o)=>ov(e,t,r,o),searchIndex:(t,r,o,i,s,a,c)=>Promise.resolve(iv(e,i,r,o,s,a,c))}}import{readFile as sv,stat as av,writeFile as cv}from"fs/promises";var ps=null,Je=null;async function ms(){return ps||(ps=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),ps}function lv(n){return{all(e,...t){let r=n.prepare(e);t.length>0&&r.bind(t);let o=[];for(;r.step();)o.push(r.get({}));return r.finalize(),o}}}async function dv(n){let e=await av(n);if(Je&&Je.dbPath===n&&Je.mtimeMs===e.mtimeMs)return Je.db;Je?.db.close();let t=await ms(),r=t.capi,o=t.wasm,i=new Uint8Array(await sv(n)),s=o.allocFromTypedArray(i),a=new t.oo1.DB(":memory:"),c=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE;return r.sqlite3_deserialize(a.pointer,"main",s,i.byteLength,i.byteLength,c),Je={dbPath:n,mtimeMs:e.mtimeMs,db:a},a}function Nd(){Je?.db.close(),Je=null}async function uv(n,e,t,r){n.exec("BEGIN");for(let o of r){let i=t(o.source);e.bind([i,o.source.sectionTitle,o.source.leadText,o.searchText,o.source.excerptTruncated?1:0]),e.step(),e.reset()}n.exec("COMMIT")}function pv(n,e,t){return r=>{let o=e.get(r.documentId);if(o!==void 0)return o;let i=n.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(i!=null){let a=Number(i);return e.set(r.documentId,a),a}t.bind([r.documentId,r.catalogId,r.docTitle]),t.step(),t.reset();let s=Number(n.selectValue("SELECT last_insert_rowid()"));return e.set(r.documentId,s),s}}async function mv(n,e,t){await Ye();let r=await ms(),o=new r.oo1.DB(":memory:","c");o.exec(fo);let i=new Map,s=o.prepare("INSERT INTO documents(document_id, catalog_id, doc_title) VALUES (?, ?, ?)"),a=o.prepare("INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated) VALUES (?, ?, ?, ?, ?)"),c=pv(o,i,s),l=e.length;for(let h=0;h<l;h+=_t){let v=e.slice(h,h+_t),D=await Promise.all(v.map(async k=>({source:k,searchText:await uo(k)})));await uv(o,a,c,D),await t?.(Math.min(h+v.length,l),l)}o.exec("ANALYZE");let u=r.capi.sqlite3_js_db_export(o);await cv(n,u),o.close(),Nd()}async function fv(n,e,t,r,o,i){let s=await dv(n);return mo(lv(s),e,t,r,o,i)}async function Ld(){return await ms(),{kind:"sqlite-wasm",resetCache:Nd,buildSearchIndex:mv,searchIndex:(n,e,t,r,o,i,s)=>fv(r,e,t,o,i,s)}}var ho=null,fs=null;async function hv(){try{let e=await Od();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 Ld();return g("doc-index: using @sqlite.org/sqlite-wasm SQLite backend"),n}async function Mn(){return ho||(ho=hv().then(n=>(fs=n,n))),ho}function _d(){fs?.resetCache(),ho=null,fs=null}async function gv(n,e,t,r,o,i,s){let a=await Mn(),c=s??Pn();return a.searchIndex(n,e,t,c,r,o,i)}function jd(){_d()}async function Fd(n,e,t){await(await Mn()).buildSearchIndex(n,e,t)}function $d(n,e,t){let r=new Set,o=[];for(let i of[...n,...e])if(!r.has(i.documentId)&&(r.add(i.documentId),o.push(i),o.length>=t))break;return o}function go(n,e,t,r,o,i){return gv(n,e,t,o,r.expandedQuery,r.rawQuery,i)}async function yv(n,e,t,r,o){let i=await go(n,e,t,r,An(r.tokens,"AND"),o);if(i.length>=t)return i;let s=await go(n,e,t,r,An(r.tokens,"OR"),o);return $d(i,s,t)}async function hs(n,e,t,r,o){return r.ftsMatch?go(n,e,t,r,r.ftsMatch,o):r.preferAnd?yv(n,e,t,r,o):go(n,e,t,r,An(r.tokens,"OR"),o)}async function vv(n,e,t,r){let o=await hs(n,"harmonyos-references",e,t,r);if(o.length>=e)return o;let i=await hs(n,void 0,e,t,r);return $d(o,i,e)}function Hd(n,e){return e!==void 0?n:Id(n)}async function Bd(n,e,t=20,r){let o=await Pd(n);if(yd(o.rawQuery,e)){let a=await vv(n,t,o,r);return Hd(a,e)}let i=e??Ad(o.rawQuery),s=await hs(n,i,t,o,r);return Hd(s,e)}import{unified as Jd}from"unified";import Kd from"remark-parse";import Zd from"remark-gfm";import{toString as vo}from"mdast-util-to-string";var wv=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,bv=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,Sv=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,Pv=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,Ev=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function yo(n){let e=n.trim(),t=e.match(Pv);return t?t[1]:e}function Dv(n){let e=n.match(wv);if(!e)return;let t=yo(e[1].trim());return{displayTitle:n,symbolName:t,searchExtras:[t,e[3]]}}function Iv(n){let e=yo(n.replace(/\([^)]*\)$/,""));if(/^[A-Z][A-Za-z0-9]*$/.test(e))return{displayTitle:n,symbolName:e,searchExtras:[e]};if(/^[A-Z][A-Za-z0-9]*(\([^)]*\))?$/.test(n))return{displayTitle:n,symbolName:e,searchExtras:[e]}}function On(n){let e=n.trim();return e?Dv(e)??(()=>{let t=e.match(bv);if(t){let r=t[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let t=e.match(Sv);if(!t)return;let r=t[1].trim(),o=t[2].trim();return{displayTitle:e,symbolName:o,searchExtras:[r,o]}})()??Iv(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function Cv(n){if(n.length<2||n.length>36||Ev.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 Wd(n){for(let e of n){let t=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(Cv(t))return t}return""}function Ud(n,e,t){let r=[n,...t.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var Av=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,Nn=/@[A-Z][a-zA-Z]+/g,Tv=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,xv=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,kv=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,Rv=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),Mv=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),Ov=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function Xd(n,e){let t=new Set,r=[n,...e];for(let o of r){for(let i of es(o)){me(t,i);let s=io(i);s&&me(t,s)}for(let i of ts(o))me(t,i);for(let i of o.matchAll(Av)){let s=i[0];Nv(s)&&t.add(s)}for(let i of o.matchAll(Nn))t.add(i[0])}return Ft([...t])}function Nv(n){let e=n.trim();if(!e||Nn.test(e))return!!e;if(e.includes(".")){let t=e.split(".")[0]??"";return Ov.has(t)?!1:/^[A-Z]/.test(t)}return Rv.has(e)?!1:Mv.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 zd(n){let e=n.trim();return!!(!e||kv.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function Qd(n,e){let t=e.jsonTitle?.trim(),r=jv(n,"").trim(),o=e.fileName.trim();return t&&!zd(t)?t:r&&!zd(r)?r:t||r||o}function eu(n){return Tv.test(n.trim())}function gs(n){let e=n.trim().replace(/\([^)]*\)$/,""),t=yo(e);return xv.test(t)}function wo(n){let e=n.trim();return e?Nn.test(e)||eu(e)||gs(e)?!0:!!On(e).symbolName:!1}function Lv(n){let e=n.trim();return!(!e||eu(e)||gs(e))}function _v(n){let e=new Set,t=[];for(let r of n){let o=r.trim();!Lv(o)||e.has(o)||(e.add(o),t.push(o))}return t}function qd(n){if(!n.includes("."))return 0;let e=n.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function Hv(n,e){let t=qd(n)-qd(e);return t!==0?t:n.localeCompare(e)}function tu(n,e=[]){let t=[...new Set(e.map(i=>i.trim()).filter(Boolean))],r=new Set(t),o=[...new Set(n.map(i=>i.trim()).filter(Boolean))].filter(i=>!r.has(i));return o.sort(Hv),[...t,...o].slice(0,xl)}function bo(n){return n.replace(/\s+/g," ").trim()}function Vd(n){return n.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function jv(n,e=""){let t=n.split(/\r?\n/),r=0;for(;r<t.length&&!t[r].trim();)r+=1;if(r>=t.length)return e;let o=Vd(t[r].trim()),i=o.match(/^#+\s+(.+)$/);if(i)return Vd(i[1].trim());if(r+1<t.length){let s=t[r+1].trim();if(/^=+$/.test(s)||/^-+$/.test(s))return o}return o||e}function nu(n){let e=bo(n.join(" "));if(e.length<=Gr)return e;let t=e.slice(0,Gr);return e.length<=Gr+Hi?t:`${t} ${e.slice(-Hi)}`}function Fv(n){let e=_v(n).join(" ");return e.length<=ji?e:e.slice(0,ji)}function ru(n){let e=bo(n),{text:t,excerptTruncated:r}=xd(e,kl);return{leadText:t,excerptTruncated:r}}function $v(n,e){let{leadText:t,excerptTruncated:r}=ru(n);return{leadText:t,excerptTruncated:r||!!e.trim()}}function ou(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)ou(r,e);return}let t=bo(vo(n));t&&e.bodyParts.push(t)}function Bv(n){let e=Jd().use(Kd).use(Zd).parse(n),t=[],r=null,o=()=>{r&&((r.sectionTitle||r.bodyParts.length||r.codeBlocks.length)&&t.push(r),r=null)},i=()=>{r||(r={sectionTitle:"",bodyParts:[],codeBlocks:[]})};for(let s of e.children){if(s.type==="heading"){let a=s,c=vo(a).trim();if(a.depth>=4&&c&&wo(c)){o(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}i(),c&&r.bodyParts.push(c);continue}i(),ou(s,r)}return o(),t.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:t}function Wv(n){return hl.test(n)}function Uv(n){return n.filter(e=>e.sectionTitle&&wo(e.sectionTitle)).length}function zv(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 Gd(n){let e=n.trim();return!e||Nn.test(e)?Nn.test(e):/对象说明$|枚举说明$/.test(e)?!0:gs(e)}function qv(n){let e=n.filter(h=>!h.sectionTitle||!wo(h.sectionTitle)),t=n.filter(h=>h.sectionTitle&&wo(h.sectionTitle)),r=t.filter(h=>Gd(h.sectionTitle)),o=t.filter(h=>!Gd(h.sectionTitle)),i=Math.max(0,fl-r.length),s=o.slice(0,i),a=o.slice(i),c=a.filter(h=>Yd(h.sectionTitle)),l=a.filter(h=>!Yd(h.sectionTitle)),u=[];for(let h=0;h<l.length;h+=Li)u.push(zv(l.slice(h,h+Li)));return[...e,...r,...s,...c,...u]}function Vv(n,e,t){let r=n.split(/\r?\n/).length,o=Uv(e);return o===0?!1:Wv(t)?r>=pl&&o>=ml:r>=dl&&o>=ul}var Gv=/^\[h2\][A-Za-z]/;function Yd(n){return Gv.test(n.trim())}function iu(n){if(!n.includes(" | ")){let t=On(n);return t.symbolName?[t.symbolName]:[]}let e=[];for(let t of n.split(" | ")){let r=On(t.trim()).symbolName;r&&e.push(r)}return e}function Yv(n,e,t,r){let o=iu(n),i=Xd(t,r);return e.symbolName&&i.push(e.symbolName),tu([...o,...i],o)}function Jv(n,e){let t=nu(n.bodyParts),r=n.sectionTitle.trim(),o=On(r),i=Wd(n.bodyParts),s=Ud(r,i,o),a=iu(r),c=r?a.length>0?`${e.docTitle} ${a.join(" ")}`:`${e.docTitle} ${o.symbolName??r}`:e.docTitle,l=[e.docTitle,s,...n.bodyParts].join(" "),{leadText:u,excerptTruncated:h}=$v(t,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:Yv(r,o,l,n.codeBlocks),bodySample:t,leadText:u,excerptTruncated:h}}function su(n,e){for(let t of n){if(t.type==="heading"){let o=vo(t).trim();o&&e.headings.push(o);continue}if(t.type==="code"){e.codeBlocks.push(t.value??"");continue}if("children"in t&&Array.isArray(t.children)){su(t.children,e);continue}let r=bo(vo(t));r&&e.bodyParts.push(r)}}function Kv(n){let e=Jd().use(Kd).use(Zd).parse(n),t={headings:[],bodyParts:[],codeBlocks:[]};return su(e.children,t),t}function Zv(n,e){let t=Kv(n),r=e.docTitle?.trim()||e.documentId,o=nu(t.bodyParts),i=[r,...t.headings,o].join(" "),{leadText:s,excerptTruncated:a}=ru(o);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:Fv(t.headings),apiSymbols:tu(Xd(i,t.codeBlocks)),bodySample:o,leadText:s,excerptTruncated:a}}function au(n,e){let t=e.docTitle?.trim()||e.documentId,r=Bv(n);return Vv(n,r,e.documentId)?qv(r).filter(o=>o.sectionTitle||o.bodyParts.length>0||o.codeBlocks.length>0).map(o=>Jv(o,{...e,docTitle:t})):[Zv(n,{...e,docTitle:t})]}async function Xv(n){let e=[];async function t(r){let o=await J.promises.readdir(r,{withFileTypes:!0});for(let i of o){if(i.name.startsWith("."))continue;let s=ee.join(r,i.name);i.isDirectory()?await t(s):i.isFile()&&i.name.endsWith(".md")&&e.push(s)}}return await t(n),e}function Qv(n,e){let t=ee.relative(e,n).split(ee.sep).join("/").split("/");if(t[0]==="docs"&&(t=t.slice(1)),t.length<2)return null;let r=t[0],o=Ol[r];if(o===void 0)return null;let i=t[t.length-1].replace(/\.md$/,"");return t[t.length-1]=i,{documentId:t.join("/"),catalogId:o,docTitle:i}}async function ew(n){let e=n.replace(/\.md$/,".json");try{let t=await J.promises.readFile(e,"utf-8");return JSON.parse(t).title?.trim()||void 0}catch{return}}async function tw(n,e){let t=Qv(n,e);if(!t)return[];let r=await J.promises.readFile(n,"utf-8"),o=Qd(r,{jsonTitle:await ew(n),fileName:t.docTitle});return au(r,{...t,docTitle:o})}async function nw(n,e,t){let r=ee.join(e,"search.db");return await Fd(r,n,async(o,i)=>{await t?.({current:o,total:i,message:`Building search index\u2026 ${o.toLocaleString()} / ${i.toLocaleString()} segments`})}),n.length}async function rw(n){let e=await Xv(n),t=[];for(let r of e){let o=await tw(r,n);t.push(...o)}return t}function ow(n,e){return{indexVersion:Vr,docsZipSha256:n.docsZipSha256,termsHash:n.termsHash,synonymsHash:n.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:n.builtBy}}async function lu(n){n.lexiconDir&&Wi(n.lexiconDir);try{let e=await rw(n.docsDir);await n.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await J.promises.mkdir(n.tmpDir,{recursive:!0});let t=await nw(e,n.tmpDir,n.onProgress),r=ow(n,t);return await J.promises.writeFile(ee.join(n.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await ql(n.tmpDir),r}finally{n.lexiconDir&&Wi(null)}}async function du(){return J.promises.mkdtemp(ee.join(cu.tmpdir(),"deveco-docs-"))}async function iw(n,e){try{await J.promises.rename(n,e)}catch(t){let r=t.code;if(r!=="EPERM"&&r!=="EXDEV")throw t;await J.promises.cp(n,e,{recursive:!0}),await J.promises.rm(n,{recursive:!0,force:!0})}}async function uu(n){let e=ee.join(n,"docs");try{await J.promises.access(e)}catch{return}let t=new Set(["docs","docs.zip"]);for(let r of await J.promises.readdir(e,{withFileTypes:!0})){if(t.has(r.name))continue;let o=ee.join(e,r.name),i=ee.join(n,r.name);await J.promises.rm(i,{recursive:!0,force:!0}),await iw(o,i)}await J.promises.rm(ee.join(e,"docs"),{recursive:!0,force:!0}),await J.promises.rm(ee.join(e,"docs.zip"),{force:!0}),await J.promises.rm(e,{recursive:!0,force:!0})}var Ln=class extends Error{constructor(e){super(e),this.name="NativeDepsError"}};function sw(){let n=jt(),e=X();return["Documentation search index is not installed yet.","",...Jr(n),`Index directory: ${e}`,"","Try:"," 1. Wait a moment and run the docs command again (postinstall may still be running)"," 2. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 3. Check the log file above for setup errors"].join(`
|
|
1344
|
-
`)}function
|
|
1345
|
-
`)}function
|
|
1346
|
-
`)}async function
|
|
1363
|
+
`),a=t.length;for(let c=0;c<a;c+=Sr){let l=t.slice(c,c+Sr),d=await Promise.all(l.map(async w=>({source:w,searchText:await ca(w)})));i.transaction(w=>{for(let S of w){let k=bA(i,o,S.source);s.run(k,S.source.sectionTitle,S.source.leadText,S.searchText,S.source.excerptTruncated?1:0)}})(d),await r?.(Math.min(c+l.length,a),a)}i.exec("ANALYZE"),i.exec("VACUUM"),i.close()}function PA(n,e,t,r,i,o,s){let a=vA(n,e);return da({all(c,...l){return a.prepare(c).all(...l)}},t,r,i,o,s)}async function Zh(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:wA,buildSearchIndex:(t,r,i)=>EA(e,t,r,i),searchIndex:(t,r,i,o,s,a,c)=>Promise.resolve(PA(e,o,r,i,s,a,c))}}import{readFile as CA,stat as IA,writeFile as AA}from"fs/promises";var Jl=null,an=null;async function Kl(){return Jl||(Jl=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),Jl}function DA(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 TA(n){let e=await IA(n);if(an&&an.dbPath===n&&an.mtimeMs===e.mtimeMs)return an.db;an?.db.close();let t=await Kl(),r=t.capi,i=t.wasm,o=new Uint8Array(await CA(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),an={dbPath:n,mtimeMs:e.mtimeMs,db:a},a}function Qh(){an?.db.close(),an=null}async function RA(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 kA(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 xA(n,e,t){await sn();let r=await Kl(),i=new r.oo1.DB(":memory:","c");i.exec(ua);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=kA(i,o,s),l=e.length;for(let h=0;h<l;h+=Sr){let w=e.slice(h,h+Sr),S=await Promise.all(w.map(async k=>({source:k,searchText:await ca(k)})));await RA(i,a,c,S),await t?.(Math.min(h+w.length,l),l)}i.exec("ANALYZE");let d=r.capi.sqlite3_js_db_export(i);await AA(n,d),i.close(),Qh()}async function NA(n,e,t,r,i,o){let s=await TA(n);return da(DA(s),e,t,r,i,o)}async function Xl(){return await Kl(),{kind:"sqlite-wasm",resetCache:Qh,buildSearchIndex:xA,searchIndex:(n,e,t,r,i,o,s)=>NA(r,e,t,i,o,s)}}var pa=null,Zl=null;function LA(){return Rr.existsSync(Ni())}function OA(n){let e=Ni(),t={backend:"sqlite-wasm",reason:"better-sqlite3-load-failed",message:n,createdAt:new Date().toISOString()};Rr.mkdirSync(eg.dirname(e),{recursive:!0}),Fi(e),Rr.writeFileSync(e,JSON.stringify(t,null,2))}async function MA(){if(LA())return Xl();try{let n=await Zh();return m("doc-index: using better-sqlite3 SQLite backend"),n}catch(n){let e=n instanceof Error?n.message:String(n);OA(e),m(`doc-index: better-sqlite3 unavailable (${e}); falling back to sqlite-wasm`)}return Xl()}async function Vi(){return pa||(pa=MA().then(n=>(Zl=n,n))),pa}function tg(){Zl?.resetCache(),pa=null,Zl=null}async function _A(n,e,t,r,i,o,s){let a=await Vi(),c=s??Mn();return a.searchIndex(n,e,t,c,r,i,o)}function kr(){tg()}async function rg(n,e,t){await(await Vi()).buildSearchIndex(n,e,t)}function ig(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 fa(n,e,t,r,i,o){return _A(n,e,t,i,r.expandedQuery,r.rawQuery,o)}async function FA(n,e,t,r,i){let o=await fa(n,e,t,r,Ui(r.tokens,"AND"),i);if(o.length>=t)return o;let s=await fa(n,e,t,r,Ui(r.tokens,"OR"),i);return ig(o,s,t)}async function Ql(n,e,t,r,i){return r.ftsMatch?fa(n,e,t,r,r.ftsMatch,i):r.preferAnd?FA(n,e,t,r,i):fa(n,e,t,r,Ui(r.tokens,"OR"),i)}async function jA(n,e,t,r){let i=await Ql(n,"harmonyos-references",e,t,r);if(i.length>=e)return i;let o=await Ql(n,void 0,e,t,r);return ig(i,o,e)}function ng(n,e){return e!==void 0?n:zh(n)}async function ed(n,e,t=20,r){let i=await Uh(n);if(Oh(i.rawQuery,e)){let a=await jA(n,t,i,r);return ng(a,e)}let o=e??Vh(i.rawQuery),s=await Ql(n,o,t,i,r);return ng(s,e)}import{unified as pg}from"unified";import fg from"remark-parse";import mg from"remark-gfm";import{toString as ha}from"mdast-util-to-string";var HA=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,$A=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,UA=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,BA=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,WA=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function ma(n){let e=n.trim(),t=e.match(BA);return t?t[1]:e}function zA(n){let e=n.match(HA);if(!e)return;let t=ma(e[1].trim());return{displayTitle:n,symbolName:t,searchExtras:[t,e[3]]}}function GA(n){let e=ma(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 qi(n){let e=n.trim();return e?zA(e)??(()=>{let t=e.match($A);if(t){let r=t[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let t=e.match(UA);if(!t)return;let r=t[1].trim(),i=t[2].trim();return{displayTitle:e,symbolName:i,searchExtras:[r,i]}})()??GA(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function VA(n){if(n.length<2||n.length>36||WA.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 og(n){for(let e of n){let t=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(VA(t))return t}return""}function sg(n,e,t){let r=[n,...t.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var qA=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,Yi=/@[A-Z][a-zA-Z]+/g,YA=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,JA=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,KA=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,XA=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),ZA=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),QA=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function hg(n,e){let t=new Set,r=[n,...e];for(let i of r){for(let o of jl(i)){ot(t,o);let s=ra(o);s&&ot(t,s)}for(let o of Hl(i))ot(t,o);for(let o of i.matchAll(qA)){let s=o[0];eD(s)&&t.add(s)}for(let o of i.matchAll(Yi))t.add(o[0])}return Ar([...t])}function eD(n){let e=n.trim();if(!e||Yi.test(e))return!!e;if(e.includes(".")){let t=e.split(".")[0]??"";return QA.has(t)?!1:/^[A-Z]/.test(t)}return XA.has(e)?!1:ZA.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 ag(n){let e=n.trim();return!!(!e||KA.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function gg(n,e){let t=e.jsonTitle?.trim(),r=iD(n,"").trim(),i=e.fileName.trim();return t&&!ag(t)?t:r&&!ag(r)?r:t||r||i}function yg(n){return YA.test(n.trim())}function td(n){let e=n.trim().replace(/\([^)]*\)$/,""),t=ma(e);return JA.test(t)}function ga(n){let e=n.trim();return e?Yi.test(e)||yg(e)||td(e)?!0:!!qi(e).symbolName:!1}function tD(n){let e=n.trim();return!(!e||yg(e)||td(e))}function nD(n){let e=new Set,t=[];for(let r of n){let i=r.trim();!tD(i)||e.has(i)||(e.add(i),t.push(i))}return t}function cg(n){if(!n.includes("."))return 0;let e=n.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function rD(n,e){let t=cg(n)-cg(e);return t!==0?t:n.localeCompare(e)}function wg(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(rD),[...t,...i].slice(0,zm)}function ya(n){return n.replace(/\s+/g," ").trim()}function lg(n){return n.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function iD(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=lg(t[r].trim()),o=i.match(/^#+\s+(.+)$/);if(o)return lg(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 vg(n){let e=ya(n.join(" "));if(e.length<=Gs)return e;let t=e.slice(0,Gs);return e.length<=Gs+vl?t:`${t} ${e.slice(-vl)}`}function oD(n){let e=nD(n).join(" ");return e.length<=Sl?e:e.slice(0,Sl)}function Sg(n){let e=ya(n),{text:t,excerptTruncated:r}=Yh(e,Gm);return{leadText:t,excerptTruncated:r}}function sD(n,e){let{leadText:t,excerptTruncated:r}=Sg(n);return{leadText:t,excerptTruncated:r||!!e.trim()}}function bg(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)bg(r,e);return}let t=ya(ha(n));t&&e.bodyParts.push(t)}function aD(n){let e=pg().use(fg).use(mg).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=ha(a).trim();if(a.depth>=4&&c&&ga(c)){i(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}o(),c&&r.bodyParts.push(c);continue}o(),bg(s,r)}return i(),t.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:t}function cD(n){return km.test(n)}function lD(n){return n.filter(e=>e.sectionTitle&&ga(e.sectionTitle)).length}function dD(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 dg(n){let e=n.trim();return!e||Yi.test(e)?Yi.test(e):/对象说明$|枚举说明$/.test(e)?!0:td(e)}function uD(n){let e=n.filter(h=>!h.sectionTitle||!ga(h.sectionTitle)),t=n.filter(h=>h.sectionTitle&&ga(h.sectionTitle)),r=t.filter(h=>dg(h.sectionTitle)),i=t.filter(h=>!dg(h.sectionTitle)),o=Math.max(0,Rm-r.length),s=i.slice(0,o),a=i.slice(o),c=a.filter(h=>ug(h.sectionTitle)),l=a.filter(h=>!ug(h.sectionTitle)),d=[];for(let h=0;h<l.length;h+=yl)d.push(dD(l.slice(h,h+yl)));return[...e,...r,...s,...c,...d]}function pD(n,e,t){let r=n.split(/\r?\n/).length,i=lD(e);return i===0?!1:cD(t)?r>=Dm&&i>=Tm:r>=Im&&i>=Am}var fD=/^\[h2\][A-Za-z]/;function ug(n){return fD.test(n.trim())}function Eg(n){if(!n.includes(" | ")){let t=qi(n);return t.symbolName?[t.symbolName]:[]}let e=[];for(let t of n.split(" | ")){let r=qi(t.trim()).symbolName;r&&e.push(r)}return e}function mD(n,e,t,r){let i=Eg(n),o=hg(t,r);return e.symbolName&&o.push(e.symbolName),wg([...i,...o],i)}function hD(n,e){let t=vg(n.bodyParts),r=n.sectionTitle.trim(),i=qi(r),o=og(n.bodyParts),s=sg(r,o,i),a=Eg(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}=sD(t,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:mD(r,i,l,n.codeBlocks),bodySample:t,leadText:d,excerptTruncated:h}}function Pg(n,e){for(let t of n){if(t.type==="heading"){let i=ha(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)){Pg(t.children,e);continue}let r=ya(ha(t));r&&e.bodyParts.push(r)}}function gD(n){let e=pg().use(fg).use(mg).parse(n),t={headings:[],bodyParts:[],codeBlocks:[]};return Pg(e.children,t),t}function yD(n,e){let t=gD(n),r=e.docTitle?.trim()||e.documentId,i=vg(t.bodyParts),o=[r,...t.headings,i].join(" "),{leadText:s,excerptTruncated:a}=Sg(i);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:oD(t.headings),apiSymbols:wg(hg(o,t.codeBlocks)),bodySample:i,leadText:s,excerptTruncated:a}}function Cg(n,e){let t=e.docTitle?.trim()||e.documentId,r=aD(n);return pD(n,r,e.documentId)?uD(r).filter(i=>i.sectionTitle||i.bodyParts.length>0||i.codeBlocks.length>0).map(i=>hD(i,{...e,docTitle:t})):[yD(n,{...e,docTitle:t})]}async function wD(n){let e=[];async function t(r){let i=await ge.promises.readdir(r,{withFileTypes:!0});for(let o of i){if(o.name.startsWith("."))continue;let s=Ae.join(r,o.name);o.isDirectory()?await t(s):o.isFile()&&o.name.endsWith(".md")&&e.push(s)}}return await t(n),e}function vD(n,e){let t=Ae.relative(e,n).split(Ae.sep).join("/").split("/");if(t[0]==="docs"&&(t=t.slice(1)),t.length<2)return null;let r=t[0],i=Ym[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 SD(n){let e=n.replace(/\.md$/,".json");try{let t=await ge.promises.readFile(e,"utf-8");return JSON.parse(t).title?.trim()||void 0}catch{return}}async function bD(n,e){let t=vD(n,e);if(!t)return[];let r=await ge.promises.readFile(n,"utf-8"),i=gg(r,{jsonTitle:await SD(n),fileName:t.docTitle});return Cg(r,{...t,docTitle:i})}async function ED(n,e,t){let r=Ae.join(e,"search.db");return await rg(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 PD(n){let e=await wD(n),t=[];for(let r of e){let i=await bD(r,n);t.push(...i)}return t}function CD(n,e){return{indexVersion:vr,docsZipSha256:n.docsZipSha256,termsHash:n.termsHash,synonymsHash:n.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:n.builtBy}}async function Ag(n){n.lexiconDir&&Cl(n.lexiconDir);try{let e=await PD(n.docsDir);await n.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await ge.promises.mkdir(n.tmpDir,{recursive:!0});let t=await ED(e,n.tmpDir,n.onProgress),r=CD(n,t);return await ge.promises.writeFile(Ae.join(n.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await sh(n.tmpDir),r}finally{n.lexiconDir&&Cl(null)}}async function Dg(){return ge.promises.mkdtemp(Ae.join(Ig.tmpdir(),"deveco-docs-"))}async function ID(n,e){try{await ge.promises.rename(n,e)}catch(t){let r=t.code;if(r!=="EPERM"&&r!=="EXDEV")throw t;await ge.promises.cp(n,e,{recursive:!0}),await ge.promises.rm(n,{recursive:!0,force:!0})}}async function Tg(n){let e=Ae.join(n,"docs");try{await ge.promises.access(e)}catch{return}let t=new Set(["docs","docs.zip"]);for(let r of await ge.promises.readdir(e,{withFileTypes:!0})){if(t.has(r.name))continue;let i=Ae.join(e,r.name),o=Ae.join(n,r.name);await ge.promises.rm(o,{recursive:!0,force:!0}),await ID(i,o)}await ge.promises.rm(Ae.join(e,"docs"),{recursive:!0,force:!0}),await ge.promises.rm(Ae.join(e,"docs.zip"),{force:!0}),await ge.promises.rm(e,{recursive:!0,force:!0})}var Ji=class extends Error{constructor(e){super(e),this.name="NativeDepsError"}};function AD(){let n=Cr(),e=J();return["Documentation search index is not installed yet.","",...Vs(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(`
|
|
1364
|
+
`)}function DD(){let n=Cr();return[`Chinese tokenizer (${b()?"jieba-wasm":"@node-rs/jieba"}) failed to load.`,"",`Node.js: ${process.version} (required: >=18)`,"",...Vs(n),"","Try:"," 1. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 2. Use Node.js 18 or newer",b()?" 3. Verify jieba-wasm package is installed (WASM backend for OpenHarmony)":" 3. Configure npm registry/proxy if your network blocks optional platform packages"].join(`
|
|
1365
|
+
`)}function TD(n){let e=Cr();return[n,"",...Vs(e)].join(`
|
|
1366
|
+
`)}async function Rg(){try{ih()}catch(n){throw rh(n)?new Ji(`${AD()}
|
|
1347
1367
|
|
|
1348
|
-
Detail: ${n.message}`):n}try{await
|
|
1368
|
+
Detail: ${n.message}`):n}try{await sn()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Ji(`${DD()}
|
|
1349
1369
|
|
|
1350
|
-
Detail: ${e}`)}try{await
|
|
1351
|
-
`)}async function
|
|
1370
|
+
Detail: ${e}`)}try{await Vi()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Ji(TD(e))}}var nd=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function xD(n){return new Promise(e=>setTimeout(e,n))}async function Lg(n){let e=Cr();await Q.promises.mkdir(ft.dirname(e),{recursive:!0}),await Q.promises.appendFile(e,`${new Date().toISOString()} ${n}
|
|
1371
|
+
`)}async function ND(n){let e=rn();if(!e)throw new Error("docs.zip not found");await Q.promises.rm(n,{recursive:!0,force:!0}),await Q.promises.mkdir(n,{recursive:!0});let t=ft.resolve(n),r=new RD(e);for(let i of r.getEntries()){let o=ft.resolve(t,i.entryName);if(!$r(o,t))throw new Error(`Unsafe docs.zip entry path: ${i.entryName}`);if(i.isDirectory){await Q.promises.mkdir(o,{recursive:!0});continue}await Q.promises.mkdir(ft.dirname(o),{recursive:!0}),await Q.promises.writeFile(o,i.getData())}await Tg(n)}async function LD(){await Ir({mode:"write"});let n=J(),e=Rt(),t=await Q.promises.readdir(e);for(let r of t){let i=ft.join(n,r);await Q.promises.rm(i,{force:!0}),await Q.promises.rename(ft.join(e,r),i)}await Q.promises.rm(e,{recursive:!0,force:!0}),await Q.promises.rm(ft.join(n,"orama.dpack"),{force:!0})}async function kg(n,e,t){e?.start(t),await on({state:"installing",phase:1,phaseLabel:"Installing index",message:t}),await fh(n),kr(),e&&(e.text="Documentation index installed.")}async function OD(n,e){try{return await kg(n,e,"Installing documentation index\u2026"),await rd(e),!0}catch(t){if(_i(t))throw t}try{return await mh(),kr(),await kg(n,e,"Retrying documentation index install\u2026"),await rd(e),!0}catch(t){if(_i(t))throw t;let r=t instanceof Error?t.message:String(t);return await Lg(`Bundled index install failed; falling back to local rebuild: ${r}`),!1}}async function MD(n,e,t){let r=Rt(),i=await Dg();await Q.promises.mkdir(J(),{recursive:!0}),await Q.promises.rm(r,{recursive:!0,force:!0}),t?.start("Building search index\u2026"),await on({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"});try{await ND(i),await Ag({docsDir:i,tmpDir:r,docsZipSha256:e,termsHash:ea(),synonymsHash:Qs(),builtBy:n.builtBy??"doc-init",onProgress:async o=>{t&&(t.text=o.message),await on({state:"indexing",current:o.current,total:o.total,message:o.message})}})}finally{await Q.promises.rm(i,{recursive:!0,force:!0})}await on({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await LD(),kr()}async function rd(n){await on({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function _D(n){let e=await Ml(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await on({state:"done",message:t,error:null})}async function FD(n,e){let t=n instanceof Error?n.message:String(n);throw await on({state:"error",error:t}),await Lg(`ERROR: ${t}`),e?.fail(t),n}async function jD(){let n=J();await Q.promises.mkdir(n,{recursive:!0});let e=qs();return Q.existsSync(e)||await Q.promises.writeFile(e,"","utf-8"),e}async function HD(){let n=await jD();return kD.lock(n,{stale:1800*1e3})}async function $D(){let n=rn(),e=(n?await Zs(n):null)??await Ol();if(!e)throw new Error("docs.zip not found");return e}async function UD(n,e){let t=await $D(),r=n.force||await _l(n.force),i=await na(n.force);if(!r&&!i&&Hi()){await _D(e);return}!n.force&&ph(t)&&await OD(t,e)||(await MD(n,t,e),await rd(e))}var Ki=class{static async run(e={}){let t=e.background??!1,i=e.quiet??t?void 0:Ng({text:"Checking documentation\u2026",color:"cyan"}),o;try{e.assumeStorageSafe||await Ir({mode:"write"}),o=await HD(),await Ll(vh("Starting documentation setup\u2026")),await UD(e,i)}catch(s){throw o&&await FD(s,i),s}finally{o&&await o()}}};async function BD(n){for(;;){let e=await ta();if(e.state==="done"&&Hi())return;if(e.state==="error")throw new nd("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 xD(500)}}async function xg(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await Ki.run({builtBy:"doc-init",force:e,quiet:!0})}async function WD(){let n=await na()!==null;if(Hi()&&!n)return;let e=Ng({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await Sh()){await BD(e),e.succeed("Documentation ready.");return}if(await _l()){await xg(e),e.succeed("Documentation ready.");return}await xg(e,!0),e.succeed("Documentation ready.")}catch(t){throw e.fail(t.message),t}}async function Xi(){await Ir({mode:"read"}),await WD(),await Rg()}function zD(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 id=class{async search(e,t,r=20){await Xi();try{return await ed(e,t,r)}catch(i){if(!zD(i))throw i;return kr(),await Ki.run({builtBy:"doc-init",force:!0,quiet:!0,assumeStorageSafe:!0}),ed(e,t,r)}}async readDocument(e){return await Xi(),lh(e)}},od=new id;function Og(...n){return e=>{if(!n.includes(e))throw new sd(`Allowed values: ${n.join(", ")}`);return e}}function qD(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new sd("Must be a positive integer.");return e}var YD=Og("json","default"),JD=Og("json","default");function ad(n){let e=n instanceof Error?n.message:String(n);return _i(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 va=new GD("docs").description("Search and read HarmonyOS documentation from local docs directory");va.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",XD,"all").option("--format <fmt>","Output format (default, json)",YD,"default").option("--limit <n>","Max number of results",qD,20).action(async(n,e)=>{try{let t=KD(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,i=await od.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(i,null,2)):ZD(i)}catch(t){console.error(wa(ad(t))),process.exit(1)}});va.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error(wa("Document ID cannot be empty.")),process.exit(1));let t=await od.readDocument(e);console.log(t)}catch(e){console.error(wa(ad(e))),process.exit(1)}});va.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",JD,"default").action(async n=>{try{if(await Xi(),n.format==="json"){let e=en.map(t=>({name:t,title:Ln[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of en)console.log(` ${e.padEnd(20)} ${VD(Ln[e])}`)}catch(e){console.error(wa(ad(e))),process.exit(1)}});function KD(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>Ri)throw new Error(`Query exceeds ${Ri} characters.`);return e}function XD(n){if(n==="all")return"all";if(!en.includes(n))throw new sd(`Invalid catalog "${n}". Allowed: all, ${en.join(", ")}`);return n}function ZD(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 Mg=va;import{Command as nR}from"commander";import{Command as dT,InvalidArgumentError as uT,Option as ld}from"commander";import{readFileSync as eT,unlinkSync as tT}from"fs";import{tmpdir as nT}from"os";import{join as rT}from"path";var Lt=class{constructor(e,t){this.hdcPath=e;this.serial=t}hdcPath;serial;async listWindows(e){let t=await this.fetchDump(),r=QD(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 Oe(this.hdcPath,e);if(t.exitCode!==0)throw new Error(`Failed to query windows: ${(t.stderr||t.stdout).trim()}`);return t.stdout}};function QD(n){let e=n.split(`
|
|
1372
|
+
`),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]),S=Number(c[4]);Number.isFinite(w)&&Number.isFinite(d)&&Number.isFinite(h)&&r.push({id:w,name:l,pid:h,displayId:d,type:S})}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 _g(n){if(!(!n||n==="HitTestMode.Default"))return n.startsWith("HitTestMode.")?n.slice(12):n}function Zi(n){if(!(n==null||n==="")){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1}}function Fg(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 jg(n){return n.originalText||void 0}function xr(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 Hg(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 iT(n){let e=eT(n,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function oT(n){return n.attributes??{}}function Sa(n,e,t){let r=oT(n),i={id:r.id||void 0,type:r.type||void 0,text:jg(r),bounds:Fg(r.bounds),clickable:Zi(r.clickable)||void 0,longClickable:Zi(r.longClickable)||void 0,scrollable:Zi(r.scrollable)||void 0,checkable:Zi(r.checkable)||void 0,hitTestBehavior:_g(r.hitTestBehavior),children:[]};return e>0&&t+1>=e||n.children&&(i.children=n.children.map(o=>Sa(o,e,t+1))),i}function sT(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 jn=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 Oe(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=rT(nT(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,r),iT(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 Oe(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}`),tT(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 Oe(this.hdcPath,i).catch(o=>{m(`Failed to clean remote dump file ${r}: ${o.message}`)})}async dumpRawNodes(e,t,r){let o=await new Lt(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=sT(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=>Sa(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:Sa(s,t,0)})}return i}async dumpCollapsedTree(e,t,r,i){return(await this.dumpRawNodes(e,r,i)).flatMap(s=>Hg(Sa(s,0,0),t))}};var ba={left:"0",right:"1",up:"2",down:"3"};function be(n,e){let t=Number(n);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function cd(n,e){n!==void 0&&be(n,e)}function $g(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function Ea(n,e){if(n!==void 0&&n.length===0)throw new Error(`${e} must not be empty`)}function Qi(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 Ug(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function Bg(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 Nr(n,e,t,r,i=!0){$g(n,e),Ea(t,"--id"),cd(n,"x"),cd(e,"y"),Ug(r),Bg(n!==void 0,!!t,!!r,i)}async function Lr(n,e){let r=await new rr(n).selectDevice(e);if(!r)throw new Error("No device selected. Use `devecocli device list` to see targets.");return r}async function mt(n){let e=await A.new(),t=await Lr(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function Or(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 Lt(n,e).listWindows({all:!0}),c=new jn(n);return aT(c,e,a,i,o)}async function aT(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 lT(s,r)}return cT(n,e,t,r)}async function cT(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 xr([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 Wg(s[0].node,r)}function lT(n,e){let t=xr(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 Wg(t[0],e)}function Wg(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 Ge(n,e,t){let r=["-t",e,"shell",...t],i=await Oe(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 pT from"ora";function fT(n){let e=parseInt(n,10);if(!Number.isInteger(e)||e<0||String(e)!==n.trim())throw new uT("depth must be a non-negative integer");return e}function mT(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 zg(n,e=0){let t=[],r=" ".repeat(e);for(let i of n)t.push(`${r}${mT(i)}`),i.children.length>0&&t.push(...zg(i.children,e+1).split(`
|
|
1373
|
+
`));return t.join(`
|
|
1374
|
+
`)}function hT(n){if(n.allWindows&&n.window)throw new Error("--all-windows and --window are mutually exclusive.")}function gT(n,e){let t=xr(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 yT(n,e){console.log(e==="json"?JSON.stringify(n,null,2):zg(n))}async function wT(n){hT(n);let e=pT({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let r=await A.new(),i=await Lr(r,n.device),o=new jn(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){gT(t,n.id);return}yT(t,n.format)}var Gg=new dT("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 ld("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(fT).default(0)).addOption(new ld("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new ld("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async n=>{await wT(n)});import{Command as vT,Option as ST}from"commander";import{yellow as bT}from"colorette";import ET from"ora";var PT=["Id","Name","Pid","DisplayId","Focused"];function CT(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(Et(PT,t))}async function IT(n){let e=ET({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let r=await A.new(),i=await Lr(r,n.device);t=await new Lt(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(bT(" No windows found."));return}CT(t,n.format)}var dd=new vT("window").description("Manage device windows");dd.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new ST("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async n=>{await IT(n)});import{Command as AT}from"commander";import _e from"fs";import Ve from"path";import{randomUUID as DT}from"crypto";import{execa as Vg}from"execa";import{green as TT,red as RT}from"colorette";function ud(){return String(Date.now())}function kT(n){if(!n?.trim())return Ve.resolve(`screenshot-${ud()}.png`);let e=Ve.resolve(n.trim());if(_e.existsSync(e)&&_e.statSync(e).isDirectory())return Ve.join(e,`screenshot-${ud()}.png`);if(Ve.extname(e).toLowerCase()!==".png"){if(!_e.existsSync(e))throw new Error(`Screenshot directory does not exist: ${e}`);if(!_e.statSync(e).isDirectory())throw new Error(`Screenshot path is not a directory: ${e}`);return Ve.join(e,`screenshot-${ud()}.png`)}let t=Ve.dirname(e);if(!_e.existsSync(t))throw new Error(`Screenshot directory does not exist: ${t}`);if(!_e.statSync(t).isDirectory())throw new Error(`Screenshot parent path is not a directory: ${t}`);return e}function qg(n){if(!_e.existsSync(n))throw new Error(`Screenshot file was not created: ${n}`);let e=_e.statSync(n);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${n}`);let t=_e.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 fd(n,e,t){m(`Executing: ${n} ${e.join(" ")}`);let{stdout:r}=await Vg(n,e,{env:{...process.env},cwd:t});return r}async function xT(n,e,t){m(`Executing: ${n} ${e.join(" ")}`);let{stdout:r,stderr:i}=await Vg(n,e,{env:{...process.env},cwd:t});return{stdout:r,stderr:i}}async function NT(n,e,t){try{return await fd(n,e,t)}catch(r){return r.stdout??""}}async function LT(n,e){let t=Z.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 OT(t,r);throw new Error(`Multiple devices found. Specify a target device using \`--device <name|serial>\`.
|
|
1375
|
+
Available devices:
|
|
1376
|
+
${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 OT(n,e){return(await Promise.all(e.map(async r=>` - ${await n.getDeviceName(r.serial)} (${r.serial})`))).join(`
|
|
1377
|
+
`)}function MT(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 _T(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}function FT(n,e){_e.copyFileSync(n,e),qg(e)}function jT(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 HT(n){let e=await NT(n.hdcPath,["-t",n.serial,"shell","ls","-l",n.remotePath]);return jT(e)}function $T(n){return[n.stdout,n.stderr].filter(Boolean).join(`
|
|
1378
|
+
`).trim()}async function UT(n,e){let t;try{t=await xT(n.hdcPath,MT(n,e))}catch(i){t={stdout:i.stdout??"",stderr:i.stderr??i.message}}let r=await HT(n);return{created:r!==void 0&&r>0,output:$T(t)}}async function BT(n){let e=[];for(let t of[void 0,"png"]){let r=await UT(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(`
|
|
1379
|
+
`)}`:`Screenshot was not created on device: ${n.remotePath}.`)}function Yg(n){try{return qg(n),!0}catch{return!1}}function Jg(n){let e=[];for(let t of _e.readdirSync(n,{withFileTypes:!0})){let r=Ve.join(n,t.name);if(t.isDirectory()){e.push(...Jg(r));continue}t.isFile()&&Yg(r)&&e.push(r)}return e}function WT(n,e){let t=Ve.join(n,Ve.basename(e));if(Yg(t))return t;let r=Jg(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}async function pd(n,e,t,r){try{await fd(n.hdcPath,["-t",n.serial,"file","recv",n.remotePath,t],r)}catch(i){m(`hdc file recv failed: ${i.message}`)}return WT(e,n.remotePath)}async function zT(n){let e=_e.mkdtempSync(Ve.join(Ve.dirname(n.localPath),".devecocli-screenshot-"));try{let t=await pd(n,e,".",e)??await pd(n,e,e)??await pd(n,e,Ve.join(e,"screenshot.png"));if(!t)throw new Error(`Screenshot file was not created in ${e}.`);FT(t,n.localPath)}finally{_e.rmSync(e,{recursive:!0,force:!0})}}async function GT(n){await fd(n.hdcPath,["-t",n.serial,"shell","rm","-f",n.remotePath]).catch(()=>{})}async function VT(n){try{await BT(n),await zT(n)}finally{await GT(n)}}async function qT(n){try{let e=n.display!==void 0?_T(n.display):void 0,t=await A.new(),r=await LT(t,n.device),i=kT(n.path),o=`/data/local/tmp/devecocli-${DT()}.png`;await VT({hdcPath:t.hdcPath,serial:r,localPath:i,remotePath:o,display:e}),console.log(TT(`Screenshot saved to ${i}`))}catch(e){console.error(RT(`Failed to capture screenshot: ${e.message}`)),process.exit(1)}}var Kg=new AT("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(qT);import{Command as cn}from"commander";async function ln(n,e,t){let r=new nt;r.start(n);try{await t(r)}catch(i){throw r.stop(),new Error(`${e}: ${i.message}`,{cause:i})}}async function YT(n,e,t){await ln("Executing click...","click failed",async r=>{Nr(n,e,t.id,t.window);let{hdcPath:i,deviceId:o}=await mt(t.device),{x:s,y:a}=await Or(i,o,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Ge(i,o,["uitest","uiInput","click",String(s),String(a)]),r.succeed(`click at (${s}, ${a})`)})}async function JT(n,e,t){await ln("Executing doubleclick...","doubleclick failed",async r=>{Nr(n,e,t.id,t.window);let{hdcPath:i,deviceId:o}=await mt(t.device),{x:s,y:a}=await Or(i,o,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Ge(i,o,["uitest","uiInput","doubleClick",String(s),String(a)]),r.succeed(`doubleclick at (${s}, ${a})`)})}async function KT(n,e,t){await ln("Executing longclick...","longclick failed",async r=>{Nr(n,e,t.id,t.window);let{hdcPath:i,deviceId:o}=await mt(t.device),{x:s,y:a}=await Or(i,o,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Ge(i,o,["uitest","uiInput","longClick",String(s),String(a)]),r.succeed(`longclick at (${s}, ${a})`)})}async function XT(n,e,t,r,i){await ln("Executing swipe...","swipe failed",async o=>{be(n,"x1"),be(e,"y1"),be(t,"x2"),be(r,"y2");let s=Qi(i.speed),{hdcPath:a,deviceId:c}=await mt(i.device),l=["uitest","uiInput","swipe",n,e,t,r];s&&l.push(s),await Ge(a,c,l),o.succeed(`swipe from (${n}, ${e}) to (${t}, ${r})`)})}async function ZT(n,e,t,r,i){await ln("Executing fling...","fling failed",async o=>{be(n,"x1"),be(e,"y1"),be(t,"x2"),be(r,"y2");let s=Qi(i.speed),{hdcPath:a,deviceId:c}=await mt(i.device),l=["uitest","uiInput","fling",n,e,t,r];s&&l.push(s),await Ge(a,c,l),o.succeed(`fling from (${n}, ${e}) to (${t}, ${r})`)})}async function QT(n,e,t,r,i){await ln("Executing drag...","drag failed",async o=>{be(n,"x1"),be(e,"y1"),be(t,"x2"),be(r,"y2");let s=Qi(i.speed),{hdcPath:a,deviceId:c}=await mt(i.device),l=["uitest","uiInput","drag",n,e,t,r];s&&l.push(s),await Ge(a,c,l),o.succeed(`drag from (${n}, ${e}) to (${t}, ${r})`)})}async function eR(n,e){await ln("Executing dircfling...","dircfling failed",async t=>{let r=ba[n];if(r===void 0)throw new Error(`Invalid direction "${n}". Valid values: ${Object.keys(ba).join(", ")}`);let{hdcPath:i,deviceId:o}=await mt(e.device);await Ge(i,o,["uitest","uiInput","dircFling",r]),t.succeed(`dircfling ${n}`)})}async function tR(n,e,t,r){await ln("Executing text input...","input failed",async i=>{Nr(e,t,r.id,r.window,!1),Ea(n,"text");let{hdcPath:o,deviceId:s}=await mt(r.device);if(e!==void 0)await Ge(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 Or(o,s,void 0,void 0,r.id,r.window);await Ge(o,s,["uitest","uiInput","inputText",`${a}`,`${c}`,n]),i.succeed(`input ${n} at (${a}, ${c})`)}else await Ge(o,s,["uitest","uiInput","text",n]),i.succeed(`input ${n}`)})}var Xg=new cn("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(YT),Zg=new cn("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(JT),Qg=new cn("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(KT),ey=new cn("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(XT),ty=new cn("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(ZT),ny=new cn("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(QT),ry=new cn("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action(eR),iy=new cn("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(tR);var qe=new nR("ui").description("Inspect and interact with UI on a connected device");qe.addCommand(Gg);qe.addCommand(dd);qe.addCommand(Kg);qe.addCommand(Xg);qe.addCommand(Zg);qe.addCommand(Qg);qe.addCommand(ey);qe.addCommand(ty);qe.addCommand(ny);qe.addCommand(ry);qe.addCommand(iy);var oy=qe;import{Command as $k}from"commander";import{execa as CR}from"execa";import Ot from"fs";import*as yd from"os";import*as H from"path";var rR=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),iR=/\r/g,oR=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,sR=/^<+\s*/,aR=/\s*>+$/,cR=[/^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 md(n){if(!n)return"";let e=n.replace(rR,"").replace(iR,`
|
|
1380
|
+
`).split(`
|
|
1381
|
+
`).map(t=>t.trimEnd()).filter(t=>dR(t));return e.length>0?`${e.join(`
|
|
1382
|
+
`)}
|
|
1383
|
+
`:""}function ly(n){let e=md(n).trim();if(!e)return{jsonText:void 0,diagnostics:""};if(dy(e))return{jsonText:e,diagnostics:""};let t=uR(e);if(!t)return{jsonText:void 0,diagnostics:`${e}
|
|
1384
|
+
`};let r=[e.slice(0,t.start).trim(),e.slice(t.end).trim()].filter(Boolean).join(`
|
|
1385
|
+
`);return{jsonText:e.slice(t.start,t.end),diagnostics:r?`${r}
|
|
1386
|
+
`:""}}function lR(n){return oR.test(n.trim())}function dR(n){let e=n.trim();return!!e&&!lR(e)&&!cR.some(t=>t.test(e))}function dy(n){try{return JSON.parse(n),!0}catch{return!1}}function uR(n){for(let e=0;e<n.length;e++){if(n[e]!=="["&&n[e]!=="{")continue;let t=pR(n,e);if(t)return t}}function pR(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(dy(i))return{start:e,end:t}}}var sy=["Error","Warning","Suggestion","Info","Off","Unknown"];function uy(n){let e=hd(n);return{issues:gR(e),summary:fR(n,e)}}function fR(n,e){let t=wR(e);return{filesChecked:vR(n).size,issues:e.length,errors:t.get("Error")??0,warnings:t.get("Warning")??0,suggestions:t.get("Suggestion")??0}}function hd(n,e=""){if(Array.isArray(n))return n.flatMap(o=>hd(o,e));if(!py(n))return[];let t=eo(n,["filePath","file","path"])??e,r=mR(n,t);if(r.length>0)return r;let i=hR(n,t);return i?[i]:[]}function mR(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=>hd(s,e));if(o.length>0)return o}}return[]}function hR(n,e){let t=eo(n,["message","description","desc","detail"])??"",r=PR(eo(n,["rule","ruleId","ruleName"])),i=bR(n,["severity","level"]),o=eo(n,["filePath","file","path"])??e;if(!(!t&&!r&&i==="Unknown"))return{file:o,line:cy(n,["line","reportLine"]),column:cy(n,["column","reportColumn"]),severity:i,rule:r,message:t}}function gR(n){return[...n].sort((e,t)=>{let r=ay(e.severity)-ay(t.severity);return r===0?yR(e,t):r})}function yR(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 wR(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 vR(n){let e=new Set;return gd(e,n,""),e}function gd(n,e,t){if(Array.isArray(e)){for(let i of e)gd(n,i,t);return}if(!py(e))return;let r=eo(e,["filePath","file","path"])??t;r&&n.add(r),SR(n,e,r)}function SR(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)gd(n,s,t)}}function bR(n,e){for(let t of e){let r=n[t];if(typeof r=="string"||typeof r=="number")return ER(r)}return"Unknown"}function ER(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 PR(n){let e=n?.normalize("NFKC").trim();if(e)return e.replace(sR,"").replace(aR,"").toLowerCase()}function ay(n){let e=sy.indexOf(n);return e===-1?sy.length:e}function eo(n,e){for(let t of e){let r=n[t];if(typeof r=="string")return r}}function cy(n,e){for(let t of e){let r=n[t];if(typeof r=="number")return r}}function py(n){return typeof n=="object"&&n!==null}var fy="deveco-codelinter-",my=[".ets",".ts",".js"],to=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=Ot.mkdtempSync(H.join(yd.tmpdir(),fy)),r=H.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=ly(c.stdout),d=l.diagnostics+md(c.stderr);try{let h=this.readJsonReport(r,l.jsonText);return{exitCode:c.exitCode,diagnostics:d,report:uy(h)}}catch(h){return{exitCode:c.exitCode,diagnostics:d,reportError:h}}}finally{this.removeTempDir(t)}}resolveLintTarget(e,t){let r=e?H.resolve(this.cwd,e):t,i=this.resolveRealPath(r,"Lint path"),o=Ot.statSync(i);if(!o.isFile()&&!o.isDirectory())throw new Error(`Lint path must be a file or directory: ${r}`);if(o.isFile()){let a=H.extname(i).toLowerCase();if(!my.some(l=>l===a))throw new Error(`Unsupported lint file extension "${a||"<none>"}": ${i}. Supported extensions: ${my.join(", ")}.`)}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?H.resolve(this.cwd,e):H.join(t.projectRoot??this.cwd,"code-linter.json5"),i=this.resolveRealPath(r,"`--config-path`");if(!Ot.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||H.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:H.dirname(e);try{return Ot.realpathSync(U.discover(r).rootDir)}catch{return}}resolveRealPath(e,t){try{return Ot.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 CR(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??[])Ot.mkdirSync(e,{recursive:!0})}readJsonReport(e,t){let i=(Ot.existsSync(e)?Ot.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=H.resolve(e),r=H.resolve(yd.tmpdir());!(t.startsWith(`${r}${H.sep}`)||t===r)||!H.basename(t).startsWith(fy)||Ot.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(H.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=[H.dirname(e.nodePath)];return t==="ide"&&e.javaPath&&r.unshift(H.dirname(e.javaPath)),r}static getResultDirectory(e){return H.resolve(e,"..","linter","result")}static getSource(e){return e.sourceType==="studio"?"ide":"command-line-tools"}};import{red as Ca,yellow as MR}from"colorette";import{Argument as _R,Command as FR,InvalidArgumentError as un}from"commander";import ro from"fs";import*as De from"path";import*as no from"path";var hy="n/a",gy=/\\/g,IR=/\|/g,AR=/\r?\n/g;function yy(n,e){if(n.issues.length===0)return`No defects found.
|
|
1387
|
+
${wd(n.summary)}
|
|
1388
|
+
`;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[TR(t),wd(n.summary)];return e!==void 0&&t.length<n.issues.length&&r.push(DR(n.issues.length,t.length)),`${r.join(`
|
|
1389
|
+
`)}
|
|
1390
|
+
`}function wy(n,e){return[wd(n.summary),`Full report: ${vd(e)}`,""].join(`
|
|
1391
|
+
`)}function vy(n){let e=["# CodeLinter report",""];return n.issues.length===0?e.push("No defects found.",""):e.push(...RR(n.issues),""),e.push("## Summary","",...xR(n.summary),""),e.join(`
|
|
1392
|
+
`)}function Sy(n){return`${JSON.stringify(n,null,2)}
|
|
1393
|
+
`}function wd(n){return`Summary: Issues: ${Ye(n.issues)} | Errors: ${Ye(n.errors)} | Warnings: ${Ye(n.warnings)} | Suggestions: ${Ye(n.suggestions)} | Files checked: ${Ye(n.filesChecked)}`}function DR(n,e){return`Showing ${Ye(e)} of ${Ye(n)} issues. Use --output-path <path> to write all results.`}function TR(n){let e=["No","File","Line","Column","Severity","Rule","Message"],t=n.map((r,i)=>({cells:LR(r,i+1)}));return["CodeLinter report","",Et(e,t)].join(`
|
|
1394
|
+
`)}function RR(n){let e=["| No | File | Line | Column | Severity | Rule | Message |","| ---: | --- | ---: | ---: | --- | --- | --- |"];for(let[t,r]of n.entries())e.push(kR(r,t+1));return e}function kR(n,e){return`| ${[String(e),vd(dn(n.file)),Pa(n.line),Pa(n.column),dn(n.severity),dn(n.rule),dn(n.message)].map(NR).join(" | ")} |`}function xR(n){return[`- Issues: ${Ye(n.issues)}`,`- Errors: ${Ye(n.errors)}`,`- Warnings: ${Ye(n.warnings)}`,`- Suggestions: ${Ye(n.suggestions)}`,`- Files checked: ${Ye(n.filesChecked)}`]}function NR(n){return n.replace(gy,"\\\\").replace(IR,"\\|").replace(AR,"<br>")}function LR(n,e){return[String(e),vd(dn(OR(n.file))),Pa(n.line),Pa(n.column),dn(n.severity),dn(n.rule),dn(n.message)]}function OR(n){if(!no.isAbsolute(n))return n;let e=no.relative(process.cwd(),n);return!e||e.startsWith("..")||no.isAbsolute(e)?n:e}function vd(n){return n.replace(gy,"/")}function dn(n){let e=n?.trim();return e||hy}function Pa(n){return n===void 0?hy:String(n)}function Ye(n){return n.toLocaleString("en-US")}var jR=/^-?\d+$/;function Sd(){return new FR("lint").description("Run DevEco Code Linter checks for TS/ArkTS code").addArgument(new _R("[path]","File or directory to lint").argParser(WR)).option("--fix","Auto-fix fixable code issues").option("--incremental","Only check uncommitted files").option("--config-path <path>","Path to lint configuration file",$R).option("--product <product>","Product name defined in build-profile.json5",UR,"default").option("--format <format>","Report format (choices: default, json)",HR,"default").option("--output-path <path>","Complete report file or directory",BR).option("--limit <number>","Maximum terminal issues to display when --output-path is omitted",zR).action(async(n,e)=>{await GR(n,e)})}function HR(n){if(n==="default"||n==="json")return n;throw new un("Invalid --format. Expected one of: default, json.")}function $R(n){bd(n,"--config-path");let e=De.extname(n).toLowerCase();if(e!==".json"&&e!==".json5")throw new un("`--config-path` must point to a .json or .json5 file.");return n}function UR(n){return by(n,"product"),n}function BR(n){return bd(n,"--output-path"),n}function WR(n){return bd(n,"path"),n}function zR(n){if(by(n,"limit"),!jR.test(n))throw new un("`--limit` must be a positive integer.");let e=Number.parseInt(n,10);if(e<=0||!Number.isSafeInteger(e))throw new un("`--limit` must be an integer greater than 0.");return e}function by(n,e){if(n.trim().length===0||Cy(n))throw new un(`Invalid --${e} value.`)}function bd(n,e){let t=`\`${e}\``;if(n.length===0||Cy(n))throw new un(`${t} must be a non-empty path without control characters.`)}async function GR(n,e){let t=process.cwd(),r=KR(e.outputPath,e.format,t);e.fix&&console.warn(MR("Running codelinter with --fix. Ensure your project source is trusted."));let i=await VR(n,e,t);tk(i.diagnostics),process.exitCode=YR(i,r,e.format,e.limit,t)}async function VR(n,e,t){let r=await A.new(),i=new to(r,t);return qR(i,{lintPath:n,configPath:e.configPath,product:e.product,fix:e.fix,incremental:e.incremental})}async function qR(n,e){let t=new nt;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 YR(n,e,t,r,i){if(!n.report)return console.error(Ca("Failed to generate Code Linter report.")),console.error(Ca(n.reportError?.message??"Native JSON report was not generated.")),n.exitCode===0?1:n.exitCode;try{if(e){JR(e,t,n.report);let o=Py(e,i);process.stdout.write(wy(n.report,o))}else process.stdout.write(yy(n.report,r));return n.exitCode}catch(o){return console.error(Ca("Failed to generate Code Linter report.")),console.error(Ca(o.message)),n.exitCode===0?1:n.exitCode}}function JR(n,e,t){ro.mkdirSync(De.dirname(n),{recursive:!0});let r=e==="json"?Sy(t):vy(t);try{ro.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 KR(n,e,t){if(!n)return;let r=QR(n,t),i=ZR(n,r),o=i?De.join(r,ek(e)):r;if(i||XR(n,e),ro.existsSync(o))throw new un(`Output file already exists: ${Py(o,t)}`);return o}function XR(n,e){let t=Ey(e);if(De.extname(n).toLowerCase()!==t)throw new un(`--output-path must use the ${t} extension for --format ${e}.`)}function ZR(n,e){return ro.existsSync(e)?ro.statSync(e).isDirectory():n.endsWith("/")||n.endsWith("\\")||De.extname(n)===""}function QR(n,e){return De.resolve(e,n)}function ek(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}${Ey(n)}`}function Ey(n){return n==="json"?".json":".md"}function Py(n,e){let t=De.relative(e,n);return t&&!t.startsWith("..")&&!De.isAbsolute(t)?t:n}function tk(n){n&&process.stderr.write(n)}function Cy(n){for(let e of n){let t=e.charCodeAt(0);if(t<=31||t===127)return!0}return!1}import{Command as nk,InvalidArgumentError as Ty}from"commander";import*as $ from"path";import*as Ed from"os";import{readdirSync as rk,existsSync as Ia,readFileSync as ik,unlinkSync as ok,copyFileSync as Ry,writeFileSync as ky}from"fs";import{execa as sk}from"execa";import{cyan as ue,yellow as xy}from"colorette";import ak from"ora";var Iy=["default","csv","json"];function Ny(n){if(Iy.includes(n))return n;throw new Ty(`--format must be one of: ${Iy.join(", ")} (got "${n}")`)}function ck(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new Ty(`--limit must be a positive integer (got "${n}")`);return e}function lk(n){return[...n].sort((e,t)=>{let r=Ay(e),i=Ay(t);return r.apiVersion-i.apiVersion||r.suffix.localeCompare(i.suffix)})}function Ay(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 Ly(n){let t=rk(n,{withFileTypes:!0}).filter(r=>r.isFile()&&r.name.toLowerCase().endsWith(".json")).map(r=>r.name.slice(0,-5));return lk(t)}function dk(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=Ny(i);return o==="default"?"csv":o}}return n}async function uk(n){let e=await A.new(),{apiChangeDir:t}=e.getApiscanPaths();m(ue(`[compat:versions] apiChangeDir: "${t}"`));let r=Ly(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(`
|
|
1395
|
+
`))}}var Dy=new Set([".ets",".c",".cpp"]);function pk(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 fk(n){for(let e of n){let t=$.resolve(e);if(!Ia(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 mk(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 hk(n){let e=[],t=[],r="",i=!1,o=0;for(;o<n.length;){let s=n[o];i?{field:r,inQuotes:i,i:o}=gk(n,o,s,r,i):s==='"'?(i=!0,o+=1):s===","?(t.push(r),r="",o+=1):s===`
|
|
1396
|
+
`?(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 gk(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 yk(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 wk(n){let e=ik(n,"utf8"),t=e.startsWith("\uFEFF")?e.slice(1):e,r=hk(t);if(r.length<2)return[];let[i,...o]=r;return yk(i,o)}function vk(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 Sk(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(ue("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 bk(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(ue(`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(xy(` ... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function Ek(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(xy(`... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function Pk(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 Ck(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}=mk(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=Pk(t,r.modules);i.push("--modulePaths",o.join(","))}else i.push("--projectPath",t.rootDir);return i.push("--outputPath",Ed.tmpdir()),i}async function Ik(n,e){let t=$.dirname(e[0]);try{let i=(await sk(n.nodePath,e,{cwd:t,stdin:"ignore",stdout:"pipe",stderr:"inherit"})).stdout;return process.env.DEVECO_CLI_DEBUG&&(console.log(ue("[compat:check] === scan stdout ===")),process.stdout.write(i),i.endsWith(`
|
|
1397
|
+
`)||process.stdout.write(`
|
|
1398
|
+
`),console.log(ue("[compat:check] === end stdout ==="))),i}catch(r){let i=r;process.env.DEVECO_CLI_DEBUG&&i.stdout&&(console.log(ue("[compat:check] === scan stdout (on error) ===")),process.stdout.write(i.stdout),i.stdout.endsWith(`
|
|
1399
|
+
`)||process.stdout.write(`
|
|
1400
|
+
`),console.log(ue("[compat:check] === end stdout ===")));let o=new Error(`Compatibility scan failed: ${i.message}`+(i.stderr?`
|
|
1401
|
+
${i.stderr}`:""));throw i.stdout&&(o.stdout=i.stdout),o}}function Ak(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 Dk(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.
|
|
1402
|
+
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 Tk(n,e,t,r,i){i==="none"&&(t==="json"?Ek(n,r):bk(n,r)),Sk(n,e)}function Rk(n,e){let t=$.dirname(n),r=$.basename(n),i=e.slice(1).map(o=>o.startsWith("--")?o:`"${o}"`).join(" ");m(ue(`[compat:check] command: cd "${t}" && node "${r}" ${i}`))}function kk(n){try{ok(n),m(ue(`[compat:check] cleaned up tmp report: "${n}"`))}catch(e){m(ue(`[compat:check] failed to clean up tmp report: ${e.message}`))}}var xk=[".csv",".json"];function Nk(n){return xk.includes(n.toLowerCase())}function Lk(n,e){if(!n)return{kind:"none"};let t=$.extname(n).toLowerCase();if(!Nk(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 Ok(n){if(n.kind==="file"){if(Ia(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(!Ia(e))throw new Error(`Target directory "${e}" does not exist. Create it first, or choose a different --output-path.`)}else if(n.kind==="dir"&&!Ia(n.dirPath))throw new Error(`Target directory "${n.dirPath}" does not exist. Create it first, or choose a different --output-path.`)}function Oy(n){return JSON.stringify({count:n.length,records:n},null,2)+`
|
|
1403
|
+
`}function Mk(n,e,t,r){r===".csv"?Ry(n,t):ky(t,Oy(e),"utf8"),m(ue(`[compat:check] saved report: "${t}"`))}function _k(n,e,t,r){if(r==="json"){let o=$.basename(n,".csv"),s=$.join(t,`${o}.json`);return ky(s,Oy(e),"utf8"),m(ue(`[compat:check] saved report: "${s}"`)),s}let i=$.join(t,$.basename(n));return Ry(n,i),m(ue(`[compat:check] saved report: "${i}"`)),i}async function Fk(n,e){let t=new Qe(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 jk(n,e){Ak(n,e);let t=U.discover(process.cwd());e.modules&&e.modules.length>0&&pk(t,e.modules),n.length>0&&fk(n);let r=await A.new(),{apiChangeDir:i,scriptPath:o}=r.getApiscanPaths();m(ue(`[compat:check] script: "${o}"`));let s=Ly(i);Dk(e,s),e.outputPath&&m(ue(`[compat:check] outputPath: "${e.outputPath}"`));let a=Lk(e.outputPath,e.format);return m(ue(`[compat:check] outputTarget: ${a.kind}`)),Ok(a),{project:t,scriptPath:o,target:a,toolProvider:r}}async function Hk(n,e){let{project:t,scriptPath:r,target:i,toolProvider:o}=await jk(n,e),s=ak({text:"Running compatibility check...",color:"cyan"}).start();try{await Fk(o,e);let a=Ck(r,n,t,e);Rk(r,a);let c=await Ik(o,a),l=vk(c,Ed.tmpdir());if(!l)throw new Error("Scanner output format unexpected: missing report path.");m(ue(`[compat:check] tmp csv: "${l}"`));let d=wk(l),h=null;if(i.kind==="file")Mk(l,d,i.filePath,i.ext),h=i.filePath;else if(i.kind==="dir")h=_k(l,d,i.dirPath,e.format);else if(i.kind!=="none")throw new Error(`Unexpected output target kind: ${i.kind}`);kk(l),s.stop(),Tk(d,h,e.format,e.limit,i.kind)}catch(a){throw s.fail("Compatibility check failed"),a}}var Pd=new nk("compat").description("Compatibility checking utilities.");Pd.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.',Ny,"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)",ck,100).action(async(n,e)=>{await Hk(n,e)});Pd.command("versions").description("List all available target SDK versions for compatibility checking").action(async()=>{let n=dk("csv");await uk(n)});var My=Pd;var _y=new $k("check").description("Run DevEco project checks").addCommand(Sd());b()||_y.addCommand(My);var Fy=_y;import{Command as AN}from"commander";import{green as Vd,red as DN}from"colorette";import qd from"fs";import Sw from"path";import TN from"json5";import{readFileSync as fx}from"fs";import{join as Uk}from"path";var K={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"},Te={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},pe={SUCCESS_MARKER:'"code":0',SQUARE_BRACKETS:"[]",OPENPROXY_BLOCKED_URL:"Openproxy_Blocked_URL_list",CERT_LIMIT_CODE:"205389872",USER_NOT_HARMONY_CODE:"205389904",DEVICE_EXCEEDS_LIMIT_CODE:"205389859",DEVICE_NAME_REPEAT_CODE:"205389857",PROVISION_EXCEEDS_LIMIT_CODE:"205389938",PROVISION_NAME_REPEAT_CODE:"205389830"},st={FORBIDDEN:403,UNAUTHORIZED:401},P={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."},q={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 Aa(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function Cd(n){let e=n.replace(Te.TEAM_ID_INVALID_CHARS,"");return`${Te.CERT_NAME_PREFIX}${e}.cer`}function Mr(n,e,t){if(n===st.FORBIDDEN)return e===pe.OPENPROXY_BLOCKED_URL?new Error(P.ERR_CERT_NETWORK_ERROR):new Error(P.ERR_FORBIDDEN);if(n===st.UNAUTHORIZED)return new Error(P.ERR_UNAUTHORIZED);if(t.includes(pe.USER_NOT_HARMONY_CODE))return new Error(P.ERR_USER_NOT_HARMONY);if(t.includes(pe.CERT_LIMIT_CODE))return new Error(P.ERR_CERT_LIMIT_REACHED);let r=Bk(t);return new Error(r??P.ERR_DOWNLOAD_CER)}function Bk(n){let e=jy(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?jy(t):t;if(r&&typeof r=="object"){let i=r.msg;if(typeof i=="string"&&i.trim()!=="")return i}return null}function jy(n){try{return JSON.parse(n)}catch{return null}}function Id(n){return JSON.parse(n)}async function Hy(n){let e=`${K.BASE_URL}${K.CERT_LIST_PATH}`,t=await N.postAllowFailure(e,{headers:Aa(n)});if(t.statusCode!==200)throw Mr(t.statusCode,t.statusText,t.data);return Id(t.data)?.certList??[]}async function Da(n,e){return(await Hy(n)).find(r=>r.certName===e)??null}async function Ad(n,e){let t=`${K.BASE_URL}${K.CERT_DELETE_PATH}`,r=await N.deleteAllowFailure(t,{headers:Aa(n),params:{certIds:[e]}});if(r.statusCode!==200)throw Mr(r.statusCode,r.statusText,r.data);return Id(r.data)?.ret?.code===0}async function Dd(n,e,t){let r=`${K.BASE_URL}${K.CERT_ADD_PATH}`,i={csr:e,certName:t,certType:Te.CERT_TYPE_DEBUG},o=await N.postAllowFailure(r,{headers:Aa(n),params:i});if(o.statusCode!==200)throw Mr(o.statusCode,o.statusText,o.data);if(!o.data.includes(pe.SUCCESS_MARKER))throw Mr(void 0,o.statusText,o.data)}async function Td(n,e){let t=`${K.BASE_URL}${K.CERT_DOWNLOAD_URL_PATH}`,r=await N.postAllowFailure(t,{headers:Aa(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw Mr(r.statusCode,r.statusText,r.data);return Id(r.data)?.urlsInfo?.[0]?.newUrl??null}import{mkdirSync as Wk,writeFileSync as zk,existsSync as Gk}from"fs";import{dirname as Vk}from"path";async function io(n,e){let{statusCode:t,statusText:r,buffer:i}=await N.getBinaryAllowFailure(n,{timeout:Te.DOWNLOAD_CONNECT_TIMEOUT_MS});if(t!==200)throw t===st.FORBIDDEN&&r===pe.OPENPROXY_BLOCKED_URL?new Error(P.ERR_CERT_NETWORK_ERROR):new Error(P.ERR_DOWNLOAD_CER);let o=Vk(e);Gk(o)||Wk(o,{recursive:!0}),zk(e,i)}import dx from"fs/promises";import{readFileSync as ux}from"fs";import Ta from"path";import By from"crypto";import qk from"os";import oo from"fs/promises";var Wy={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},$y=["ECC","RSA"],Uy=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],Yk={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},Jk=8,Rd=64,Kk=/[\\:*?"<>|=-]/g,at={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function Xk(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>Rd)throw new Error(`The length of keyAlias cannot exceed ${Rd}`);if(!$y.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${$y.join(" / ")}`);let e=Yk[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function Zk(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(!Uy.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${Uy.join(" / ")}`)}function Qk(n){return By.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function ex(n){let e=n?.trim()??"";return e&&e.replace(Kk,"_").slice(0,Rd)||at.productName}async function zy(){let n=await A.new(),e=n.javaPath;if(!e&&!b())throw new Error("Java runtime not found. DevEco Studio JBR is required to run hap-sign-tool.jar.");let t=n.sdkPath;f.info(`\u8BFB\u53D6SDK\u6839\u76EE\u5F55\uFF1A${t}`);let r=b()?"hap-sign-tool":"hap-sign-tool.jar",i=Ta.join(t,"default","openharmony","toolchains","lib",r);try{await oo.access(i)}catch(o){throw new Error(`${r} not found: ${i}`,{cause:o})}return{javaPath:e,toolPath:i}}async function tx(n){let{javaPath:e,toolPath:t}=await zy(),r=[Wy.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(" ")),b()?[t,...r]:[e,"-jar",t,...r]}async function nx(n){let{javaPath:e,toolPath:t}=await zy(),r=[Wy.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(" ")),b()?[t,...r]:[e,"-jar",t,...r]}async function rx(n){f.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),Xk(n);let e=await tx(n),t=await Jr(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 ix(n){f.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),Zk(n);let e=await nx(n),t=await Jr(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 ox(n=Jk){return By.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function sx(){let n=qk.homedir();try{await oo.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=Ta.join(n,b()?"Documents":"",".ohos","config");try{await oo.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 ye(n,e,t){let r=ex(n),i=Ta.basename(e),o=Qk(e),s=`${r}_${i}_${o}=.${t}`,a=await sx();return Ta.join(a,s)}function ax(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 cx(n){try{await oo.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function lx(n){try{await oo.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function kd(n,e,t){let r=process.cwd(),i=ax(r);await cx(i),f.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${i}`);let o=ox(),s=await ye(n??"",i,"p12"),a=await ye(n??"",i,"csr");return console.log("Start generating p12"),await rx({keyAlias:e?.keyAlias??at.keyAlias,keyPwd:o,keyAlg:e?.keyAlg??at.keyAlg,keySize:e?.keySize??at.keySize,keystoreFile:s,keystorePwd:o}),await lx(s),console.log("Start generating csr"),await ix({subject:t?.subject??at.csrSubject,outFile:a,keyAlias:t?.keyAlias??at.keyAlias,keyPwd:o,signAlg:t?.signAlg??at.signAlg,keystoreFile:s,keystorePwd:o}),{p12FilePath:s,csrFilePath:a,keyPwd:o,keyAlias:e?.keyAlias??at.keyAlias}}var px=["p12","cer","csr","p7b"];async function xd(n,e){for(let t of px){let r=await ye(n,e,t);await dx.rm(r,{force:!0})}}function Nd(n){let e;try{e=ux(n,"utf-8")}catch{throw new Error(P.ERR_CERT_INVALIDATE)}if(!Te.CERT_PATTERN.test(e))throw new Error(P.ERR_CERT_INVALIDATE)}async function Gy(n,e){return{certPath:await ye(n,e,"cer"),csrPath:await ye(n,e,"csr"),p12Path:await ye(n,e,"p12"),profilePath:await ye(n,e,"p7b")}}async function Ld(n,e){let t=e??"",r=U.discover(process.cwd()).rootDir;await xd(t,r);let i=Cd(n.teamId),o=await Da(n,i);if(o&&!await Ad(n,o.id))throw new Error(P.ERR_DOWNLOAD_CER);let s=await kd(e),a;try{a=fx(s.csrFilePath,"utf-8")}catch{throw new Error(P.ERR_READ_CSR)}console.log("Start generating certificate"),await Dd(n,a,i);let c=await Da(n,i);if(!c)throw new Error(P.ERR_DOWNLOAD_CER);let l=await Td(n,c.certObjectId);if(!l)throw new Error(P.ERR_DOWNLOAD_CER);let d=await ye(t,r,"cer");await io(l,d),Nd(d);let h=await ye(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 ja from"crypto";import hn from"fs";import*as sw from"path";import Mx from"json5";import{execa as rw}from"execa";import iw from"node-forge";import{createCipheriv as mx,createDecipheriv as hx,pbkdf2Sync as gx,randomBytes as Fd}from"crypto";import{promises as $n}from"fs";import{dirname as yx,join as ct}from"path";var Ra=3,so=16,wx=1e4,Vy="material",vx=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Ky="aes-128-gcm",Hn=12,ka=16,pn=4;function Od(n){return new Uint8Array(Fd(n))}function Sx(n){return Fd(n).toString("hex")}function bx(...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 qy(n,e,t=wx,r=so){let i=[...n,vx],o=bx(...i),s=Buffer.from(o).toString("utf8"),a=Buffer.from(s,"utf8"),c=gx(a,e,t,r,"sha256");return new Uint8Array(c)}function Yy(n,e){let t=Fd(Hn),r=mx(Ky,n,t),i=Buffer.concat([r.update(e),r.final()]),o=r.getAuthTag(),s=Buffer.concat([i,o]),a=s.length,c=Buffer.alloc(pn+Hn+s.length);return c.writeUInt32BE(a,0),t.copy(c,pn),s.copy(c,pn+Hn),c}function Jy(n,e){if(e.length<pn+Hn+ka)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(pn,pn+Hn),i=e.subarray(pn+Hn,pn+Hn+t);if(i.length<ka)throw new Error("Ciphertext too short for auth tag");let o=i.subarray(0,i.length-ka),s=i.subarray(i.length-ka),a=hx(Ky,n,r);return a.setAuthTag(s),Buffer.concat([a.update(o),a.final()])}async function Ex(n){try{await $n.rm(n,{recursive:!0,force:!0})}catch{}}async function Md(n){let e=await $n.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 $n.readFile(ct(n,t[0]))}async function _d(n,e){let t=Sx(so),r=ct(n,t);return await $n.writeFile(r,e),t}var fn=class{static async generateMaterial(e){let t=ct(e,Vy);await Ex(t);let r=ct(t,"ac"),i=ct(t,"ce");await $n.mkdir(r,{recursive:!0}),await $n.mkdir(i,{recursive:!0});for(let d=0;d<Ra;d++)await $n.mkdir(ct(t,"fd",String(d)),{recursive:!0});let o=Od(so),s=[];for(let d=0;d<Ra;d++)s.push(Od(so));let a=Od(so),c=qy(s,o),l=Yy(c,a);await _d(r,o),await _d(i,l);for(let d=0;d<Ra;d++){let h=ct(t,"fd",String(d));await _d(h,s[d])}return a}static async readMaterial(e){let t=ct(e,Vy),r=ct(t,"ac"),i=new Uint8Array(await Md(r)),o=[];for(let d=0;d<Ra;d++){let h=ct(t,"fd",String(d)),w=await Md(h);o.push(new Uint8Array(w))}let s=ct(t,"ce"),a=await Md(s),c=qy(o,i),l=Jy(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t=yx(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 Yy(r,i).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),i=Buffer.from(e,"hex");return Jy(r,i).toString("utf8")}};import tw from"fs";import _a from"path";import Tx from"json5";import*as xa from"fs";import*as Xy from"path";function Na(n){let e=Xy.resolve(n);if(!xa.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=xa.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 Fr from"fs";import*as Re from"path";import{debuglog as _r}from"util";var Zy={"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 Px(n){return Object.prototype.hasOwnProperty.call(Zy,n)}function La(n){if(Px(n))return Zy[n]}var Qy={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as Cx}from"url";var Ma=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 Oa(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function ew(n){return n==null||n.length===0}function Ix(n){return!ew(n)}function jd(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function Ax(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 Dx(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 mn=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=Re.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=Re.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=Re.join(t.sdkPath,"default","sdk-pkg.json"),a=Na(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=Re.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(Fr.existsSync(e))return Fr.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=Cx(e);if(t.includes("dist")){let s=Re.dirname(t),a=Re.dirname(s);return Re.join(a,"src","resources")}let r=Re.dirname(t),i=Re.dirname(r),o=Re.dirname(i);return Re.join(o,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{_r("read builtin acl permission failed.");return}if(r!==void 0)try{let i=JSON.parse(r),s=(Array.isArray(i)?i:Oa(i)?Object.values(i):[]).filter(Oa).map(a=>new Ma(a));s.forEach(a=>{let c=a.permissionInsteadName;Ix(c)&&(a.permissionInsteadName=La(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(i){_r(`failed to parse aclPermissionsInfo.json: ${i}`)}}static initAclPermissionFromSDK(e,t,r){let i=this.parsePermissionDefinitionFile(e);i&&i.forEach(o=>{if(!Oa(o))return;let s=o,a=jd(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(ew(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||jd(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||jd(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:Ax(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let i=new Ma;i.permissionName=t;let o=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;i.permissionDisplayName=o;let s=Dx(r,this.ACL_SINCE_KEY);i.minSupportApiLevel=String(s),this.handleInsteadName(i,o),e.add(i)}static parsePermissionDefinitionFile(e){let t=Re.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!Fr.existsSync(t))return;let r;try{r=Fr.readFileSync(t,"utf-8")}catch(s){_r(`failed to load permissionDefinitions.json: ${s}`);return}let i;try{let s=JSON.parse(r);if(!Oa(s)){_r("json object is null");return}i=s}catch(s){_r(`failed to parse permissionDefinitions.json: ${s}`);return}let o=i[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(o)){_r("definePermissions is not an array");return}return o}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=La(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=La(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function Fa(n,e){let t=new Set,r=new Set;mn.handleSpecificAclPermissions(),mn.initAclPermission(n,e);for(let i of n.profile.modules){let o=nw(i,n,e,r,_a.join("src","main"));for(let a of o)t.add(a);let s=nw(i,n,e,r,_a.join("src","ohosTest"));for(let a of s)t.add(a)}return Rx(r),t}function Rx(n){if(n.size>0)throw new Error(Qy.DUPLICATE_PERMISSION)}function nw(n,e,t,r,i){let o=xx(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 S=kx(w,"name");S&&s.push(S)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=_a.join(t.sdkPath,"default","sdk-pkg.json"),l=Na(c),d=mn.getAclPermissionInfos(e),h=new Set(Array.from(d).filter(w=>{let S=Number(w.minSupportApiLevel);return Number.isFinite(S)&&S<=l}).map(w=>w.permissionName));for(let w of Array.from(a))h.has(w)||a.delete(w);return a}function kx(n,e){let t=n[e];return typeof t=="string"?t:""}function xx(n,e,t){let r=_a.join(n,e.srcPath,t,"module.json5"),i=Nx(r);if(i==null)return null;let o=Lx(i,"module");return o==null?null:Ox(o,"requestPermissions")}function Nx(n){try{if(!tw.existsSync(n))return null;let e=tw.readFileSync(n,"utf-8");return Tx.parse(e)}catch{return null}}function Lx(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 Ox(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var $d=class{verifyStorePassword(e,t){try{let r=hn.readFileSync(e),i=iw.asn1.fromDer(r.toString("binary"));return iw.pkcs12.pkcs12FromAsn1(i,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=hn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(i=>this.formatFp(new ja.X509Certificate(i).fingerprint256));try{return[this.formatFp(new ja.X509Certificate(hn.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let i=hn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let o of i)try{let s=new ja.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 _x(n){let e=hn.readFileSync(n,"utf-8"),t=Fx(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let i=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:Hd(i["bundle-name"]),expiryDate:jx(r?.validity?.["not-after"]),cerFingerprintInProfile:Hx(Hd(i["development-certificate"])),deviceUdidsInProfile:$x(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:Ux(r?.acls?.["allowed-acls"]),teamIdInProfile:Hd(i["developer-id"])}}function Fx(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 jx(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function Hx(n){if(!n)return null;try{let t=new ja.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function $x(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 Hd(n){return typeof n=="string"?n:null}var ao=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([Bx(o,a),zx(t.hdcPath)]),d=null;if(ow(c).allExist)try{d=_x(c.profileFile)}catch{}return{force:r,teamId:i,productName:o,projectPath:a,materialPaths:c,bundleName:s.getBundleName(),deviceUdids:l,storePassword:await Wx(a,o,c.storeFile),localAclPermissions:[...Fa(s,t)].sort(),hapSignTool:new $d,profileInfo:d}}static#t(e){return e.force?(m("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:Fe({force:!0})}):null}static#n(e){let t=ow(e.materialPaths);return t.allExist?null:(m(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:Fe({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:Fe({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:Fe({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:Fe({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:Fe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=Vx(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:Fe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return qx(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(m("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:Fe({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:Fe({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:Fe({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:Fe({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:Fe({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:Fe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function Bx(n,e){let[t,r,i,o]=await Promise.all([ye(n,e,"p12"),ye(n,e,"csr"),ye(n,e,"cer"),ye(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:i,profileFile:o}}async function Wx(n,e,t){let r=sw.join(n,"build-profile.json5");if(!hn.existsSync(r))return;let i;try{i=Mx.parse(hn.readFileSync(r,"utf-8"))}catch{return}let a=(i?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await fn.decryptPassword(a,t)}catch{return}}async function zx(n){m(`Executing: ${n} list targets`);let{stdout:e}=await rw(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
|
|
1404
|
+
`)){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 rw(n,["-t",i,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),s=Gx(o);s&&r.push(s)}catch{m(`[reGenerateSign] Failed to get UDID for ${i}, skipping`)}return r}function Gx(n){let e=n.trim();if(!e)return null;let t=e.split(`
|
|
1405
|
+
`);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 ow(n){let e=[n.storeFile,n.csrFile,n.cerFile,n.profileFile],t=[];for(let r of e)hn.existsSync(r)||t.push(r);return{allExist:t.length===0,missing:t}}function Vx(n,e){let t=[];for(let r of e)n.includes(r)||t.push(r);return{allPresent:t.length===0,missing:t}}function qx(n,e){let t=[...n].sort(),r=[...e].sort();return t.length!==r.length?!1:t.every((i,o)=>i===r[o])}function Fe(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 Ud}from"util";import{execa as Bd}from"execa";async function cw(n,e){let t=await Ha(n);if(!t)throw new Error(P.DEVICE_LIST_EMPTY);let r=await Kx(e);if(t.length===0)for(let s of r)await Yx(n,s.udid,s.deviceName);else for(let s of r)await Jx(n,t,s.udid,s.deviceName);let o=(await Ha(n)).map(s=>s.id);if(o.length===0)throw new Error(P.DEVICE_LIST_EMPTY);return o}async function Yx(n,e,t){await uw(n,e,lw(t))}async function Jx(n,e,t,r){for(let i=0;i<e.length;i++){if(t===e[i].udid)return;if(i===e.length-1){await uw(n,t,lw(r));return}}}function lw(n){switch(n){case"liteWearable":return"1";case"wearable":return"2";case"tv":return"3";default:return"4"}}async function aw(n,e=1,t=100){let r=`${K.BASE_URL}${K.DEVICE_LIST_PATH}?encodeFlag=0&start=${e}&pageSize=${t}`,i=pw(n),o=await N.get(r,{headers:i});if(!o)throw Ud("query devices failed: response is null"),new Error(P.ERROR_WHILE_ADD_DEVICE);if(o.statusCode!==200)throw dw(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.list)throw Ud("query devices failed: response list is null"),new Error(s.ret?.msg||P.ERROR_WHILE_ADD_DEVICE);return{deviceList:s.list,total:s.totalCount||0}}function dw(n,e,t){return n===st.FORBIDDEN?e===pe.OPENPROXY_BLOCKED_URL?new Error(P.ERR_CERT_NETWORK_ERROR):new Error(P.ERR_FORBIDDEN):n===st.UNAUTHORIZED?new Error(P.ERR_UNAUTHORIZED):t.includes(pe.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(P.DEVICE_LIMIT_REACHED):new Error(P.ERROR_WHILE_ADD_DEVICE)}async function Ha(n){let t=await aw(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 aw(n,s,100);if(!a||!a.deviceList||a.deviceList.length===0)break;r.push(...a.deviceList)}return r}async function uw(n,e,t){let r=`${K.BASE_URL}${K.DEVICE_ADD_PATH}`,i=pw(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 Ud("add device failed: response is null"),new Error(P.ERROR_WHILE_ADD_DEVICE);if(a.statusCode!==200)throw dw(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(pe.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(P.DEVICE_LIMIT_REACHED):c.includes(pe.DEVICE_NAME_REPEAT_CODE)?new Error(P.DEVICE_NAME_REPEAT):new Error(P.ERROR_WHILE_ADD_DEVICE)}function pw(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}async function Kx(n){let{stdout:e}=await Bd(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
|
|
1406
|
+
`)){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 Xx(i,n),s=await Zx(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 Xx(n,e){let{stdout:t}=await Bd(e,["-t",n,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),r=t.trim();if(!r)return"";let i=r.split(`
|
|
1407
|
+
`);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 Zx(n,e){let{stdout:t}=await Bd(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return Qx(t)}function Qx(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 Un from"fs";import{createHash as eN}from"crypto";import{debuglog as Mt}from"util";import{Buffer as mw}from"buffer";import{createPublicKey as tN,X509Certificate as Wd}from"crypto";import{readFileSync as nN}from"fs";import Bn from"node-forge";async function hw(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(P.DEVICE_LIST_EMPTY);let d=`${K.BASE_URL}${K.PROVISION_ADD_TEST_PATH}`,h=rN(t,r),w=await oN(n,d,a||[],r,s,h,o||[]);if(!w||!w.profileInfo||!w.profileInfo.provisionFileUrl)throw Mt("add provision failed, the provision file url is null"),new Error(P.ADD_PROFILE_FAIL);let S=w.profileInfo,we=(await lN(n,S.provisionFileUrl)).urlList,Je=w.profileInfo.id;if(we&&we.length>0){let ke=await Gy(t,i),ht=ke.profilePath;if(!await dN(we,ht))throw await fw(n,Je),new Error(P.ERROR_WHILE_DOWNLOAD_PROFILE);if(await fw(n,Je),Un.existsSync(ke.certPath)&&Un.existsSync(ht)&&Un.existsSync(ke.p12Path)){let Pw=Un.readFileSync(ke.certPath,"utf8"),Cw=Un.readFileSync(ht,"utf8");return uN(Cw,Pw,ke.p12Path,c,l)||cN(ht),ht}}throw new Error(P.ADD_PROFILE_FAIL)}function rN(n,e){let t=n?`${n}_`:"";return`${iN(`${t}${e}_${e}`)}`}function iN(n){return eN("sha256").update(n).digest("hex").substring(0,16)}async function oN(n,e,t,r,i,o,s){sN(r);let a=Gd(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 Mt("add provision failed: response is null"),new Error(P.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw zd(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw Mt(`add provision fail: ${l.data}`),aN(l.data,o),new Error(d.ret?.msg||P.ADD_PROFILE_FAIL);let h=d.provisionFileUrl;return{profileInfo:{id:d.id,name:o,provisionFileUrl:h}}}function zd(n,e,t){return n===st.FORBIDDEN?e===pe.OPENPROXY_BLOCKED_URL?new Error(P.ERR_CERT_NETWORK_ERROR):new Error(P.ERR_FORBIDDEN):n===st.UNAUTHORIZED?new Error(P.ERR_UNAUTHORIZED):t.includes(pe.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(P.TEST_PROVISION_EXCEEDS_LIMIT):new Error(P.ADD_PROFILE_FAIL)}function sN(n){if(!n||n.trim().length===0)throw new Error(P.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!Te.BUNDLE_NAME_REGEX.test(n))throw new Error(P.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function aN(n,e){if(n.includes(pe.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(P.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(pe.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(P.PROFILE_NAME_REPEAT)}async function fw(n,e){if(!e||e.trim().length===0)return;let t=`${K.BASE_URL}${K.PROVISION_DELETE_PATH}?id=${e}`,r=await N.deleteAllowFailure(t,{headers:Gd(n)});if(r.statusCode!==200)throw zd(r.statusCode,r.statusText,r.data);let i=JSON.parse(r.data);(!i||!i.ret||i.ret.code!==0)&&Mt(`delete provision failed: ${r.data}`)}function cN(...n){for(let e of n)try{Un.existsSync(e)&&Un.unlinkSync(e)}catch(t){Mt(`delete local sign file error: ${t.message}`)}}async function lN(n,e){let t=`${K.BASE_URL}${K.CERT_DOWNLOAD_URL_PATH}`,r=Gd(n),i={sourceUrls:e},o=await N.postAllowFailure(t,{headers:r,params:i});if(!o)throw Mt("get download list failed: response is null"),new Error(P.ADD_PROFILE_FAIL);if(o.statusCode!==200)throw zd(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw Mt("download: The application does not exist"),new Error(s.ret?.msg||P.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function dN(n,e){if(!n||n.length===0)return!1;let t=n[0].newUrl;return await io(t,e),!0}function uN(n,e,t,r,i){return pN(n,e),r=r||Te.TARGET_FRIENDLY_NAME,i=i||"",fN(e,t,r,i),!0}function pN(n,e){if(e.lastIndexOf(Te.CERT_BEGIN_HEADER)<0)throw new Error(P.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(Te.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(P.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function fN(n,e,t,r){let i=n.matchAll(Te.CERTIFICATE_PATTERN_GLOBAL),o=[],s=new Date;for(let c of i)try{let l=c[0],d=mN(l),h=new Date(d.validFrom),w=new Date(d.validTo);if(s<h||s>w){let S=`Certificate is not valid, Valid from ${h} to ${w}`;throw console.warn(`checkCertificateInValidityPeriod: ${S}`),new Error(P.CERTIFICATE_HAS_EXPIRED)}o.push(d)}catch(l){throw console.warn(`checkCertificateInValidityPeriod\uFF1A ${l.message}`),new Error(P.CERTIFICATE_HAS_EXPIRED,{cause:l})}if(!o||o.length===0)throw new Error(P.CERTIFICATE_HAS_EXPIRED);if(!gN(e,t,r,o))throw new Error(P.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function mN(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new Wd(t);let r=mw.from(t,"base64");return new Wd(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function hN(n){if(n.cert){let e=Bn.pki.publicKeyToPem(n.cert.publicKey);return tN(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=Bn.asn1.toDer(n.asn1).getBytes(),t=mw.from(e,"binary");return new Wd(t).publicKey.export({type:"spki",format:"der"})}catch(e){return Mt(`Failed to parse cert from asn1: ${e}`),null}return null}function gN(n,e,t,r){try{let i=nN(n),o=Bn.asn1.fromDer(Bn.util.createBuffer(i)),c=Bn.pkcs12.pkcs12FromAsn1(o,t).getBags({bagType:Bn.pki.oids.certBag})[Bn.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let h=hN(l);if(!h)continue;if(r.some(S=>{let k=S.publicKey.export({type:"spki",format:"der"});return h.equals(k)}))return!0}return!1}catch(i){let o=i instanceof Error?i.message:String(i);return Mt(`Failed to process P12 file: ${n}, error: ${o}`),!1}}function Gd(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var yw="https://developer.huawei.com",yN={"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"},wN="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function vN(n){let e=yN[n];return e?`${yw}${e}`:void 0}function SN(){return`${yw}${wN}`}var bN={"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 gw(n,e){return(bN[n]??n).replace(/\{(\d+)\}/g,(r,i)=>String(e[Number(i)]??""))}function EN(n){return Array.from(n).join(", ")}function ww(n,e){if(n.size===0)return;let t=mn.getAclPermissionInfos(e),r=new Set;for(let h of t)n.has(h.permissionName)&&r.add(h);for(let h of r){let w=vN(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=SN(),a=gw("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=o.size>0?Array.from(o).join(", ")+".":"",d=gw("acl.permissions.warn",[EN(i),l,c]);console.log(d)}var $a=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(q.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:q.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import PN from"fs";import vw from"path";var Ua=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(q.JAVA_PLATFORM_UNSUPPORTED)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=b()?"hap-sign-tool":"hap-sign-tool.jar",i=vw.join(t,"default","openharmony","toolchains","lib",r);if(!PN.existsSync(i)){let o=vw.join("sdk","default","openharmony","toolchains","lib",r);return e(`${r} not found.Check whether ${o} exists.`)}return{passed:!0,message:""}}};var Ba=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await re.getUserInfo()}catch(e){return m(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await re.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(q.LOGIN_REQUIRED)}catch(t){return m(`[EnvCheck] Login check failed: ${t.message}`),e(q.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(q.TEAM_INFO_FAILED);try{if((await zt()).teamList.length>0)return{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Team API error: ${r.message}`),e(q.TEAM_INFO_FAILED)}return m("[EnvCheck] No teams found for current user"),e(q.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(q.REALNAME_REQUIRED):t.isRealName!==!0?(m("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(q.REALNAME_REQUIRED)):{passed:!0,message:""}:e(q.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let i=await zt();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(q.REGION_CHINA_ONLY):{passed:!0,message:""}:(m("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(q.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function CN(n){try{let{teamList:e}=await zt();if(e.length>0)return e[0].id}catch(e){m(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function IN(n){let e=await re.getUserInfo(),t=await re.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await CN(e.userId);if(!r)throw new Error("No team found");let i={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await Ha(i)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var Wa=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t){try{let r=await IN(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 Z.from(this.toolProvider).listDevices();return o.length===0?(m("[EnvCheck] Scenario 4 Device check: no local devices found"),e(q.DEVICE_MISSING)):o.some(a=>Cn(a.serial))?{passed:!0,message:""}:(m("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(q.DEVICE_MISSING))}catch(r){return m(`[EnvCheck] Scenario 4 Device check failed: ${r.message}`),e(q.DEVICE_DETECT_FAILED)}}};var za=class{projectChecker=new $a;toolchainChecker=null;authChecker=new Ba;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 A.new();return this.toolchainChecker=new Ua(e),this.deviceChecker=new Wa(e),!0}catch(e){throw m(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(q.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 RN(n){if(qd.existsSync(n)){let e=qd.readFileSync(n,"utf-8");return TN.parse(e)}return{app:{signingConfigs:[],products:[]}}}function kN(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function xN(n){if(n.keyPwd===n.storePassword){let r=await fn.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await fn.encryptedPassword(n.keyPwd,n.p12FilePath),t=await fn.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function NN(n,e,t){let r=Sw.join(n,"build-profile.json5"),i=RN(r);kN(i);let o=t??"default",{keyPassword:s,storePassword:a}=await xN(e),c={name:o,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:at.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}),qd.writeFileSync(r,JSON.stringify(i,null,2),"utf-8")}async function LN(n){let e=await re.getUserInfo(),t=await re.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 ON(n){let e=n.product||"default";await new za().preflight({productName:e,teamId:n.teamId}),console.log("Executing signature generate command");let r=await LN(n),i=await A.new(),{shouldRegenerate:o}=await ao.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product},i);if(!o){console.log(Vd("Signature generation completed successfully."));return}await MN(n,r,i),console.log(Vd("Signature generation completed successfully."))}async function MN(n,e,t){let r=await Ld(e,n.product),i=_N(n,e,r,t);i.allDeviceIds=await cw(e,t.hdcPath),await hw(e,i);let o=U.discover(process.cwd()).rootDir;await NN(o,r,n.product??"default"),console.log(Vd(`Signing config written to ${Sw.join(o,"build-profile.json5")}`))}function _N(n,e,t,r){let i=process.cwd(),o=U.discover(i),s=Fa(o,r);return ww(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 bw=new AN("signature").description("Generate application signature.");bw.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 ON(n)}catch(e){console.error(DN(e.message)),process.exit(1)}});var Ew=bw;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";FN();ne.name("devecocli").description("HarmonyOS application development command line tool").version("0.3.0-TD.1.1");ne.addCommand(Lu);ne.addCommand(Qu);ne.addCommand(rp);ne.addCommand(gp);ne.addCommand(uf);ne.addCommand(_f);ne.addCommand($f);ne.addCommand(Kf);ne.addCommand(im);ne.addCommand(Cm);ne.addCommand(Mg);ne.addCommand(Ew);ne.addCommand(Fy);b()||(ne.addCommand(Wp),ne.addCommand(oy));var Yd=process.argv.slice(2);Yd.length>=2&&Yd[Yd.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var HN=new Set(["update","auth"]);ne.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==ne;)t=t.parent;HN.has(t.name())||await A.checkVersion()});ne.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(jN(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
|