@deveco-test/hmos-deveco-cli 0.1.0-TD.5.2 → 0.2.0
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/SKILL.md +11 -15
- package/dist/cli.js +73 -79
- package/index.zip +0 -0
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,66 +1,60 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{bootstrap as
|
|
2
|
+
import{bootstrap as Ow}from"global-agent";import{program as te}from"commander";import{red as Nw}from"colorette";import{Command as Nu}from"commander";import{green as Ls,red as Mo,yellow as _s}from"colorette";import j from"fs";import*as q from"path";import Re from"json5";import*as Do from"fs";import*as $ from"path";function g(n){process.env.DEVECO_CLI_DEBUG&&console.log(`[DEBUG] ${n}`)}var P=class n{static ASCII_CONTROL_MAX=31;static ASCII_DELETE=127;static parsePositiveInteger(e,t="value"){let r=e.trim();if(!/^\d+$/.test(r))throw new Error(`${t} must be a positive integer`);let o=Number.parseInt(r,10);if(!Number.isInteger(o)||o<=0)throw new Error(`${t} must be a positive integer`);return o}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
|
|
3
3
|
`)}static parseDurationToSeconds(e,t="value"){let o=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!o)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported).`);let i=o[1];if((o[2]??"s")==="s")return n.parsePositiveInteger(i,t);if(!/^\d+(?:\.\d)?$/.test(i))throw new Error(`${t} supports a maximum of 1 decimal place for minutes (e.g. 2.5m).`);let a=Number.parseFloat(i);if(!Number.isFinite(a)||a<=0)throw new Error(`${t} must be a positive duration.`);return Math.round(a*60)}static assertRelativeTimeRange(e,t){if(e!==void 0&&t!==void 0&&e<t)throw new Error("--from must be greater than or equal to --to when both are provided (e.g. --from 30s --to 10s)")}static filterLogsByRelativeWindow(e,t,r,o=new Date){if(!t&&!r)return e;let[i,s]=n.resolveTimeBounds(t,r,o),a=e.split(/\r?\n/),c=[],l=!1;for(let u of a){let h=n.extractTimestampFromLogLine(u,o);h&&(l=n.isWithinBounds(h,i,s)),l&&c.push(u)}return c.join(`
|
|
4
|
-
`)}static resolveTimeBounds(e,t,r){let o=e?new Date(r.getTime()-e*1e3):null,i=t?new Date(r.getTime()-t*1e3):null;return o&&i?o<i?[o,i]:[i,o]:o?[o,r]:i?[null,i]:[null,null]}static isWithinBounds(e,t,r){let o=e.getTime(),i=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(i!==null&&o<i||s!==null&&o>s)}static extractTimestampFromLogLine(e,t){let r=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!r)return null;let o=t.getFullYear(),i=Number.parseInt(r[1],10)-1,s=Number.parseInt(r[2],10),a=Number.parseInt(r[3],10),c=Number.parseInt(r[4],10),l=Number.parseInt(r[5],10),u=r[6]??"0",h=Number.parseInt(u.padEnd(3,"0").slice(0,3),10),v=new Date(o,i,s,a,c,l,h);return v.getTime()>t.getTime()+1440*60*1e3&&v.setFullYear(o-1),v}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(r=>{let o=r.charCodeAt(0);return o<=n.ASCII_CONTROL_MAX||o===n.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let r=`'${e.replace(/'/g,"'\\''")}'`;return g(`quotePosixShellArg: ${e} -> ${r}`),r}static assertCrashFilename(e){if(!/^\w+-.+\d+-\d+$/.test(e))throw new Error(`Invalid crash log filename: ${JSON.stringify(e)}`)}static assertHilogLevel(e){if(!/^[DIWEF]$/.test(e))throw new Error(`Invalid log level: ${e}`)}static resolvePathWithinRoot(e,t){if($.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=$.resolve($.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=$.normalize(e),o=$.relative(r,t);if(o.split($.sep)[0]===".."||$.isAbsolute(o))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||$.isAbsolute(e)}static isPathContained(e,t){let r=$.resolve(t,e),o=$.relative(t,r);return n.isPathEscaping(o)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){if($.isAbsolute(e))return{contained:!1,reason:`Absolute path is not allowed: ${e}`};let r=n.isPathContained(e,t);if(!r.contained)return r;let o;try{o=Eo.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let i=$.resolve(o,e),s;try{s=Eo.realpathSync(i)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${i}`}}return n.isPathContained(s,o)}};var Ze=class n{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let r=n.tryLoadProjectProfile(t);if(r)return new n(t,r);let o=q.dirname(t);if(o===t)break;t=o}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=q.join(e,"build-profile.json5");if(!j.existsSync(t))return null;try{let r=j.readFileSync(t,"utf-8"),o=Re.parse(r);return o.app?o:null}catch(r){return console.error(`Error parsing ${t}:`,r),null}}getModuleType(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=P.resolvePathWithinRoot(this.rootDir,t.srcPath),o=q.join(r,"src","main","module.json5");if(!j.existsSync(o))return"entry";try{let i=j.readFileSync(o,"utf-8");return Re.parse(i)?.module?.type||"entry"}catch(i){return console.warn(`Warning: Failed to parse ${o}:`,i),"entry"}}getModuleProfile(e){let t=this.profile.modules.find(a=>a.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=P.resolvePathWithinRoot(this.rootDir,t.srcPath),o=q.join(r,"build-profile.json5");if(!j.existsSync(o))throw new Error(`Build profile for module '${e}' not found at ${o}.`);let i=j.readFileSync(o,"utf-8");return Re.parse(i)}getBundleName(){let e=q.join(this.rootDir,"AppScope","app.json5");if(j.existsSync(e))try{let t=j.readFileSync(e,"utf-8"),r=Re.parse(t);if(r?.app?.bundleName)return r.app.bundleName}catch(t){console.warn(`Warning: Failed to parse ${e}:`,t)}throw new Error("Could not find bundleName in AppScope/app.json5.")}getMainAbility(e,t){if(t)return t;let r=this.profile.modules.find(s=>s.name===e);if(!r)return"EntryAbility";let o=P.resolvePathWithinRoot(this.rootDir,r.srcPath),i=q.join(o,"src","main","module.json5");if(!j.existsSync(i))return"EntryAbility";try{let s=j.readFileSync(i,"utf-8"),c=Re.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let l=c.find(u=>u.name==="EntryAbility");return l?l.name:c[0].name}catch(s){return console.warn(`Warning: Failed to parse ${i}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new Error(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`);if(!this.profile.app.products?.some(r=>r.name===e)){let r=this.profile.app.products?.map(o=>o.name).join(", ")||"none";throw new Error(`Product '${e}' not found in project configuration. Available products: ${r}`)}}getModuleDependencies(e){let t=this.profile.modules.find(s=>s.name===e);if(!t)return[];let r=P.resolvePathWithinRoot(this.rootDir,t.srcPath),o=q.join(r,"oh-package.json5");if(!j.existsSync(o))return[];let i=[];try{let s=j.readFileSync(o,"utf-8"),c=Re.parse(s)?.dependencies||{};for(let l of Object.values(c)){if(typeof l!="string")continue;let u=l;if(!(u.startsWith("file:")||u.startsWith(".")||u.startsWith("..")))continue;u.startsWith("file:")&&(u=u.substring(5));let v=q.join(t.srcPath,u),D=P.resolvePathWithinRoot(this.rootDir,v),k=this.profile.modules.find(ee=>q.resolve(this.rootDir,ee.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(ee=>ee.name===e);if(!i)throw new Error(`Module '${e}' not found`);let a=this.getModuleType(e)==="shared",c=a?"hspName":"hapName",l=this.buildOutputPath(i.srcPath,o,["intermediates",a?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!j.existsSync(l))throw new Error(`Build metadata not found for module '${e}' at ${l}. Build the project first.`);let{packageName:u,isSigned:h}=this.parseOutputMetadata(l,c),v=u;if(!h){let ee=this.getSignedHapName(u,i.srcPath,o,t);ee&&(v=ee)}let 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 To}from"child_process";import M,{existsSync as As}from"fs";import*as E from"path";import*as W from"os";import Du from"regedit";import{join as Ts}from"path";import{red as Iu}from"colorette";import*as Ss from"os";function I(){return Do()==="openharmony"}function Do(){return Ss.platform()}var Io={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 Oe}from"os";import be from"path";import{xdgConfig as Eu}from"xdg-basedir";var B={"trae-cn":be.join(Oe(),".trae-cn"),opencode:be.join(Eu,"opencode"),cursor:be.join(Oe(),".cursor"),codebuddy:be.join(Oe(),".codebuddy"),qoder:be.join(Oe(),".qoder"),"claude-code":be.join(Oe(),".claude"),codex:be.join(Oe(),".codex"),bitfun:be.join(Oe(),".bitfun"),opendesk:be.join(Oe(),".opendesk")};import Ne from"path";var Co="https://matrix.openharmony.cn",ce={TAGS_API_URL:`${Co}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${Co}/api/registry/skill/skills`,SKILL_API_BASE:`${Co}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},Ps={"trae-cn":{path:Ne.join(B["trae-cn"],"skills"),displayName:"trae-cn"},opencode:{path:Ne.join(B.opencode,"skills"),displayName:"opencode"},cursor:{path:Ne.join(B.cursor,"skills"),displayName:"cursor"},codebuddy:{path:Ne.join(B.codebuddy,"skills"),displayName:"codebuddy"},qoder:{path:Ne.join(B.qoder,"skills"),displayName:"qoder"},"claude-code":{path:Ne.join(B["claude-code"],"skills"),projectPath:".claude/skills",displayName:"claude-code"},codex:{path:Ne.join(B.codex,"skills"),displayName:"codex"}},Es={opencode:{path:Ne.join(B.opencode,"skills"),displayName:"opencode"}};function Se(){return I()?Es:Ps}import{homedir as Ut}from"os";import re from"path";var fe="deveco-mcp";var Le={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(Ut(),"AppData","Roaming"),"Trae CN","User"):re.join(Ut(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:re.join(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(Ut(),"AppData","Roaming"),"Qoder","SharedClientCache"):re.join(Ut(),"Library","Application Support","Qoder","SharedClientCache"),"mcp.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"standard"},"claude-code":{name:"claude-code",displayName:"Claude Code",supportsGlobal:!0,globalConfigPath:re.join(Ut(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:re.join(B.codex,"config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function Is(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function Ds(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Cs(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function jn(n,e){return n.format==="opencode"?Is(e):n.format==="claude-code"||n.format==="codex"?Ds(e):Cs(e)}var le={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var Ao="https://developer.huawei.com/consumer/cn/download/";var xs="6.1.0",Cu=["sdk","default","openharmony","native","llvm","bin","clangd"],Fn=n=>new Promise((e,t)=>{Du.list(n,(r,o)=>{r?t(r):e(o)})}),_=class n{_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;_emulatorLauncherPath;_clangdPath;_lspServerPath;static _verifiedPaths=new Set;static _powerShellPath;static verifyAndCache(e){!e||e===""||I()||n._verifiedPaths.has(e)||(n.verifySignature(e),n._verifiedPaths.add(e))}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return n.verifyAndCache(this._nodePath),this._nodePath}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get javaPath(){return n.verifyAndCache(this._javaPath),this._javaPath}get sdkPath(){return this._sdkPath}get hdcPath(){return n.verifyAndCache(this._hdcPath),this._hdcPath}get emulatorPath(){return n.verifyAndCache(this._emulatorPath),this._emulatorPath}get emulatorLauncherPath(){return this._emulatorLauncherPath&&n.verifyAndCache(this._emulatorLauncherPath),this._emulatorLauncherPath}get clangdPath(){return n.verifyAndCache(this._clangdPath),this._clangdPath}get lspServerPath(){return n.verifyAndCache(this._lspServerPath),this._lspServerPath}constructor(e,t,r,o,i,s,a,c,l,u,h){this._devecoStudioPath=e,this._nodePath=t,this._ohpmJsPath=r,this._hvigorJsPath=o,this._javaPath=i,this._sdkPath=s,this._hdcPath=a,this._emulatorPath=c,this._emulatorLauncherPath=l,this._clangdPath=u,this._lspServerPath=h}static enforceStudioMinVersion(e){let t=n.parseProductInfoVersion(e);if(t===void 0)throw new Error(`Failed to determine DevEco Studio version at ${e}`);n.assertMinVersion(e,t)}static async checkVersion(){if(I())return;let e=await n.findDevEcoStudio();n.enforceStudioMinVersion(e)}static async new(e){if(I())return n.newForOpenHarmony();let t=e??await n.findDevEcoStudio(),{nodePath:r,ohpmJsPath:o,hvigorJsPath:i,javaPath:s,sdkPath:a,hdcPath:c,emulatorPath:l,clangdPath:u,lspServerPath:h}=n.resolveTools(t),v=n.getEmulatorExe(t);return new n(t,r,o,i,s,a,c,l,v??void 0,u,h)}static async newForOpenHarmony(){let e=process.env.COMMAND_LINE_TOOL_PATH;if(!e)throw new Error("COMMAND_LINE_TOOL_PATH environment variable is not set. ");let t=E.join(e,"node","bin","node"),r=E.join(e,"ohpm","bin","pm-cli.js"),o=E.join(e,"hvigor","bin","hvigorw.js");n.verifyTools(t,r,o);let i=E.join(e,"sdk"),s=E.join(e,"clangd","clangd"),a=E.join(e,"ace-server","out","index.js");if(!M.existsSync(s))throw new Error(`clangd not found at: ${s}`);if(!M.existsSync(a))throw new Error(`ace-server not found at: ${a}`);let c=n.resolveHdcPath(i,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(M.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,...Cu);t.add(W.platform()==="win32"?i+".exe":i)}return[...t]}static resolveClangdPath(e){let t=n.clangdCandidatesFromDevecoHome(e);for(let r of t)if(M.existsSync(r))return r;throw new Error(`clangd executable not found. Searched in:
|
|
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
5
|
${t.join(`
|
|
6
|
-
`)}`)}static _cachedInstallRoot;static async findDevEcoStudio(){if(n._cachedInstallRoot!==void 0)return g(`[ToolProvider] findDevEcoStudio: cache hit -> ${n._cachedInstallRoot}`),n._cachedInstallRoot;let e=W.platform(),t=e==="win32"?await n.collectCandidatesWindows():e==="darwin"?n.collectCandidatesMac():(()=>{throw new Error("Linux is not fully supported yet for automatic DevEco Studio detection.")})();return n._cachedInstallRoot=n.pickLatestByProductInfo(t),n._cachedInstallRoot}static async collectCandidatesWindows(){let e=new Set,t=[],r=(o,i)=>{if(!n.isExistingDirectory(o))return;let s=E.normalize(o).toLowerCase();e.has(s)||(e.add(s),t.push(o),g(`[ToolProvider] Found via ${i}: ${o}`))};if(await n.addFromUninstallKey(r),await n.addFromHuaweiStudioKeys(r),n.addFromDefaultWindowsPath(r),t.length===0)throw new Error("DevEco Studio installation not found in registry or default locations.");return t}static UNINSTALL_REGISTRY_PARENTS=["HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall","HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"];static HUAWEI_STUDIO_REGISTRY_KEYS=["HKLM\\SOFTWARE\\Huawei\\DevEco Studio","HKLM\\SOFTWARE\\WOW6432Node\\Huawei\\DevEco Studio"];static isDevEcoStudioUninstallSubkey(e){return e.normalize("NFKC").trim().toLowerCase().startsWith("deveco studio")}static async addFromUninstallKey(e){for(let t of n.UNINSTALL_REGISTRY_PARENTS)try{let i=((await Fn([t]))[t]?.keys??[]).filter(n.isDevEcoStudioUninstallSubkey);if(i.length===0)continue;let s=i.map(c=>`${t}\\${c}`),a=await Fn(s);for(let c of s){let l=a[c]?.values?.InstallLocation?.value;e(l,`Uninstall registry key (${c})`)}}catch{}}static async addFromHuaweiStudioRegistryKey(e,t,r){try{let i=(await Fn([t]))[t]?.keys??[];if(i.length===0)return;let s=i.map(c=>`${t}\\${c}`),a=await Fn(s);for(let c of s){let l=a[c]?.values?.[""]?.value;e(l,`${r} subkey ${c}`)}}catch{}}static async addFromHuaweiStudioKeys(e){for(let t of n.HUAWEI_STUDIO_REGISTRY_KEYS){let r=t.includes("WOW6432Node")?"Huawei DevEco Studio (WOW6432Node)":"Huawei DevEco Studio";await n.addFromHuaweiStudioRegistryKey(e,t,r)}}static addFromDefaultWindowsPath(e){let t=E.join("C:","Program Files","Huawei","DevEco Studio");e(t,"default installation path")}static collectCandidatesMac(){let e=W.homedir(),t=[E.join(e,"Applications"),"/Applications"],r=[],o=new Set;for(let i of t){if(!
|
|
6
|
+
`)}`)}static _cachedInstallRoot;static async findDevEcoStudio(){if(n._cachedInstallRoot!==void 0)return g(`[ToolProvider] findDevEcoStudio: cache hit -> ${n._cachedInstallRoot}`),n._cachedInstallRoot;let e=W.platform(),t=e==="win32"?await n.collectCandidatesWindows():e==="darwin"?n.collectCandidatesMac():(()=>{throw new Error("Linux is not fully supported yet for automatic DevEco Studio detection.")})();return n._cachedInstallRoot=n.pickLatestByProductInfo(t),n._cachedInstallRoot}static async collectCandidatesWindows(){let e=new Set,t=[],r=(o,i)=>{if(!n.isExistingDirectory(o))return;let s=E.normalize(o).toLowerCase();e.has(s)||(e.add(s),t.push(o),g(`[ToolProvider] Found via ${i}: ${o}`))};if(await n.addFromUninstallKey(r),await n.addFromHuaweiStudioKeys(r),n.addFromDefaultWindowsPath(r),t.length===0)throw new Error("DevEco Studio installation not found in registry or default locations.");return t}static UNINSTALL_REGISTRY_PARENTS=["HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall","HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"];static HUAWEI_STUDIO_REGISTRY_KEYS=["HKLM\\SOFTWARE\\Huawei\\DevEco Studio","HKLM\\SOFTWARE\\WOW6432Node\\Huawei\\DevEco Studio"];static isDevEcoStudioUninstallSubkey(e){return e.normalize("NFKC").trim().toLowerCase().startsWith("deveco studio")}static async addFromUninstallKey(e){for(let t of n.UNINSTALL_REGISTRY_PARENTS)try{let i=((await Fn([t]))[t]?.keys??[]).filter(n.isDevEcoStudioUninstallSubkey);if(i.length===0)continue;let s=i.map(c=>`${t}\\${c}`),a=await Fn(s);for(let c of s){let l=a[c]?.values?.InstallLocation?.value;e(l,`Uninstall registry key (${c})`)}}catch{}}static async addFromHuaweiStudioRegistryKey(e,t,r){try{let i=(await Fn([t]))[t]?.keys??[];if(i.length===0)return;let s=i.map(c=>`${t}\\${c}`),a=await Fn(s);for(let c of s){let l=a[c]?.values?.[""]?.value;e(l,`${r} subkey ${c}`)}}catch{}}static async addFromHuaweiStudioKeys(e){for(let t of n.HUAWEI_STUDIO_REGISTRY_KEYS){let r=t.includes("WOW6432Node")?"Huawei DevEco Studio (WOW6432Node)":"Huawei DevEco Studio";await n.addFromHuaweiStudioRegistryKey(e,t,r)}}static addFromDefaultWindowsPath(e){let t=E.join("C:","Program Files","Huawei","DevEco Studio");e(t,"default installation path")}static collectCandidatesMac(){let e=W.homedir(),t=[E.join(e,"Applications"),"/Applications"],r=[],o=new Set;for(let i of t){if(!R.existsSync(i))continue;let s;try{s=R.readdirSync(i)}catch{continue}for(let a of s){if(!a.endsWith(".app")||!a.toLowerCase().includes("deveco"))continue;let l=E.join(i,a);n.isExistingDirectory(l)&&(o.has(l)||(o.add(l),r.push(l),g(`[ToolProvider] Found macOS candidate: ${l}`)))}}if(r.length===0)throw new Error("DevEco Studio not found in /Applications or ~/Applications.");return r}static productInfoPath(e){return W.platform()==="darwin"?E.join(e,"Contents","product-info.json"):E.join(e,"product-info.json")}static macInfoPlistPath(e){return E.join(e,"Contents","Info.plist")}static readMacInfoPlistKey(e,t){if(!R.existsSync(e)){g(`[ToolProvider] Info.plist not found at: ${e}`);return}try{let r=xo("defaults",["read",e,t],{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:5e3}).trim();if(r.length>0&&r!=="(null)")return r}catch{g(`[ToolProvider] defaults read failed for ${e} key ${t}`)}}static extractCompactBuildCode(e){let t=e.split(".").at(-1);if(t!==void 0&&/^\d+$/.test(t))return t}static compactPrefixFromShortVersion(e){let t=e.split(".").slice(0,3);if(!(t.length<3||!t.every(r=>/^\d+$/.test(r))))return t.join("")}static extractFourthSegmentMatchingShortVersion(e,t){let r=n.compactPrefixFromShortVersion(e),o=n.extractCompactBuildCode(t);if(r===void 0||o===void 0)return;if(!o.startsWith(r)){g(`[ToolProvider] CFBundleVersion suffix ${o} does not match short-version prefix ${r} (${e})`);return}let i=o.slice(r.length);if(!(i.length===0||!/^\d+$/.test(i)))return i}static readMacFourthSegmentFromPlist(e,t){let r=n.readMacInfoPlistKey(e,"CFBundleVersion");if(r!==void 0){let s=n.extractFourthSegmentMatchingShortVersion(t,r);if(s!==void 0)return s}let o=n.readMacInfoPlistKey(e,"CFBundleGetInfoString");if(o===void 0)return;let i=o.match(/DS-[\d.]+/);if(i!==null)return n.extractFourthSegmentMatchingShortVersion(t,i[0])}static parseMacInfoPlistVersion(e){let t=n.macInfoPlistPath(e),r=n.readMacInfoPlistKey(t,"CFBundleShortVersionString");if(r!==void 0){let o=n.readMacFourthSegmentFromPlist(t,r);return o!==void 0?`${r}.${o}`:r}return n.readMacInfoPlistKey(t,"CFBundleVersion")}static parseProductInfoVersion(e){if(W.platform()==="darwin"){let r=n.parseMacInfoPlistVersion(e);if(r!==void 0)return r}let t=n.productInfoPath(e);if(!R.existsSync(t)){g(`[ToolProvider] product-info.json not found at: ${t}`);return}try{let o=JSON.parse(R.readFileSync(t,"utf-8"))?.version;if(typeof o!="string"||o.trim()===""){g(`[ToolProvider] product-info.json at ${t} has no valid "version" field`);return}return o.trim()}catch{g(`[ToolProvider] Failed to parse product-info.json at: ${t}`);return}}static compareVersion(e,t){let r=e.split(".").map(s=>parseInt(s,10)||0),o=t.split(".").map(s=>parseInt(s,10)||0),i=Math.max(r.length,o.length);for(let s=0;s<i;s++){let a=(r[s]??0)-(o[s]??0);if(a!==0)return a}return 0}static pickLatestByProductInfo(e){let t=n.selectHighestVersion(e);return g(`[ToolProvider] Selected DevEco Studio ${t.version} at ${t.installRoot}`),t.installRoot}static selectHighestVersion(e){let t=[];for(let r of e){let o=n.parseProductInfoVersion(r);o!==void 0?(t.push({installRoot:r,version:o}),g(`[ToolProvider] ${r} => version ${o}`)):g(`[ToolProvider] Skipping ${r}: could not read version (Info.plist / product-info.json).`)}if(t.length===0){let r=e.join(`
|
|
7
7
|
`),o=W.platform()==="darwin"?"Contents/Info.plist (CFBundleShortVersionString / CFBundleVersion) and Contents/product-info.json":"product-info.json";throw new Error(`Failed to determine DevEco Studio version from ${o}.
|
|
8
8
|
Searched locations:
|
|
9
9
|
${r}
|
|
10
10
|
Please reinstall DevEco Studio or download the latest version from:
|
|
11
|
-
`+
|
|
12
|
-
`+
|
|
11
|
+
`+To)}return t.reduce((r,o)=>n.compareVersion(o.version,r.version)>0?o:r)}static assertMinVersion(e,t){n.compareVersion(t,Rs)>=0||(g(`[ToolProvider] Selected DevEco Studio ${t} at ${e} \u2014 below minimum`),console.error(Su(`Error: The detected DevEco Studio version is ${t}, which is below the minimum required version ${Rs}. Upgrade to the latest version before using deveco-cli:`)+`
|
|
12
|
+
`+To),process.exit(1))}static isExistingDirectory(e){return!!e&&R.existsSync(e)&&R.statSync(e).isDirectory()}static resolveWindowsTools(e){let t=E.join(e,"tools");return{nodePath:E.join(t,"node","node.exe"),ohpmJsPath:E.join(t,"ohpm","bin","pm-cli.js"),hvigorJsPath:E.join(t,"hvigor","bin","hvigorw.js"),javaPath:E.join(e,"jbr","bin","java.exe"),sdkPath:E.join(e,"sdk")}}static resolveMacTools(e){let t=E.join(e,"Contents","tools");return{nodePath:E.join(t,"node","bin","node"),ohpmJsPath:E.join(t,"ohpm","bin","pm-cli.js"),hvigorJsPath:E.join(t,"hvigor","bin","hvigorw.js"),javaPath:E.join(e,"Contents","jbr","Contents","Home","bin","java"),sdkPath:E.join(e,"Contents","sdk")}}static resolveTools(e){let t=W.platform(),r=t==="win32"?n.resolveWindowsTools(e):t==="darwin"?n.resolveMacTools(e):(()=>{throw new Error("Linux is not fully supported yet.")})();n.verifyTools(r.nodePath,r.ohpmJsPath,r.hvigorJsPath,r.javaPath);let o=n.resolveHdcPath(r.sdkPath,t),i=n.resolveEmulatorPath(e,t),s=n.resolveClangdPath(e),a=n.resolveLspServerPath(e);return{...r,hdcPath:o,emulatorPath:i,clangdPath:s,lspServerPath:a}}static resolveHdcPath(e,t){let r=t==="win32"?".exe":"",o=[E.join(e,"default","openharmony","toolchains",`hdc${r}`),E.join(e,"toolchains",`hdc${r}`)];for(let i of o)if(R.existsSync(i))return i;throw new Error(`hdc executable not found. Searched in:
|
|
13
13
|
${o.join(`
|
|
14
|
-
`)}`)}static resolveEmulatorPath(e,t){let r;if(t==="win32")r=E.join(e,"tools","emulator","Emulator.exe");else if(t==="darwin")r=E.join(e,"Contents","tools","emulator","Emulator");else throw new Error("Linux is not fully supported yet");if(!M.existsSync(r))throw new Error(`Emulator executable not found at: ${r}`);return r}static verifyTools(e,t,r,o){if(!M.existsSync(e))throw new Error(`Node executable not found at: ${e}`);if(!M.existsSync(t))throw new Error(`ohpm js file not found at: ${t}`);if(!M.existsSync(r))throw new Error(`hvigor js file not found at: ${r}`);if(o&&!M.existsSync(o))throw new Error(`java executable not found at: ${o}`)}static getEmulatorExe(e){let t=W.platform(),r;if(t==="win32")r=Ts(e,"tools","emulator","Emulator.exe");else if(t==="darwin")r=Ts(e,"Contents","tools","emulator","Emulator");else return;return As(r)?r:void 0}static isValidApiLevel(e,t){let r=t??23;return Number.isInteger(e)&&e>=17&&e<=r}static parseApiLevelFromFile(e){if(M.existsSync(e))try{let t=M.readFileSync(e,"utf-8"),r=JSON.parse(t),o=r?.apiVersion??r?.data?.apiVersion;if(typeof o!="string"&&typeof o!="number")return;let i=Number(o);return Number.isInteger(i)&&i>=17?i:void 0}catch{return}}static detectFromSdkPkg(e){let t=E.join(e,"default","sdk-pkg.json");return n.parseApiLevelFromFile(t)}static detectFromOhUniPackage(e){let t=[E.join(e,"default","openharmony","toolchains","oh-uni-package.json"),E.join(e,"default","openharmony","native","oh-uni-package.json"),E.join(e,"default","openharmony","previewer","oh-uni-package.json")];for(let r of t){let o=n.parseApiLevelFromFile(r);if(o!==void 0)return o}}getMaxApiLevel(){let e=n.detectFromSdkPkg(this.sdkPath);if(e!==void 0)return e;let t=n.detectFromOhUniPackage(this.sdkPath);return t!==void 0?t:23}detectApiLevel(){return this.getMaxApiLevel()}static findPowerShellPath(){if(n._powerShellPath)return n._powerShellPath;if(W.platform()!=="win32")return n._powerShellPath="",n._powerShellPath;let e=E.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return As(e)?(g(`[ToolProvider] Found PowerShell at: ${e}`),n._powerShellPath=e,e):(n._powerShellPath="",n._powerShellPath)}static verifySignature(e){if(!M.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=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 M.accessSync(e,M.constants.X_OK),!0}catch{return!1}return!1}static createSignatureScript(){let e=M.mkdtempSync(E.join(W.tmpdir(),"deveco-verify-")),t=E.join(e,"Verify-Signature.ps1");return M.writeFileSync(t,"$env:PSModulePath = ($env:PSModulePath -split ';' | Where-Object { $_ -notmatch 'windowsapps' }) -join ';'; Get-AuthenticodeSignature -FilePath $args[0] | ConvertTo-Json -Depth 3 -Compress","utf-8"),{tmpDir:e,scriptPath:t}}static verifyWindowsSignature(e){let t=n.findPowerShellPath();if(!t)throw new Error("PowerShell application not found");let{tmpDir:r,scriptPath:o}=n.createSignatureScript();try{let i=To(t,["-NoProfile","-ExecutionPolicy","Bypass","-File",o,e],{encoding:"utf-8",timeout:5e3,stdio:["pipe","pipe","ignore"]}),s=JSON.parse(i);return{signed:s?.Status===0,signer:s?.SignerCertificate?.Subject??void 0}}catch(i){return g(`[ToolProvider] verify Windows Signature, error msg: ${i}`),{signed:!0}}finally{try{M.rmSync(r,{recursive:!0,force:!0})}catch{}}}static verifyMacSignature(e){try{return To("codesign",["-v",e],{encoding:"utf-8",timeout:5e3}),{signed:!0}}catch{return{signed:!1}}}};import{execa as Au}from"execa";import*as pt from"path";import*as ks 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(ks.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 Au(t,r,{cwd:this.projectRoot,env:this.env,stdout:"inherit",stderr:"inherit"})}};import{execa as Tu}from"execa";var _e=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 Tu(e,t,{cwd:this.projectRoot,stdout:"inherit",stderr:"inherit"})}};import{mkdir as xu}from"fs/promises";import{dirname as ku,resolve as Mu}from"path";import{execa as Ru}from"execa";import{lock as xo,check as eS}from"proper-lockfile";function ko(n){return Mu(n,".hvigor",".build-lock")}function Ou(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function Ms(n){let e=ku(ko(n));if(await xu(e,{recursive:!0}),process.platform==="win32")try{await Ru("attrib",["+h",e])}catch{}}async function Nu(n,e){let t=new AbortController,r=Ou(e);await Ms(n);let o={lockfilePath:ko(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await xo(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 xo(n,{...o,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Xe(n,e,t){let{release:r,signal:o}=await Nu(n,t);try{return await e(o)}finally{await r()}}async function Rs(n,e){let t=new AbortController;await Ms(n);let r={lockfilePath:ko(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},o;try{o=await xo(n,{...r,retries:0})}catch(i){if(i&&typeof i=="object"&&"code"in i&&i.code==="ELOCKED")return{acquired:!1};throw i}try{return{acquired:!0,result:await e(t.signal)}}finally{await o()}}import*as He from"fs";import*as Qe from"path";import Lu from"json5";var _u=1e3;function Bn(n){g(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=Qe.join(n,le.SYNC_OUTPUT_PATH);if(!He.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return g(`[ProjectCheck] ${l.reason}`),l}let t=He.statSync(e).mtimeMs;g(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Hu(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return g(`[ProjectCheck] ${l.reason}`),l}let o=Qe.join(n,le.OH_PACKAGE_JSON5),i=$n(o,t,"root");if(i.required)return g(`[ProjectCheck] Root check: ${i.reason}`),i;let s=Qe.join(n,le.BUILD_PROFILE_JSON5),a=$n(s,t,"build-profile");if(a.required)return g(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let u=Qe.join(n,l.srcPath,le.OH_PACKAGE_JSON5),h=$n(u,t,l.name);if(h.required)return g(`[ProjectCheck] Module '${l.name}' check: ${h.reason}`),h;let v=Qe.join(n,l.srcPath,le.BUILD_PROFILE_JSON5),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(!He.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=He.statSync(n).mtimeMs;return r-e>_u?{required:!0,reason:`${t}: source mtime (${new Date(r).toISOString()}) is newer than sync baseline (${new Date(e).toISOString()})`}:{required:!1,reason:`${t}: up-to-date`}}function Hu(n){let e=Qe.join(n,le.BUILD_PROFILE_JSON5);try{let t=He.readFileSync(e,"utf-8");if(!t.trim())return null;let r=Lu.parse(t);if(typeof r!="object"||r===null)return null;let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}function Fu(n,e){if(e.product&&n.validateProduct(e.product),e.buildMode&&!n.profile.app.buildModeSet.some(r=>r.name===e.buildMode))throw new Error(`Build mode '${e.buildMode}' not found in project build-profile.json5.`)}function $u(n,e){let t;if(e.modules&&e.modules.length>0)t=e.modules;else{let o=n.profile.modules,i=o.filter(s=>n.getModuleType(s.name)==="entry");if(o.length===1)t=[o[0].name];else if(i.length===1)t=[i[0].name];else throw i.length>1?new Error(`Multiple entry modules found (${i.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`):new Error(`No entry module found and multiple modules available (${o.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`)}let r=new Set;for(let o of t){let i=o.indexOf("@"),s=i!==-1?o.substring(0,i):o,a=i!==-1?o.substring(i+1):"default";r.add(`${s}@${a}`)}return Array.from(r)}function qt(n,e){let t=new Set;for(let r of e){let o=r.indexOf("@"),i=o!==-1?r.substring(0,o):r,s=n.getModuleType(i);s==="shared"?t.add("assembleHsp"):s==="har"?t.add("assembleHar"):t.add("assembleHap")}return t}function zt(n,e){let t=e,r=`${n} failed`;console.error(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 Vt(n,e,t,r,o,i){let s=Bn(i);console.log(`
|
|
15
|
-
[ohpm install] Running...`);try{await n.installAll()}catch(a){
|
|
16
|
-
[hvigor sync] Running...`);try{await e.sync(t,r)}catch(a){
|
|
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
|
+
[ohpm install] Running...`);try{await n.installAll()}catch(a){Ut("ohpm install",a)}if(s.required){console.log(`
|
|
16
|
+
[hvigor sync] Running...`);try{await e.sync(t,r)}catch(a){Ut("hvigor sync",a)}}else console.log(`
|
|
17
17
|
[hvigor sync] Skipped (configurations unchanged)`);console.log(`
|
|
18
|
-
[hvigor build] Running...`);try{o.type==="product"?await e.buildProduct(t,r):await e.buildModules(t,r,o.modulesToBuild,o.moduleTasks)}catch(a){
|
|
19
|
-
`+
|
|
20
|
-
[1/2] Running hvigor clean...`);try{await r.clean()}catch(o){
|
|
21
|
-
[2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(o){
|
|
22
|
-
`+
|
|
18
|
+
[hvigor build] Running...`);try{o.type==="product"?await e.buildProduct(t,r):await e.buildModules(t,r,o.modulesToBuild,o.moduleTasks)}catch(a){Ut("hvigor build",a)}}var Hs=new Nu("build").description("Build HarmonyOS project").option("--product <product>","Product name defined in build-profile.json5 (default: default)").option("--modules <modules...>","Modules to build (format: module or module@target)").option("--build-mode <mode>","Build mode (buildModeSet in build-profile.json5; e.g. debug, release; default: debug)").action(async n=>{try{let e=process.cwd(),t=Ze.discover(e);console.warn(_s("Ensure the project source is trustworthy before proceeding."));let r=await _.new();Lu(t,n);let o=n.product||"default",i=n.buildMode||"debug",s;if(n.product&&!n.modules)s={type:"product"};else{let l=_u(t,n),u=zt(t,l);s={type:"modules",modulesToBuild:l,moduleTasks:u}}let a=new Le(r,t.rootDir),c=new Pe(r,t.rootDir);await Xe(t.rootDir,async()=>qt(a,c,o,i,s,t.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")}),console.log(`
|
|
19
|
+
`+Ls("Build completed successfully"))}catch(e){console.error(Mo(e.message)),process.exit(1)}});Hs.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{try{let n=process.cwd(),e=Ze.discover(n);console.warn(_s("Ensure the project source is trusted before proceeding."));let t=await _.new(),r=new Pe(t,e.rootDir);await Xe(e.rootDir,async()=>{console.log(`
|
|
20
|
+
[1/2] Running hvigor clean...`);try{await r.clean()}catch(o){Ut("hvigor clean",o)}console.log(`
|
|
21
|
+
[2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(o){Ut("hvigor --stop-daemon",o)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
|
|
22
|
+
`+Ls("Clean completed successfully."))}catch(n){console.error(Mo(n.message)),process.exit(1)}});var js=Hs;import{Command as vp}from"commander";import{green as Ys,red as wp,yellow as bp}from"colorette";import{randomUUID as Ju}from"crypto";import{execa as Ku}from"execa";import{execa as Yu}from"execa";import{execFile as Hu,spawn as ju}from"child_process";import{promisify as Fu}from"util";var $u=Fu(Hu);function Fs(n,e,t){let o=n.replace(/\r\n/g,`
|
|
23
23
|
`).split(`
|
|
24
|
-
`),i=o.pop()??"",s=o.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),i}function
|
|
25
|
-
`)){let o=r.trim();if(!o||o.startsWith("[Empty]"))continue;let i=o.split(/\s+/),s=i[0];if(!s||s.startsWith("[Empty]"))continue;let a=i.length>=2?i[1]:"device";if(a.toLowerCase()==="unauthorized"){g(`[DeviceManager] Skipping unauthorized device: ${s}`);continue}t.push({serial:s,status:a})}return t}extractDisplayName(e){let t=e.get("ohos.qemu.hvd.name");if(t)return t;let r=e.get("const.product.name");if(r&&r!=="emulator")return r;let o=e.get("const.product.model");if(o&&o!=="emulator"){let s=e.get("const.product.brand");return this.stripBrandPrefix(o,s)}let i=e.get("const.build.product");if(i&&i!=="emulator")return i}async getDeviceName(e){let t=await ft(this.hdcPath,e,[...
|
|
24
|
+
`),i=o.pop()??"",s=o.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),i}function $s(n,e,t){let r=n.endsWith("\r")?n.slice(0,-1):n;r.length>0&&t.onData([r],e)}function Bu(n,e){return{stdout:n.stdoutChunks.join(""),stderr:n.stderrChunks.join(""),exitCode:e??-1}}function Wu(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function Uu(n,e,t,r,o){n.stdout?.on("data",i=>{let s=i.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=Fs(e.stdoutLineBuffer+s,"stdout",t)}),n.stderr?.on("data",i=>{let s=i.toString();e.stderrChunks.push(s),e.stderrLineBuffer=Fs(e.stderrLineBuffer+s,"stderr",t)}),n.on("error",i=>{e.settled||(e.settled=!0,t.onError(i),o(i))}),n.on("close",i=>{if(e.settled)return;e.settled=!0,$s(e.stdoutLineBuffer,"stdout",t),$s(e.stderrLineBuffer,"stderr",t),t.onClose(i);let s=Bu(e,i);r(s)})}async function Bs(n,e=[],t={}){try{let{stdout:r,stderr:o}=await $u(n,e,t);return{stdout:typeof r=="string"?r.trim():"",stderr:typeof o=="string"?o.trim():"",exitCode:0}}catch(r){let o=r;return{stdout:o.stdout?.trim()||"",stderr:o.stderr?.trim()||o.message,exitCode:typeof o.code=="number"?o.code:1}}}async function Ws(n,e,t){return await new Promise((r,o)=>{let i=ju(n,e,{stdio:["inherit","pipe","pipe"]}),s=Wu();Uu(i,s,t,r,o)})}function Us(n){let e=n.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var zu=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],qu=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function mt(n){return n?zu.some(e=>e.test(n))?"transient":qu.some(e=>e.test(n))?"fatal":"ok":"ok"}var Oo=[800,1500,2500];function Vu(n){return new Promise(e=>setTimeout(e,n))}async function Vt(n,e){let t=1+Oo.length,r={stdout:"",stderr:"",exitCode:-1};for(let o=0;o<t;o++){if(r=await Bs(n,e),r.exitCode===0||mt(r.stderr)!=="transient"||o>=t-1)return r;g(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${Oo[o]}ms`),await Vu(Oo[o])}return r}async function Wn(n,e,t){let r=await Vt(n,["-t",e,"shell","param","get",t]);if(r.exitCode!==0)return;let o=r.stdout.trim();if(!(!o||mt(o)!=="ok"))return Us(o)}var No="__DEVECO_PARAM_DELIM__";function Gu(n,e){let t=new Map,r=n.split(No);for(let o=0;o<e.length;o++){let i=(r[o]??"").trim();if(!i||mt(i)!=="ok")continue;let s=Us(i);s&&t.set(e[o],s)}return t}async function ft(n,e,t){if(t.length===0)return new Map;if(t.length===1){let s=new Map,a=await Wn(n,e,t[0]);return a&&s.set(t[0],a),s}let r=t.map(s=>`param get ${s}`).join(`; echo ${No}; `)+`; echo ${No}`,o=await Vt(n,["-t",e,"shell",r]);if(o.exitCode===0){let s=Gu(o.stdout,t);if(s.size>0)return s}g(`Batched param fetch failed (exit=${o.exitCode}), falling back to individual calls for ${e}`);let i=new Map;for(let s of t){let a=await Wn(n,e,s);a&&i.set(s,a)}return i}function Gt(n){return n.startsWith("127.0.0.1:")}var zs=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],K=class n{hdcPath;constructor(e){this.hdcPath=e}static from(e){return new n(e.hdcPath)}static withHdcPath(e){return new n(e)}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}stripBrandPrefix(e,t){let r=e.trim(),o=t?.trim();if(!r||!o)return r;let i=new RegExp(`^${this.escapeRegExp(o)}(\\s+|[-_]+)?`,"i");return r.replace(i,"").trim()||r}async executeHdc(e){return Yu(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let r of e.split(`
|
|
25
|
+
`)){let o=r.trim();if(!o||o.startsWith("[Empty]"))continue;let i=o.split(/\s+/),s=i[0];if(!s||s.startsWith("[Empty]"))continue;let a=i.length>=2?i[1]:"device";if(a.toLowerCase()==="unauthorized"){g(`[DeviceManager] Skipping unauthorized device: ${s}`);continue}t.push({serial:s,status:a})}return t}extractDisplayName(e){let t=e.get("ohos.qemu.hvd.name");if(t)return t;let r=e.get("const.product.name");if(r&&r!=="emulator")return r;let o=e.get("const.product.model");if(o&&o!=="emulator"){let s=e.get("const.product.brand");return this.stripBrandPrefix(o,s)}let i=e.get("const.build.product");if(i&&i!=="emulator")return i}async getDeviceName(e){let t=await ft(this.hdcPath,e,[...zs]);return this.extractDisplayName(t)??e}async getDeviceInfo(e,t){if(e.length===0)return null;if(t){let r=e.find(s=>s.serial===t);if(r)return r;let o=t.toLowerCase(),i=[];for(let s of e){let a=await this.getDeviceName(s.serial);a.toLowerCase()===o&&i.push({device:s,name:a})}if(i.length===1)return i[0].device;throw i.length>1?new Error(`Multiple devices match "${t}". Use a serial instead:
|
|
26
26
|
`+i.map(s=>` - ${s.name} (${s.device.serial})`).join(`
|
|
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 ft(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=r.get("const.product.devicetype");let o=r.get("const.ohos.apiversion"),i=r.get("const.ohos.releasetype");o&&(t.osVersion=i?`API ${o} (${i})`:`API ${o}`)}catch{}return t}async listDevicesWithName(){let e=await this.listDevices();return Promise.all(e.map(async t=>({serial:t.serial,name:await this.getDeviceName(t.serial)})))}async getConnectedEntries(){let e=await this.listDevices();return Promise.all(e.map(t=>this.buildConnectedEntry(t.serial)))}async buildConnectedEntry(e){let t=I()?!1:
|
|
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
|
|
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 ft(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=r.get("const.product.devicetype");let o=r.get("const.ohos.apiversion"),i=r.get("const.ohos.releasetype");o&&(t.osVersion=i?`API ${o} (${i})`:`API ${o}`)}catch{}return t}async listDevicesWithName(){let e=await this.listDevices();return Promise.all(e.map(async t=>({serial:t.serial,name:await this.getDeviceName(t.serial)})))}async getConnectedEntries(){let e=await this.listDevices();return Promise.all(e.map(t=>this.buildConnectedEntry(t.serial)))}async buildConnectedEntry(e){let t=I()?!1:Gt(e),r,o;try{let i=await ft(this.hdcPath,e,[...zs]);r=this.extractDisplayName(i),o=i.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:o}}};var Yt=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=K.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;g(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:o}=await Ku(r,e,{env:{...process.env}});return o}catch(o){if(t)throw o;return o.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){let r=await this.runHdc(["-t",e,"shell","bm","uninstall","-n",t],!1);if(r.includes("uninstall bundle successfully"))return!0;if(r.includes("uninstall missing installed bundle"))return!1;throw new Error(`Uninstall failed: ${r}`)}async installApp(e,t){if(t.length===0)return;let o=`/data/local/tmp/${Ju()}`;try{await this.runHdc(["-t",e,"shell","mkdir",o]);for(let s of t){let a=await this.runHdc(["-t",e,"file","send",s,o+"/"]);if(!a.startsWith("FileTransfer finish"))throw new Error(a)}let i=await this.runHdc(["-t",e,"shell","bm","install","-p",o]);if(!i.includes("install bundle successfully."))throw new Error(i);console.log("App installed successfully")}finally{await this.runHdc(["-t",e,"shell","rm","-rf",o],!1)}}async launchApp(e,t,r){let o=["-t",e,"shell","aa","start","-a",r,"-b",t];return await this.runHdc(o)}async connectTarget(e){await this.runHdc(["tconn",e])}async disconnectTarget(e){await this.runHdc(["tconn",e,"-remove"],!1)}async listRawTargets(){return(await this.runHdc(["list","targets"],!1)).split(`
|
|
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
29
|
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.`)}function
|
|
31
|
-
|
|
32
|
-
--devices <names>: launch specified device types (comma-separated)
|
|
33
|
-
Please specify only one of them.`);let t=n.devices.split(",").map(s=>s.trim()).filter(s=>s.length>0);if(t.length===0)throw new Error(`--devices is empty. Example: --devices "Pura 90 Pro,MatePad 11.5'S"`);let r=[],o=[];for(let s of t){let a=qs(e,s);if(a.spec)r.push(a.spec),a.matchType==="fuzzy"?console.warn(Lo(` [fuzzy] "${s}" \u2192 ${a.matchedName}`)):(a.matchType==="alias"||a.matchType==="substring")&&console.log(` [${a.matchType}] "${s}" \u2192 ${a.matchedName}`);else{if(a.ambiguous&&a.ambiguous.length>0)throw new Error(`Ambiguous device name "${s}". Candidates:
|
|
34
|
-
`+a.ambiguous.map(c=>` - ${c}`).join(`
|
|
30
|
+
Please start DevEco Studio manually, then retry.`)}async function Vs(n){if(!n)return!1;let e=n.split(",").map(o=>o.trim()).filter(o=>o.length>0);if(e.length===0)return!1;let t=await Lo(),r=t.length>0?t:[Jt];return e.every(o=>_o(r,o).spec!==void 0)}function cp(n,e){if(!n)return[e[0]||Jt];let t=n.split(",").map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0)return[e[0]||Jt];let r=[],o=[];for(let i of t){let s=_o(e,i);if(s.spec)r.push(s.spec),s.matchType==="fuzzy"?console.warn(jo(` [fuzzy] "${i}" \u2192 ${s.matchedName}`)):(s.matchType==="alias"||s.matchType==="substring")&&console.log(` [${s.matchType}] "${i}" \u2192 ${s.matchedName}`);else{if(s.ambiguous&&s.ambiguous.length>0)throw new Error(`Ambiguous device name "${i}". Candidates:
|
|
31
|
+
`+s.ambiguous.map(a=>` - ${a}`).join(`
|
|
35
32
|
`)+`
|
|
36
|
-
Please specify a more precise name.`);o.push(
|
|
37
|
-
Available: ${
|
|
33
|
+
Please specify a more precise name.`);o.push(i)}}if(o.length>0){let i=e.map(s=>s.productName).join(", ");throw new Error(`Device type(s) not found: ${o.join(", ")}
|
|
34
|
+
Available: ${i}`)}return lp(r)}function lp(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 dp(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=qs.createInterface({input:np,output:rp});try{let t=await e.question("Wireless debugging port: ");if(t.trim()){let r=`127.0.0.1:${t.trim()}`;return await n.connectTarget(r),console.log(ht(`Connected to local device: ${r}`)),r}}catch{}finally{e.close()}}async function up(n,e){if(e){let i=e.includes(":")?e:`127.0.0.1:${e}`;return await n.connectTarget(i),console.log(`Connected to local device: ${i}`),i}let t=process.env.DEVECO_HDC_PORT;if(t){let i=`127.0.0.1:${t}`;try{return await n.connectTarget(i),console.log(`Connected to local device via DEVECO_HDC_PORT: ${i}`),i}catch{console.warn(jo(`DEVECO_HDC_PORT=${t} but connect failed, trying other methods...`))}}let r=await n.listRawTargets();if(r.length>0){let i=r[0];return g(`[preview] Found existing target: ${i}`),i}let o=await dp(n);if(o)return o;throw new Error(`Cannot connect to local HarmonyOS device.
|
|
38
35
|
Please either:
|
|
39
36
|
1. Run with --device 127.0.0.1:<port>, or
|
|
40
37
|
2. Set DEVECO_HDC_PORT env var, or
|
|
41
|
-
3. Open wireless debugging in system settings first.`)}async function
|
|
42
|
-
`))}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let o=await n.getDeviceName(r.serial);console.log(`Auto-selected device: ${o} (${r.serial})`)}return r.serial}function
|
|
43
|
-
[multi-preview] Building with multiAppMode (appClone) for multi-instance preview...`);let v=new
|
|
44
|
-
Launching DevEco Studio previewer on ${n}...`),console.log(` bundleName : ${e}`),console.log(` abilityName : ${t}`),console.log(` moduleName : ${r}`),console.log(` instanceId : ${o}`),console.log(` mode : ${i?"multi":"single"}`),console.log(` previewers : ${s.map(a=>a.productName).join(", ")}`)}async function
|
|
45
|
-
[${l+1}/${e.length}] Launching ${u.productName} (${u.productType}/${u.subProductType})...`);try{let v=await n.launchPreview(r,o,i,u.productName,u.productType,s,u.subProductType,a,h),D=/start ability successfully/i.test(v);c.push({name:u.productName,success:D,output:v}),D?console.log(ht(` \u2713 ${u.productName}: ${v.trim()}`)):console.error(qn(` \u2717 ${u.productName}: ${v.trim()}`))}catch(v){let D=v.message;c.push({name:u.productName,success:!1,output:D}),console.error(qn(` \u2717 ${u.productName}: ${D}`))}}return c}function
|
|
46
|
-
`+"\u2500".repeat(50));let e=n.filter(r=>r.success).length,t=n.length-e;console.log(`Previewer launch summary: ${ht(String(e))} succeeded, ${t>0?qn(String(t)):"0"} failed.`);for(let r of n){let o=r.success?ht("\u2713"):qn("\u2717");console.log(` ${o} ${r.name}`)}return t===0}async function Gs(n,e,t,r,o,i){let s=
|
|
47
|
-
`))}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let o=await n.getDeviceName(r.serial);console.log(`Auto-selected device: ${o} (${r.serial})`)}return r.serial}function
|
|
38
|
+
3. Open wireless debugging in system settings first.`)}async function pp(n,e){let t=await n.listDevices();if(t.length===0)throw new Error(I()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device.");if(!e&&t.length>1){let o=await n.listDevicesWithName();throw new Error("Multiple devices found. Please specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+o.map(i=>` - ${i.name} (${i.serial})`).join(`
|
|
39
|
+
`))}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let o=await n.getDeviceName(r.serial);console.log(`Auto-selected device: ${o} (${r.serial})`)}return r.serial}function mp(n){if(!zn.existsSync(n))throw new Error(`app.json5 not found at ${n}`);let e=zn.readFileSync(n,"utf8"),t=op.parse(e);return t.app?.multiAppMode?(console.log("[multi-preview] app.json5 already has multiAppMode, skipping injection."),()=>{}):(t.app||(t.app={}),t.app.multiAppMode={multiAppModeType:"appClone",maxCount:5},zn.writeFileSync(n,JSON.stringify(t,null,2),"utf8"),console.log(`[multi-preview] Injected multiAppMode into ${Kt.basename(n)}`),()=>{zn.writeFileSync(n,e,"utf8"),console.log(`[multi-preview] Restored original ${Kt.basename(n)}`)})}async function fp(n,e,t,r,o,i){let s=Kt.join(e.rootDir,"AppScope","app.json5"),a=mp(s);try{let c=n.product||"default",l=n.buildMode||"debug",u="default",h=o.includes("127.0.0.1")||o.includes("localhost");console.log(`
|
|
40
|
+
[multi-preview] Building with multiAppMode (appClone) for multi-instance preview...`);let v=new Le(t,e.rootDir),D=new Pe(t,e.rootDir),ne=e.collectNonHarDependentModuleList(i).map(vu=>`${vu}@${u}`),ut=zt(e,ne),Ke={type:"modules",modulesToBuild:ne,moduleTasks:ut};await Xe(e.rootDir,async()=>{await qt(v,D,c,l,Ke,e.rootDir)},()=>console.log("Another build is already running. Waiting...")),console.log(ht("[multi-preview] Build completed."));let Eo=e.findArtifactPath(i,u,h,c);console.log(`[multi-preview] Installing multiAppMode hap to ${o}...`),await r.installApp(o,[Eo]),console.log(ht("[multi-preview] Installed multiAppMode hap."))}finally{a()}}function hp(n,e,t,r,o,i,s){console.log(`
|
|
41
|
+
Launching DevEco Studio previewer on ${n}...`),console.log(` bundleName : ${e}`),console.log(` abilityName : ${t}`),console.log(` moduleName : ${r}`),console.log(` instanceId : ${o}`),console.log(` mode : ${i?"multi":"single"}`),console.log(` previewers : ${s.map(a=>a.productName).join(", ")}`)}async function gp(n,e,t,r,o,i,s,a){let c=[];for(let l=0;l<e.length;l++){let u=e[l],h=t?l:-1;console.log(`
|
|
42
|
+
[${l+1}/${e.length}] Launching ${u.productName} (${u.productType}/${u.subProductType})...`);try{let v=await n.launchPreview(r,o,i,u.productName,u.productType,s,u.subProductType,a,h),D=/start ability successfully/i.test(v);c.push({name:u.productName,success:D,output:v}),D?console.log(ht(` \u2713 ${u.productName}: ${v.trim()}`)):console.error(qn(` \u2717 ${u.productName}: ${v.trim()}`))}catch(v){let D=v.message;c.push({name:u.productName,success:!1,output:D}),console.error(qn(` \u2717 ${u.productName}: ${D}`))}}return c}function yp(n){console.log(`
|
|
43
|
+
`+"\u2500".repeat(50));let e=n.filter(r=>r.success).length,t=n.length-e;console.log(`Previewer launch summary: ${ht(String(e))} succeeded, ${t>0?qn(String(t)):"0"} failed.`);for(let r of n){let o=r.success?ht("\u2713"):qn("\u2717");console.log(` ${o} ${r.name}`)}return t===0}async function Gs(n,e,t,r,o,i){let s=await Lo(),a=s.length>0?s:[Jt],c=cp(n.device,a),l=c.length>1,u;if(I()){let Ke=(await r.listRawTargets()).find(Eo=>Eo.includes("127.0.0.1:"));Ke?(u=Ke,console.log(`Using self-connected device: ${u}`)):(console.warn(jo("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...")),u=await up(r,void 0))}else u=await pp(o,void 0);l&&await fp(n,e,t,r,u,i),await ap(r,u);let h=e.getBundleName(),v=e.getMainAbility(i,n.ability),D=e.getModuleName(i),k=process.pid;hp(u,h,v,D,k,l,c);let ne=await gp(r,c,l,u,h,v,D,k);return yp(ne)}function Sp(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 Pp(n,e){let t=await n.listDevices();if(t.length===0)throw new Error(I()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device.");if(!e&&t.length>1){let o=await n.listDevicesWithName();throw new Error("Multiple devices found. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+o.map(i=>` - ${i.name} (${i.serial})`).join(`
|
|
44
|
+
`))}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let o=await n.getDeviceName(r.serial);console.log(`Auto-selected device: ${o} (${r.serial})`)}return r.serial}function Ep(n,e){if(e&&e.length>0)return e;let t=n.profile.modules.filter(r=>{let o=n.getModuleType(r.name);return o==="entry"||o==="feature"||o==="shared"});if(t.length===1){let r=t[0].name;return console.log(`Auto-selected module: ${r}`),[r]}throw new Error(`Specify module(s) using --module <name> [<name>...].
|
|
48
45
|
Available runnable modules:
|
|
49
46
|
`+t.map(r=>` - ${r.name}`).join(`
|
|
50
|
-
`))}function
|
|
47
|
+
`))}function Dp(n,e,t){if(t)return t;let r=e.find(({moduleName:i})=>n.getModuleType(i)==="entry");if(r)return n.getMainAbility(r.moduleName);let o=e.find(({moduleName:i})=>n.getModuleType(i)==="feature");if(o)return n.getMainAbility(o.moduleName)}async function Ip(n,e,t,r,o,i){if(i&&(console.log(`Uninstalling ${t}...`),await n.uninstallApp(e,t)||console.log(`App ${t} not installed; skipping uninstallation.`)),console.log(`
|
|
51
48
|
Installing artifacts to device ${e}...`),await n.installApp(e,r),o){console.log(`Launching ${t}/${o}...`);let s=await n.launchApp(e,t,o);console.log(Ys(`
|
|
52
49
|
Application '${t}': ${s}`))}else console.log(`
|
|
53
|
-
Application '${t}' installed successfully (no ability to launch).`)}var
|
|
54
|
-
`+Ys("Build completed successfully."))}async function
|
|
55
|
-
${
|
|
56
|
-
|
|
57
|
-
`+Ks(`${n} updated successfully to version ${r}.`))}catch(t){let r=t;console.error(Zs(`Failed to update ${n}`)),r.message&&console.error(Zs(r.message)),process.exit(1)}}),Qs=Bp;import{Command as lm}from"commander";import{execa as $o}from"execa";function V(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as Wp}from"child_process";var Up=2500;function zp(n,e,t,r,o,i){n.once("exit",s=>{if(i())return;clearTimeout(e);let a=t();s===0||s===null?r():o(a||`Emulator process exited with code ${s}`)})}function qp(n,e,t,r){let o=!1,i=()=>o,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{o||(o=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners(),n.stderr?.destroy(),n.unref(),t())},c=u=>{if(!o){o=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners();try{n.kill()}catch{}r(new Error(u))}},l=setTimeout(a,Up);n.once("error",u=>c(u.message)),zp(n,l,s,a,c,i)}function ea(n,e,t){return g(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,o)=>{let i=[],s=Wp(n,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>i.push(a)),qp(s,i,r,o)})}import*as gt from"path";function Vp(n){let e=new Set,t=[];for(let r of n){let o=JSON.stringify(r);e.has(o)||(e.add(o),t.push(r))}return t}function Gp(n){let e=n.instancePath?.trim();if(e)return gt.dirname(gt.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?gt.dirname(gt.normalize(t)).replace(/\\/g,"/"):""}function Yp(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function ta(n,e){return e?[...n,"-bootmode",e]:n}function Jp(n,e,t){let r=[ta(["-start",n],t)],o=Gp(e);if(o)for(let i of Yp(e.imageRoot))r.push(ta(["-hvd",n,"-path",o,...i],t));return Vp(r)}async function na(n,e,t,r){let o=new Error("No start strategy ran"),i=Jp(n,e,r);for(let s of i)try{return await t(s),{ok:!0}}catch(a){o=a}return{ok:!1,lastError:o}}async function Ho(n){return(await K.withHdcPath(n).listDevices()).map(t=>t.serial).filter(Yt)}async function jo(n){let e=await Ho(n);return e.length===0?[]:(await Promise.all(e.map(r=>Wn(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function ra(n,e){return(await jo(n)).includes(e)}import*as vt from"path";import{existsSync as Kp,statSync as Zp}from"fs";function yt(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function Xp(n){let e=yt(n,["instancePath","instance_path","InstancePath","instancepath","instanceDir","instance_dir","InstanceDir","deployPath","deploy_path","deployedPath","deployed_path","workPath","work_path","dataPath","data_path"]);if(e)return e;for(let[t,r]of Object.entries(n)){if(typeof r!="string"||!r.trim())continue;let o=t.toLowerCase();if(o.includes("instance")&&(o.includes("path")||o.includes("dir"))||o==="deployedpath")return r.trim()}return""}function Qp(n){return yt(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function em(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=vt.dirname(vt.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let o=vt.join(t,r.name);Kp(o)&&Zp(o).isDirectory()&&(r.instancePath=o.replace(/\\/g,"/"))}}function tm(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=Qp(t),o=yt(t,["deviceType","DeviceType","devicetype"]),i=yt(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:Xp(t),path:yt(t,["path","Path","hvdPath","hvd_path"]),imageRoot:yt(t,["imageRoot","image_root","ImageRoot"]),uuid:r||void 0,deviceType:o||void 0,osVersion:i||void 0}}).filter(t=>t.name):null}catch{return null}}function nm(n){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,r=null,o;for(;(o=t.exec(n))!==null;){let[,i,s]=o;if(i.toLowerCase()==="name")r&&e.push(r),r={name:s.trim()};else if(r){let a=i.toLowerCase();a==="isrunning"?r.isRunning=s.trim().toLowerCase()==="true":a==="instancepath"?r.instancePath=s.trim():a==="path"?r.path=s.trim():a==="imageroot"?r.imageRoot=s.trim():a==="devicetype"?r.deviceType=s.trim():a==="os.osversion"&&(r.osVersion=s.trim())}}return r&&e.push(r),e}function oa(n){let t=tm(n)??nm(n);return em(t),t}function Fo(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function rm(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function om(n){if(!rm(n))return null;let e=Fo(n,["osVersion","OsVersion","OSVersion"]),t=Fo(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=Fo(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function Vn(n){let e=n.trim();if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let r=[];for(let o of t){if(!o||typeof o!="object")continue;let i=om(o);i&&r.push(i)}return r}catch{return[]}}function ia(n){let t=Vn(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var sa=/no images are available/i;function he(n){return n.normalize("NFKC").trim().toLowerCase()}function im(n){let e=n.message||"";return sa.test(e)}var wt=class n{emulatorPath;sdkPath;hdcPath;constructor(e,t,r){this.emulatorPath=e,this.sdkPath=t,this.hdcPath=r}static from(e){return new n(e.emulatorPath,e.sdkPath,e.hdcPath)}async executeEmulator(e){return $o(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return ea(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return oa(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let r of t)r.name&&r.deviceType&&e.set(V(r.name),r.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),r=V(e),o=t.find(a=>V(a.name)===r);if(!o)throw new Error(`Emulator "${e}" not found.`);let i=o.name;if(await this.isAlreadyRunning(i,o))return"already-running";await this.assertSystemImageAvailable(o);let s=await na(i,o,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return"started";if(await this.isAlreadyRunning(i))return"already-running";throw new Error(`Unable to start emulator "${e}". All methods failed.
|
|
58
|
-
Last error: ${s.lastError.message||"unknown"}`)}async isAlreadyRunning(e,t){return t?.isRunning===!0||t===void 0&&(await this.listEmulators()).find(o=>o.name===e)?.isRunning===!0?!0:ra(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=V(e),o=t.find(a=>V(a.name)===r);if(!o)throw new Error(`Emulator "${e}" not found.`);let i=o.name;return await this.isAlreadyRunning(i,o)?(await this.executeEmulator(["-stop",i]),"stopped"):"already-stopped"}async executeEmulatorInherit(e){let{exitCode:t}=await $o(this.emulatorPath,e,{stdio:"inherit",env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1});if(t!==0)throw new Error(`Emulator exited with code ${t===null?"null":t}.`)}async installEmulatorImage(e){let t=["-install","-deviceType",e.deviceType,"-osVersion",e.osVersion];e.force&&t.push("-force"),await this.executeEmulatorInherit(t)}async uninstallEmulatorImage(e){let t=await this.resolveSoftwareVersionsForUninstall(e);if(t.length===0)throw new Error(`No downloaded image matches --os-version "${e.osVersion}" for --device-type "${e.deviceType}".`);let r;try{await this.runUninstallImageChecked(e.deviceType,e.osVersion)}catch(i){if(!im(i))throw i;r=i}(r!==void 0||await this.hasMatchingDownloadedImage(e))&&await this.runSoftwareVersionFallback(e,t,r)}async listEmulatorImages(e){let t=["-imageList"];e.deviceType&&t.push("-deviceType",e.deviceType),e.downloaded!==void 0&&t.push("-downloaded",e.downloaded?"true":"false");let{stdout:r}=await this.executeEmulator(t);return r}async listDownloadedImageOsVersions(){let e=await this.listEmulatorImages({downloaded:!0});return ia(e)}async hasMatchingDownloadedImage(e){return(await this.findMatchingDownloadedImages(e)).length>0}async runSoftwareVersionFallback(e,t,r){try{for(let o of t)await this.runUninstallImageChecked(e.deviceType,o)}catch(o){let i=r!==void 0?`Primary uninstall failed: ${r.message}
|
|
59
|
-
`:"";throw new Error(`${i}Fallback uninstall failed: ${o.message}`,{cause:o})}if(await this.hasMatchingDownloadedImage(e))throw new Error(`Image for --device-type "${e.deviceType}" and --os-version "${e.osVersion}" remains listed as downloaded after uninstallation.`)}async resolveSoftwareVersionsForUninstall(e){let t=await this.findMatchingDownloadedImages(e);return[...new Set(t.map(r=>r.softwareVersion).filter(Boolean))]}async findMatchingDownloadedImages(e){let t=await this.listEmulatorImages({deviceType:e.deviceType,downloaded:!0}),r=Vn(t),o=he(e.deviceType),i=he(e.osVersion);return r.filter(s=>he(s.deviceType)===o&&(he(s.osVersion)===i||he(s.softwareVersion)===i))}async hasDownloadedSystemImage(e,t){let r=await this.listEmulatorImages({downloaded:!0}),o=Vn(r),i=he(t),s=e?.trim()?he(e):void 0;return o.some(a=>he(a.osVersion)===i||he(a.softwareVersion)===i?s===void 0?!0:he(a.deviceType)===s:!1)}async assertSystemImageAvailable(e){let t=e.osVersion?.trim();if(!t)throw new Error("The system image file cannot be found, download it again.");if(!await this.hasDownloadedSystemImage(e.deviceType,t))throw new Error(`The system image file ${t} cannot be found, download it again.`)}async runUninstallImageChecked(e,t){await this.runEmulatorChecked(["-uninstall","-deviceType",e,"-osVersion",t,"-force"],{printOutputOnSuccess:!0,extraReject:[sa]})}async runEmulatorChecked(e,t){let{stdout:r,stderr:o,exitCode:i}=await $o(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:20971520}),s=[r,o].filter(Boolean).join(`
|
|
50
|
+
Application '${t}' installed successfully (no ability to launch).`)}var Cp=new vp("run").description("Build and run the project on a connected device").option("--module <modules...>","Module(s) to run (format: module or module@target)").option("--device <device>","Target device name or serial").option("--product <product>","Product name (default: default)").option("--build-mode <mode>","Build mode (options: debug, release; default: debug)").option("--ability <ability>","Ability name to launch").option("--uninstall","Uninstall existing app before installation").option("--skip-build","Skip build step and deploy existing artifacts").action(async n=>{try{await Rp(n)}catch(e){console.error(wp(e.message)),process.exit(1)}});async function Ap(n,e,t,r,o){let i=new Le(e,n.rootDir),s=new Pe(e,n.rootDir),a=new Set;for(let{moduleName:h,targetName:v}of t)for(let D of n.collectNonHarDependentModuleList(h))a.add(`${D}@${v}`);let c=[...a],l=zt(n,c),u={type:"modules",modulesToBuild:c,moduleTasks:l};await Xe(n.rootDir,()=>qt(i,s,r,o,u,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion...")),console.log(`
|
|
51
|
+
`+Ys("Build completed successfully."))}async function Tp(n,e,t,r,o){let i=new Yt(t),s=K.from(t),a=r[0]?.moduleName||o[0];await Gs(n,e,t,i,s,a)||process.exit(1)}function xp(n,e){for(let{moduleName:t}of e){let r=n.getModuleType(t);if(r!=="entry"&&r!=="feature"&&r!=="shared")throw new Error(`Module '${t}' '${r}' is not runnable. Specify an entry or feature module.`)}}function kp(n,e,t,r){let o=new Set;for(let{moduleName:i,targetName:s}of e){let a=n.collectNonHarDependentModuleList(i);for(let c of a)o.add(n.findArtifactPath(c,s,t,r));o.add(n.findArtifactPath(i,s,t,r))}return[...o]}async function Rp(n){let e=Ze.discover(process.cwd());console.warn(bp("Ensure the project source is trusted before proceeding."));let t=await _.new(),r=Ep(e,n.module),o=r.map(Sp);if(await Vs(n.device)){await Tp(n,e,t,o,r);return}xp(e,o);let i=new Yt(t),s=K.from(t),a=await Pp(s,n.device),c=a.includes("127.0.0.1")||a.includes("localhost"),l=n.product||"default";e.validateProduct(l);let u=n.buildMode||"debug";n.skipBuild||await Ap(e,t,o,l,u);let h=kp(e,o,c,l),v=e.getBundleName(),D=Dp(e,o,n.ability);await Ip(i,a,v,h,D,!!n.uninstall)}var Js=Cp;import{Command as Qp}from"commander";import{execa as Wo}from"execa";function V(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as Mp}from"child_process";var Op=2500;function Np(n,e,t,r,o,i){n.once("exit",s=>{if(i())return;clearTimeout(e);let a=t();s===0||s===null?r():o(a||`Emulator process exited with code ${s}`)})}function Lp(n,e,t,r){let o=!1,i=()=>o,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{o||(o=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners(),n.stderr?.destroy(),n.unref(),t())},c=u=>{if(!o){o=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners();try{n.kill()}catch{}r(new Error(u))}},l=setTimeout(a,Op);n.once("error",u=>c(u.message)),Np(n,l,s,a,c,i)}function Ks(n,e,t){return g(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,o)=>{let i=[],s=Mp(n,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>i.push(a)),Lp(s,i,r,o)})}import*as gt from"path";function _p(n){let e=new Set,t=[];for(let r of n){let o=JSON.stringify(r);e.has(o)||(e.add(o),t.push(r))}return t}function Hp(n){let e=n.instancePath?.trim();if(e)return gt.dirname(gt.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?gt.dirname(gt.normalize(t)).replace(/\\/g,"/"):""}function jp(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function Zs(n,e){return e?[...n,"-bootmode",e]:n}function Fp(n,e,t){let r=[Zs(["-start",n],t)],o=Hp(e);if(o)for(let i of jp(e.imageRoot))r.push(Zs(["-hvd",n,"-path",o,...i],t));return _p(r)}async function Xs(n,e,t,r){let o=new Error("No start strategy ran"),i=Fp(n,e,r);for(let s of i)try{return await t(s),{ok:!0}}catch(a){o=a}return{ok:!1,lastError:o}}async function Fo(n){return(await K.withHdcPath(n).listDevices()).map(t=>t.serial).filter(Gt)}async function $o(n){let e=await Fo(n);return e.length===0?[]:(await Promise.all(e.map(r=>Wn(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function Qs(n,e){return(await $o(n)).includes(e)}import*as vt from"path";import{existsSync as $p,statSync as Bp}from"fs";function yt(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function Wp(n){let e=yt(n,["instancePath","instance_path","InstancePath","instancepath","instanceDir","instance_dir","InstanceDir","deployPath","deploy_path","deployedPath","deployed_path","workPath","work_path","dataPath","data_path"]);if(e)return e;for(let[t,r]of Object.entries(n)){if(typeof r!="string"||!r.trim())continue;let o=t.toLowerCase();if(o.includes("instance")&&(o.includes("path")||o.includes("dir"))||o==="deployedpath")return r.trim()}return""}function Up(n){return yt(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function zp(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=vt.dirname(vt.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let o=vt.join(t,r.name);$p(o)&&Bp(o).isDirectory()&&(r.instancePath=o.replace(/\\/g,"/"))}}function qp(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=Up(t),o=yt(t,["deviceType","DeviceType","devicetype"]),i=yt(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:Wp(t),path:yt(t,["path","Path","hvdPath","hvd_path"]),imageRoot:yt(t,["imageRoot","image_root","ImageRoot"]),uuid:r||void 0,deviceType:o||void 0,osVersion:i||void 0}}).filter(t=>t.name):null}catch{return null}}function Vp(n){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,r=null,o;for(;(o=t.exec(n))!==null;){let[,i,s]=o;if(i.toLowerCase()==="name")r&&e.push(r),r={name:s.trim()};else if(r){let a=i.toLowerCase();a==="isrunning"?r.isRunning=s.trim().toLowerCase()==="true":a==="instancepath"?r.instancePath=s.trim():a==="path"?r.path=s.trim():a==="imageroot"?r.imageRoot=s.trim():a==="devicetype"?r.deviceType=s.trim():a==="os.osversion"&&(r.osVersion=s.trim())}}return r&&e.push(r),e}function ea(n){let t=qp(n)??Vp(n);return zp(t),t}function Bo(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function Gp(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function Yp(n){if(!Gp(n))return null;let e=Bo(n,["osVersion","OsVersion","OSVersion"]),t=Bo(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=Bo(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function Vn(n){let e=n.trim();if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let r=[];for(let o of t){if(!o||typeof o!="object")continue;let i=Yp(o);i&&r.push(i)}return r}catch{return[]}}function ta(n){let t=Vn(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var na=/no images are available/i;function he(n){return n.normalize("NFKC").trim().toLowerCase()}function Jp(n){let e=n.message||"";return na.test(e)}var wt=class n{emulatorPath;sdkPath;hdcPath;constructor(e,t,r){this.emulatorPath=e,this.sdkPath=t,this.hdcPath=r}static from(e){return new n(e.emulatorPath,e.sdkPath,e.hdcPath)}async executeEmulator(e){return Wo(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return Ks(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return ea(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let r of t)r.name&&r.deviceType&&e.set(V(r.name),r.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),r=V(e),o=t.find(a=>V(a.name)===r);if(!o)throw new Error(`Emulator "${e}" not found.`);let i=o.name;if(await this.isAlreadyRunning(i,o))return"already-running";await this.assertSystemImageAvailable(o);let s=await Xs(i,o,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return"started";if(await this.isAlreadyRunning(i))return"already-running";throw new Error(`Unable to start emulator "${e}". All methods failed.
|
|
52
|
+
Last error: ${s.lastError.message||"unknown"}`)}async isAlreadyRunning(e,t){return t?.isRunning===!0||t===void 0&&(await this.listEmulators()).find(o=>o.name===e)?.isRunning===!0?!0:Qs(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=V(e),o=t.find(a=>V(a.name)===r);if(!o)throw new Error(`Emulator "${e}" not found.`);let i=o.name;return await this.isAlreadyRunning(i,o)?(await this.executeEmulator(["-stop",i]),"stopped"):"already-stopped"}async executeEmulatorInherit(e){let{exitCode:t}=await 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(i){if(!Jp(i))throw i;r=i}(r!==void 0||await this.hasMatchingDownloadedImage(e))&&await this.runSoftwareVersionFallback(e,t,r)}async listEmulatorImages(e){let t=["-imageList"];e.deviceType&&t.push("-deviceType",e.deviceType),e.downloaded!==void 0&&t.push("-downloaded",e.downloaded?"true":"false");let{stdout:r}=await this.executeEmulator(t);return r}async listDownloadedImageOsVersions(){let e=await this.listEmulatorImages({downloaded:!0});return ta(e)}async hasMatchingDownloadedImage(e){return(await this.findMatchingDownloadedImages(e)).length>0}async runSoftwareVersionFallback(e,t,r){try{for(let o of t)await this.runUninstallImageChecked(e.deviceType,o)}catch(o){let i=r!==void 0?`Primary uninstall failed: ${r.message}
|
|
53
|
+
`:"";throw new Error(`${i}Fallback uninstall failed: ${o.message}`,{cause:o})}if(await this.hasMatchingDownloadedImage(e))throw new Error(`Image for --device-type "${e.deviceType}" and --os-version "${e.osVersion}" remains listed as downloaded after uninstallation.`)}async resolveSoftwareVersionsForUninstall(e){let t=await this.findMatchingDownloadedImages(e);return[...new Set(t.map(r=>r.softwareVersion).filter(Boolean))]}async findMatchingDownloadedImages(e){let t=await this.listEmulatorImages({deviceType:e.deviceType,downloaded:!0}),r=Vn(t),o=he(e.deviceType),i=he(e.osVersion);return r.filter(s=>he(s.deviceType)===o&&(he(s.osVersion)===i||he(s.softwareVersion)===i))}async hasDownloadedSystemImage(e,t){let r=await this.listEmulatorImages({downloaded:!0}),o=Vn(r),i=he(t),s=e?.trim()?he(e):void 0;return o.some(a=>he(a.osVersion)===i||he(a.softwareVersion)===i?s===void 0?!0:he(a.deviceType)===s:!1)}async assertSystemImageAvailable(e){let t=e.osVersion?.trim();if(!t)throw new Error("The system image file cannot be found, download it again.");if(!await this.hasDownloadedSystemImage(e.deviceType,t))throw new Error(`The system image file ${t} cannot be found, download it again.`)}async runUninstallImageChecked(e,t){await this.runEmulatorChecked(["-uninstall","-deviceType",e,"-osVersion",t,"-force"],{printOutputOnSuccess:!0,extraReject:[na]})}async runEmulatorChecked(e,t){let{stdout:r,stderr:o,exitCode:i}=await Wo(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:20971520}),s=[r,o].filter(Boolean).join(`
|
|
60
54
|
`).trim(),a=/Invalid command|无效命令|鏃犳晥鍛戒护/i.test(s)||/please attach the correct parameter/i.test(s),c=(t?.extraReject??[]).some(u=>u.test(s));if(i!==0||a||c)throw new Error(s||`emulator exited with code ${i===null?"null":i}`);if(t?.printOutputOnSuccess!==!1&&s){let u=(t?.transformOutput?t.transformOutput(s):s).trim();u&&console.log(u)}}async checkExistingVirtualDevice(e,t){let r=await this.listEmulators(),o=V(e),i=r.find(s=>V(s.name)===o);if(i)if(t)await this.deleteVirtualDevice(i.name);else throw new Error(`Emulator "${e}" already exists. Use \`--force\` to overwrite.`);return o}async createVirtualDevice(e){let t=await this.checkExistingVirtualDevice(e.name,e.force),r=["-create",e.name,"-deviceType",e.deviceType,"-osVersion",e.osVersion];if(await this.runEmulatorChecked(r,{extraReject:[/Device create fail/i,/already exists/i,/Invalid OS version/i,/cannot be empty/i],printOutputOnSuccess:!0,transformOutput:i=>i.split(/\r?\n/).map(s=>s.trim().startsWith("Device create success.")?"Device create success.":s).join(`
|
|
61
55
|
`)}),!await this.waitForEmulatorPresenceByList(t))throw new Error(`Emulator "${e.name}" was reported as created, but it did not appear in the emulator list within the waiting period. Open the device manager list in DevEco Studio, then run this command again.`)}async waitForEmulatorPresenceByList(e,t=1e4,r=500){let o=Date.now()+t;for(;Date.now()<o;){if((await this.listEmulators()).some(a=>V(a.name)===e))return!0;await new Promise(a=>setTimeout(a,r))}return!1}async deleteVirtualDevice(e){let t=await this.listEmulators(),r=V(e),o=t.find(s=>V(s.name)===r);if(!o)throw new Error(`Emulator "${e}" not found.`);let i=o.name;if(o.isRunning===!0||await this.isAlreadyRunning(i,o))throw new Error(`Failed to delete device: ${i}
|
|
62
|
-
The device may be running.`);return await this.runEmulatorChecked(["-delete",i,"-force"],{printOutputOnSuccess:!1}),i}};import{red as
|
|
63
|
-
`)}function
|
|
56
|
+
The device may be running.`);return await this.runEmulatorChecked(["-delete",i,"-force"],{printOutputOnSuccess:!1}),i}};import{red as Uo,yellow as oa,gray as ia}from"colorette";import em from"ora";import{red as Kp}from"colorette";function Gn(n,e){n?n.fail(e):console.error(Kp(e)),process.exit(1)}import{green as Zp}from"colorette";function ra(n,e){return n+" ".repeat(Math.max(0,e-n.length))}function Xp(n,e){return n.map((t,r)=>{let o=t.length;for(let i of e){let s=i.cells[r]??"";o=Math.max(o,s.length)}return o})}function Zt(n,e){let t=Xp(n,e),r=[];r.push(n.map((o,i)=>ra(o,t[i])).join(" ")),r.push(t.map(o=>"-".repeat(o)).join(" "));for(let o of e){let i=o.cells.map((s,a)=>ra(s??"",t[a])).join(" ").trimEnd();r.push(o.highlight?Zp(i):i)}return r.join(`
|
|
57
|
+
`)}function tm(n,e){if(e.size!==0)for(let t of n){if(!t.isEmulator||!t.name)continue;let r=e.get(V(t.name));r&&(t.deviceType=r)}}var nm=["Name","Serial","Kind","Device Type"];function rm(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function om(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function im(){console.log(oa(" No active devices.")),console.log(ia(I()?" Connect a USB device with debugging enabled.":" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function sm(n){let t=[...n].sort(om).map(rm);console.log(Zt(nm,t))}async function am(n,e){if(I()||!n.some(o=>o.isEmulator)||!e.emulatorPath)return;let r=await wt.from(e).getDeviceTypeByName();tm(n,r)}async function cm(n,e,t){try{let r=await n.getConnectedEntries();await am(r,e),t?.stop(),r.length===0?im():sm(r)}catch(r){Gn(t,`Failed to list devices: ${r.message}`)}}async function lm(n,e){let t=await n.listDevices();if(!(t.length<2)){console.error(Uo("Multiple devices connected. Specify a device with:"));for(let r of t){let o=await n.getDeviceName(r.serial);console.error(ia(` ${e} -t ${r.serial} # ${o}`))}process.exit(1)}}async function dm(n,e){try{e||await lm(n,"devecocli device view");let t=await n.listDevices(),r=await n.getDeviceInfo(t,e);r||(console.log(oa("No connected device found.")),process.exit(1));let o=await n.getDeviceDetail(r.serial),i=await n.getDeviceName(r.serial);console.log(` Serial: ${r.serial}`),console.log(` Device Name: ${i}`),o.deviceType&&console.log(` Device Type: ${o.deviceType}`),o.osVersion&&console.log(` OS Version: ${o.osVersion}`)}catch(t){console.error(Uo(`Failed to show device details: ${t.message}`)),process.exit(1)}}async function sa(){try{let n=await _.new();return{manager:K.from(n),toolProvider:n}}catch(n){console.error(Uo(`Failed to initialize device manager: ${n.message}`)),process.exit(1);return}}var zo=new Qp("device").description("Manage connected devices");zo.command("list").description("List all connected devices").action(async()=>{let{manager:n,toolProvider:e}=await sa(),t=em({text:"Querying connected devices\u2026",color:"cyan"}).start();await cm(n,e,t)});zo.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").action(async n=>{let{manager:e}=await sa();await dm(e,n.target)});var aa=zo;import{Command as Jo,Option as Pa}from"commander";import{green as Jn,cyan as St,red as Q,yellow as ge,gray as Qt}from"colorette";import xm from"ora";import um from"readline/promises";import{execa as la}from"execa";import*as He from"fs/promises";import*as Vo from"os";import*as et from"path";var qo=`1/4:\r
|
|
64
58
|
---------------------------------------\r
|
|
65
59
|
Statement About HarmonyOS and Privacy\r
|
|
66
60
|
\r
|
|
@@ -1230,61 +1224,61 @@ Part I: Chinese mainland.\r
|
|
|
1230
1224
|
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
|
|
1231
1225
|
\r
|
|
1232
1226
|
Part III: Other countries and regions.\r
|
|
1233
|
-
---------------------------------------\r`;var
|
|
1234
|
-
`),
|
|
1235
|
-
`)}function
|
|
1236
|
-
${t}.`);return
|
|
1237
|
-
`,"utf8"),!0}catch{}return!1}async function
|
|
1227
|
+
---------------------------------------\r`;var pm=new Set,Yn=new Map,Go="HarmonyOS_Software_Service_Agreement",da=["Emulator license agreements are not accepted yet.","","Accept the agreements in an interactive terminal:"," devecocli emulator license accept","","To review the agreement text (read-only):"," devecocli emulator license view"].join(`
|
|
1228
|
+
`),ua=da,Yo="HarmonyOS_SDK_Agreement";function pa(n,e){return`${n}\0${e}`}function mm(){pm.clear(),Yn.clear()}var fm=da,de=class extends Error{constructor(e=fm){super(e),this.name="EmulatorLicenseBlockedError"}};function ma(n,e){return[n??"",e??""].join(`
|
|
1229
|
+
`)}function fa(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 hm(n){return`Emulator${n.trim()}`}function ha(n){let e=hm(n);if(process.platform==="win32"){let r=process.env.LOCALAPPDATA;if(!r)throw new Error("LOCALAPPDATA is not set; cannot resolve .emu_config path.");return et.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return et.join(Vo.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||et.join(Vo.homedir(),".cache");return et.join(t,"Huawei",e,".emu_config")}async function gm(n,e,t){let r=pa(n,e),o=Yn.get(r);if(o!==void 0)return o;let i=await la(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=ma(i.stdout,i.stderr).trim();if(i.exitCode!==0||!s)throw new de(t);return Yn.set(r,s),s}function ym(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function vm(n){try{let e=JSON.parse(n);if(e&&typeof e=="object"&&!Array.isArray(e)){let t={};for(let[r,o]of Object.entries(e))t[r]={value:typeof o=="string"?o:String(o),delimiter:"json"};return t}}catch{return}}function wm(n){let e=n.trim();if(!(!e||e.startsWith("#")))for(let t of["=",":"]){let r=e.indexOf(t);if(r<=0)continue;let o=e.slice(0,r).trim();if(!o||t===":"&&o.includes("//"))continue;let i=ym(e.slice(r+1).trim());return{key:o,entry:{value:i,delimiter:t}}}}function bm(n){let e={};for(let t of n.split(/\r?\n/)){let r=wm(t);r&&(e[r.key]=r.entry)}return e}function Sm(n){let e=n.trim();if(!e)return{};let t=vm(e);return t||bm(n)}function Pm(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function ga(n,e,t,r){let o=await gm(n,e,r),i=fa(o);if(!i)throw new de(r);let s=ha(i),a;try{a=await He.readFile(s,"utf8")}catch(u){throw u.code==="ENOENT"?new de(r):u}let l=Sm(a)[t];if(!l)throw new de(r);if(l.delimiter==="=")throw new de(r);if(!Pm(l.value))throw new de(r)}async function ya(n,e){await ga(n,e,Go,ua)}async function va(n,e){await ga(n,e,Yo,ua)}async function Em(n,e){let t=await la(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),r=ma(t.stdout,t.stderr).trim();if(t.exitCode!==0||!r)throw new Error(`Emulator -version failed (exit ${String(t.exitCode)}); cannot resolve .emu_config path.`);let o=pa(n,e);return Yn.set(o,r),r}async function Dm(n,e){let t=await Em(n,e),r=fa(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
|
|
1230
|
+
${t}.`);return ha(r)}function ca(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function Im(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[Go]="agree",r[Yo]="agree",await He.writeFile(n,`${JSON.stringify(r,null,2)}
|
|
1231
|
+
`,"utf8"),!0}catch{}return!1}async function Cm(n,e){let t=Go,r=Yo,o=[{k:t,re:new RegExp(`^\\s*${ca(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${ca(r)}\\s*[:=]`)}],i=e.length===0?[]:e.split(/\r?\n/),s=[],a=new Set;for(let c of i){let l=!1;for(let{k:u,re:h}of o)if(h.test(c)){s.push(`${u}:agree`),a.add(u),l=!0;break}l||s.push(c)}a.has(t)||s.push(`${t}:agree`),a.has(r)||s.push(`${r}:agree`),await He.writeFile(n,s.join(`
|
|
1238
1232
|
`)+(s.length>0?`
|
|
1239
|
-
`:""),"utf8")}async function Hm(n){await je.mkdir(et.dirname(n),{recursive:!0});let e="";try{e=await je.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await Lm(n,e,t)||await _m(n,e)}async function Ea(n,e){return console.log(Uo),0}var jm="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function Da(n,e){if(console.log(Uo),!process.stdin.isTTY||!process.stdout.isTTY)return console.error("`devecocli emulator license accept` requires an interactive terminal."),1;let r=Sm.createInterface({input:process.stdin,output:process.stdout}),o;try{o=await r.question(jm)}finally{r.close()}let i=o.trim().toLowerCase();if(i!=="y"&&i!=="yes")return 1;try{let s=await Nm(n,e);await Hm(s),Em()}catch(s){return console.error(s.message),1}return 0}var $m=["ohos.qemu.hvd.name","const.product.name","const.product.model"];function Bm(n){let e=n.trim();if(!e||!/^[A-Za-z0-9_ ]+$/.test(e))throw new Error("The virtual device name can only contain letters, spaces, numbers, and underscores (_).")}function Wm(n){let e=n.trim();if(!e)throw new Error("--os-version must not be empty.");if(/^\d+$/.test(e))throw new Error(`--os-version "${n}" is invalid. use the full image label, e.g. HarmonyOS 5.1.1(19).`);if(!/^HarmonyOS\s+/i.test(e))throw/^HarmonyOS$/i.test(e)?new Error('--os-version is incomplete (only "HarmonyOS"). On PowerShell/cmd, quote the full label, e.g. --os-version "HarmonyOS 6.0.1(21)".'):new Error(`Invalid --os-version "${n}". It must start with "HarmonyOS " (e.g. "HarmonyOS 5.1.1(19)").`)}function Um(n,e){let t=o=>o.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(ge("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(ge("Run `devecocli emulator image download ...` followed by `devecocli emulator image list` and then copy an `osVersion` string exactly.")),new Error("No downloaded osVersion values parsed; cannot validate --os-version.");if(!e.some(o=>t(o)===r)){console.error(te("--os-version does not match any downloaded image (exact string required).")),console.log(ge("Use one of these --os-version values:"));for(let o of e)console.log(` ${o}`);throw new Error(`No downloaded image matches --os-version "${n}".`)}}var zm=["Name","Status","Serial","Device Type","OS Version"];function qm(n,e,t){return{cells:[n.name,t?"running":"stopped",e??"-",n.deviceType??"-",n.osVersion??"-"],highlight:t}}async function Vm(n,e){let t=await Promise.all(e.map(async r=>{let o=await ft(n,r,$m);return[r,o]}));return new Map(t)}async function Gm(n){let e=await Ho(n),t=await Vm(n,e);return{serials:e,params:t}}function Ym(n,e,t,r,o){if(e)for(let i of["const.product.name","const.product.model"]){let s=e.get(i);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),o.set(s,n);let c=r.indexOf(n);c!==-1&&r.splice(c,1);return}}function Jm(n,e,t){let r=new Map,o=new Map,i=[...n],s=[...t];for(let a of n){let c=e.get(a),l=c?.get("ohos.qemu.hvd.name");l&&o.set(l,a),t.length>0&&Ym(a,c,s,i,r)}for(let a=0;a<s.length&&a<i.length;a++)r.set(s[a],i[a]);return{productSerialMap:r,hvdSerialMap:o}}function Km(n,e,t){let r=n.map(o=>({emu:o,serial:e.get(o.name)??t.get(o.name),effectiveRunning:o.isRunning===!0||t.has(o.name)}));return r.sort((o,i)=>o.effectiveRunning!==i.effectiveRunning?o.effectiveRunning?-1:1:o.emu.name.localeCompare(i.emu.name)),r.map(o=>qm(o.emu,o.serial,o.effectiveRunning))}async function Zm(n,e,t){try{let[r,o]=await Promise.all([n.listEmulators(),Gm(e)]);if(r.length===0){t?.stop(),console.log(ge(" No emulator instances found."));return}let i=r.filter(l=>l.isRunning).map(l=>l.name),{productSerialMap:s,hvdSerialMap:a}=Jm(o.serials,o.params,i);t?.stop();let c=Km(r,s,a);console.log(Zt(zm,c))}catch(r){Gn(t,`Failed to list emulators: ${r.message}`)}}function Aa(n,e,t){let r=!1;for(let o=0;o<n.length;o++){let i=n[o];if(i.status!=="rejected")continue;r=!0;let s=i.reason;console.error(te(`Failed to ${t} emulator "${e[o]}": ${s.message}`)),s.stdout&&console.error(Qt(s.stdout)),s.stderr&&console.error(Qt(s.stderr))}return r}var Xm=2e3,Qm=6e4;async function ef(n,e){let t=V(e);return(await jo(n)).some(o=>V(o)===t)}async function Ta(n,e,t,r=Qm,o=Xm){let i=Date.now()+r;for(;Date.now()<i;){if(await ef(n,e)===t)return!0;await new Promise(a=>setTimeout(a,o))}return!1}async function tf(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(ge(`Emulator "${t}" is already running.`));return}console.log(St(`Starting emulator "${t}"...`));let o=await Ta(e,t,!0);console.log(o?Jn(`Emulator "${t}" started successfully.`):ge(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function nf(n,e,t){let r=await Promise.allSettled(t.map(i=>tf(n,e,i)));Aa(r,t,"start")&&process.exit(1)}async function rf(n,e){let t=e.trim();if(!Yt(t))return t;let r=await K.withHdcPath(n).getDeviceName(t);if(r===t)throw new Error(`Cannot resolve a running emulator with serial "${t}". Use \`devecocli emulator list\` or pass the emulator name instead.`);return r}async function of(n,e,t){let r=await rf(e,t);if(console.log(St(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(ge(`Emulator "${r}" is already stopped.`));return}let i=await Ta(e,r,!1);console.log(i?Jn(`Emulator "${r}" stopped successfully.`):ge(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function sf(n,e,t){let r=await Promise.allSettled(t.map(i=>of(n,e,i)));Aa(r,t,"stop")&&process.exit(1)}async function ye(){try{let n=await _.new();return{manager:wt.from(n),toolProvider:n}}catch(n){console.error(te(`Failed to initialize emulator: ${n.message}`)),process.exit(1);return}}var Fe=new Go("emulator").description("Manage emulator instances"),af=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Kn(n){let e=new Ca("--device-type <type>","Emulator device type").choices([...af]);return n?e.makeOptionMandatory():e}function bt(n,e){for(let t of e)if(t in n)return n[t]}function Xt(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function Ia(n){let e=Xt(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var cf=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],lf="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function xa(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function ka(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let o=r,i=Xt(bt(o,["osVersion","OsVersion","OSVersion","os_version"])),s=Xt(bt(o,["deviceType","DeviceType","device_type"])),a=Ia(bt(o,["downloaded","Downloaded","isDownloaded"])),c=Xt(bt(o,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=Xt(bt(o,["releaseType","ReleaseType","release_type"])),u=Ia(bt(o,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[i,s,c,l,u,a],highlight:e&&a==="true"})}return t}function df(n){let e=n.trim();if(!e)return!0;let t=xa(e);return t===null?!1:t.length===0?!0:ka(t,!0).length===0}function uf(n,e){let t=n.trim();if(!t)return"";let r=xa(t);if(!r)return n.trimEnd();let o=ka(r,e);return Zt(cf,o)}var Zn=new Go("image").description("HarmonyOS emulator system images (download, list, remove)");Zn.command("download").description("Download system image").addOption(Kn(!1)).option("--os-version <version>","Example: HarmonyOS 5.1.1(19) or HarmonyOS 6.0.1(21) (required)").option("--force","Overwrite an existing image").action(async n=>{let{manager:e,toolProvider:t}=await ye();try{await Pa(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof de&&(console.error(te(r.message)),process.exit(1)),r}n.deviceType?.trim()||(console.error(te("Error: missing required option '--device-type <type>'")),process.exit(1)),n.osVersion?.trim()||(console.error(te("Error: misssing required option '--os-version <version>'")),process.exit(1));try{await e.installEmulatorImage({deviceType:n.deviceType.trim(),osVersion:n.osVersion.trim(),force:n.force===!0})}catch(r){console.error(te(`Failed to download system image: ${r.message}`)),process.exit(1)}});Zn.command("remove").description("Remove a downloaded system image").addOption(Kn(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let{manager:e}=await ye();try{await e.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})}catch(t){console.error(te(`Failed to remove system image: ${t.message}`)),process.exit(1)}});Zn.command("list").description("List system images").addOption(Kn(!1)).option("--all","List all images (local and remote)").addOption(new Ca("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await ye();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if(df(r)){console.log(ge(lf));return}if(n.format==="json"){console.log(r.trimEnd());return}let o=uf(r,n.all===!0);console.log(o)}catch(t){console.error(te(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});Fe.addCommand(Zn);var Yo=new Go("license").description("local emulator license");Yo.command("view").description("Review agreement text(read-only)").action(async()=>{let{toolProvider:n}=await ye(),e=await Ea(n.emulatorPath,n.sdkPath);process.exit(e)});Yo.command("accept").description("Review and accept agreements").action(async()=>{let{toolProvider:n}=await ye(),e=await Da(n.emulatorPath,n.sdkPath);process.exit(e)});Fe.addCommand(Yo);Fe.command("list").description("List all emulator instances").action(async()=>{let{manager:n,toolProvider:e}=await ye(),t=Fm({text:"Listing emulators\u2026",color:"cyan"}).start();await Zm(n,e.hdcPath,t)});Fe.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await ye();try{await Sa(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof de&&(console.error(te(r.message)),process.exit(1)),r}n?.length||(console.error(te("Error: missing required argument 'names'")),process.exit(1)),await nf(e,t.hdcPath,n)});Fe.command("stop <names...>").description("Stop one or more emulator instances (by name or serial,e.g.,127.0.0.1:<port>)").action(async n=>{let{manager:e,toolProvider:t}=await ye();n?.length||(console.error(te("Error: missing required argument 'names'")),process.exit(1)),await sf(e,t.hdcPath,n)});var Ma=Fe.command("create <name>").description("Create a local emulator by running emulator -create <name> \u2026. --os-version must match a downloaded image from `emulator image list`.").addOption(Kn(!0)).requiredOption("--os-version <version>",'Downloaded image label. which will be quoted in PowerShell (e.g. "HarmonyOS 6.0.1(21)") or be used in the format --os-version="\u2026";For details, run`devecocli emulator image list`.').option("--force","Overwrite if supported");Ma.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
|
|
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(`
|
|
1240
1234
|
${ge("Tip: ")}${Qt("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
|
|
1241
1235
|
${St('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
|
|
1242
1236
|
${St('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
|
|
1243
|
-
`)}});
|
|
1244
|
-
${r}`)})}async get(e,t){let r=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}async post(e,t){let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,headers:e.headers}}parseJson(e){return JSON.parse(e.data)}async getBinary(e,t){let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout});if(r.status!==200)throw new Error(`HTTP ${r.status}`);return Buffer.from(r.data)}},$e=new Jo;var La=["DevEco"];async function Xn(){let n=await $e.get(ce.TAGS_API_URL),t=Qn(n,"Tags API").data.skill.filter(r=>r.name==="HMOS");if(t.length===0)throw new Error("No HMOS tag found.");return t.map(r=>r.id)}async function ff(n){let e=[],t=ce.DEFAULT_PAGE_SIZE,r=1;for(;;){let o=await $e.post(ce.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:r,pageSize:t,tagIds:[n]}}),i=Qn(o,"Skills API");if(e.push(...i.data.list),i.data.list.length<t)break;r++}return e}async function Ko(n){let e=new Map,t=n.map(o=>ff(o)),r=await Promise.all(t);for(let o of r)for(let i of o)e.has(i.id)||e.set(i.id,i);return Array.from(e.values()).filter(o=>o.tags?.every(i=>!La.includes(i.name)))}async function hf(n,e){let t=await $e.post(ce.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:ce.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return Qn(t,"Skills API").data.list}async function Zo(n,e){let t=new Map,r=e.map(i=>hf(n,i)),o=await Promise.all(r);for(let i of o)for(let s of i)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(i=>i.tags?.every(s=>!La.includes(s.name)))}function _a(n){let e=[],t=Se();for(let[,r]of Object.entries(t)){let o=Na.join(r.path,n);Oa.existsSync(o)&&e.push(r.displayName)}return e.sort()}function Qn(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=$e.parseJson(n);if(t.code!==ce.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Ha(n){let e=`${ce.SKILL_API_BASE}/${n}/checksum`,t=await $e.get(e);return Qn(t,"Checksum API").data}import gf from"adm-zip";import yf from"crypto";import Fa from"fs";import H from"path";import{fileURLToPath as vf}from"url";import{red as wf}from"colorette";var Ee=Fa.promises;function Xo(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function ja(n,e){let t=H.resolve(e),r=H.resolve(n),o=H.relative(r,t);if(o.startsWith("..")||H.isAbsolute(o))throw new Error(`Path traversal detected: ${e}.`)}function Qo(n){return H.isAbsolute(n)?n:H.resolve(process.cwd(),n)}function bf(n){return yf.createHash("sha256").update(n).digest("hex")}async function Sf(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=bf(n),o=e.sha256.toLowerCase();if(r!==o)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function $a(n){let e=`${ce.SKILL_API_BASE}/${n}/install?format=zip`,t=await $e.getBinary(e),r=await Ha(n);return await Sf(t,r),t}async function Pf(n,e,t){Xo(t);let r=new gf(n),o=r.getEntries();try{await Ee.stat(e)}catch{await Ee.mkdir(e,{recursive:!0})}let i=H.join(e,t);ja(e,i);for(let s of o){let a=H.join(i,s.entryName);ja(i,a)}r.extractAllTo(i,!0)}async function ei(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 ti(n){return Se()[n].path}function ni(n,e){let r=Se()[e],o="projectPath"in r?r.projectPath:H.join("."+e,"skills");return H.join(n,o)}async function Ef(n,e,t){Xo(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 ri(n,e,t){await Pf(n,e,t),console.log(`Skill ${t} installed to ${H.join(e,t)}.`)}async function oi(n,e,t){let r=H.join(e,t);await Ee.mkdir(r,{recursive:!0});let o=H.join(r,H.basename(n));await Ee.copyFile(n,o),console.log(`Skill ${t} installed to ${r}.`)}function Ba(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(wf(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function Pt(n,e,t,r){try{let o=await e(),{shouldSkip:i}=await Ef(o,n,r);return i?{success:!0,skipped:!0}:(await t(o),{success:!0})}catch(o){return Ba(n,o,"Installation failed")}}async function ii(n,e){try{Xo(n);let t=await e(),r=H.join(t,n);try{await Ee.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await Ee.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return Ba(n,t,"Removal failed")}}async function Wa(n,e,t,r=!1){return Pt(n,()=>ti(e),o=>ri(t,o,n),r)}async function Ua(n,e,t,r=!1){return Pt(n,()=>t,o=>ri(e,o,n),r)}async function za(n,e,t,r,o=!1){return Pt(n,()=>ni(t,r),i=>ri(e,i,n),o)}async function qa(n,e,t,r=!1){return Pt(n,()=>ti(t),o=>oi(e,o,n),r)}async function Va(n,e,t,r,o=!1){return Pt(n,()=>ni(t,r),i=>oi(e,i,n),o)}async function Ga(n,e,t,r=!1){return Pt(n,()=>t,o=>oi(e,o,n),r)}async function Ya(n,e){return ii(n,()=>ti(e))}async function Ja(n,e){return ii(n,()=>e)}async function Ka(n,e,t){return ii(n,()=>ni(e,t))}function Za(){let e=H.dirname(vf(import.meta.url));for(;;){let t=H.join(e,"SKILL.md");if(Fa.existsSync(t))return t;let r=H.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import Xa from"fs";import{cyan as Df}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 ei(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 ei(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(Df("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function Be(n,e,t){if(!Xa.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!Xa.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function rn(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?Qo(n):void 0,resolvedProject:e?Qo(e):void 0}}async function er(n,e,t){let r=[],o=[],i;if(e?i=e:t&&n.agent?o=(await en(n.agent)).map(a=>({project:t,agent:a})):t?o=(await tn()).map(a=>({project:t,agent:a})):n.agent?r=await en(n.agent):r=await tn(),!i&&r.length===0&&o.length===0)throw new Error("No agents found. Install an AI agent (opencode, etc.) or use `--path` for a custom location.");return{agents:r,projectAgents:o,customPath:i}}async function Tf(n){let e=await Xn();if(n.all)return(await Ko(e)).map(r=>r.enName);{let r=(await Zo(n.skill,e)).find(o=>o.enName===n.skill);if(!r)throw new Error(`Skill "${n.skill}" not found`);return[r.enName]}}async function xf(n,e,t,r){let o=[];if(t.customPath){let i=await Ua(n,e,t.customPath,r);return o.push(i),o}for(let i of t.agents){let s=await Wa(n,i,e,r);o.push(s)}for(let{project:i,agent:s}of t.projectAgents){let a=await za(n,e,i,s,r);o.push(a)}return o}function kf(n){if(n.all&&n.skill)throw new Error("`--all` and `--skill` cannot be specified together.");if(!n.all&&!n.skill)throw new Error("Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=rn(n.path,n.project,n.agent);return t&&Be(t,"Project directory",n.force),e&&Be(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}async function Mf(n,e,t){let r=await er(n,e,t);return{skillNames:await Tf(n),targets:r}}async function Rf(n){try{let e=await $a(n);return{name:n,buffer:e,success:!0}}catch(e){let t=e instanceof Error?e.message:"unknown error";return{name:n,error:t,success:!1}}}async function Of(n,e,t,r){let o=[],i=n.length,s=Af(5),a=n.map(c=>s(()=>Rf(c)));for(let c=0;c<n.length;c++){let l=n[c],u=i>1?` (${c+1}/${i})`:"";r.start(`Installing ${l}${u}...`);let h=await a[c];if(!h.success){r.fail(),console.log(on(`${l}: Download failed - ${h.error}`)),o.push({success:!1});continue}r.stop();let v=await xf(l,h.buffer,e,t);o.push(...v)}return o}async function Nf(n){let e=new tt;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=kf(n),{skillNames:o,targets:i}=await Mf(n,t,r),s=await Of(o,i,n.force||!1,e);e.stop(),nn(s)}catch(t){throw e.stop(),t}}function Lf(n){let{resolvedPath:e,resolvedProject:t}=rn(n.path,n.project,n.agent);return t&&Be(t,"Project directory"),e&&Be(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function _f(n,e){let t=new tt;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:o}=Lf(e);t.stop();let i=await Hf(e,n,r,o);t.stop(),nn(i)}catch(r){throw t.stop(),r}}function Qa(n,e=""){if(n.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function tr(n,e){let t=[];for(let r of e){let o=r.type==="agent"?await Ya(n,r.agent):await Ka(n,r.project,r.agent);t.push(o)}return t}async function Hf(n,e,t,r){if(t)return[await Ja(e,t)];if(r&&n.agent){let a=(await en(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return tr(e,a)}if(r){let s=await tn();Qa(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return tr(e,a)}if(n.agent){let a=(await en(n.agent)).map(c=>({type:"agent",agent:c}));return tr(e,a)}let o=await tn();Qa(o,"or use --path for a custom location.");let i=o.map(s=>({type:"agent",agent:s}));return tr(e,i)}var sn=new If("skills").description("Manage HarmonyOS skills");sn.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async n=>{let e=new tt;try{e.start("Fetching skills...");let t=await Xn(),r=await Ko(t);if(r.length===0){e.stop(),console.log(tc("No skills available."));return}e.succeed(`Fetched ${r.length} skills`);for(let o of r)if(n.long){console.log(ec(o.enName)),console.log(nc(o.description));let i=_a(o.enName);i.length>0&&console.log(Cf(`Installed for: ${i.join(", ")}`)),console.log()}else console.log(o.enName)}catch(t){e.stop(),console.error(on(t.message)),process.exit(1)}});sn.command("find <keyword>").description("Search skills by keyword").action(async n=>{let e=new tt;try{e.start("Searching skills...");let t=await Xn(),r=await Zo(n,t);if(r.length===0){console.log(tc(`No skills found matching '${n}'.`)),e.stop();return}e.succeed(`Found ${r.length} skills.`);for(let o of r)console.log(ec(o.enName)),console.log(nc(o.description)),console.log()}catch(t){e.stop(),console.error(on(t.message)),process.exit(1)}});sn.command("add").description("Install skills to AI agents").option("--all","Install all available skills").option("--agent <agents>","Target agents, comma-separated; Omit to install to all available agents.").option("--skill <skill-name>","Name of the skill to install").option("-f, --force","Overwrite an existing skill installation").option("--project <path>","Project root directory for skill installation").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").action(async n=>{try{await Nf(n)}catch(e){console.error(on(e.message)),process.exit(1)}});sn.command("remove").description("Remove an installed skill from AI agents").requiredOption("--skill <skill-name>","Name of the skill to remove").option("--agent <agents>","Target agents, comma-separated.Omit to remove from all available agents").option("--project <path>","Project root directory for skill removal").option("--path <path>","Path for skill removal").action(async n=>{try{await _f(n.skill,n)}catch(e){console.error(on(e.message)),process.exit(1)}});var rc=sn;import{Command as Ff,InvalidArgumentError as sc}from"commander";import{cyan as nr}from"colorette";function nt(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=mt(t);return r==="transient"?new Error(`${e}: Device communication channel unavailable. Retry in a few seconds.`):r==="fatal"?new Error(`${e}: ${t.trim()}`):null}var si=[800,1500,2500];function jf(n){return new Promise(e=>setTimeout(e,n))}function oc(){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(`
|
|
1237
|
+
`)}});Aa.action(async(n,e)=>{try{Rm(n),Mm(e.osVersion);let{manager:t}=await ye(),r=await t.listDownloadedImageOsVersions();Om(e.osVersion,r),console.log(St(`Creating emulator "${n}"...`)),await t.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(Jn(`Emulator "${n}" created successfully.`))}catch(t){console.error(Q(`${t.message}`)),process.exit(1)}});je.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let{manager:e}=await ye();console.log(St(`Deleting emulator "${n}"...`));try{let t=await e.deleteVirtualDevice(n);console.log(Jn(`Emulator "${t}" deleted successfully.`))}catch(t){let r=t;console.error(Q(r.message)),r.stdout&&console.error(Qt(r.stdout)),r.stderr&&console.error(Qt(r.stderr)),process.exit(1)}});var Ta=je;import{Command as hf}from"commander";import{green as gf,red as on,cyan as Ka,yellow as Za,dim as Xa}from"colorette";import yf from"p-limit";import tf from"ora";var tt=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=tf(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 xa from"fs";import*as ka from"path";import nf from"axios";var Zo=class{client;constructor(){let e={timeout:Co.HTTP_TIMEOUT_MS,headers:{"User-Agent":Hn.USER_AGENT,"accept-language":Hn.ACCEPT_LANGUAGE},transformResponse:[t=>t],proxy:!1};this.client=nf.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}
|
|
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(`
|
|
1245
1239
|
`)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let o=t[0];return g(nr(`Using device serial: ${o}`)),o}if(e&&t.includes(e))return g(nr(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let o=this.findDeviceByArg(r,e);if(o)return g(nr(`Using device: ${o.name} (${o.serial})`)),o.serial;let i=this.formatConnectedDeviceList(r);throw new Error(`Device '${e}' not found.
|
|
1246
1240
|
Available devices:
|
|
1247
|
-
${i}`)}if(r.length===1){let o=r[0];return g(nr(`Using device: ${o.name} (${o.serial})`)),o.serial}throw new Error("Multiple devices found. Specify a target device using `--device <name>` or `--device <serial>`.\nAvailable devices:\n"+this.formatConnectedDeviceList(r))}async getConnectedDeviceSerials(){let e=await this.deviceManager.listDevices();if(e.length===0)throw new Error(
|
|
1241
|
+
${i}`)}if(r.length===1){let o=r[0];return g(nr(`Using device: ${o.name} (${o.serial})`)),o.serial}throw new Error("Multiple devices found. Specify a target device using `--device <name>` or `--device <serial>`.\nAvailable devices:\n"+this.formatConnectedDeviceList(r))}async getConnectedDeviceSerials(){let e=await this.deviceManager.listDevices();if(e.length===0)throw new Error(ec());return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error(ec());return e}async getPidForBundle(e,t,r){g(`Retrieving PID for bundle ${r}`),P.assertBundleName(r);let o=await Vt(e,["-t",t,"shell","pidof",r]),i=nt(o,"Failed to look up PID");if(i)throw i;if(o.exitCode===0&&o.stdout.trim()){let s=o.stdout.trim(),a=s.split(/\s+/)[0]||s;return g(`Found PID for ${r}: ${a}`),a}return g(`No PID found for bundle: ${r}`),null}async resizeHilogBuffer(e,t,r){g(`Setting hilog buffer size to: ${r}`);let o=await Vt(e,["-t",t,"shell","hilog","-G",r]),i=nt(o,"Failed to resize hilog buffer");if(i)throw i;o.exitCode!==0&&console.error(`Failed to resize hilog buffer: ${o.stderr||o.stdout}`)}buildHilogCommand(e,t,r,o){let i=this.buildHilogShellCommand(r,o);return[e,["-t",t,"shell",i]]}buildHilogShellCommand(e,t){let r=["hilog"];return e.isFollow||r.push("-x"),e.tag&&(P.assertHilogToken(e.tag,"tag"),r.push("-T",e.tag)),e.level&&(P.assertHilogLevel(e.level),r.push("-L",e.level)),e.domain&&(P.assertHilogToken(e.domain,"domain"),r.push("-D",e.domain)),t&&r.push("-P",t),e.keyword&&(P.assertHilogKeyword(e.keyword),r.push("-e",P.quotePosixShellArg(e.keyword))),r.join(" ")}async followHilog(e,t,r,o,i){let a=await Ws(e,t,{onData:r,onError:o,onClose:i});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}async runHilogWithSpawnRetry(e,t,r,o,i){let s=1+ci.length,a={stdout:"",stderr:"",exitCode:-1};for(let c=0;c<s;c++){if(a=await this.followHilog(e,t,r,o,i),a.exitCode===0||mt(a.stderr)!=="transient"||c>=s-1)return a;g(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${ci[c]}ms`),await Tf(ci[c])}return a}async runHilogStreamingCollect(e,t,r){return this.runHilogWithSpawnRetry(e,t,()=>{},o=>{g(`Callback triggered when an error occurs during ${r}: ${o.message}`)},()=>{})}async printTailSnapshotIfNeeded(e,t,r,o){if(!r.tail&&!r.fromSeconds&&!r.toSeconds)return;let i={...r,isFollow:!1},[s,a]=this.buildHilogCommand(e,t,i,o);g(`Ready to run hilog snapshot command: ${s} ${a.join(" ")}`);let c=await this.runHilogStreamingCollect(s,a,"a hilog snapshot streaming read"),l=nt(c,"Failed to get hilog");if(l)throw l;if(c.exitCode!==0&&c.stderr)throw new Error(`Failed to get hilog: ${c.stderr}`);let u=P.filterLogsByRelativeWindow(c.stdout||c.stderr,r.fromSeconds,r.toSeconds);u=P.getLastLines(u,r.tail),u.trim()&&console.log(u)}async getHilogOnce(e,t,r,o){let[i,s]=this.buildHilogCommand(e,t,r,o);g(`Ready to run hilog command: ${i} ${s.join(" ")}`);let a=await this.runHilogStreamingCollect(i,s,"a single hilog streaming read"),c=nt(a,"Failed to get hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to get hilog: ${a.stderr}`);let l=a.stdout||a.stderr,u=P.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return u=P.getLastLines(u,r.tail),u}async runHilogFollow(e,t,r,o){try{await this.printTailSnapshotIfNeeded(e,t,r,o)}catch(l){console.error(`Warning: Failed to fetch log snapshot, continuing with live stream: ${l.message}`)}let[i,s]=this.buildHilogCommand(e,t,r,o);g(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${i} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(i,s,this.createFollowLineHandler(),l=>{g(`Spawn error during hilog follow: ${l.message}`)},()=>{}),c=nt(a,"Failed to follow hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to follow hilog: ${a.stderr}`);return""}async getHilog(e,t){let r=this.toolProvider.hdcPath,o=t.bundleName?await this.getPidForBundle(r,e,t.bundleName):void 0;if(t.bundleName&&!o)throw new Error(`No running process found for bundle '${t.bundleName}'. Ensure the app is launched on the device before fetching logs.`);return t.logSize&&await this.resizeHilogBuffer(r,e,t.logSize),t.isFollow?await this.runHilogFollow(r,e,t,o||""):await this.getHilogOnce(r,e,t,o||"")}async getCrashLog(e,t){g(`Fetching crash logs from device: ${e}`);let r=this.toolProvider.hdcPath,o=await this.listCrashLogs(r,e,t);if(o.length===0)return t?`No crash logs found for bundle '${t}'.`:"No crash logs found.";let s=[...o].sort((c,l)=>{let u=c.split("-").pop()||"";return(l.split("-").pop()||"").localeCompare(u)})[0],a=await this.fetchCrashLogContent(r,e,s);return`--- Latest Crash Log File: ${s} ---${a}`}async listCrashLogs(e,t,r){let o=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];g(`Running command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log list streaming read"),s=nt(i,"Failed to list crash logs");if(s)throw s;if(i.exitCode!==0)throw new Error(`Failed to list crash logs: ${i.stderr||i.stdout}`);return g(`Crash logs list output:
|
|
1248
1242
|
${i.stdout}`),this.parseCrashLogFilenames(i.stdout,r)}parseCrashLogFilenames(e,t){return e.split(`
|
|
1249
|
-
`).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 ai,red as ac}from"colorette";import $f from"ora";function Bf(n){try{return P.parsePositiveInteger(n,"tail")}catch{throw new sc("`tail` must be a positive integer.")}}function ic(n,e){try{return P.parseDurationToSeconds(n,e)}catch{throw new sc(`${e} must be a valid duration string (e.g.,30s, 5m or 2.5m).Supported units: s and m.when specified in seconds(with \`s\` or as a raw number), the value must be an integer.`)}}function Wf(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.");P.assertRelativeTimeRange(n.from,n.to)}async function Uf(n,e,t,r,o){return t.crash?await n.getCrashLog(e,t.bundleName):await n.getHilog(e,{level:t.level,bundleName:t.bundleName,keyword:t.keyword,isFollow:!!t.follow,tail:t.tail,fromSeconds:r,toSeconds:o})}function zf(n,e,t,r){let o=P.filterLogsByRelativeWindow(n,t,r);return e.tail?P.getLastLines(o,e.tail):o}var qf=new Ff("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(ac(n))}).option("--device <device>","Target device (name or serial)").option("--crash","Only obtain crash logs").option("--level <level>","Log level filter: D, I, W, E, F").option("--bundle-name <bundle-name>","Filter by application bundle name").option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",Bf).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>ic(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>ic(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await Vf(n)});async function Vf(n){let e=$f({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),Wf(n);let r=n.from,o=n.to,i=await _.new(),s=new rr(i),a=await s.selectDevice(n.device);a||(t(),process.exit(1)),g(ai(`deviceId: ${a}`)),g(ai(`type: ${n.crash?"Crash logs":"Common logs"}`)),g(ai("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await Uf(s,a,n,r,o);t(),n.crash&&c&&(c=zf(c,n,r,o)),c&&console.log(c)}catch(r){t(),console.error(ac(r.message)),process.exit(1)}}var cc=qf;import cn from"path";import De from"fs";import di from"process";import hc from"os";import{Command as ih}from"commander";import{green as pc,red as ci,cyan as sh,yellow as li}from"colorette";import F from"fs-extra";import R from"path";import*as lc from"os";import{fileURLToPath as Gf}from"url";var Yf={17:{sdkVersion:"5.0.5(17)",modelVersion:"5.0.5"},18:{sdkVersion:"5.1.0(18)",modelVersion:"5.1.0"},19:{sdkVersion:"5.1.1(19)",modelVersion:"5.1.1"},20:{sdkVersion:"6.0.0(20)",modelVersion:"6.0.0"},21:{sdkVersion:"6.0.1(21)",modelVersion:"6.0.1"},22:{sdkVersion:"6.0.2(22)",modelVersion:"6.0.2"},23:{sdkVersion:"6.1.0(23)",modelVersion:"6.1.0"},24:{sdkVersion:"6.1.1(24)",modelVersion:"6.1.1"}},Jf=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function Kf(){let n=import.meta.url,e=Gf(n);if(e.includes("dist")){let i=R.dirname(e),s=R.dirname(i);return R.join(s,"templates","application")}let t=R.dirname(e),r=R.dirname(t),o=R.dirname(r);return R.join(o,"templates","application")}function dc(n,e){F.mkdirSync(e,{recursive:!0});for(let t of F.readdirSync(n,{withFileTypes:!0})){let r=R.join(n,t.name),o=R.join(e,t.name);if(t.isDirectory()){dc(r,o);continue}F.existsSync(o)||(F.mkdirSync(R.dirname(o),{recursive:!0}),F.copyFileSync(r,o))}}function an(n,e){let t=F.readFileSync(n,"utf-8"),r=t;for(let[o,i]of e)r=r.replaceAll(o,i);r!==t&&F.writeFileSync(n,r,"utf-8")}function Zf(n,e){if(e===22)return;let t=Yf[e];t&&(an(R.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),an(R.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),an(R.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function Xf(n){return Jf.filter(t=>!F.existsSync(R.join(n,t))).length===0}function Qf(){return Buffer.from([137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,1,0,0,0,1,8,2,0,0,0,144,119,83,222,0,0,0,12,73,68,65,84,8,215,99,248,255,255,255,0,5,254,2,254,0,0,0,0,73,69,78,68,174,66,96,130])}function eh(n){return lc.platform()==="darwin"?R.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):R.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function th(n,e){let t=eh(e);if(!F.existsSync(t))return!1;let r=[["AppScope/resources/base/media/background.png","AppScope/resources/base/media/background.png"],["AppScope/resources/base/media/foreground.png","AppScope/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/background.png"],["entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/startIcon.png","entry/src/main/resources/base/media/startIcon.png"]];for(let[o,i]of r){let s=R.join(t,o),a=R.join(n,i);F.existsSync(s)&&(F.mkdirSync(R.dirname(a),{recursive:!0}),F.copyFileSync(s,a))}return!0}function nh(n){let e=Qf(),t=["AppScope/resources/base/media/background.png","AppScope/resources/base/media/foreground.png","entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/startIcon.png"];for(let r of t){let o=R.join(n,r);F.mkdirSync(R.dirname(o),{recursive:!0}),F.writeFileSync(o,e)}}function rh(n,e){e&&th(n,e)||nh(n)}function oh(n){let e=[R.join(n,"gitignore.txt"),R.join(n,"entry","gitignore.txt")];for(let t of e)F.existsSync(t)&&F.renameSync(t,t.replace(/\/gitignore\.txt$/,"/.gitignore"))}function uc(n,e,t,r,o){let i=Kf();if(!F.existsSync(i))throw new Error(`Template directory not found: ${i}`);F.mkdirSync(n,{recursive:!0}),dc(i,n),oh(n),rh(n,o),an(R.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),an(R.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),Zf(n,r);let s=Xf(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function ah(n){if(n.length<1||n.length>200)throw new Error(`App name length must be 1-200 characters. Current: ${n.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(n))throw new Error("Application name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function ch(n){if(n.length<7||n.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${n.length}`);if(n.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let e=n.split(".");if(e.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let t=/^[a-zA-Z0-9_]+$/;for(let r=0;r<e.length;r++){let o=e[r];if(!t.test(o))throw new Error(`Segment "${o}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(r===0){if(!/^[a-zA-Z]/.test(o))throw new Error(`First segment "${o}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(o))throw new Error(`Segment "${o}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(o))throw new Error(`Segment "${o}" must end with a letter or digit.`)}}function gc(n){if(hc.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function mc(n){if(n.length===0)throw new Error("Project path cannot be empty.");if(n.length>120)throw new Error(`Project path cannot exceed 120 characters (current: ${n.length}).`);let e=hc.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(n)){let i=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new Error(`Project path can only contain ${i}.`)}let r=gc(n);if(/[\u4e00-\u9fff]/.test(r))throw new Error("Project path cannot contain Chinese characters.");if(r.endsWith("."))throw new Error("Project path cannot end with a dot (.)")}function lh(n){let e=n,t=cn.parse(n).root;for(;e!==t;){if(De.existsSync(e))return e;e=cn.dirname(e)}return De.existsSync(t)?t:null}function fc(n){let e=lh(n);if(!e)throw new Error(`No existing parent directory found for '${n}'. Cannot create project directory.`);try{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 dh(n){return`com.example.${n.toLowerCase()}`}function uh(n,e){if(e){let o=gc(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 fc(i);return i}let t=di.cwd(),r=cn.join(t,n);if(De.existsSync(r))throw new Error(`Directory '${r}' already exists. Cannot create project here.`);return fc(r),r}function ph(n,e){let t=e?.getMaxApiLevel(),r=23;if(n.apiLevel){let o=Number(n.apiLevel);if(!Number.isInteger(o)||o<17)throw new Error(`Invalid API version ${n.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(o>t)throw new Error(`Invalid API version ${n.apiLevel}. Your SDK supports API version 17-${t}`)}else if(o>r){let i=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 mh(){try{return await _.new()}catch(n){let e=n,t=I()?"Toolchain not found":"DevEco Studio not found";console.error(li(`${t}: ${e.message}`)),I()?console.log(li("Please install commandLineTools. Use placeholder API level instead.")):console.log(li("Use placeholder API level instead."));return}}var fh=new ih("create").description("Scaffold a new HarmonyOS application project").option("--project-path <path>","Project directory path (default: ./<app-name>)").option("--app-name <name>","Application name").option("--bundle-name <bundle>","Bundle name (auto-derived as com.example.<app-name> if omitted)").option("--api-level <level>","API level (auto-detected from SDK if omitted; minimum: 17)").action(async n=>{try{n.appName||(console.error(ci("Error: --app-name is required")),di.exit(1));let e=n.appName;ah(e);let t=n.bundleName||dh(e);ch(t),n.projectPath&&mc(n.projectPath);let r=uh(e,n.projectPath);mc(r),console.log(sh("Initializing project...")),console.log(`Project path: ${r}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let o=await mh(),i=ph(n,o);console.log(`API level: ${i}`);let s=o?.devecoStudioPath,a=uc(r,e,t,i,s);console.log(`
|
|
1250
|
-
`+
|
|
1251
|
-
Failed to create project.`)),console.error(
|
|
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
|
+
`+cc("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(cc("Template integrity check passed."))}catch(e){let t=e;console.error(di(`
|
|
1245
|
+
Failed to create project.`)),console.error(di(t.message)),pi.exit(1)}}),mc=oh;import{Command as uh}from"commander";import{red as ph,cyan as bc}from"colorette";import ih from"fs";import or from"path";import{cyan as sh}from"colorette";import*as ir from"smol-toml";var Et=ih.promises;async function ah(n){try{let e=await Et.readFile(n,"utf8");return e.trim()===""?{}:JSON.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read configuration file ${n}: ${e.message}`,{cause:e})}}async function ch(n){try{let e=await Et.readFile(n,"utf8");return e.trim()===""?{}:ir.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read TOML config file ${n}: ${e.message}`,{cause:e})}}async function lh(n,e){let t=or.dirname(n);await Et.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await Et.writeFile(n,r,"utf8")}async function dh(n,e){let t=or.dirname(n);await Et.mkdir(t,{recursive:!0});let r=ir.stringify(e);await Et.writeFile(n,r,"utf8")}function fc(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function hc(n,e,t,r,o){(!n[e]||typeof n[e]!="object")&&(n[e]={});let i=n[e];return t in i&&!o?!1:(i[t]=r,!0)}async function gc(n,e){return n.format==="codex"?ch(e):ah(e)}async function yc(n,e,t){return n.format==="codex"?dh(e,t):lh(e,t)}async function vc(n,e,t=!1){let r=Ne[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Ne).join(", ")}`};if(!r.supportsGlobal)return{success:!1,error:`${r.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let o=await gc(r,r.globalConfigPath);if(fc(o,r.mcpServersKey,fe)&&!t)return console.log(`MCP server ${fe} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let i=jn(r,void 0);return hc(o,r.mcpServersKey,fe,i,t),await yc(r,r.globalConfigPath,o),console.log(`MCP server ${fe} configured in ${r.globalConfigPath}.`),{success:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${o.message}`}}}async function mi(n,e,t=!1){let r=Ne[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Ne).join(", ")}`};let o=or.isAbsolute(r.projectConfigPath)?r.projectConfigPath:or.join(e,r.projectConfigPath);try{let i=await gc(r,o);if(fc(i,r.mcpServersKey,fe)&&!t)return console.log(`MCP server ${fe} already configured in ${o}.`),{success:!0,skipped:!0,configPath:o,agentName:n,installType:"project"};let s=jn(r,e);return hc(i,r.mcpServersKey,fe,s,t),await yc(r,o,i),console.log(`MCP server ${fe} configured in ${o}.`),{success:!0,configPath:o,agentName:n,installType:"project"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${i.message}`}}}function wc(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(sh("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`);for(let o of n)!o.success&&o.error&&console.error(` - ${o.agentName??"unknown"}: ${o.error}`);r>0&&(process.exitCode=1)}var fi="deveco-cli";async function mh(n,e,t){if(n.customPath)return[await Ua(fi,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>Wa(fi,e,s,a,t.force)),...n.agents.map(s=>()=>Ba(fi,e,s,t.force))],o=5,i=[];for(let s=0;s<r.length;s+=o){let a=r.slice(s,s+o);i.push(...await Promise.all(a.map(c=>c())))}return i}async function fh(n,e,t){let r=[];for(let{project:o,agent:i}of n.projectAgents){let s=await mi(i,o,t);r.push(s)}for(let o of n.agents){let i=await mi(o,e,t);r.push(i)}return r}async function hh(n,e){let t=[];for(let r of n){if(!Ne[r])continue;let i=await vc(r,process.cwd(),e);t.push(i)}return t}async function gh(n,e,t){if(t.agent&&t.agent.split(",").map(l=>l.trim()).includes("qoder"))throw new Error("Qoder does not support MCP configuration via DevEco CLI. Use other supported agents instead.");let r=t.force??!1,o=n.projectAgents.filter(c=>c.agent!=="qoder"),i=n.agents.filter(c=>c!=="qoder"),s={...n,projectAgents:o,agents:i},a=e?await fh(s,e,r):await hh(s.agents,r);a.length>0&&(console.log(bc("MCP Configuration:")),wc(a))}async function yh(n){if(n.skill&&n.mcp)throw new Error("Cannot use `--skill` and `--mcp` together. Use `--skill` for skill installation only, or `--mcp` for MCP configuration only.");let{resolvedPath:e,resolvedProject:t}=rn(n.path,n.project,n.agent);t&&$e(t,"Project directory",n.force),e&&$e(e,"Directory",n.force);let r=await er(n,e,t);if(n.mcp){await gh(r,t,n);return}let o=Ga(),i=await mh(r,o,n);console.log(),i.length>0&&(console.log(bc("Skill Installation:")),nn(i))}var vh=new uh("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 yh(n)}catch(e){console.error(ph(e.message)),process.exit(1)}}),Sc=vh;import{Command as Cg}from"commander";import{McpServer as Eg}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Dg}from"@modelcontextprotocol/sdk/server/stdio.js";import*as qr from"path";import{z as Mi}from"zod";var sr=class{tools=new Map;add(e,t){return this.tools.set(e.name,{definition:e,handler:t}),this}getAll(){return Array.from(this.tools.values())}registerToServer(e){for(let{definition:t,handler:r}of this.getAll())e.registerTool(t.name,{description:t.description,inputSchema:t.inputSchema},(async o=>r(o)))}};function hi(){return new sr}import*as xe from"fs";import*as we from"path";import{z as Ti}from"zod";import U from"fs";import*as ar from"os";import*as L from"path";import wh from"json5";var bh=3;function gi(n){if(!U.existsSync(n)||!U.statSync(n).isDirectory())return!1;let e=U.existsSync(L.join(n,"build-profile.json5")),t=U.existsSync(L.join(n,"hvigorfile.js"))||U.existsSync(L.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=U.readFileSync(L.join(n,"build-profile.json5"),"utf-8");return wh.parse(r).app!==void 0}catch{return!1}}function Pc(n,e,t){if(e>=t)return null;let r=Sh(n),o=Ph(r);if(o)return o;for(let i of r){let s=Pc(i,e+1,t);if(s)return s}return null}function Sh(n){try{let e=U.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(L.join(n,r.name));return t}catch{return[]}}function Ph(n){for(let e of n)if(gi(e))return e;return null}function Ie(n){if(!n||n.trim()==="")return null;let e=L.resolve(n),t;try{t=U.realpathSync(e)}catch{t=e}if(!U.existsSync(t))return null;if(gi(t))return t;let r=t;for(let o=1;o<=3;o++){let i=L.dirname(r);if(i===r)break;if(gi(i))return i;r=i}if(U.statSync(t).isDirectory()){let o=Pc(t,0,bh);if(o)return o}return null}var yi=[I()?".bitfun":".idea",".deveco",I()?".cxx":"cxx","compile_commands.json"];function dn(n){return L.join(n,...yi)}function Ec(n){return new Promise(e=>setTimeout(e,n))}var Eh=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function cr(n){let e=L.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&Eh.has(e)}function Dc(n){return L.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function ve(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function vi(n){return ve(n)}function rt(n){let e=vi(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function ln(n){try{let e=new URL(n);if(e.protocol==="file:"){let t=decodeURIComponent(e.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(t)&&(t=t.slice(1)),rt(t)}}catch{}return n}function Ic(n){let e=[],t=n.lastIndexOf("file:/");if(t>=0){let r=n.slice(t).replace(/^file:\/+/,"");if(r){let o=r.startsWith("/")?`file://${r}`:`file:///${r}`,i=ln(o);i!==n&&i!==ln(n)&&e.push(i)}}return e}function lr(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??L.join(ar.homedir(),"AppData","Local");return L.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?L.join(ar.homedir(),"Library","Logs","devecocli-mcp-server"):L.join(ar.homedir(),".local","share","devecocli-mcp-server","logs")}function Cc(n,e){let t=Dh(e),r=Ih(t,n);if(r!==null)return r;let o=Date.now(),s=`${n.replace(/:/g,"\\:")}=${o}`,a=Ch(t,n,s);return Ah(e,a),o}function Dh(n){let e;try{e=U.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function Ih(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let i=parseInt(t.slice(r+1),10);return Number.isFinite(i)&&i>0?i:null}return null}function Ch(n,e,t){let r=!1,o=n.map(i=>{if(r)return i;let s=i.indexOf("=");return s<=0?i:i.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):i});return r||o.push(t),o}function Ah(n,e){try{U.mkdirSync(L.dirname(n),{recursive:!0})}catch{}try{U.writeFileSync(n,e.join(`
|
|
1252
1246
|
`)+`
|
|
1253
|
-
`,"utf8")}catch{}}function
|
|
1254
|
-
`;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
|
|
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
|
|
1255
1249
|
\r
|
|
1256
1250
|
${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this.buffer.indexOf(`\r
|
|
1257
1251
|
\r
|
|
1258
|
-
`);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 Pi(e,t))}clearMessages(){this.messages=[]}clear(){this.receivedTypes.clear(),this.uniqueMessages.clear(),this.messages=[]}hasReceivedAllTypes(e){for(let t of e)if(!this.receivedTypes.has(t))return!1;return!0}getMessages(){return this.messages.map(e=>e.diagnostics)}},Pi=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var 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 Ei(n){return Array.isArray(n)&&n.every(e=>typeof e=="string")}function qh(n){if(!y(n))return!1;let e=n.textDocument;return y(e)&&typeof e.uri=="string"}function Vh(n){return y(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function Gh(n){return y(n)&&typeof n.moduleName=="string"&&typeof n.current=="number"&&typeof n.total=="number"?`indexing module '${n.moduleName}', ${n.current} of total ${n.total} modules`:`params=${JSON.stringify(n??null)}`}var wr=class n{client;isInitialized=!1;stopOnce=null;callbacks=new vr;requestCallbacks=new gr;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;static EXPECTED_DIAGNOSTIC_TYPES=new Set([1e3,2e3,3e3,3001]);constructor(e){this.client=new hr(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{d.info("[ClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.EXIT,params:{}}),se.EXIT),d.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),d.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(b.BROADCAST),this.callbacks.register(b.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(b.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(b.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(b.INDEXING_PROGRESS_UPDATE,e)}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}sendInitialize(e,t){this.client.send("initialize",e,t)}sendInitialized(e){this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.INITIALIZED,params:{editors:e}}),se.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:O,id:0,result:{}}),se.EMPTY)}sendAsyncRequest(e,t,r,o){if(!y(t)){d.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!qh(t)){d.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof r!="number"){d.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(r)}`);return}let i=t.textDocument.uri,s=Ce(i);t.textDocument.uri=s,delete t.requestId;let a=o??e;d.info(`[LSP] sendAsyncRequest ${a}, filePath: ${i}`),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:e,params:{params:t,requestId:r}}),a)}onDidChangeWatchedFiles(e){if(d.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let r of e){if(!Vh(r)){d.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),b.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!y(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){d.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;d.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),se.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let o=Ce(t);e.textDocument.uri=o,d.info(`[LSP] onAsyncOpenFile, uri: ${o}`);let i=this.diagnosticMap.get(o);i||(i=new yr(o),this.diagnosticMap.set(o,i),this.registerDiagnosticTimeout(o,mr.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(i.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),se.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=Ce(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,mr.PUBLISH_DIAGNOSTICS)),d.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),se.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=Ce(e);d.info(`[LSP] didClose, uri: ${r}`);let o=this.diagnosticMap.get(r);if(!t&&(!o||o.isFromEditor)){d.info(`[LSP] closeFile skip, !diagnostic: ${!o}, isFromEditor: ${o?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:O,method:b.DID_CLOSE,params:{textDocument:{uri:r}}}),se.DID_CLOSE)}getDiagnosticMessage(e){let t=Ce(e),r=this.diagnosticMap.get(t);return r?r.getMessages():[]}clear(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){try{let t=JSON.parse(e);this.handleLspMessage(t)}catch(t){let r=t instanceof Error?t.message:String(t);d.error(`[LSP] JSON parse error: ${r}, raw: ${e}`)}}handleError(e){let t=this.getPendingDiagnosticUris();if(t.length>0){let r=JSON.stringify({message:e.message,severity:"Error",severityStr:"Error"});for(let o of t)this.finalizeDiagnostic(o,b.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:O,method:b.ARKTS_ERROR,params:{message:e.message}})}handleLspMessage(e){let t=e.method;t!==void 0&&(!this.isInitialized&&this.handlePreInitMessage(t,e)||this.handlePostInitMessage(t,e))}handlePreInitMessage(e,t){switch(e){case b.MODULE_INIT_FINISH:return d.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(b.MODULE_INIT_FINISH),this.callbacks.unregister(b.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case b.INDEXING_PROGRESS_UPDATE:return d.info(`[LSP] onIndexingProgressUpdate: ${Gh(t.params)}`),this.callbacks.invoke(b.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case b.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case b.ON_PACKAGE_CHANGE_FINISH:d.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case b.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case b.ON_ASYNC_HOVER:this.handleAsyncResponse(t,b.HOVER);return;case b.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,b.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case b.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,b.REFERENCES);return;default:d.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){d.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;y(t)&&y(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){d.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,r={jsonrpc:O,method:b.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){d.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(r);return}if(!(t.length>0&&t[0]===!0)){d.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(r);return}d.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){d.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let r=e.params;if(!y(r)){d.warn("[LSP] aceProject/onAsyncHover message invalid");return}let o=r.requestId;if(typeof o!="number"){d.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(o,t,r)}handleForceOpenFile(e){if(!e){d.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,b.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){d.info("[LSP] publishDiagnostics uri is null");return}let r=e.version??-1;if(r===-1)return;let o=this.diagnosticMap.get(t);if(!o){d.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let i=e.diagnostics||[];i.length!==0?i.forEach(s=>{this.normalizeDiagnostic(s),o.addMessage(r,JSON.stringify(s))}):o.setReceivedType(r),o.hasReceivedAllTypes(n.EXPECTED_DIAGNOSTIC_TYPES)&&this.finalizeDiagnostic(t,b.PUBLISH_DIAGNOSTICS,o.getMessages())}normalizeDiagnostic(e){if(delete e.source,e.severity!==void 0){let t=typeof e.severity=="number"?e.severity:parseInt(e.severity),r={1:"Error",2:"Warning",3:"Information",4:"Hint"};e.severityStr=r[t]||"Unknown",e.severity=e.severityStr}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let r=e[t];r&&typeof r.line=="number"&&(r.line=r.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,n.DIAGNOSTIC_TIMEOUT_MS,()=>{let r=this.diagnosticMap.get(e),o=r?r.getMessages():[];this.finalizeDiagnostic(e,t,o,o.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,o){let i={uri:e,diagnostics:r,...o?{errorMessage:o}:{}};this.requestCallbacks.emit(e,t,i),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import Di 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 Vc from"path";var fn=class{productName="default";buildModeName="debug";targetName="default";arkTSVersion="1.1";resourceDirectories=[];targetESVersion="ES2021";maxFlowDepth=2e3;caseSensitiveCheck=!0;tsImportSendable=!1;compatibleSdkVersionStage="";useNormalizedOHMUrl=!0;reExportCheckMode="noCheck";skipOhModulesLint=!1;byteCodeHar=!0;obfuscationRuleOptionsEnable=!1;enableStrictCheckOHModules=!1;sourceRoots=[];constructor(e){e&&this.resourceDirectories.push(G(Vc.join(e,"src","main","resources")))}};var Yh="OS",Ct=class{deviceType=[5];aceLoaderPath;modulePath;jsComponentType="declarative";sdkJsPath;compatibleSdkVersion;compatibleSdkLevel;compileSdkLevel;compileSdkVersion="6.0.1.112";compileSdkType="Release";syscap={NDeviceSysCaps:[],addedSysCaps:[]};apiType="stageMode";hosSdkPath;runtimeOs=`Harmony${Yh}`;moduleName;moduleType;compileMode="jsbundle";crossPlatform=!1;ignoreCrossPlatform=!1;packageManagerType="ohpm";permissions=[];testPermissions=[];buildProfileParam;appParam={bundleType:"app"};packageName;projectType="OHOS";projectName;moduleDependencies;moduleJsonParam=null;globalDeclarationFiles=[];constructor(e){e?(this.modulePath=e,this.buildProfileParam=new fn(e)):this.buildProfileParam=new fn}toString(){return JSON.stringify(this)}};var At=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as ae from"path";import*as kt from"fs";var Ar=class{modulePath;dependencies={};dynamicDependencies={}};var ot=class{registryType;resolved;name;version;type;constructor(e){let t=typeof e=="object"&&e!==null?e:{};this.name=typeof t.name=="string"?t.name:"",this.version=typeof t.version=="string"?t.version:"",typeof t.registryType=="string"?this.registryType=t.registryType:this.registryType=typeof t.path=="string"?"local":"ohpm",typeof t.resolved=="string"?this.resolved=t.resolved:typeof t.storePath=="string"?this.resolved=t.storePath:this.resolved="",this.type=typeof t.type=="string"?t.type:void 0}};var Tt=class{constructor(e,t,r){this.projectPath=e;this.moduleName=t;this.modulePath=r}projectPath;moduleName;modulePath;dependencies=[];devDependencies=[];dynamicDependencies=[];finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[]};import*as Ae from"path";import*as Tr from"fs";var xt=class{name="";version="";storePath="";dependencyPath="";path=""};var A={HVIGOR_CACHE:".hvigor",DEPENDENCY:"dependencyMap",JSON5:".json5",KEY_DEPENDENCY:"dependencies",KEY_DYNAMIC_DEPENDENCY:"dynamicDependencies",KEY_DEV_DEPENDENCY:"devDependencies",OH_MODULES_PATH:"oh_modules",OHPM_PATH:".ohpm",LOCK_JSON5_FILE:"lock.json5",OH_PACKAGE_JSON5:le.OH_PACKAGE_JSON5},hn=`${A.HVIGOR_CACHE}/${A.DEPENDENCY}`,it=`${A.DEPENDENCY}${A.JSON5}`,VC=le.SYNC_OUTPUT_PATH;var gn=class n{dependencyPath;modulePath;projectPath;static FILE_DEPENDENCY_PREFIX="file:";static PARAMETER_PREFIX="@param:";fileSpecPattern;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;static PACKAGE_JSON_PARSER_MAP=new Map;dependencies=[];devDependencies=[];dynamicDependencies=[];static getInstance(e,t,r){let o=this.PACKAGE_JSON_PARSER_MAP.get(e);return o||(o=new n(e,t,r),this.PACKAGE_JSON_PARSER_MAP.set(e,o)),o}constructor(e,t,r){this.dependencyPath=e,this.modulePath=t,this.projectPath=r,this.fileSpecPattern=n.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=Ae.join(this.dependencyPath,A.OH_PACKAGE_JSON5),r=oe(t);r&&(this.dependencies=this.getDependencyList(r,A.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(r,A.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(r,A.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let r=[];if(!y(e))return r;let o=e[t];if(!y(o))return r;for(let[i,s]of Object.entries(o)){if(typeof s!="string"){d.error(`${i} package dependency value is not String ${t}`);continue}let a=new xt;a.name=i;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(n.PARAMETER_PREFIX)||this.parseDependencyPath(i,c,a,!1),r.push(a)}return r}parseDependencyPath(e,t,r,o){if(!(!e||!t))try{let i=Ae.normalize(Ae.join(this.modulePath,A.OH_MODULES_PATH,e));if(!(t.startsWith(n.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){r.dependencyPath=i;return}if(r.path=t,this.fileNameForOhpm.test(t)){r.dependencyPath=i;return}let s=t;if(t.startsWith(n.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(n.FILE_DEPENDENCY_PREFIX.length)),Ae.isAbsolute(s)){r.dependencyPath=i;return}if(!o){let a=Ae.resolve(this.modulePath,s);i=P.ensurePathWithinRoot(this.projectPath,a)}Tr.existsSync(i)&&Tr.statSync(i).isDirectory()&&(r.dependencyPath=i)}catch(i){d.error("parser dependency path is invalid",i)}}};import*as yn from"fs";import*as vn from"path";import Jh from"json5";var xr=class n{projectPath;static FILE_DEPENDENCY_PREFIX="file:";fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[];storePathMap=new Map;lockFileCache=null;lockFileParsed=!1;constructor(e=""){this.projectPath=e}parseDependencies(e){if(!this.ensureLockFileParsed())return!1;let t=this.lockFileCache;return this.extractDependencies(t.modules,t.storePathMap,e),!0}ensureLockFileParsed(){if(this.lockFileParsed)return this.lockFileCache!==null;this.lockFileParsed=!0;let e=this.getLockFilePath(),t=this.readLockFile(e);if(!t)return!1;let r=this.validateLockFile(t);return r.valid?(this.lockFileCache={modules:r.modules,storePathMap:this.parseStorePathMap(r.packages)},!0):!1}getLockFilePath(){return vn.join(this.projectPath,A.OH_MODULES_PATH,A.OHPM_PATH,A.LOCK_JSON5_FILE)}readLockFile(e){if(!yn.existsSync(e))return d.error("lock file does not exist"),this.clearDependencies(),null;try{let t=yn.readFileSync(e,"utf8"),r=Jh.parse(t);return r||(d.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return d.error("Error parsing lock.json5:",t),this.clearDependencies(),null}}validateLockFile(e){if(!y(e))return d.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return d.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let r=e.packages;return r?{valid:!0,modules:t,packages:r}:(d.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,r){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,A.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,A.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,A.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!y(e))return t;for(let[r,o]of Object.entries(e)){if(!y(o)){d.error(`${r} value is not json object`);continue}typeof o.storePath=="string"&&t.set(r,o.storePath)}return t}getDependencyList(e,t,r){if(!y(e))return[];for(let[o,i]of Object.entries(e))if(y(i)){let s=typeof i.name=="string"?i.name:"";if(r==="."&&s===""||s===r)return this.getFinalDependencyList(e,t,o)}return[]}getFinalDependencyList(e,t,r){let o=e[r];if(!y(o))return d.error("moduleJsonObject is null"),[];let i=[],s=o[t];if(!y(s))return[];for(let[a,c]of Object.entries(s)){if(!y(c))continue;let l=typeof c.specifier=="string"?c.specifier:"",u=typeof c.version=="string"?c.version:"",h=new xt;h.name=a,h.version=u.startsWith(n.FILE_DEPENDENCY_PREFIX)?u.substring(n.FILE_DEPENDENCY_PREFIX.length):u,this.parseDependencyPath(h,r,a,l,u);let v=`${a}@${u}`;this.storePathMap.has(v)&&(h.storePath=this.storePathMap.get(v)||""),i.push(h)}return i}parseDependencyPath(e,t,r,o,i){let s=P.resolvePathWithinRoot(this.projectPath,vn.join(t,A.OH_MODULES_PATH,r));try{let a=i.startsWith(n.FILE_DEPENDENCY_PREFIX)?i.substring(n.FILE_DEPENDENCY_PREFIX.length):i,c=vn.isAbsolute(a)?P.ensurePathWithinRoot(this.projectPath,a):P.resolvePathWithinRoot(this.projectPath,a);yn.existsSync(c)?(e.path=o,e.dependencyPath=this.fileNameForOhpm.test(i)?s:c):e.dependencyPath=s}catch(a){d.error("Invalid dependency path in lock.json5",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};var st=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=zc(this.projectRoot);try{let t=oe(e);if(typeof t!="object"||t===null)return[];let r=t.modules;return Array.isArray(r)?r.filter(o=>{if(typeof o!="object"||o===null)return!1;let i=o;return typeof i.name=="string"&&typeof i.srcPath=="string"}):[]}catch(t){return d.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};function Gc(n){return y(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var wn=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new st(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=ae.join(t,hn),o=ae.join(r,it);if(!kt.existsSync(r)||!kt.existsSync(o)){let c="Dependency map or JSON not found";return d.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let i=new Tt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(r,i),this.parseLockJson(i);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return d.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:c}}let a=Date.now();for(let c=0;c<s.length;c++){let l=s[c];Gc(l)&&(this.parseSingleModule(l,r,i,e),(c+1)%100===0&&d.info(`[Parser] getAllDependencyMap progress: ${c+1}/${s.length} (${Date.now()-a}ms)`))}return d.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-a}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],r=this.projectPath,o=ae.join(r,hn),i=ae.join(o,it);if(!kt.existsSync(o)||!kt.existsSync(i))return d.warn("[Parser] Dependency map or JSON not found."),t;let s=e&&e.length>0?new Set(e.map(l=>l.trim()).filter(Boolean)):null,a=new Tt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(o,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return d.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let l of c){if(!Gc(l))continue;let u=l.name;if(s&&!s.has(u))continue;let h=P.resolvePathWithinRoot(this.projectPath,l.srcPath),v=ae.join(o,u),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 Mt=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Yc=(w=>(w[w.File=1]="File",w[w.Module=2]="Module",w[w.Namespace=3]="Namespace",w[w.Package=4]="Package",w[w.Class=5]="Class",w[w.Method=6]="Method",w[w.Property=7]="Property",w[w.Field=8]="Field",w[w.Constructor=9]="Constructor",w[w.Enum=10]="Enum",w[w.Interface=11]="Interface",w[w.Function=12]="Function",w[w.Variable=13]="Variable",w[w.Constant=14]="Constant",w[w.String=15]="String",w[w.Number=16]="Number",w[w.Boolean=17]="Boolean",w[w.Array=18]="Array",w[w.Object=19]="Object",w[w.Key=20]="Key",w[w.Null=21]="Null",w[w.EnumMember=22]="EnumMember",w[w.Struct=23]="Struct",w[w.Event=24]="Event",w[w.Operator=25]="Operator",w[w.TypeParameter=26]="TypeParameter",w))(Yc||{}),Jc=()=>Object.values(Yc).filter(n=>typeof n=="number");var Mr=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Rr=class{applyEdit=!0;workspaceEdit=new Mr;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new kr(Jc());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Mt;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Or=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Nr=class{constructor(e=[]){this.valueSet=e}valueSet};var Lr=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var Kc=(S=>(S[S.Text=1]="Text",S[S.Method=2]="Method",S[S.Function=3]="Function",S[S.Constructor=4]="Constructor",S[S.Field=5]="Field",S[S.Variable=6]="Variable",S[S.Class=7]="Class",S[S.Interface=8]="Interface",S[S.Module=9]="Module",S[S.Property=10]="Property",S[S.Unit=11]="Unit",S[S.Value=12]="Value",S[S.Enum=13]="Enum",S[S.Keyword=14]="Keyword",S[S.Snippet=15]="Snippet",S[S.Color=16]="Color",S[S.File=17]="File",S[S.Reference=18]="Reference",S[S.Folder=19]="Folder",S[S.EnumMember=20]="EnumMember",S[S.Constant=21]="Constant",S[S.Struct=22]="Struct",S[S.Event=23]="Event",S[S.Operator=24]="Operator",S[S.TypeParameter=25]="TypeParameter",S))(Kc||{}),Zc=()=>Object.values(Kc).filter(n=>typeof n=="number");var _r=class{completionItemKind=new Nr(Zc());completionItem=new Lr;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Hr=class{synchronization=new Or;completion=new _r;hover={contentFormat:{},dynamicRegistration:{}};signatureHelp={signatureInformation:{},contextSupport:{},dynamicRegistration:{}};references={dynamicRegistration:{}};documentHighlight={dynamicRegistration:!0};documentSymbol=null;formatting={dynamicRegistration:{}};rangeFormatting={dynamicRegistration:{}};onTypeFormatting={dynamicRegistration:{}};declaration={};definition={linkSupport:{},dynamicRegistration:{}};codeLens=null;documentLink={tooltipSupport:{},dynamicRegistration:{}};colorProvider=null;rename={prepareSupport:!0,prepareSupportDefaultBehavior:null,honorsChangeAnnotations:null,dynamicRegistrationSupport:null};publishDiagnostics=null;foldingRage=null;typeHierarchy=null;callHierarchy={dynamicRegistration:{}};selectionRange=null;semanticTokens=new Mt;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var jr=class{workspace=new Rr;textDocument=new Hr;notebookDocument=null;window=null;general=null;experimental=null};var Fr=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};function Rt(n){return y(n)?typeof n.line=="number"&&typeof n.character=="number":!1}function Xc(n){return y(n)?typeof n.uri=="string"&&typeof n.text=="string"&&typeof n.languageId=="string"&&typeof n.version=="number":!1}function Qc(n){if(!y(n)||typeof n.text!="string")return!1;let e=n.range;return y(e)?Rt(e.start)&&Rt(e.end):!1}var $r=class{messageHandle;serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}sdkPath;rootUri;nodeMaxOldSpaceSize;nodePath;constructor(e){this.sdkPath=e.sdkPath,this.rootUri=e.workspaceRoot,this.nodeMaxOldSpaceSize=e.nodeMaxOldSpaceSize,this.nodePath=e.nodePath,this.serverPath=e.arktsLangServerPath,this.logPath=Fc(),this.indexLogPath=e.indexLogPath||this.logPath,this.messageHandle=new wr({serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath,nodePath:this.nodePath}),this.messageHandle.setBroadcastToClients(t=>this.onLspMessage(t))}async start(e,t){let r=!1;try{d.info(`serverPath: ${this.serverPath}`),d.info(`rootUri: ${this.rootUri}`),d.info(`sdkPath: ${this.sdkPath}`),d.info(`logPath: ${this.logPath}`);let o=Ce(this.rootUri),i=new 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=Uc(s.length,this.nodeMaxOldSpaceSize);await this.messageHandle.start(l),this.currentParams=new Fr(o,i,new jr),this.messageHandle.sendInitialize(this.currentParams,1),this.messageHandle.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:O,method:b.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((u,h)=>{this.messageHandle.onIndexingProgressUpdate(h),this.messageHandle.onInitializationCompleted(u)},"LSP initialization",un),this.messageHandle.sendInitialized(e),r=!0}catch(o){this.lastStartErrorMessage=o instanceof Error?o.message:String(o),d.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(r)}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){let t=Ce(e);this.messageHandle.registerRequestCallback(t,(r,o)=>{let i=y(o)?o:{};d.info(`[LSP] onDiagnosticCompleted called, filePath: ${e}`);let s={jsonrpc:O,method:r,params:{uri:typeof i.uri=="string"?i.uri:t,diagnostics:Array.isArray(i.diagnostics)?i.diagnostics.filter(a=>typeof a=="string"):[],...typeof i.errorMessage=="string"?{errorMessage:i.errorMessage}:{}}};this.onLspMessage(s)})}registerRequestCallback(e,t){this.messageHandle.registerRequestCallback(t,(r,o)=>{d.info(`[LSP] onRequestCompleted called, requestId: ${t}, method: ${r}`);let i={jsonrpc:O,id:e,result:y(o)?o.result:void 0};this.onLspMessage(i)})}reloadDependenciesOnly(e){let t=e?.fullReload??!1,r=new wn(this.rootUri,this.sdkPath),o=this.getModuleModelsByName();if(t){d.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let l=r.getDependenciesOnly();this.markDependencyTypesIncremental(l);let u=this.mergeDepsOnlyIntoModuleList(l,o);return this.applyModuleModelsUpdate(u),d.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${u.length}`),this.lastDepsOnlyForDiff=l,l}let i=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(i.length===0&&s.size===0)return d.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];d.info(`[LspServerProxy] Module-level deps changed, parsing: [${i.join(", ")}]`);let a=r.getDependenciesOnly(i);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),d.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),r=new Map(this.lastDepsOnlyForDiff.map(o=>[o.moduleName??"",o]));for(let o of e){let i=o.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(i,t,r),c=o.dependencies??{},l=o.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(u,h)=>{(o.dependencies??={})[u]=this.makeDeleteEntry(u,h)}),this.markAddAndDeleteInDeps(a,l,(u,h)=>{(o.dynamicDependencies??={})[u]=this.makeDeleteEntry(u,h)})}}getOldDepsForModule(e,t,r){let o=t.get(e),i=o?.moduleDependencies?.dependencies??{},s=o?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(i).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(i=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:i,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let o of Object.keys(t))o in e||(t[o].type="add");for(let o of Object.keys(e))o in t||r(o,e[o])}makeDeleteEntry(e,t){return new ot({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Ct(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new At([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let o of e){let i=o.moduleName??"",s=t.get(i);s?(s.modulePath=o.modulePath,s.moduleDependencies=o):s=this.createMinimalModelFromDepsItem(o),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let o=new Map(r.map(s=>[s.moduleName??"",s])),i=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=o.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,o.delete(a)),i.push(s)}for(let[,s]of o)i.push(this.createMinimalModelFromDepsItem(s));return i}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=fr(Di.join(t,"default/openharmony/ets/build-tools/ets-loader")),o=fr(Di.join(t,"default/openharmony/ets/api")),i=fr(Di.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=o,s.hosSdkPath=i}sendRequest(e){switch(e.method){case b.HOVER:this.handleHoverRequest(e);break;case b.DEFINITION:this.handleDefinitionRequest(e);break;case b.REFERENCES:this.handleReferencesRequest(e);break;default:d.warn(`Unhandled LSP request: ${e.method}`)}}handleHoverRequest(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/hover, params missing or not an object");return}let{textDocument:r,position:o,requestId:i}=t;if(!y(r)||typeof r.uri!="string"||!Rt(o)){d.error("Invalid client textDocument/hover, malformed or missing required parameters");return}if(typeof i!="number"){d.error("Invalid client textDocument/hover, requestId missing or not a number");return}this.registerRequestCallback(e.id,i),this.messageHandle.sendAsyncRequest(b.ON_ASYNC_HOVER,t,i,se.ON_ASYNC_HOVER)}handleDefinitionRequest(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/definition, params missing or not an object");return}let{textDocument:r,position:o}=t;if(!y(r)||typeof r.uri!="string"||!Rt(o)){d.error("Invalid client textDocument/definition, malformed or missing required parameters");return}let i=this.resolveRequestId(t.requestId,e.id);if(!Number.isFinite(i)){d.error("Invalid client textDocument/definition, requestId missing or not a valid number");return}this.registerRequestCallback(e.id,i),this.messageHandle.sendAsyncRequest(b.ON_ASYNC_DEFINITION,t,i,se.ON_ASYNC_DEFINITION)}handleReferencesRequest(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/references, params missing or not an object");return}let{textDocument:r,position:o}=t;if(!y(r)||typeof r.uri!="string"||!Rt(o)){d.error("Invalid client textDocument/references, malformed or missing required parameters");return}let i=this.resolveRequestId(t.requestId,e.id);if(!Number.isFinite(i)){d.error("Invalid client textDocument/references, requestId missing or not a valid number");return}this.registerRequestCallback(e.id,i),this.messageHandle.sendAsyncRequest(b.ON_ASYNC_FIND_USAGES,t,i,se.ON_ASYNC_FIND_USAGES)}resolveRequestId(e,t){let r=e??t;return typeof r=="number"?r:Number(r)}sendNotification(e){if(!_c(e)){d.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case b.DID_OPEN:this.handleDidOpenNotification(e);break;case b.DID_CHANGE:this.handleDidChangeNotification(e);break;case b.DID_CLOSE:this.handleDidCloseNotification(e);break;case b.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:this.handleDidChangePackageDependencies(e);break;case b.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;default:d.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/didOpen, params missing or not an object");return}let{textDocument:r,editorFiles:o}=t;if(!Xc(r)||!Ei(o)){d.error("Invalid client textDocument/didOpen, malformed or missing required parameters");return}let s={isFromEditor:typeof t.isFromEditor=="boolean"?t.isFromEditor:!1,editorFiles:o,textDocument:r};this.registerDiagnosticCallback(r.uri),this.messageHandle.onAsyncOpenFile(s)}handleDidChangeNotification(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/didChange, params missing or not an object");return}let{textDocument:r,contentChanges:o}=t;if(!y(r)||typeof r.uri!="string"||typeof r.version!="number"){d.error("Invalid client textDocument/didChange, malformed or missing required parameters");return}if(!Array.isArray(o)||!o.every(Qc)){d.error("Invalid client textDocument/didChange, contentChanges invalid");return}let i=r.uri,s=r.version;this.registerDiagnosticCallback(i),this.messageHandle.onAsyncDidChange({uri:i,version:s,contentChanges:o})}handleDidCloseNotification(e){let t=e.params;if(!y(t)){d.error("Invalid client textDocument/didClose, params missing or not an object");return}let{textDocument:r}=t;if(!y(r)||typeof r.uri!="string"){d.error("Invalid client textDocument/didClose, malformed or missing required parameters");return}let o=typeof t.isManual=="boolean"?t.isManual:!1;this.messageHandle.closeFile(r.uri,o)}handleDidChangePackageDependencies(e){let t=e.params;if(!y(t)){d.error("Invalid client aceProject/onDidChangePakcageDependencies, params missing or not an object");return}let{moduleSet:r}=t;if(!Array.isArray(r)||r.length===0){d.error("Invalid client aceProject/onDidChangePakcageDependencies, malformed or missing required parameters");return}this.messageHandle.sendModuleDependencyUpdate(t)}handleDidChangeWatchedFiles(e){let t=e.params;if(!y(t)){d.error("Invalid client workspace/didChangeWatchedFiles, params missing or not an object");return}let{changes:r}=t;if(!Array.isArray(r)){d.error("Invalid client workspace/didChangeWatchedFiles, malformed or missing required parameters");return}this.messageHandle.onDidChangeWatchedFiles(r)}withResettableTimeout(e,t,r){return new Promise((o,i)=>{let s,a=()=>{s=setTimeout(()=>{i(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),o()},c)})}async dispose(){await this.messageHandle.stop()}};import*as Te from"fs";import*as We from"path";import{createHash as Kh}from"crypto";import{EventEmitter as Zh}from"events";var Br=class extends Zh{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r}projectRoot;watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),r=new Set(this.watchers.keys());for(let o of t)r.has(o)||this.watchFile(o);for(let o of r)t.has(o)||(this.unwatchFile(o),d.info(`[ConfigFileWatcher] Stopped watching: ${o}`));d.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!Te.existsSync(t)){d.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Te.watch(t,r=>{r==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",r=>{d.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${r.message}`)}),d.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(r){d.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${r instanceof Error?r.message:String(r)}`)}}emitModuleAddedEvents(t,r){for(let o of t){let i=P.resolvePathWithinRoot(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:i,relativePath:o.srcPath,timestamp:r,moduleName:o.name})}}emitModuleRemovedEvents(t,r){for(let o of t){let i=P.resolvePathWithinRoot(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:i,relativePath:o.srcPath,timestamp:r,removedModuleName:o.name})}}emitModuleRenamedEvents(t,r){for(let o of t){let i=P.resolvePathWithinRoot(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:i,relativePath:o.after.srcPath,timestamp:r,moduleName:o.after.name,removedModuleName:o.before.name})}}emitModuleMovedEvents(t,r){for(let o of t){let i=P.resolvePathWithinRoot(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:i,relativePath:o.after.srcPath,timestamp:r,moduleName:o.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let r=Date.now();this.emitModuleAddedEvents(t.added,r),this.emitModuleRemovedEvents(t.removed,r),this.emitModuleRenamedEvents(t.renamed,r),this.emitModuleMovedEvents(t.moved,r)}onBuildProfileChanged(){let t="__build_profile__",r=this.debounceTimers.get(t);r&&clearTimeout(r);let o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(i);if(s===this.lastModulesSnapshot){d.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,i);this.lastModules=i,this.lastModulesSnapshot=s,d.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,o)}computeModulesSnapshot(t){return t.map(o=>`${o.name}::${o.srcPath}`).sort().join("|")}diffModules(t,r){let o=this.buildModuleMatchState(r),i={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,o),this.matchRenamedModules(t,o,i),this.matchMovedModules(t,o,i),this.collectRemovedModules(t,o,i),this.collectAddedModules(r,o,i),i}buildModuleMatchState(t){let r=new Map,o=new Map;for(let i of t)r.set(i.srcPath,i),o.set(i.name,i);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:o}}matchExactModules(t,r){for(let o of t){let i=r.newBySrc.get(o.srcPath);i&&i.name===o.name&&(r.matchedOld.add(o),r.matchedNew.add(i))}}matchRenamedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newBySrc.get(i.srcPath);s&&!r.matchedNew.has(s)&&s.name!==i.name&&(o.renamed.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}matchMovedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newByName.get(i.name);s&&!r.matchedNew.has(s)&&s.srcPath!==i.srcPath&&(o.moved.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}collectRemovedModules(t,r,o){for(let i of t)r.matchedOld.has(i)||o.removed.push(i)}collectAddedModules(t,r,o){for(let i of t)r.matchedNew.has(i)||o.added.push(i)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=oe(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return d.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=We.join(this.projectRoot,A.OH_PACKAGE_JSON5);Te.existsSync(r)&&t.push(r);let o=this.parseModulesFromBuildProfile();for(let i of o){let s=P.resolvePathWithinRoot(this.projectRoot,i.srcPath),a=We.join(s,A.OH_PACKAGE_JSON5);Te.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return We.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Te.readFileSync(t,"utf-8");return Kh("sha256").update(r).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let r=this.computeFileHash(t);r&&this.contentHashes.set(t,r);let o=Te.watch(t,i=>{i==="change"&&this.onFileChanged(t)});o.on("error",i=>{d.error(`[ConfigFileWatcher] Watch error for ${t}: ${i.message}`)}),this.watchers.set(t,o)}catch(r){d.error(`[ConfigFileWatcher] Failed to watch ${t}: ${r instanceof Error?r.message:String(r)}`)}}unwatchFile(t){let r=this.watchers.get(t);r&&(r.close(),this.watchers.delete(t)),this.contentHashes.delete(t);let o=this.debounceTimers.get(t);o&&(clearTimeout(o),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.computeFileHash(t);if(!i){d.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===i){d.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,i),d.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:We.basename(t),relativePath:We.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,o)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),d.info("[ConfigFileWatcher] All watchers stopped")}};import*as Ue from"fs";import*as ue from"path";import{createHash as Xh}from"crypto";import{EventEmitter as Qh}from"events";var Wr=class extends Qh{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=ue.join(t,hn)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!Ue.existsSync(this.depMapDir)){d.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=Ue.watch(this.depMapDir,{recursive:!0},(t,r)=>this.onDirEvent(t,r)),this.dirWatcher.on("error",t=>{d.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){d.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),d.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return G(ue.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let o=r.replace(/\\/g,"/"),i;if(o===A.OH_PACKAGE_JSON5)i="root-oh-package";else if(o===it)i="dep-map-json";else{let a=o.match(/^([^/]+)\/oh-package\.json5$/);i=a?`module:${a[1]}`:""}if(!i)return;let s=ue.join(this.depMapDir,r);Ue.existsSync(s)&&this.scheduleDebouncedFullScan()}stop(){this.dirWatcher&&(this.dirWatcher.close(),this.dirWatcher=null),this.fullScanTimer&&(clearTimeout(this.fullScanTimer),this.fullScanTimer=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.coalesceTimer&&(clearTimeout(this.coalesceTimer),this.coalesceTimer=null),this.pendingTags=[],this.pendingRenames=[],this.contentHashes.clear(),this.initialScanDone=!1,d.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=ue.join(this.depMapDir,A.OH_PACKAGE_JSON5),r=ue.join(this.depMapDir,it),o=this.parseModulesFromDepMap(),i=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...o.map(s=>({path:ue.join(this.depMapDir,s.name,A.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of i){if(!Ue.existsSync(s))continue;let c=this.canonicalPath(s),l=this.computeFileHash(s);if(!l)continue;let u=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,l);continue}u!==l&&(this.contentHashes.set(c,l),d.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=ue.join(this.depMapDir,it);try{let r=oe(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return d.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${r instanceof Error?r.message:String(r)}`),[]}}scheduleCoalescedReload(t){this.pendingTags.push(t),t==="dep-map-json"&&this.applyDepMapJsonDiff(),this.coalesceTimer&&clearTimeout(this.coalesceTimer),this.coalesceTimer=setTimeout(()=>{this.coalesceTimer=null,this.flushPendingReload()},this.coalesceMs)}collectPendingState(){let t=this.pendingTags,r=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:r}}processTagsIntoSets(t,r,o,i){for(let s of t)s.startsWith("module:")?(o.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(o.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(i.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,o,i,s){for(let a of t)s.push(a.info),o.add(a.info.newName),i.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let o=new Set;for(let i of t)i.startsWith("dep-added:")&&o.add(i.substring(10));for(let i of r)o.add(i.info.newName);return o}emitIncrementalReload(t,r,o,i,s){d.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...o].join(",")}], added=[${[...i].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...o],addedModuleNames:[...i],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:r}=this.collectPendingState();if(t.length===0&&r.length===0)return;if(d.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${r.length}`),t.includes("root-oh-package")){d.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let o=new Set,i=new Set,s=new Set,a=[];this.processTagsIntoSets(t,o,i,s),this.processRenameEntries(r,o,i,s,a);for(let l of i)s.delete(l);if(i.size===0&&s.size===0&&a.length===0){d.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(o,i,s,c,a)}normalizeSrcPath(t){return G(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(i=>[i.name,i])),o=new Map(t.map(i=>[this.normalizeSrcPath(i.srcPath),i]));return{byName:r,bySrcPath:o}}detectModuleRenames(t,r,o,i){for(let[s,a]of t){let c=r.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),o.add(a.name),i.add(c.name);let l=ue.join(this.depMapDir,a.name,A.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(l)),d.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,r,o,i){for(let[s,a]of t){if(o.has(s))continue;let c=r.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),o.add(s),i.add(s),d.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,o){for(let[i]of t)o.has(i)||r.has(i)||(this.pendingTags.push(`dep-added:${i}`),o.add(i))}detectRemovedModules(t,r,o){for(let[i]of t)if(!o.has(i)&&!r.has(i)){this.pendingTags.push(`dep-removed:${i}`),o.add(i);let s=ue.join(this.depMapDir,i,A.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(o=>o.startsWith("dep-")),r=this.pendingRenames.map(o=>`${o.kind}(${o.info.oldName}\u2192${o.info.newName})`);d.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:o}=this.buildModuleLookupMaps(this.lastModules),{byName:i,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(o,s,a,c),this.detectModuleMoves(r,i,a,c),this.detectAddedModules(i,r,c),this.detectRemovedModules(r,i,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=Ue.readFileSync(t,"utf-8");return Xh("sha256").update(r).digest("hex")}catch{return null}}};import*as el from"os";import*as tl from"path";import{spawn as eg}from"child_process";var tg=600*1e3;function ng(n){let e=[],t=[];return n.stdout?.on("data",r=>{e.push(r.toString())}),n.stderr?.on("data",r=>{t.push(r.toString())}),{stdout:e,stderr:t}}function Ur(n){return n.join("")}function rg(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
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+`.
|
|
1259
1253
|
Output so far:
|
|
1260
|
-
`+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function
|
|
1254
|
+
`+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function Yh(n,e,t){return new Promise(r=>{let o=zh(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:i,stderr:s}=Vh(o),a=setTimeout(()=>{o.kill();let c=[Ur(i),Ur(s)].filter(Boolean).join(`
|
|
1261
1255
|
`).trim();r({success:!1,output:`Build process timeout after 10 minutes.
|
|
1262
1256
|
Output so far:
|
|
1263
|
-
`+c,exitCode:-1})},
|
|
1264
|
-
`).trim()||"";r(
|
|
1257
|
+
`+c,exitCode:-1})},qh);o.on("close",(c,l)=>{clearTimeout(a);let u=[Ur(i),Ur(s)].filter(Boolean).join(`
|
|
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(`
|
|
1265
1259
|
`);o({exitCode:c??-1,output:l})}),i.on("error",c=>{let l=[s,a].filter(Boolean).join(`
|
|
1266
1260
|
`);o({exitCode:-1,output:l+`
|
|
1267
|
-
`+c.message})})})}function
|
|
1268
|
-
`):"\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
|
|
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(`
|
|
1269
1263
|
`)),t.length>0&&r.push(t.join(`
|
|
1270
1264
|
`));let o=r.join(`
|
|
1271
|
-
`).trim(),i=e.length>0;return!i&&t.length===0&&(o="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:o}],isError:i}}async shutdown(){if(this.failAllPending(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(e){f.warn(`Failed to dispose ArktsLspManager: ${e}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null,this.clearInitHandlers()}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":case"textDocument/didOpen":this.handleDiagnosticsNotification(t.params);break;case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(un),f.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{f.info("Received arkts/initialized");let o=this.initResolve;this.clearInitHandlers(),o?.();break}case"arkts/initializationFailed":{let i=t.params?.message??"unknown";f.error(`LSP initialization failed: ${i}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${i}`));break}case"workspace/didChangeConfiguration":f.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let r=this.resolveDiagnosticWaiter(t);if(!r)return;if(typeof e.errorMessage=="string"){f.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let o=e.diagnostics,i=Array.isArray(o)?o.length:0;f.debug(`diagnostics received uri=${t} count=${i}`),r.resolve(Array.isArray(o)?o:[])}resolveDiagnosticWaiter(e){let t=ln(e),r=this.popDiagnosticWaiter(t);if(r)return r;for(let o of
|
|
1265
|
+
`).trim(),i=e.length>0;return!i&&t.length===0&&(o="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:o}],isError:i}}async shutdown(){if(this.failAllPending(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(e){f.warn(`Failed to dispose ArktsLspManager: ${e}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null,this.clearInitHandlers()}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":case"textDocument/didOpen":this.handleDiagnosticsNotification(t.params);break;case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(un),f.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{f.info("Received arkts/initialized");let o=this.initResolve;this.clearInitHandlers(),o?.();break}case"arkts/initializationFailed":{let i=t.params?.message??"unknown";f.error(`LSP initialization failed: ${i}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${i}`));break}case"workspace/didChangeConfiguration":f.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let r=this.resolveDiagnosticWaiter(t);if(!r)return;if(typeof e.errorMessage=="string"){f.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let o=e.diagnostics,i=Array.isArray(o)?o.length:0;f.debug(`diagnostics received uri=${t} count=${i}`),r.resolve(Array.isArray(o)?o:[])}resolveDiagnosticWaiter(e){let t=ln(e),r=this.popDiagnosticWaiter(t);if(r)return r;for(let o of Ic(e)){let i=this.popDiagnosticWaiter(o);if(i)return i}}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}failAllPending(e){for(let[,r]of this.diagnosticWaiters)clearTimeout(r.timer),r.reject(e);this.diagnosticWaiters.clear();let t=this.initReject;this.clearInitHandlers(),t?.(e)}getLogAndIndexPath(e){try{let t=we.join(lr(),"ArkTSCheck"),r=we.join(t,"mapping-config.properties"),o=Cc(e,r),i=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=we.join(t,"lsp-log",String(o),i),a=we.join(t,"lsp-index",String(o));return xe.mkdirSync(s,{recursive:!0}),xe.mkdirSync(a,{recursive:!0}),{logPath:ve(s),indexPath:ve(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function rg(n,e){if(Array.isArray(e))return e.length===0?`${n} => no diagnostics`:`${n} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${n} diagnostic failed, error_message: ${t}`}return`${n} => diagnostic failed, result: ${JSON.stringify(e)}`}import{spawn as og}from"child_process";import*as C from"fs";import*as Z from"path";import{z as xi}from"zod";var tl=60*1e3,ig=30*1e3,sg=new Set(["textDocument/didOpen","textDocument/didChange","textDocument/didClose","textDocument/didSave"]),ag=1e3,Ri=class{nextRequestId=1;pendingRequests=new Map;diagnosticWaiters=new Map;fileCheckLock=Promise.resolve();closed=!1;wrapperState="preInitialize";queuedDocumentNotifications=[];backendReady=!1;projectPath=null;clangdStdin=null;clangdStdout=null;clangdBuffer=Buffer.alloc(0);constructor(){}isClosed(){return this.closed}async initialize(e){this.projectPath=e,this.wrapperState="waitingForDatabase"}async connectClangdProcess(e,t){if(this.closed)throw new Error("Client is already closed");this.clangdStdin=e,this.clangdStdout=t,this.wrapperState="startingBackend",this.clangdStdout.on("data",a=>this.handleClangdData(a)),this.clangdStdout.on("error",a=>{f.warn(`[CppCheck] clangd stdout error: ${a}`),this.failAll(new Error(`clangd stdout error: ${a}`))}),this.clangdStdout.on("end",()=>{this.failAll(new Error("C++ language server connection closed"))});let r=ve(this.projectPath),o=rt(r),i=Z.basename(r)||"workspace",s={processId:null,clientInfo:{name:"devecocli-mcp-server",version:"0.2.0"},rootPath:r,rootUri:o,workspaceFolders:[{uri:o,name:i}],capabilities:{}};await this.sendRequestToClangd("initialize",s,tl),await this.sendNotificationToClangd("initialized",{}),this.backendReady=!0,this.wrapperState="proxying";for(let a of this.queuedDocumentNotifications)await this.writeToClangd(a);this.queuedDocumentNotifications.length=0,f.info("[CppCheck] clangd backend ready, switched to proxying mode")}async waitForBackendReady(){if(this.backendReady)return;let e=tl,t=Date.now();for(;!this.backendReady&&!this.closed&&Date.now()-t<e;)await new Promise(r=>setTimeout(r,500));if(!this.backendReady)throw new Error("Timed out waiting for clangd backend to be ready")}async checkFile(e){await this.waitForBackendReady();let t=await this.acquireFileCheckLock();try{return await this.doCheckFile(e)}finally{t()}}async doCheckFile(e){let t;try{t=C.realpathSync(e)}catch{t=e}let r=rt(t),o=Dc(t),i=await C.promises.readFile(t,"utf8"),s=new Promise((a,c)=>{let l=setTimeout(()=>{this.diagnosticWaiters.delete(r)&&c(new Error(`Timed out waiting for diagnostics: ${e}`))},ig);this.diagnosticWaiters.set(r,{resolve:a,reject:c,timer:l})});try{await this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,languageId:o,version:1,text:i}})}catch(a){let c=this.diagnosticWaiters.get(r);throw c&&(clearTimeout(c.timer),this.diagnosticWaiters.delete(r)),a}try{return await s}finally{await this.closeFile(r).catch(a=>{f.warn(`[CppCheck] didClose failed for ${r}: ${a}`)})}}async close(){if(!this.closed&&(this.closed=!0,this.wrapperState="shuttingDown",this.backendReady&&this.clangdStdin)){try{await this.sendRequestToClangd("shutdown",null,3e3)}catch(e){f.warn(`[CppCheck] shutdown request failed: ${e}`)}try{await this.sendNotificationToClangd("exit",null)}catch(e){f.warn(`[CppCheck] exit notification failed: ${e}`)}try{this.clangdStdin.end()}catch(e){f.warn(`[CppCheck] stdin.end() failed: ${e}`)}}}async sendNotification(e,t){let r={jsonrpc:"2.0",method:e,params:t??void 0};if(this.backendReady&&this.clangdStdin){await this.writeToClangd(r);return}sg.has(e)&&this.queuedDocumentNotifications.push(r)}async closeFile(e){await this.sendNotification("textDocument/didClose",{textDocument:{uri:e}})}async sendRequestToClangd(e,t,r){let o=this.nextRequestId++;return new Promise((i,s)=>{let a=setTimeout(()=>{this.pendingRequests.delete(o)&&s(new Error(`Timed out waiting for ${e} response`))},r);this.pendingRequests.set(o,{resolve:i,reject:s,timer:a}),this.writeToClangd({jsonrpc:"2.0",id:o,method:e,params:t??void 0}).catch(c=>{this.pendingRequests.delete(o)&&(clearTimeout(a),s(c))})})}async sendNotificationToClangd(e,t){await this.writeToClangd({jsonrpc:"2.0",method:e,params:t??void 0})}async writeToClangd(e){if(!this.clangdStdin)throw new Error("clangd stdin not available");return new Promise((t,r)=>{let o;try{o=JSON.stringify(e)}catch(u){r(new Error(`Failed to encode LSP message: ${u}`));return}let i=Buffer.from(o,"utf8"),s=Buffer.from(`Content-Length: ${i.length}\r
|
|
1272
1266
|
\r
|
|
1273
1267
|
`,"ascii"),a=!1,c=u=>{a||(a=!0,u?r(u):t())};if(this.clangdStdin.write(Buffer.concat([s,i]),u=>{u?c(u):a||c()}))c();else{let u=()=>c();this.clangdStdin.once("drain",u)}})}handleClangdData(e){for(this.clangdBuffer=this.clangdBuffer.length===0?e:Buffer.concat([this.clangdBuffer,e]);;){let t=this.clangdBuffer.indexOf(`\r
|
|
1274
1268
|
\r
|
|
1275
|
-
`);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=
|
|
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(`
|
|
1276
1270
|
`):"\u6CA1\u6709\u6709\u6548\u7684 C/C++ \u6587\u4EF6"}],isError:!0};let i;try{i=await this.ensureInitializedWithFiles(o)}catch(a){return t.push(a.message),{content:[{type:"text",text:t.join(`
|
|
1277
1271
|
`)}],isError:!0}}return await this.runDiagnosticsForFiles(i,o,t,r)&&this.shutdown().catch(a=>{f.warn(`[CppCheck] shutdown after diagnostic failure: ${a}`)}),this.formatCallResult(t,r)}async runDiagnosticsForFiles(e,t,r,o){let i=!1;for(let s of t)try{let a=await e.checkFile(s);a.length===0?o.push(`${s} => \u65E0\u8BCA\u65AD`):o.push(`${s} => Diagnostic: ${JSON.stringify(a)}`)}catch(a){i=!0,r.push(`${s} => \u83B7\u53D6\u8BCA\u65AD\u5931\u8D25: ${a.message}`)}return i}formatCallResult(e,t){let r=e.length>0;return!r&&t.length===0&&t.push("\u6CA1\u6709\u8FD4\u56DE\u4EFB\u4F55\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:[t.join(`
|
|
1278
1272
|
`),e.join(`
|
|
1279
1273
|
`)].filter(i=>i.trim().length>0).join(`
|
|
1280
|
-
`).trim()}],isError:r}}async ensureInitializedWithFiles(e){let t=ve(this.projectPath),r=this.prepareCppCheck(t,e);if(
|
|
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(`
|
|
1281
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(`
|
|
1282
|
-
`)}],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}=
|
|
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(`
|
|
1283
1277
|
`),a.join(`
|
|
1284
1278
|
`)].filter(h=>h.trim().length>0).join(`
|
|
1285
|
-
`).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 ${
|
|
1286
|
-
`);o&&(e.isError?t.push(o):r.push(o))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{f.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool&&(this.cppCheckTool.shutdown().catch(t=>{f.warn("Failed to shutdown CppCheckTool during setProjectPath:",t)}),this.cppCheckTool=null),this.initPromise?(this.needsReinit=!0,f.info("Project path changed while init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{f.warn("Failed to re-init project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new Ng;if(await this.server.connect(e),f.info("devecocli-mcp-server started"),!this.config.debug){let t=Nc();t&&f.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=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=ll(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>=dl?(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 / ${dl/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"),Oc(),Rc()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function Lg(n){let e=[],t=[],r=[];for(let o of n)qr.extname(o).toLowerCase()===".ets"?e.push(o):cr(o)?t.push(o):r.push(o);return{etsFiles:e,cppFiles:t,unsupported:r}}function Ri(n){return new zr(n)}async function Hg(){let n=process.env.PROJECT_PATH||"",e=process.env.DEVECO_PATH,t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=process.env.DEBUG==="true"||process.env.DEBUG==="1",o=await _.new(e),s=Ri({toolProvider:o,projectPath:n,nodeMaxOldSpaceSize:t,debug:r}),a=async()=>{await s.shutdown(),process.exit(0)};process.once("SIGINT",a),process.once("SIGTERM",a),process.platform==="win32"&&process.once("SIGBREAK",a);try{await s.start()}catch(c){console.error("Failed to start MCP server:",c),process.exit(1)}}var pl=new _g("serve").description("Host bundled auxiliary protocol servers");pl.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await Hg()});var ml=pl;import{Command as Lw,InvalidArgumentError as ws}from"commander";import{red as So,dim as _w}from"colorette";import*as z from"fs";import*as Bt from"path";import ww from"adm-zip";import bw from"proper-lockfile";import wu from"ora";import*as pe from"fs";import*as Dn from"path";var ze=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],at={"harmonyos-guides":"\u5F00\u53D1\u6307\u5357","harmonyos-references":"API\u53C2\u8003","best-practices":"\u6700\u4F73\u5B9E\u8DF5","harmonyos-faqs":"FAQ","harmonyos-releases":"\u7248\u672C\u8BF4\u660E","harmonyos-roadmap":"\u53D8\u66F4\u9884\u544A"};var Vr="1.9.1",kk=48*1024*1024,fl=280,hl=6,gl=100,yl=3,vl=28,Oi=10,wl=/API参考|APIReference/i,Sn=200,bl=12,Sl=4,Ni=8,Pl=6,Gr=700,Li=250,_i=400,El=1320,Dl=120,Il=450,Cl=250,Al=500,Tl=480,xl=80,kl=200,Ml=60,Rl=200,Ol=40,Nl=200,Ll=200,_l=40,_t=500,Hl=Object.fromEntries(ze.map((n,e)=>[at[n],e])),qe=Object.fromEntries(ze.map((n,e)=>[n,e]));import*as $l from"fs";import*as x from"path";import{fileURLToPath as Bl}from"url";import*as Yr from"path";import{homedir as jg}from"os";var Fg="deveco-cli";function Fl(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function $g(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&Fl(n)!==""}function jl(){return Yr.join(jg(),".local","share",Fg)}function Jr(n){let e=Kr();return $g()?[`Data directory (DEVECO_CLI_DATA_DIR): ${e}`,"If you changed this in System Environment Variables, open a new terminal and retry.",`Log file: ${n}`]:[`Data directory (default): ${e}`,"To use a custom location, set DEVECO_CLI_DATA_DIR and open a new terminal.",`Log file: ${n}`]}function Kr(){let n=process.env.DEVECO_CLI_DATA_DIR;if(n===void 0||n==="")return jl();let e=Fl(n);return e?Yr.resolve(e):jl()}var Bg="docs";function Zr(){return x.join(Kr(),Bg)}function X(){return x.join(Zr(),".index")}function Wl(){return x.join(X(),"build.lock")}function Hi(){return x.join(X(),"build-status.json")}function Xr(){return x.join(X(),"build-meta.json")}function Pn(){return x.join(X(),"search.db")}function Ht(){return x.join(X(),".tmp")}function Wg(){return x.join(Kr(),"logs")}function jt(){return x.join(Wg(),"doc-init.log")}function Ug(n,e){let t=e;for(;!t.endsWith(`${x.sep}dist`)&&t!==x.dirname(t);)t=x.dirname(t);return t}function Ul(n,e){return x.dirname(Ug(n,e))}function zg(){let n=Bl(import.meta.url),e=x.dirname(n);return n.includes(`${x.sep}dist${x.sep}`)?Ul(n,e):x.join(e,"..","..","..")}function qg(...n){let e=Bl(import.meta.url),t=x.dirname(e);return e.includes(`${x.sep}dist${x.sep}`)?[x.join(Ul(e,t),...n)]:[x.join(t,"..","..","..",...n)]}function zl(...n){for(let e of qg(...n))if($l.existsSync(e))return e;return null}function Ve(){return zl("docs.zip")}function ji(){return zl("index.zip")}function ql(){return x.join(zg(),"index","data")}import*as ke from"fs";import*as ct from"path";var lt=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Qr=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function Vl(n){return n instanceof Qr}var Fi=null;function $i(n){Fi=n}function Bi(){if(Fi)return Fi;let n=X();if(lt.every(o=>ke.existsSync(ct.join(n,o))))return n;let t=ql();if(lt.every(o=>ke.existsSync(ct.join(t,o))))return t;throw new Qr("Lexicon files not found. Install the documentation index first (index.zip).")}function Gl(){Bi()}function dt(n){let e=ct.join(Bi(),n);return ke.readFileSync(e,"utf-8")}function Yl(n,e){return ke.readFileSync(ct.join(e,n),"utf-8")}async function Jl(n,e=Bi()){await ke.promises.mkdir(n,{recursive:!0});for(let t of lt){let r=ct.join(e,t),o=ct.join(n,t);await ke.promises.copyFile(r,o)}}import*as eo from"fs";import*as Kl from"path";import*as Zl from"yauzl";var En=null;function Vg(n){return new Promise((e,t)=>{Zl.open(n,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(r,o)=>{if(r||!o){t(r??new Error(`Failed to open zip: ${n}`));return}e(o)})})}function Gg(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function Yg(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",o=>{let i=Gg(o);i.endsWith("/")||e.set(i,o),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function Jg(){En?.zipfile.close(),En=null}async function Kg(n){let e=Kl.resolve(n),t=await eo.promises.stat(e),r=En;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;Jg();let o=await Vg(e),i=await Yg(o);return En={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:o,entries:i,readChain:Promise.resolve()},En}function Zg(n,e){return new Promise((t,r)=>{n.openReadStream(e,(o,i)=>{if(o||!i){r(o??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];i.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),i.on("end",()=>{t(Buffer.concat(s))}),i.on("error",r)})})}async function Xg(n,e){let t=n.readChain,r;n.readChain=new Promise(o=>{r=o}),await t;try{return await Zg(n.zipfile,e)}finally{r()}}function Qg(n){let e=n.replace(/\\/g,"/").replace(/\.md$/,"");return[`docs/${e}.md`,`${e}.md`,`docs/${e}`,e]}function ey(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function Xl(n){let e=Ve();if(!e)throw new Error("docs.zip not found");let t=await Kg(e),r=ey(t.entries,Qg(n));if(!r)throw new Error(`Document not found: ${n}`);return(await Xg(t,r)).toString("utf-8")}function Wi(){let n=Ve();return n!==null&&eo.existsSync(n)}import*as Y from"fs";import*as Ge from"path";import Ql from"adm-zip";var ed=["search.db","build-meta.json",...lt],ty=["corpus.json","corpus-offsets.json","orama.dpack"];async function ny(n){for(let e of ty)await Y.promises.rm(Ge.join(n,e),{force:!0})}async function ry(n){let e=await Y.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await Y.promises.rm(Ge.join(n,t.name),{recursive:!0,force:!0})}function oy(n){let t=new Ql(n).getEntry("build-meta.json");if(!t)throw new Error("index.zip is missing build-meta.json");return JSON.parse(t.getData().toString("utf-8"))}async function iy(n){let e=X();await Y.promises.mkdir(e,{recursive:!0});for(let t of ed){let r=Ge.join(e,t);await Y.promises.rm(r,{force:!0}),await Y.promises.rename(Ge.join(n,t),r)}await ny(e),await Y.promises.rm(Ht(),{recursive:!0,force:!0})}function Ui(){let n=ji();return n!==null&&Y.existsSync(n)}async function td(n){let e=ji();if(!e)throw new Error("index.zip not found");let t=oy(e);if(t.docsZipSha256!==n)throw new Error("Bundled index.zip does not match docs.zip. Rebuild index.zip with npm run build:index.");if(t.segmentCount<=0)throw new Error("Bundled index.zip is empty");let r=Ht();await Y.promises.rm(r,{recursive:!0,force:!0}),await Y.promises.mkdir(r,{recursive:!0});let o=new Ql(e);for(let s of ed){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await Y.promises.writeFile(Ge.join(r,s),a.getData())}let i=JSON.parse(await Y.promises.readFile(Ge.join(r,"build-meta.json"),"utf-8"));if(!Y.existsSync(Ge.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await iy(r),await Y.promises.mkdir(Zr(),{recursive:!0}),await ry(Zr()),i}import{createHash as nd}from"crypto";import*as rd from"fs";async function to(n){return new Promise((e,t)=>{let r=nd("sha256"),o=rd.createReadStream(n);o.on("data",i=>r.update(i)),o.on("error",t),o.on("end",()=>e(r.digest("hex")))})}function od(n){return nd("sha256").update(n,"utf8").digest("hex")}var zi=null;function sy(){let n=dt("harmonyos-synonyms.json");return JSON.parse(n)}function ay(n){let e=new Map;for(let t of n){let r=t.map(o=>o.trim()).filter(Boolean);for(let o of r){let i=r.filter(s=>s!==o);e.set(o.toLowerCase(),i),o!==o.toLowerCase()&&e.set(o,i)}}return e}function cy(){let n=ay(sy()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function ly(){return zi||(zi=cy()),zi}function qi(n,e){let t=ly(),r=n.split(/\s+/).filter(Boolean),o=new Set,i=Number.isFinite(e)?e:r.length;for(let s=0;s<r.length&&o.size<i;s+=1){let a=r[s];o.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(o.size>=i)break;o.add(l)}}return[...o].join(" ")}function id(n,e){let t=e?Yl(n,e):dt(n);return od(t)}function no(n){return id("harmonyos-synonyms.json",n)}function ro(n){return id("harmonyos-terms.txt",n)}var dy={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function oo(){try{let n=await pe.promises.readFile(Hi(),"utf-8");return JSON.parse(n)}catch{return{...dy}}}async function Vi(n){let e=Hi();await pe.promises.mkdir(Dn.dirname(e),{recursive:!0}),await pe.promises.writeFile(e,JSON.stringify(n,null,2))}function sd(n){let e=Date.now();return{state:"extracting",phase:1,phaseLabel:"Extracting documentation",current:0,total:0,message:n,startedAt:e,updatedAt:e,error:null}}async function Ye(n){let t={...await oo(),...n,updatedAt:Date.now()};return await Vi(t),t}async function Gi(){let n=Ve();return n?to(n):null}async function Yi(){try{let n=await pe.promises.readFile(Xr(),"utf-8");return JSON.parse(n)}catch{return null}}async function Ji(n=!1){if(n)return"no-index";let e=await Yi();if(!e||e.segmentCount===0)return"no-index";let t=await Gi();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(!Wi()||!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 Ki(n=!1){return n?!0:Wi()?In()?await Ji()!==null:!0:!1}async function ad(){let n=await oo();return["installing","indexing","persisting"].includes(n.state)}import*as J from"fs";import*as pu from"os";import*as ne from"path";var cd=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),Zi=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),ld=new Set(["a","an","and","api","app","application","arkts","arkui","for","get","harmonyos","how","in","oh","ohos","on","or","set","the","to","use","using","what","when","where","which","with","without","data","file","main","model","name","network","stage","system","type","user"]),dd=new Set(["ability","extension","module","service","context","options","config","info","event","code","state","type","data","request","response","client","server","handler","helper","utils","factory","builder","listener","callback","observer","provider","consumer","delegate","adapter","driver","buffer","stream","channel","session","task","worker","controller","component","container","attribute","descriptor","modifier","validator","parser","formatter","encoder","decoder","filter","converter","generator","iterator","dispatcher","resolver","scanner","tracker","monitor","scheduler","renderer","loader","subscriber","proxy","button","surface","stack","heap","map","set","array","list"]);var uy=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,py=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,my=/[A-Z][a-zA-Z0-9]{2,}/g,fy=/@[A-Z][a-zA-Z0-9]*/g,hy=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,ud=6,gy=/^[a-z][a-z0-9]{2,}$/,yy=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,vy=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,wy=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,by=/^[A-Z][a-zA-Z0-9]+$/;function Sy(n){return`"${n.replace(/"/g,'""')}"`}function An(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(Sy).join(` ${e} `)}function Cn(n){return An(n,"OR")}function pd(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?Cn([...t,...r]):`(${Cn(t)}) AND (${Cn(r)})`}function Tn(n){return vy.test(n)}function md(n){return wy.test(n)&&n.length>=ud}function Py(n){return by.test(n)}function xn(n){return Tn(n)||md(n)||Py(n)}function Ey(n){let e=n.trim().toLowerCase();return dd.has(e)?!1:cd.has(e)}function Dy(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 Xi(n){return[...n.matchAll(uy)].map(e=>e[0])}function Qi(n,e=ud){let t=[];for(let r of n.matchAll(py))r[0].length>=e&&t.push(r[0]);return t}function Ft(n){return n.filter(e=>{let t=e.toLowerCase();return!n.some(r=>{if(r===e)return!1;let o=r.toLowerCase();return o.length>t.length&&o.endsWith(t)&&t.length>=4})})}function me(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function Iy(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 Iy(n);let e=new Set;return me(e,n),Ft([...e])}function ao(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(yy);if(!t)return null;let r=t[1].toLowerCase(),o=t[2].toLowerCase();if(!gy.test(r)||ld.has(r)||!Ey(o))return null;let i=Dy(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function es(n){let e=ao(n.trim());return!e||e.second!=="manager"?null:e}function Cy(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function fd(n){let e=n.trim(),t=es(e);if(t&&Zi.has(t.first))return!0;if(md(e)){let r=Cy(e);return r!==null&&Zi.has(r)}return!1}function ts(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 ns(n){let e=n.trim();if(xn(e))return so(e);let t=new Set;for(let r of Xi(n)){me(t,r);let o=io(r);o&&me(t,o)}for(let r of Qi(n))me(t,r);for(let r of n.matchAll(fy))t.add(r[0]);for(let r of n.matchAll(hy))t.add(r[0]);for(let r of n.matchAll(my))r[0].length>=4&&t.add(r[0]);return Ft([...t])}function hd(n){let e=n.trim();if(xn(e))return so(e);let t=new Set,r=ao(e);r&&me(t,r.camelCase);for(let o of ns(e))t.add(o);for(let o of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let i=o[0];i!==i.toLowerCase()&&t.add(i)}return Ft([...t])}function gd(n){return xn(n)}var N={pureApiSymbol:/^[A-Z][a-zA-Z0-9]+$/,stageModelExact:/^Stage\s*模型$/i,stageModelEnglishExact:/^stage\s+model$/i,stageModel:/Stage\s*模型/i,stageModelEntryPage:/Stage\s*模型.*EntryAbility.*(页面|新页面)/,declarePermissionBoost:/声明.*权限|应用权限.*声明|如何声明应用权限/,declarePermissionCatalog:/如何声明应用权限/,declarePermissionTokens:/如何声明应用权限|声明应用权限/,uiAbilityLifecycleBoost:/UIAbility.*生命周期|生命周期.*UIAbility|UIAblity/i,uiAbilityLifecycleCatalog:/UIAblity.*生命周期|UIAbility.*生命周期/i,entryAbilityPage:/EntryAbility.*(页面|启动|跳转|新页面)/,stateDecoratorBoost:/@State|@Prop|@Link|@Provide|@Consume/,stateDecoratorCatalog:/@State\s*装饰器|@Prop\s*装饰器|@Link\s*装饰器/,stateManagement:/状态管理原理/,routerRoute:/Router\s+路由/,dialogPopupExact:/^Dialog\s+弹窗$/,dialogPopupBoost:/Dialog\s+弹窗/};function yd(n){return N.pureApiSymbol.test(n.trim())}function kn(n){let e=n.trim();return N.stageModelExact.test(e)||N.stageModelEnglishExact.test(e)}function vd(n){let e=[];return kn(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),N.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),N.stageModelEntryPage.test(n)&&e.push("\u9875\u9762\u8DEF\u7531","pushUrl"),/UIAblity|UIAbility/.test(n)&&/生命周期/.test(n)&&e.push("UIAbility\u7EC4\u4EF6\u751F\u547D\u5468\u671F"),e}function wd(n){return kn(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var Ay=[{matches:n=>N.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>kn(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!kn(n)&&N.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>N.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>N.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>N.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>N.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>N.routerRoute.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:1.4},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]},{matches:n=>N.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function Ty(n,e){for(let{catalog:t,multiplier:r}of e){let o=qe[t];n.set(o,(n.get(o)??1)*r)}}function bd(n,e){for(let t of Ay)t.matches(n)&&Ty(e,t.weights)}function Sd(n,e){if(e!==void 0)return!1;let t=n.trim();return Tn(t)||N.pureApiSymbol.test(t)||fd(t)}function Pd(n){let e=n.trim();if(Tn(e)||N.pureApiSymbol.test(e))return"harmonyos-references";if(kn(e)||N.uiAbilityLifecycleCatalog.test(e)||N.stateDecoratorCatalog.test(e)||N.stateManagement.test(e)||N.declarePermissionCatalog.test(e)||N.stageModelEntryPage.test(e)||N.routerRoute.test(e)||N.dialogPopupExact.test(e))return"harmonyos-guides"}var co=null,os=null,is=null,Ed=!1,rs=null;function xy(){if(co)return co;let n=dt("harmonyos-stopwords.txt");return co=new Set(n.split(`
|
|
1287
|
-
`).map(e=>e.trim()).filter(Boolean)),co}function
|
|
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)),co}function by(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t]?.trim();if(!r)continue;let o=n[t+1]?.trim();if(r==="@"&&o&&/^[A-Z][a-zA-Z0-9]*$/.test(o)){e.push(`@${o}`),t+=1;continue}e.push(r)}return e}function bd(n){let e=wy(),t=[];for(let r of by(n)){let o=r.trim();!o||e.has(o)||(t.push(o.toLowerCase()),/[A-Z]/.test(o)&&/[a-zA-Z]/.test(o)&&t.push(o))}return t}async function Sy(){let n=await import("jieba-wasm");ss=n.cut,as=n.cut_for_search;let e=dt("harmonyos-terms.txt");n.with_dict(e)}async function Py(){let{Jieba:n}=await import("@node-rs/jieba"),{dict:e}=await import("@node-rs/jieba/dict.js"),t=n.withDict(e),r=dt("harmonyos-terms.txt");t.loadDict(Buffer.from(r,"utf-8")),ss=t.cut.bind(t),as=t.cutForSearch.bind(t)}async function Ye(){wd||(is||(is=(I()?Sy():Py()).then(()=>{wd=!0})),await is)}async function Ey(n){return await Ye(),bd(as(n,!0))}async function Sd(n){return await Ye(),bd(ss(n,!0))}async function lo(n,e){let t=n.trim();if(!t||e<=0)return"";let r=(await Ey(t)).join(" ");return r.length<=e?r:r.slice(0,e)}async function Dy(n,e){let t=[];for(let o of n){let i=o.trim();i&&(t.push(i.toLowerCase()),/[A-Z]/.test(i)&&t.push(i))}let r=[...new Set(t)].join(" ");return r.length<=e?r:r.slice(0,e)}async function uo(n){let e=!!n.sectionTitle.trim(),t=n.titleTokens.trim(),r=e?Dl:wl,o=e?Cl:Sl,i=e?await Dy(n.apiSymbols,o):await lo(n.apiSymbols.join(" "),o),a=(await Promise.all([lo(t,e?Il:bl),Promise.resolve(i),lo(n.headingsText,e?Al:Pl),lo(n.bodySample,e?Tl:El)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}function Iy(n){return n.join(" ").replace(/\s+/g," ").trim().slice(0,Sn)}function cs(n,e){let t=new Set,r=[];for(let o of[...n,...e]){let i=o.toLowerCase();if(!(!o||t.has(i))&&(t.add(i),r.push(o),r.length>=gl))break}return r}function Cy(n){return n.length>=2&&n.length<=yl}function Ay(n,e){let t=Gi(n,_i),r=t.split(/\s+/).filter(Boolean),o=[e.first,...r.filter(a=>a!==e.second),e.lower,e.camelCase],i=[e.second,e.lower,e.camelCase],s=cs(o,i);return{rawQuery:n,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:cd(o,i)}}function Ty(n,e){let t=cs(so(e),[]);return{rawQuery:n,expandedQuery:n,tokens:t,preferAnd:!1,ftsMatch:Cn(t)}}async function Pd(n){let e=Iy(n),t=e.trim(),r=hd(t);if(r)return{rawQuery:e,expandedQuery:r.expandedQuery,tokens:r.tokens,preferAnd:!1};let o=ao(t);if(o)return Ay(e,o);if(xn(t))return Ty(e,t);let i=fd(e),s=[...os(e),...i],c=pd(t)?e:Gi(e,_i),l=await Sd(c),u=cs(s,l);return{rawQuery:e,expandedQuery:c,tokens:u,preferAnd:i.length===0&&Cy(u)}}var Ed=["harmonyos-releases","harmonyos-roadmap"],xy=new Set(Ed.map(n=>ze[n])),ky=Ed.map(n=>`${at[n]}/`);function Ry(n){return xy.has(n)}function My(n){return ky.some(e=>n.startsWith(e))}function Dd(n){let e=[],t=[];for(let r of n)Ry(r.catalog_id)?t.push(r):e.push(r);return[...e,...t]}function Id(n){let e=[],t=[];for(let r of n)My(r.documentId)?t.push(r):e.push(r);return[...e,...t]}var Oy=[{pattern:/@ohos\./i,catalog:"harmonyos-references",multiplier:1.5},{pattern:/@[A-Z][a-zA-Z]+/,catalog:"harmonyos-guides",multiplier:1.35},{pattern:/(如何|怎么|怎样|步骤)/,catalog:"harmonyos-guides",multiplier:1.45},{pattern:/(生命周期|原理|概述|什么是|模型|介绍)/,catalog:"harmonyos-guides",multiplier:1.35},{pattern:/(报错|失败|错误|异常|排查)/,catalog:"harmonyos-guides",multiplier:1.25},{pattern:/(报错|失败|FAQ)/i,catalog:"harmonyos-faqs",multiplier:1.2},{pattern:/(构建|签名|打包|发布|上架|应用市场|hvigor|ohpm)/i,catalog:"harmonyos-guides",multiplier:1.3},{pattern:/(行为变更|changelog|升级|适配|版本说明)/i,catalog:"harmonyos-releases",multiplier:1.3},{pattern:/(路由|弹窗|手势|页面|权限|装饰器)/,catalog:"harmonyos-guides",multiplier:1.25,skipForPureApiSymbol:!0}];function Rn(n,e,t){let r=ze[e];n.set(r,(n.get(r)??1)*t)}function Ny(n,e){let t=n.trim(),r=/[\u4e00-\u9fff]/.test(t),o=/\b[A-Z][a-zA-Z0-9]{2,}\b/.test(t),i=/\b[a-z][a-zA-Z0-9]{3,}\b/.test(t);if(r&&(o||i)){Rn(e,"harmonyos-guides",1.45),Rn(e,"harmonyos-references",1.35);return}(o||i)&&Rn(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&Rn(e,"harmonyos-references",1.75)}function Cd(n){let e=new Map,t=n.trim();if(!t)return e;let r=md(t);Ny(t,e),gd(t,e);for(let o of Oy)o.pattern.test(t)&&(o.skipForPureApiSymbol&&r||Rn(e,o.catalog,o.multiplier));return e}function Ad(n){return vd(n)}var Ly=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function Td(n,e){let t=-1;for(let r of Ly){let o=n.lastIndexOf(r);o>t&&(t=o)}return t>=e?t:-1}function xd(n,e){let t=n.trim();if(t.length<=e)return{text:t,excerptTruncated:!1};let r=t.slice(0,e),o=Td(r,e-20),i=o>=0?o:e;return{text:t.slice(0,i).trimEnd(),excerptTruncated:!0}}function kd(n,e,t={}){let{maxLen:r=Rl,contextChars:o=Ml,excerptTruncated:i=!1}=t,s=n.replace(/\s+/g," ").trim();if(!s)return"";if(s.length<=r)return i?`${s}...`:s;let a=e.split(/\s+/).map(ut=>ut.trim()).filter(Boolean),c=0;for(let ut of a){let Ke=s.toLowerCase().indexOf(ut.toLowerCase());if(Ke>=0){c=Ke;break}}let l=Math.max(0,c-o),u=Math.min(s.length,l+r),h=s.slice(l,u),v=Td(h,r-25);v>=0&&(u=l+v);let D=s.slice(l,u).trim(),k=l>0?"...":"",ne=u<s.length||i?"...":"";return`${k}${D}${ne}`}var _y=`
|
|
1288
1282
|
SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
|
|
1289
1283
|
d.catalog_id, bm25(segments_fts) AS bm25
|
|
1290
1284
|
FROM segments_fts
|
|
@@ -1293,7 +1287,7 @@ Output so far:
|
|
|
1293
1287
|
WHERE segments_fts MATCH ?
|
|
1294
1288
|
ORDER BY bm25(segments_fts)
|
|
1295
1289
|
LIMIT ?
|
|
1296
|
-
`,
|
|
1290
|
+
`,Hy=`
|
|
1297
1291
|
SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
|
|
1298
1292
|
d.catalog_id, bm25(segments_fts) AS bm25
|
|
1299
1293
|
FROM segments_fts
|
|
@@ -1302,7 +1296,7 @@ Output so far:
|
|
|
1302
1296
|
WHERE segments_fts MATCH ? AND d.catalog_id = ?
|
|
1303
1297
|
ORDER BY bm25(segments_fts)
|
|
1304
1298
|
LIMIT ?
|
|
1305
|
-
`,
|
|
1299
|
+
`,jy=3.5,Fy=1.4,$y=4,By=1.8,Wy=1.35,Uy=3.5,zy=1.8,qy=120,Rd=6;function ds(n){return n.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function Vy(n){return n.split(/[^\p{L}\p{N}@.]+/u).map(ds).filter(e=>e.length>=2)}function Gy(n,e){return e.length>1&&e.every(t=>n.includes(t))}function Yy(n){return/^[a-z0-9]{1,4}$/.test(n.trim().toLowerCase())}function Jy(n,e){return n===e?Uy:n.startsWith(e)||n.includes(`@ohos.${e}`)?zy:1}function Ky(n,e){let t=ds(e);if(t.length<2)return 1;let r=ds(n.doc_title);if(Yy(e))return Jy(r,t);if(r.includes(t))return $y;if(t.length>=Rd&&r.includes(t.slice(0,Rd)))return By;let o=Vy(e);return Gy(r,o)?Wy:1}function Zy(n,e){return e<=1?n:n<0?n*e:n/e}function po(n,e,t,r){let o=n.bm25/(e.get(n.catalog_id)??1);return o=Zy(o,Ky(n,t)),r&&rs(n.doc_title,n.section_title,r)&&(o/=jy,n.catalog_id===ze["harmonyos-references"]&&(o/=Fy)),o}function ls(n,e,t,r){return n.reduce((o,i)=>po(i,e,t,r)<po(o,e,t,r)?i:o)}function Xy(n,e){return e.some(t=>n.section_title.includes(t)||n.doc_title.includes(t))}function Qy(n,e,t,r,o){if(o){let i=n.filter(s=>rs(s.doc_title,s.section_title,o));if(i.length>0)return ls(i,t,r,o)}if(e.length>0){let i=n.filter(s=>Xy(s,e));if(i.length>0)return ls(i,t,r,o)}return ls(n,t,r,o)}function Md(n,e,t,r,o){let i=Cd(e),s=ud(e),c=ns(e)?.camelCase,l=new Map;for(let D of n){let k=l.get(D.document_id)??[];k.push(D),l.set(D.document_id,k)}let u=[];for(let D of l.values())u.push(Qy(D,s,i,t,c));let h=u.sort((D,k)=>po(D,i,t,c)-po(k,i,t,c));return(o?Dd(h):h).slice(0,r)}function mo(n,e,t,r,o,i){let s=e?ze[e]:void 0,a=Math.max(t,t*vl,qy),c=s===void 0?n.all(_y,r,a):n.all(Hy,r,s,a);return(s===void 0?Md(c,i,o,t,!0):Md(c,i,o,t,!1)).map(u=>({title:u.doc_title,documentId:u.document_id,sectionTitle:u.section_title||void 0,snippet:kd(u.lead_text,o,{excerptTruncated:!!u.excerpt_truncated})}))}var fo=`
|
|
1306
1300
|
CREATE TABLE documents (
|
|
1307
1301
|
id INTEGER PRIMARY KEY,
|
|
1308
1302
|
document_id TEXT NOT NULL UNIQUE,
|
|
@@ -1340,18 +1334,18 @@ CREATE TRIGGER segments_au AFTER UPDATE ON segments BEGIN
|
|
|
1340
1334
|
END;
|
|
1341
1335
|
|
|
1342
1336
|
CREATE INDEX segments_doc_id_idx ON segments(doc_id);
|
|
1343
|
-
`;var $t=null,
|
|
1337
|
+
`;var $t=null,us=null;function ev(){$t?.close(),$t=null,us=null}function tv(n,e){if($t&&us===e)return $t;$t?.close();let t=new n(e,{readonly:!0,fileMustExist:!0});return $t=t,us=e,t.pragma("mmap_size = 268435456"),t.pragma("cache_size = -8000"),t.pragma("query_only = ON"),t}function nv(n,e){let t=new n(e);return t.pragma("journal_mode = OFF"),t.pragma("synchronous = OFF"),t.pragma("temp_store = MEMORY"),t.exec(fo),t}function rv(n,e,t){let r=e.get(t.documentId);if(r!==void 0)return r;let i=n.prepare("SELECT id FROM documents WHERE document_id = ?").get(t.documentId);if(i)return e.set(t.documentId,i.id),i.id;let a=n.prepare(`
|
|
1344
1338
|
INSERT INTO documents(document_id, catalog_id, doc_title)
|
|
1345
1339
|
VALUES (?, ?, ?)
|
|
1346
|
-
`).run(t.documentId,t.catalogId,t.docTitle),c=Number(a.lastInsertRowid);return e.set(t.documentId,c),c}async function
|
|
1340
|
+
`).run(t.documentId,t.catalogId,t.docTitle),c=Number(a.lastInsertRowid);return e.set(t.documentId,c),c}async function ov(n,e,t,r){await Ye();let o=nv(n,e),i=new Map,s=o.prepare(`
|
|
1347
1341
|
INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated)
|
|
1348
1342
|
VALUES (?, ?, ?, ?, ?)
|
|
1349
|
-
`),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=mv(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 hv(n,e,t,r,o,i,s){let a=uv(n,e);return mo({all(c,...l){return a.prepare(c).all(...l)}},t,r,o,i,s)}async function Hd(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:dv,buildSearchIndex:(t,r,o)=>fv(e,t,r,o),searchIndex:(t,r,o,i,s,a,c)=>Promise.resolve(hv(e,i,r,o,s,a,c))}}import{readFile as gv,stat as yv,writeFile as vv}from"fs/promises";var ds=null,Ke=null;async function us(){return ds||(ds=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),ds}function wv(n){return{all(e,...t){let r=n.prepare(e);t.length>0&&r.bind(t);let o=[];for(;r.step();)o.push(r.get({}));return r.finalize(),o}}}async function bv(n){let e=await yv(n);if(Ke&&Ke.dbPath===n&&Ke.mtimeMs===e.mtimeMs)return Ke.db;Ke?.db.close();let t=await us(),r=t.capi,o=t.wasm,i=new Uint8Array(await gv(n)),s=o.allocFromTypedArray(i),a=new t.oo1.DB(":memory:"),c=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE;return r.sqlite3_deserialize(a.pointer,"main",s,i.byteLength,i.byteLength,c),Ke={dbPath:n,mtimeMs:e.mtimeMs,db:a},a}function jd(){Ke?.db.close(),Ke=null}async function Sv(n,e,t,r){n.exec("BEGIN");for(let o of r){let i=t(o.source);e.bind([i,o.source.sectionTitle,o.source.leadText,o.searchText,o.source.excerptTruncated?1:0]),e.step(),e.reset()}n.exec("COMMIT")}function Pv(n,e,t){return r=>{let o=e.get(r.documentId);if(o!==void 0)return o;let i=n.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(i!=null){let a=Number(i);return e.set(r.documentId,a),a}t.bind([r.documentId,r.catalogId,r.docTitle]),t.step(),t.reset();let s=Number(n.selectValue("SELECT last_insert_rowid()"));return e.set(r.documentId,s),s}}async function Ev(n,e,t){await Je();let r=await us(),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 Sv(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 vv(n,u),o.close(),jd()}async function Dv(n,e,t,r,o,i){let s=await bv(n);return mo(wv(s),e,t,r,o,i)}async function Fd(){return await us(),{kind:"sqlite-wasm",resetCache:jd,buildSearchIndex:Ev,searchIndex:(n,e,t,r,o,i,s)=>Dv(r,e,t,o,i,s)}}var ho=null,ps=null;async function Iv(){try{let e=await Hd();return g("doc-index: using better-sqlite3 SQLite backend"),e}catch(e){g(`doc-index: better-sqlite3 unavailable (${e.message}); falling back to sqlite-wasm`)}let n=await Fd();return g("doc-index: using @sqlite.org/sqlite-wasm SQLite backend"),n}async function Rn(){return ho||(ho=Iv().then(n=>(ps=n,n))),ho}function $d(){ps?.resetCache(),ho=null,ps=null}async function Cv(n,e,t,r,o,i,s){let a=await Rn(),c=s??Pn();return a.searchIndex(n,e,t,c,r,o,i)}function Wd(){$d()}async function Ud(n,e,t){await(await Rn()).buildSearchIndex(n,e,t)}function zd(n,e,t){let r=new Set,o=[];for(let i of[...n,...e])if(!r.has(i.documentId)&&(r.add(i.documentId),o.push(i),o.length>=t))break;return o}function go(n,e,t,r,o,i){return Cv(n,e,t,o,r.expandedQuery,r.rawQuery,i)}async function Av(n,e,t,r,o){let i=await go(n,e,t,r,An(r.tokens,"AND"),o);if(i.length>=t)return i;let s=await go(n,e,t,r,An(r.tokens,"OR"),o);return zd(i,s,t)}async function ms(n,e,t,r,o){return r.ftsMatch?go(n,e,t,r,r.ftsMatch,o):r.preferAnd?Av(n,e,t,r,o):go(n,e,t,r,An(r.tokens,"OR"),o)}async function Tv(n,e,t,r){let o=await ms(n,"harmonyos-references",e,t,r);if(o.length>=e)return o;let i=await ms(n,void 0,e,t,r);return zd(o,i,e)}function Bd(n,e){return e!==void 0?n:xd(n)}async function qd(n,e,t=20,r){let o=await Cd(n);if(Sd(o.rawQuery,e)){let a=await Tv(n,t,o,r);return Bd(a,e)}let i=e??Md(o.rawQuery),s=await ms(n,i,t,o,r);return Bd(s,e)}import{unified as Qd}from"unified";import eu from"remark-parse";import tu from"remark-gfm";import{toString as vo}from"mdast-util-to-string";var xv=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,kv=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,Mv=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,Rv=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,Ov=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function yo(n){let e=n.trim(),t=e.match(Rv);return t?t[1]:e}function Nv(n){let e=n.match(xv);if(!e)return;let t=yo(e[1].trim());return{displayTitle:n,symbolName:t,searchExtras:[t,e[3]]}}function Lv(n){let e=yo(n.replace(/\([^)]*\)$/,""));if(/^[A-Z][A-Za-z0-9]*$/.test(e))return{displayTitle:n,symbolName:e,searchExtras:[e]};if(/^[A-Z][A-Za-z0-9]*(\([^)]*\))?$/.test(n))return{displayTitle:n,symbolName:e,searchExtras:[e]}}function On(n){let e=n.trim();return e?Nv(e)??(()=>{let t=e.match(kv);if(t){let r=t[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let t=e.match(Mv);if(!t)return;let r=t[1].trim(),o=t[2].trim();return{displayTitle:e,symbolName:o,searchExtras:[r,o]}})()??Lv(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function _v(n){if(n.length<2||n.length>36||Ov.test(n))return!1;let e=[...n.replace(/\s/g,"")];return e.length===0?!1:e.filter(r=>new RegExp("\\p{Script=Han}","u").test(r)).length/e.length>=.4}function Vd(n){for(let e of n){let t=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(_v(t))return t}return""}function Gd(n,e,t){let r=[n,...t.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var Hv=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,Nn=/@[A-Z][a-zA-Z]+/g,jv=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,Fv=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,$v=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,Bv=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),Wv=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),Uv=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function nu(n,e){let t=new Set,r=[n,...e];for(let o of r){for(let i of Xi(o)){me(t,i);let s=io(i);s&&me(t,s)}for(let i of Qi(o))me(t,i);for(let i of o.matchAll(Hv)){let s=i[0];zv(s)&&t.add(s)}for(let i of o.matchAll(Nn))t.add(i[0])}return Ft([...t])}function zv(n){let e=n.trim();if(!e||Nn.test(e))return!!e;if(e.includes(".")){let t=e.split(".")[0]??"";return Uv.has(t)?!1:/^[A-Z]/.test(t)}return Bv.has(e)?!1:Wv.has(e)?!0:e.length<=3?!1:/^[A-Z][a-z]+[A-Z]/.test(e)?!0:e.length>=6&&/^[A-Z][A-Za-z0-9]+$/.test(e)}function Yd(n){let e=n.trim();return!!(!e||$v.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function ru(n,e){let t=e.jsonTitle?.trim(),r=Yv(n,"").trim(),o=e.fileName.trim();return t&&!Yd(t)?t:r&&!Yd(r)?r:t||r||o}function ou(n){return jv.test(n.trim())}function fs(n){let e=n.trim().replace(/\([^)]*\)$/,""),t=yo(e);return Fv.test(t)}function wo(n){let e=n.trim();return e?Nn.test(e)||ou(e)||fs(e)?!0:!!On(e).symbolName:!1}function qv(n){let e=n.trim();return!(!e||ou(e)||fs(e))}function Vv(n){let e=new Set,t=[];for(let r of n){let o=r.trim();!qv(o)||e.has(o)||(e.add(o),t.push(o))}return t}function Jd(n){if(!n.includes("."))return 0;let e=n.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function Gv(n,e){let t=Jd(n)-Jd(e);return t!==0?t:n.localeCompare(e)}function iu(n,e=[]){let t=[...new Set(e.map(i=>i.trim()).filter(Boolean))],r=new Set(t),o=[...new Set(n.map(i=>i.trim()).filter(Boolean))].filter(i=>!r.has(i));return o.sort(Gv),[...t,...o].slice(0,Ol)}function bo(n){return n.replace(/\s+/g," ").trim()}function Kd(n){return n.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function Yv(n,e=""){let t=n.split(/\r?\n/),r=0;for(;r<t.length&&!t[r].trim();)r+=1;if(r>=t.length)return e;let o=Kd(t[r].trim()),i=o.match(/^#+\s+(.+)$/);if(i)return Kd(i[1].trim());if(r+1<t.length){let s=t[r+1].trim();if(/^=+$/.test(s)||/^-+$/.test(s))return o}return o||e}function su(n){let e=bo(n.join(" "));if(e.length<=Gr)return e;let t=e.slice(0,Gr);return e.length<=Gr+Li?t:`${t} ${e.slice(-Li)}`}function Jv(n){let e=Vv(n).join(" ");return e.length<=_i?e:e.slice(0,_i)}function au(n){let e=bo(n),{text:t,excerptTruncated:r}=Od(e,Nl);return{leadText:t,excerptTruncated:r}}function Kv(n,e){let{leadText:t,excerptTruncated:r}=au(n);return{leadText:t,excerptTruncated:r||!!e.trim()}}function cu(n,e){if(n.type==="code"){e.codeBlocks.push(n.value??"");return}if("children"in n&&Array.isArray(n.children)){for(let r of n.children)cu(r,e);return}let t=bo(vo(n));t&&e.bodyParts.push(t)}function Zv(n){let e=Qd().use(eu).use(tu).parse(n),t=[],r=null,o=()=>{r&&((r.sectionTitle||r.bodyParts.length||r.codeBlocks.length)&&t.push(r),r=null)},i=()=>{r||(r={sectionTitle:"",bodyParts:[],codeBlocks:[]})};for(let s of e.children){if(s.type==="heading"){let a=s,c=vo(a).trim();if(a.depth>=4&&c&&wo(c)){o(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}i(),c&&r.bodyParts.push(c);continue}i(),cu(s,r)}return o(),t.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:t}function Xv(n){return wl.test(n)}function Qv(n){return n.filter(e=>e.sectionTitle&&wo(e.sectionTitle)).length}function ew(n){return{sectionTitle:n.map(e=>e.sectionTitle.trim()).join(" | "),bodyParts:n.flatMap(e=>e.bodyParts).slice(0,40),codeBlocks:n.flatMap(e=>e.codeBlocks).slice(0,8)}}function Zd(n){let e=n.trim();return!e||Nn.test(e)?Nn.test(e):/对象说明$|枚举说明$/.test(e)?!0:fs(e)}function tw(n){let e=n.filter(h=>!h.sectionTitle||!wo(h.sectionTitle)),t=n.filter(h=>h.sectionTitle&&wo(h.sectionTitle)),r=t.filter(h=>Zd(h.sectionTitle)),o=t.filter(h=>!Zd(h.sectionTitle)),i=Math.max(0,vl-r.length),s=o.slice(0,i),a=o.slice(i),c=a.filter(h=>Xd(h.sectionTitle)),l=a.filter(h=>!Xd(h.sectionTitle)),u=[];for(let h=0;h<l.length;h+=Oi)u.push(ew(l.slice(h,h+Oi)));return[...e,...r,...s,...c,...u]}function nw(n,e,t){let r=n.split(/\r?\n/).length,o=Qv(e);return o===0?!1:Xv(t)?r>=gl&&o>=yl:r>=fl&&o>=hl}var rw=/^\[h2\][A-Za-z]/;function Xd(n){return rw.test(n.trim())}function lu(n){if(!n.includes(" | ")){let t=On(n);return t.symbolName?[t.symbolName]:[]}let e=[];for(let t of n.split(" | ")){let r=On(t.trim()).symbolName;r&&e.push(r)}return e}function ow(n,e,t,r){let o=lu(n),i=nu(t,r);return e.symbolName&&i.push(e.symbolName),iu([...o,...i],o)}function iw(n,e){let t=su(n.bodyParts),r=n.sectionTitle.trim(),o=On(r),i=Vd(n.bodyParts),s=Gd(r,i,o),a=lu(r),c=r?a.length>0?`${e.docTitle} ${a.join(" ")}`:`${e.docTitle} ${o.symbolName??r}`:e.docTitle,l=[e.docTitle,s,...n.bodyParts].join(" "),{leadText:u,excerptTruncated:h}=Kv(t,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:ow(r,o,l,n.codeBlocks),bodySample:t,leadText:u,excerptTruncated:h}}function du(n,e){for(let t of n){if(t.type==="heading"){let o=vo(t).trim();o&&e.headings.push(o);continue}if(t.type==="code"){e.codeBlocks.push(t.value??"");continue}if("children"in t&&Array.isArray(t.children)){du(t.children,e);continue}let r=bo(vo(t));r&&e.bodyParts.push(r)}}function sw(n){let e=Qd().use(eu).use(tu).parse(n),t={headings:[],bodyParts:[],codeBlocks:[]};return du(e.children,t),t}function aw(n,e){let t=sw(n),r=e.docTitle?.trim()||e.documentId,o=su(t.bodyParts),i=[r,...t.headings,o].join(" "),{leadText:s,excerptTruncated:a}=au(o);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:Jv(t.headings),apiSymbols:iu(nu(i,t.codeBlocks)),bodySample:o,leadText:s,excerptTruncated:a}}function uu(n,e){let t=e.docTitle?.trim()||e.documentId,r=Zv(n);return nw(n,r,e.documentId)?tw(r).filter(o=>o.sectionTitle||o.bodyParts.length>0||o.codeBlocks.length>0).map(o=>iw(o,{...e,docTitle:t})):[aw(n,{...e,docTitle:t})]}async function cw(n){let e=[];async function t(r){let o=await J.promises.readdir(r,{withFileTypes:!0});for(let i of o){if(i.name.startsWith("."))continue;let s=ne.join(r,i.name);i.isDirectory()?await t(s):i.isFile()&&i.name.endsWith(".md")&&e.push(s)}}return await t(n),e}function lw(n,e){let t=ne.relative(e,n).split(ne.sep).join("/").split("/");if(t[0]==="docs"&&(t=t.slice(1)),t.length<2)return null;let r=t[0],o=Hl[r];if(o===void 0)return null;let i=t[t.length-1].replace(/\.md$/,"");return t[t.length-1]=i,{documentId:t.join("/"),catalogId:o,docTitle:i}}async function dw(n){let e=n.replace(/\.md$/,".json");try{let t=await J.promises.readFile(e,"utf-8");return JSON.parse(t).title?.trim()||void 0}catch{return}}async function uw(n,e){let t=lw(n,e);if(!t)return[];let r=await J.promises.readFile(n,"utf-8"),o=ru(r,{jsonTitle:await dw(n),fileName:t.docTitle});return uu(r,{...t,docTitle:o})}async function pw(n,e,t){let r=ne.join(e,"search.db");return await Ud(r,n,async(o,i)=>{await t?.({current:o,total:i,message:`Building search index\u2026 ${o.toLocaleString()} / ${i.toLocaleString()} segments`})}),n.length}async function mw(n){let e=await cw(n),t=[];for(let r of e){let o=await uw(r,n);t.push(...o)}return t}function fw(n,e){return{indexVersion:Vr,docsZipSha256:n.docsZipSha256,termsHash:n.termsHash,synonymsHash:n.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:n.builtBy}}async function mu(n){n.lexiconDir&&$i(n.lexiconDir);try{let e=await mw(n.docsDir);await n.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await J.promises.mkdir(n.tmpDir,{recursive:!0});let t=await pw(e,n.tmpDir,n.onProgress),r=fw(n,t);return await J.promises.writeFile(ne.join(n.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await Jl(n.tmpDir),r}finally{n.lexiconDir&&$i(null)}}async function fu(){return J.promises.mkdtemp(ne.join(pu.tmpdir(),"deveco-docs-"))}async function hw(n,e){try{await J.promises.rename(n,e)}catch(t){let r=t.code;if(r!=="EPERM"&&r!=="EXDEV")throw t;await J.promises.cp(n,e,{recursive:!0}),await J.promises.rm(n,{recursive:!0,force:!0})}}async function hu(n){let e=ne.join(n,"docs");try{await J.promises.access(e)}catch{return}let t=new Set(["docs","docs.zip"]);for(let r of await J.promises.readdir(e,{withFileTypes:!0})){if(t.has(r.name))continue;let o=ne.join(e,r.name),i=ne.join(n,r.name);await J.promises.rm(i,{recursive:!0,force:!0}),await hw(o,i)}await J.promises.rm(ne.join(e,"docs"),{recursive:!0,force:!0}),await J.promises.rm(ne.join(e,"docs.zip"),{force:!0}),await J.promises.rm(e,{recursive:!0,force:!0})}var Ln=class extends Error{constructor(e){super(e),this.name="NativeDepsError"}};function gw(){let n=jt(),e=X();return["Documentation search index is not installed yet.","",...Jr(n),`Index directory: ${e}`,"","Try:"," 1. Wait a moment and run the docs command again (postinstall may still be running)"," 2. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 3. Check the log file above for setup errors"].join(`
|
|
1350
|
-
`)}function
|
|
1351
|
-
`)}function
|
|
1352
|
-
`)}async function
|
|
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 aw(){let n=jt();return[`Chinese tokenizer (${I()?"jieba-wasm":"@node-rs/jieba"}) failed to load.`,"",`Node.js: ${process.version} (required: >=18)`,"",...Jr(n),"","Try:"," 1. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 2. Use Node.js 18 or newer",I()?" 3. Verify jieba-wasm package is installed (WASM backend for OpenHarmony)":" 3. Configure npm registry/proxy if your network blocks optional platform packages"].join(`
|
|
1345
|
+
`)}function cw(n){let e=jt();return[n,"",...Jr(e)].join(`
|
|
1346
|
+
`)}async function pu(){try{Ul()}catch(n){throw Wl(n)?new Ln(`${sw()}
|
|
1353
1347
|
|
|
1354
|
-
Detail: ${n.message}`):n}try{await
|
|
1348
|
+
Detail: ${n.message}`):n}try{await Ye()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Ln(`${aw()}
|
|
1355
1349
|
|
|
1356
|
-
Detail: ${e}`)}try{await
|
|
1357
|
-
`)}async function
|
|
1350
|
+
Detail: ${e}`)}try{await Mn()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Ln(cw(e))}}var ys=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function uw(n){return new Promise(e=>setTimeout(e,n))}async function pw(n){let e=jt();await z.promises.mkdir(Bt.dirname(e),{recursive:!0}),await z.promises.appendFile(e,`${new Date().toISOString()} ${n}
|
|
1351
|
+
`)}async function mw(n){let e=qe();if(!e)throw new Error("docs.zip not found");await z.promises.rm(n,{recursive:!0,force:!0}),await z.promises.mkdir(n,{recursive:!0}),new lw(e).extractAllTo(n,!0),await uu(n)}async function fw(){let n=X(),e=Ht(),t=await z.promises.readdir(e);for(let r of t){let o=Bt.join(n,r);await z.promises.rm(o,{force:!0}),await z.promises.rename(Bt.join(e,r),o)}await z.promises.rm(e,{recursive:!0,force:!0}),await z.promises.rm(Bt.join(n,"orama.dpack"),{force:!0})}async function hw(n,e){e?.start("Installing documentation index\u2026"),await Ge({state:"installing",phase:1,phaseLabel:"Installing index",message:"Installing documentation index\u2026"}),await Zl(n),e&&(e.text="Documentation index installed.")}async function gw(n,e,t){let r=Ht(),o=await du();await z.promises.mkdir(X(),{recursive:!0}),await z.promises.rm(r,{recursive:!0,force:!0}),t?.start("Building search index\u2026"),await Ge({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"});try{await mw(o),await lu({docsDir:o,tmpDir:r,docsZipSha256:e,termsHash:ro(),synonymsHash:no(),builtBy:n.builtBy??"doc-init",onProgress:async i=>{t&&(t.text=i.message),await Ge({state:"indexing",current:i.current,total:i.total,message:i.message})}})}finally{await z.promises.rm(o,{recursive:!0,force:!0})}await Ge({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await fw(),jd()}async function mu(n){await Ge({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function yw(n){let e=await Ki(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await Ge({state:"done",message:t,error:null})}async function vw(n,e){let t=n instanceof Error?n.message:String(n);throw await Ge({state:"error",error:t}),await pw(`ERROR: ${t}`),e?.fail(t),n}async function ww(){let n=X();await z.promises.mkdir(n,{recursive:!0});let e=jl();return z.existsSync(e)||await z.promises.writeFile(e,"","utf-8"),e}async function bw(){let n=await ww();return dw.lock(n,{stale:1800*1e3})}async function Sw(){let n=qe(),e=(n?await to(n):null)??await Ji();if(!e)throw new Error("docs.zip not found");return e}async function Pw(n,e){let t=await Sw(),r=n.force||await Xi(n.force),o=await Zi(n.force);if(!r&&!o&&In()){await yw(e);return}if(qi()&&!n.force){await hw(t,e),await mu(e);return}await gw(n,t,e),await mu(e)}var vs=class{static async run(e={}){let t=e.background??!1,o=e.quiet??t?void 0:hu({text:"Checking documentation\u2026",color:"cyan"}),i;try{i=await bw(),await Yi(nd("Starting documentation setup\u2026")),await Pw(e,o)}catch(s){await vw(s,o)}finally{i&&await i()}}};async function Ew(n){for(;;){let e=await oo();if(e.state==="done"&&In())return;if(e.state==="error")throw new ys("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 uw(500)}}async function fu(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await vs.run({builtBy:"doc-init",force:e,quiet:!0})}async function Dw(){if(In())return;let n=hu({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await rd()){await Ew(n),n.succeed("Documentation ready.");return}if(await Xi()){await fu(n),n.succeed("Documentation ready.");return}await fu(n,!0),n.succeed("Documentation ready.")}catch(e){throw n.fail(e.message),e}}async function _n(){await Dw(),await pu()}var ws=class{async search(e,t,r=20){return await _n(),Bd(e,t,r)}async readDocument(e){return await _n(),Yl(e)}},bs=new ws;function gu(...n){return e=>{if(!n.includes(e))throw new Ss(`Allowed values: ${n.join(", ")}`);return e}}function Aw(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new Ss("Must be a positive integer.");return e}var Tw=gu("json","default"),xw=gu("json","default"),Po=new Iw("docs").description("Search and read HarmonyOS documentation from local docs directory");Po.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",Rw,"all").option("--format <fmt>","Output format (default, json)",Tw,"default").option("--limit <n>","Max number of results",Aw,20).action(async(n,e)=>{try{let t=kw(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await bs.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):Mw(o)}catch(t){console.error(So(t.message)),process.exit(1)}});Po.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error(So("Document ID cannot be empty.")),process.exit(1));let t=await bs.readDocument(e);console.log(t)}catch(e){console.error(So(e.message)),process.exit(1)}});Po.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",xw,"default").action(async n=>{try{if(await _n(),n.format==="json"){let e=Ue.map(t=>({name:t,title:at[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of Ue)console.log(` ${e.padEnd(20)} ${Cw(at[e])}`)}catch(e){console.error(So(e.message)),process.exit(1)}});function kw(n){let e=n.map(r=>r.trim()).filter(Boolean);if(e.length===0)throw new Error("Keywords cannot be empty.");if(e.join(" ").length>Sn)throw new Error(`Query exceeds ${Sn} characters.`);return e}function Rw(n){if(n==="all")return"all";if(!Ue.includes(n))throw new Ss(`Invalid catalog "${n}". Allowed: all, ${Ue.join(", ")}`);return n}function Mw(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 yu=Po;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";Ow();te.name("devecocli").description("HarmonyOS application development command line tool").version("0.2.0");te.addCommand(js);te.addCommand(Js);te.addCommand(aa);I()||te.addCommand(Ta);te.addCommand(Qa);te.addCommand(oc);te.addCommand(mc);te.addCommand(Sc);te.addCommand(ll);te.addCommand(yu);var Ps=process.argv.slice(2);Ps.length>=2&&Ps[Ps.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var Lw=new Set(["update"]);te.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==te;)t=t.parent;Lw.has(t.name())||await _.checkVersion()});te.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(Nw(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
|